Orders.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. <?php namespace App\Http\Controllers\Api;
  2. use App\Http\Controllers\Api\Api;
  3. use App\Models\Orders as Model;
  4. use App\Models\Product;
  5. use App\Models\Product\Skus as ProductSkus;
  6. use App\Http\Requests\Api\Orders as Request;
  7. use App\Models\Business;
  8. use App\Models\CustomAddr;
  9. use App\Models\CustomCoupon;
  10. use App\Models\CustomScore;
  11. use App\Models\OrdersAddr;
  12. use App\Models\OrdersProduct;
  13. use App\Models\ShopCart;
  14. use Illuminate\Support\Facades\DB;
  15. /**
  16. * 订单接口
  17. *
  18. * @author 刘相欣
  19. *
  20. * */
  21. class Orders extends Api{
  22. /**
  23. * 创建订单 /api/orders/create
  24. *
  25. * @param string $car_info 需要下单的产品ID
  26. * @param string $buyer_number 需要下单的数量
  27. *
  28. * */
  29. public function create(Request $request,Model $Model,OrdersAddr $OrdersAddr,OrdersProduct $OrdersProduct,Product $Product,ProductSkus $ProductSkus,CustomCoupon $CustomCoupon,ShopCart $ShopCart,CustomAddr $CustomAddr,CustomScore $CustomScore){
  30. // 接口验签
  31. // $this->verify_sign();
  32. // 验证参数
  33. $request->scene('create')->validate();
  34. // 检查登录
  35. $uid = $this->checkLogin();
  36. // 接收参数
  37. $isCart = request('is_cart',0);
  38. $productList = request('product_list','[]');
  39. $customCouponId = request('custom_coupon_id',1);
  40. $addr = $CustomAddr->getOne(request('addr_id',0));
  41. // 如果不存在数据
  42. if( !$addr ) return json_send(['code'=>'error','msg'=>'地址有误,请核对','data'=>['error'=>'没有找到对应的地址']]);
  43. // 重组数据
  44. $addr = ['contact_name'=>$addr['contact_name'],'contact_shop'=>$addr['contact_shop'],'contact_phone'=>$addr['contact_phone'],'contact_province'=>$addr['contact_province'],'contact_city'=>$addr['contact_city'],'contact_area'=>$addr['contact_area'],'contact_addr'=>$addr['contact_addr']];
  45. // 解码购买信息
  46. $buyList = json_decode($productList,true);
  47. // 如果不存在数据
  48. if( empty($buyList) ) return json_send(['code'=>'error','msg'=>'没有需下单的产品','data'=>['error'=>'产品列表为空']]);
  49. // 商品购买数量
  50. $buyNum = [];
  51. // 循环购买信息
  52. foreach ($buyList as $key => $value) {
  53. // 获取每个商品的总量
  54. $buyNum[$value['product_id']] = isset($buyNum[$value['product_id']]) ? ($buyNum[$value['product_id']] + $value['buy_num']) : $value['buy_num'];
  55. }
  56. // 查询产品信息
  57. $productList = $Product->getListByIds(array_column($buyList,'product_id'));
  58. $skusList = $ProductSkus->getListByIds(array_column($buyList,'product_skuid'));
  59. // 当前时间
  60. $time = time();
  61. // 产品以商业公司分组,方便写入订单
  62. $orderProduct = [];
  63. // 产品价格同级,用于优惠券计算
  64. $productPrice = [];
  65. // 循环处理购买信息
  66. foreach ($buyList as $buyInfo) {
  67. // 如果产品不存在
  68. if( empty($productList[$buyInfo['product_id']]) ) return json_send(['code'=>'error','msg'=>'产品不存在或已下架','data'=>['error'=>'产品不存在或已下架=>'.$buyInfo['product_id']]]);
  69. // 获取产信息
  70. $productInfo = $productList[$buyInfo['product_id']];
  71. // 如果产品限购
  72. if( $productInfo['quota'] ) {
  73. // 是否在限购时间,当前时间大于开始时间,并且小于结束时间
  74. if( $productInfo['quota_start'] <= $time && $time <= $productInfo['quota_end'] ){
  75. // 通过时间查询商品的购买总数
  76. $total = $OrdersProduct->query()->where([['custom_uid','=',$uid],['product_id','=',$productInfo['id']],['insert_time','>=',$productInfo['quota_start']],['insert_time','<=',$productInfo['quota_end']]])->sum('buy_num');
  77. // 判断限购数量
  78. $total = $buyNum[$buyInfo['product_id']] + $total;
  79. // 如果超过数量
  80. if( $total > $productInfo['quota'] ) return json_send(['code'=>'error','msg'=>'已限购'.$productInfo['product_name'],'data'=>['error'=>'已超限=>'.($total - $productInfo['quota'])]]);
  81. }
  82. }
  83. // 如果存在SKU
  84. if( $buyInfo['product_skuid'] ) {
  85. // 判断SKU信息存不存在
  86. if( empty($skusList[$buyInfo['product_skuid']]) ) return json_send(['code'=>'error','msg'=>'该产品规格不存在或已下架','data'=>['error'=>'SKU不存在或已下架=>'.$buyInfo['product_skuid']]]);
  87. // 产品ID不匹配的话
  88. if( $skusList[$buyInfo['product_skuid']]['product_id'] != $buyInfo['product_id'] ) return json_send(['code'=>'error','msg'=>'该产品规格不存在或已下架','data'=>['error'=>'SKU不匹配=>'.$buyInfo['product_skuid']]]);
  89. // 如果SKU存在,合并产品信息
  90. $productInfo = array_merge($productInfo,$skusList[$buyInfo['product_skuid']]);
  91. // 扣除库存
  92. $skusList[$buyInfo['product_skuid']]['stock'] = $skusList[$buyInfo['product_skuid']]['stock'] - $buyInfo['buy_num'];
  93. }
  94. // 判断库存
  95. if( $productInfo['stock'] < $buyInfo['buy_num'] ) return json_send(['code'=>'error','msg'=>'产品库存不足','data'=>['error'=>'产品库存不足=>'.$buyInfo['product_id']]]);
  96. // 扣除库存
  97. $productList[$buyInfo['product_id']]['stock'] = $productList[$buyInfo['product_id']]['stock'] - $buyInfo['buy_num'];
  98. // 计算价值
  99. $priceTotal = $buyInfo['buy_num'] * $productInfo['price'];
  100. // 购买信息
  101. $buyInfo = ['is_rebate'=>0,'custom_uid'=>$uid,'business_id'=>$productInfo['business_id'],'product_id'=>$buyInfo['product_id'],'buy_num'=>$buyInfo['buy_num'],'price_total'=>$priceTotal,'pay_total'=>$priceTotal,'coupon_total'=>0,'product_name'=>$productInfo['product_name'],'sku_attr_names'=>$productInfo['sku_attr_names'],'product_thumb'=>$productInfo['product_thumb']];
  102. // 获取信息
  103. if( !isset($orderProduct[$buyInfo['business_id']]) ) $orderProduct[$buyInfo['business_id']] = ['business_id'=>$buyInfo['business_id'],'custom_uid'=>$buyInfo['custom_uid'],'price_total'=>0,'pay_total'=>0,'coupon_total'=>0,'product_list'=>[]];
  104. // 订单产品
  105. $orderProduct[$buyInfo['business_id']]['price_total'] += $buyInfo['price_total'];
  106. $orderProduct[$buyInfo['business_id']]['pay_total'] += $buyInfo['price_total'];
  107. $orderProduct[$buyInfo['business_id']]['product_list'][] = $buyInfo;
  108. // 商品优惠信息不存在,创建
  109. if( !isset($productPrice[$buyInfo['product_id']]) ) $productPrice[$buyInfo['product_id']] = ['price_total'=>0,'rebate_price'=>0];
  110. // 计算总价
  111. $productPrice[$buyInfo['product_id']]['price_total'] = $productPrice[$buyInfo['product_id']]['price_total'] + $priceTotal;
  112. }
  113. // 优惠券数据
  114. $couponRebate = $CustomCoupon->getRebatePrice($customCouponId,$uid,$productPrice);
  115. // 判断是否使用了优惠券
  116. $usedCoupon = $couponRebate['is_used'];
  117. // 获取优惠券扣减金额
  118. $productPrice = $couponRebate['product_price'];
  119. // 获取优惠券赠品信息
  120. $rebateProduct = $couponRebate['rebate_product'];
  121. // 库存处理
  122. foreach ($productList as $key => $value) {
  123. $productList[$key] = ['id'=>$value['id'],'stock'=>$value['stock']];
  124. }
  125. foreach ($skusList as $key => $value) {
  126. $skusList[$key] = ['id'=>$value['sku_id'],'stock'=>$value['stock']];
  127. }
  128. // 组合订单数据
  129. foreach ($orderProduct as $key => $order) {
  130. // 判断哪一家的赠品
  131. if( isset($rebateProduct[$order['business_id']]) ){
  132. // 循环赠品
  133. foreach ( $rebateProduct[$order['business_id']] as $value) {
  134. // 没有对应的产品
  135. if( !isset($productList[$value['product_id']]) ) $productList[$value['product_id']] = ['id'=>$value['id'],'stock'=>$value['stock']];
  136. // 判断库存,如果库存不足,只赠送最后的库存
  137. if( $productList[$value['product_id']]['stock'] <= $value['buy_num'] ) $value['buy_num'] = $productList[$value['product_id']]['stock'];
  138. // 库存扣减
  139. $productList[$value['product_id']]['stock'] = $productList[$value['product_id']]['stock'] - $value['buy_num'];
  140. // 追加到订单表
  141. $order['product_list'][] = ['is_rebate'=>1,'custom_uid'=>$uid,'business_id'=>$value['business_id'],'product_id'=>$value['product_id'],'buy_num'=>$value['buy_num'],'price_total'=>$value['price_total'],'pay_total'=>$value['pay_total'],'coupon_total'=>$value['coupon_total'],'product_name'=>$value['product_name'],'sku_attr_names'=>$value['sku_attr_names'],'product_thumb'=>$value['product_thumb']];
  142. }
  143. }
  144. // 计算总价格
  145. foreach ($order['product_list'] as $k=>$product) {
  146. // 商品不存在,不进行扣减
  147. if( empty($productPrice[$product['product_id']]['rebate_price']) ) {
  148. // 重组
  149. $order['product_list'][$k] = $product;
  150. continue;
  151. }
  152. // 总优惠增加
  153. $order['coupon_total'] = $order['coupon_total'] + $productPrice[$product['product_id']]['rebate_price'];
  154. // 当前商品的优惠折扣计算
  155. $product['coupon_total'] = number_format( $productPrice[$product['product_id']]['rebate_price'] * ($product['price_total'] / $productPrice[$product['product_id']]['price_total']) , 2 , '.' ,'');
  156. // 成交小计
  157. $product['pay_total'] = $product['pay_total'] - $product['coupon_total'];
  158. // 重组
  159. $order['product_list'][$k] = $product;
  160. }
  161. // 成交总价
  162. $order['pay_total'] = $order['pay_total'] - $order['coupon_total'];
  163. // 赠送积分
  164. $order['order_score'] = (config('order_score_send',0) && floor( $order['pay_total'] * 1 ) > 0 ) ? floor( $order['pay_total'] * 1 ) : 0;
  165. // 成交总价
  166. $order['custom_uid'] = $uid;
  167. // 重组
  168. $orderProduct[$key] = $order;
  169. }
  170. // 组合数据,写入订单表,子表
  171. DB::beginTransaction();
  172. // 写入数据
  173. try {
  174. // 更新库存
  175. $Product->updateBatch(array_values($productList));
  176. // 更新库存
  177. $ProductSkus->updateBatch(array_values($skusList));
  178. // 循环订单数据
  179. foreach ($orderProduct as $order) {
  180. // 先获取产品列表,并去除key
  181. $productList = array_values($order['product_list']);
  182. // 删除非必要数据
  183. unset($order['product_list']);
  184. // 创建总订单
  185. $orderId = $Model->add($order);
  186. // 如果订单写入失败
  187. if( !$orderId ) {
  188. // 回退数据
  189. DB::rollBack();
  190. // 错误提示
  191. return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'订单创建失败']]);
  192. }
  193. // 创建子订单
  194. foreach ($productList as $key=>$value) {
  195. // 增加订单ID
  196. $value['order_id'] = $orderId;
  197. // 增加订单ID
  198. $value['insert_time']= $time;
  199. $value['update_time']= $time;
  200. // 结果
  201. $productList[$key] = $value;
  202. }
  203. // 写入子表
  204. $result = $OrdersProduct->query()->insert($productList);
  205. // 如果扣减失败
  206. if( !$result ) {
  207. // 回退数据
  208. DB::rollBack();
  209. // 提示信息
  210. return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'子订单创建失败']]);
  211. }
  212. // 写入订单地址表
  213. $addr['order_id'] = $orderId;
  214. // 写入订单地址表
  215. $result = $OrdersAddr->add($addr);
  216. // 地址写入失败
  217. if( !$result ) {
  218. // 回退数据
  219. DB::rollBack();
  220. // 提示信息
  221. return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'地址写入失败']]);
  222. }
  223. // 赠送积分
  224. if( $order['order_score'] > 0 ) $CustomScore->trade($order['custom_uid'],$orderId,$order['order_score'],5,1);
  225. // 如果使用了优惠券
  226. if( $usedCoupon ) $CustomCoupon->edit($usedCoupon,['status'=>1,'order_id'=>$orderId]);
  227. // 购物车
  228. if( $isCart ) $ShopCart->query()->where([['custom_uid','=',$uid]])->whereIn('skuid',array_column($buyList,'product_skuid'))->delete();
  229. }
  230. // 自动发放优惠券
  231. $this->autoCoupon($uid);
  232. // 提交数据
  233. DB::commit();
  234. // 返回结果
  235. return json_send(['code'=>'success','msg'=>'下单成功','data'=>['id'=>null]]);
  236. // 返回结果
  237. } catch (\Throwable $th) {
  238. // 回退数据
  239. DB::rollBack();
  240. // 判断结果,如果库存扣减失败的话
  241. if( stripos($th->getMessage(),'UNSIGNED') ) return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'产品库存扣减失败']]);
  242. // 下单失败提示
  243. return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>$th->getMessage().$th->getLine()]]);
  244. }
  245. }
  246. /**
  247. * 获取产品列表 /api/orders/get_list
  248. *
  249. * @param string $name 产品名称
  250. * @param int $page 页码,默认1
  251. * @param int $limit 每页条数,默认10条
  252. *
  253. * */
  254. public function get_list(Request $request,Model $Model,OrdersProduct $OrdersProduct,Business $Business){
  255. // 接口验签
  256. // $this->verify_sign();
  257. // 验证参数
  258. $request->scene('get_list')->validate();
  259. // 检查登录
  260. $uid = $this->checkLogin();
  261. // 接收参数
  262. $status = request('status',0);
  263. $limit = request('limit',10);
  264. // 显示
  265. $map = [['custom_uid','=',$uid]];
  266. // 查询状态
  267. if( $status ) $map[] = ['status','=',$status];
  268. // 查询
  269. $Paginator = $Model->query()->where($map)->orderByDesc('id')->paginate($limit,['id','pay_total','status','price_total','coupon_total','business_id','pay_total','weizan_orderid','insert_time']);
  270. // 订单产品
  271. $productList = $OrdersProduct->query()->whereIn('order_id', array_column($Paginator->items(),'id'))->select(['id as item_id','order_id','product_id','buy_num','is_rebate','sku_attr_names as product_spec','product_name','product_thumb'])->get()->toArray();
  272. // 循环处理
  273. foreach ($Paginator as $key => $order) {
  274. // 商品列表
  275. $itemList = [];
  276. // 返回结果
  277. foreach ($productList as $item) {
  278. // 产品图路径
  279. $item['product_thumb'] = path_compat($item['product_thumb']);
  280. // 如果是订单的
  281. if( $item['order_id'] == $order['id'] ) $itemList[] = $item;
  282. }
  283. // 获取子列表
  284. $order['state'] = (string) $Model->getState($order['status'],'state');
  285. // 获取子列表
  286. $order['business_name'] = (string) ($order['business_id'] ? $Business->getOne($order['business_id'],'name') : ($order['weizan_orderid'] ? '微赞订单' : ''));
  287. // 获取子列表
  288. $order['contents_class']= 0;
  289. // 获取子列表
  290. $order['product_list'] = $itemList;
  291. // 重组
  292. $Paginator[$key] = $order;
  293. }
  294. // 获取数据
  295. $data['total'] = $Paginator->total();
  296. $data['current_page'] = $Paginator->currentPage();
  297. $data['per_page'] = $Paginator->perPage();
  298. $data['last_page'] = $Paginator->lastPage();
  299. $data['data'] = $Paginator->items();
  300. // 返回结果
  301. return json_send(['code'=>'success','msg'=>'获取成功','data'=>$data]);
  302. }
  303. /**
  304. * 自动发放优惠券
  305. *
  306. */
  307. private function autoCoupon($uid){
  308. // 模型实例
  309. $Rule = new \App\Models\CouponRewardRule();
  310. // 获取配置列表
  311. $ruleList = $Rule->getList();
  312. // 如果没有信息的话
  313. if( !$ruleList ) return ['success'=>'暂无活动'];
  314. // 其他实例
  315. $RuleProduct = new \App\Models\CouponRewardProduct();
  316. $OrdersProduct = new \App\Models\OrdersProduct();
  317. $Custom = new \App\Models\Custom();
  318. $Coupon = new \App\Models\Coupon();
  319. $CustomCoupon = new \App\Models\CustomCoupon();
  320. // 获取客户城市ID
  321. $customCityId = (int) $Custom->getValue($uid,'city_id');
  322. // 循环配置列表
  323. foreach ( $ruleList as $value ) {
  324. // 如果存在城市范围,并且不在城市范围,不参与这个活动
  325. if( $value['city_ids'] && !in_array($customCityId,explode(',',$value['city_ids'])) ) continue;
  326. // 未到开始时间
  327. if( $value['start_time'] > time() ) continue;
  328. // 通过配置ID获取对应的商品范围
  329. $productList = $RuleProduct->getListByRule($value['id']);
  330. // 如果不存在产品范围,跳过
  331. if( !$productList ) continue;
  332. // 获取客户 规定时段内订单的商品ID以及购买数量
  333. $orderList = $OrdersProduct->query()->where([['custom_uid','=',$uid],['status','=',1],['insert_time','>=',$value['start_time']],['insert_time','<=',$value['end_time']]])->get(['product_id','buy_num'])->toArray();
  334. // 如果没有订单总数
  335. if( !$orderList ) continue;
  336. // 计算商品总量
  337. $total = 0;
  338. // 循环商品范围
  339. foreach ($productList as $scope) {
  340. // 循环订单产品
  341. foreach ($orderList as $order) {
  342. // 如果产品不相等
  343. if( $scope['product_id'] != $order['product_id'] ) continue;
  344. // 相等的计算总量
  345. $total += $scope['product_units'] * $order['buy_num'];
  346. }
  347. }
  348. // 判断总数是不是达标
  349. if( $total < $value['std_num'] ) continue;
  350. // 达标的是否已经发送过优惠券
  351. $havaCoupon = $CustomCoupon->query()->where([['custom_uid','=',$uid],['coupon_id','=',$value['coupon_id']]])->first(['status']);
  352. // 已经发过优惠券的,不发
  353. if( $havaCoupon ) continue;
  354. // 获取优惠券的可用时间
  355. $expTime = $Coupon->query()->where([['id','=',$value['coupon_id']]])->value('exp_time');
  356. // 时间转时间
  357. $expTime = $Coupon->getExpTime($expTime);
  358. // 发送优惠券
  359. $CustomCoupon->add(['coupon_id'=>$value['coupon_id'],'custom_uid'=>$uid,'exp_time'=>$expTime]);
  360. }
  361. // 返回成功
  362. return ['success'=>'操作成功'];
  363. }
  364. /**
  365. * 取消 /api/orders/cancel
  366. *
  367. * */
  368. public function cancel( Request $request, Model $Model,OrdersProduct $OrdersProduct,CustomScore $CustomScore){
  369. // 验证参数
  370. $request->scene('cancel')->validate();
  371. // 检查登录
  372. $uid = $this->checkLogin();
  373. // 接收参数
  374. $id = request('id',0);
  375. $status = 4;
  376. // 获取产品和数量
  377. $oldData = $Model->query()->where([['id','=',$id],['custom_uid','=',$uid]])->first(['id','order_score','custom_uid']);
  378. // 如果用户不存在
  379. if( !$oldData ) return json_send(['code'=>'error','msg'=>'订单不存在']);
  380. // 组合数据,写入订单表,子表
  381. DB::beginTransaction();
  382. try{
  383. // 查询数据
  384. $result = $Model->edit($id,['status'=>$status]);
  385. // 提示新增失败
  386. if( !$result ) {
  387. // 回退数据
  388. DB::rollBack();
  389. // 提示信息
  390. return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>'订单修改失败']]);
  391. }
  392. // 查询数据
  393. $result = $OrdersProduct->query()->where([['order_id','=',$id]])->update(['status'=>$status,'update_time'=>time()]);
  394. // 提示新增失败
  395. if( !$result ) {
  396. // 回退数据
  397. DB::rollBack();
  398. // 提示信息
  399. return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>'子订单修改失败']]);
  400. }
  401. // 如果取消订单
  402. if( $status == 4 ) {
  403. // 赠送积分
  404. if( $oldData['order_score'] > 0 ) {
  405. // 如果扣减失败
  406. $result = $CustomScore->trade($oldData['custom_uid'],$oldData['id'],($oldData['order_score']*-1),6,1);
  407. // 提示新增失败
  408. if( isset($result['error']) ) {
  409. // 回退数据
  410. DB::rollBack();
  411. // 提示信息
  412. return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>$result['error']]]);
  413. }
  414. }
  415. }
  416. // 提交数据
  417. DB::commit();
  418. // 告知结果
  419. return json_send(['code'=>'success','msg'=>'取消成功']);
  420. // 返回结果
  421. } catch (\Throwable $th) {
  422. // 回退数据
  423. DB::rollBack();
  424. // 下单失败提示
  425. return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>$th->getMessage().$th->getLine()]]);
  426. }
  427. }
  428. }