Orders.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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']]['decr'] = empty($skusList[$buyInfo['product_skuid']]['decr']) ? $buyInfo['buy_num'] : $skusList[$buyInfo['product_skuid']]['decr'] + $buyInfo['buy_num'];
  93. }
  94. // 判断库存
  95. if( $productInfo['stock'] - $buyInfo['buy_num'] < $buyInfo['buy_num'] ) return json_send(['code'=>'error','msg'=>'产品库存不足','data'=>['error'=>'产品库存不足=>'.$buyInfo['product_id']]]);
  96. // 需要扣除的库存
  97. $productList[$buyInfo['product_id']]['decr'] = empty($productList[$buyInfo['product_id']]['decr']) ? $buyInfo['buy_num'] : $productList[$buyInfo['product_id']]['decr'] + $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 ($orderProduct as $key => $order) {
  123. // 判断哪一家的赠品
  124. if( isset($rebateProduct[$order['business_id']]) ){
  125. // 循环赠品
  126. foreach ( $rebateProduct[$order['business_id']] as $value) {
  127. // 没有对应的产品
  128. if( !isset($productList[$value['product_id']]) ) $productList[$value['product_id']] = ['id'=>$value['id'],'stock'=>$value['stock']];
  129. // 判断库存,如果库存不足,只赠送最后的库存
  130. if( $productList[$value['product_id']]['stock'] <= $value['buy_num'] ) $value['buy_num'] = $productList[$value['product_id']]['stock'];
  131. // 库存扣减
  132. $productList[$value['product_id']]['stock'] = $productList[$value['product_id']]['stock'] - $value['buy_num'];
  133. // 追加到订单表
  134. $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']];
  135. }
  136. }
  137. // 计算总价格
  138. foreach ($order['product_list'] as $k=>$product) {
  139. // 商品不存在,不进行扣减
  140. if( empty($productPrice[$product['product_id']]['rebate_price']) ) {
  141. // 重组
  142. $order['product_list'][$k] = $product;
  143. continue;
  144. }
  145. // 总优惠增加
  146. $order['coupon_total'] = $order['coupon_total'] + $productPrice[$product['product_id']]['rebate_price'];
  147. // 当前商品的优惠折扣计算
  148. $product['coupon_total'] = number_format( $productPrice[$product['product_id']]['rebate_price'] * ($product['price_total'] / $productPrice[$product['product_id']]['price_total']) , 2 , '.' ,'');
  149. // 成交小计
  150. $product['pay_total'] = $product['pay_total'] - $product['coupon_total'];
  151. // 重组
  152. $order['product_list'][$k] = $product;
  153. }
  154. // 成交总价
  155. $order['pay_total'] = $order['pay_total'] - $order['coupon_total'];
  156. // 赠送积分
  157. $order['order_score'] = (config('order_score_send',0) && floor( $order['pay_total'] * 1 ) > 0 ) ? floor( $order['pay_total'] * 1 ) : 0;
  158. // 成交总价
  159. $order['custom_uid'] = $uid;
  160. // 重组
  161. $orderProduct[$key] = $order;
  162. }
  163. // 组合数据,写入订单表,子表
  164. DB::beginTransaction();
  165. // 写入数据
  166. try {
  167. // 扣减商品库存
  168. foreach ($productList as $key => $value) {
  169. // 扣减库存
  170. $result = $Product->edit($value['id'],['stock'=>DB::raw('stock+-'.$value['decr'])]);
  171. // 判断结果
  172. if( !$result ) {
  173. // 回退数据
  174. DB::rollBack();
  175. // 错误提示
  176. return json_send(['code'=>'error','msg'=>'库存扣减失败','data'=>['error'=>'库存扣减失败']]);
  177. }
  178. }
  179. // 扣减商品库存
  180. foreach ($skusList as $key => $value) {
  181. // 扣减库存
  182. $result = $ProductSkus->edit($value['sku_id'],['stock'=>DB::raw('stock+-'.$value['decr'])]);
  183. // 判断结果
  184. if( !$result ) {
  185. // 回退数据
  186. DB::rollBack();
  187. // 错误提示
  188. return json_send(['code'=>'error','msg'=>'库存扣减失败','data'=>['error'=>'库存扣减失败']]);
  189. }
  190. }
  191. // 循环订单数据
  192. foreach ($orderProduct as $order) {
  193. // 先获取产品列表,并去除key
  194. $productList = array_values($order['product_list']);
  195. // 删除非必要数据
  196. unset($order['product_list']);
  197. // 创建总订单
  198. $orderId = $Model->add($order);
  199. // 如果订单写入失败
  200. if( !$orderId ) {
  201. // 回退数据
  202. DB::rollBack();
  203. // 错误提示
  204. return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'订单创建失败']]);
  205. }
  206. // 创建子订单
  207. foreach ($productList as $key=>$value) {
  208. // 增加订单ID
  209. $value['order_id'] = $orderId;
  210. // 增加订单ID
  211. $value['insert_time']= $time;
  212. $value['update_time']= $time;
  213. // 结果
  214. $productList[$key] = $value;
  215. }
  216. // 写入子表
  217. $result = $OrdersProduct->query()->insert($productList);
  218. // 如果扣减失败
  219. if( !$result ) {
  220. // 回退数据
  221. DB::rollBack();
  222. // 提示信息
  223. return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'子订单创建失败']]);
  224. }
  225. // 写入订单地址表
  226. $addr['order_id'] = $orderId;
  227. // 写入订单地址表
  228. $result = $OrdersAddr->add($addr);
  229. // 地址写入失败
  230. if( !$result ) {
  231. // 回退数据
  232. DB::rollBack();
  233. // 提示信息
  234. return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'地址写入失败']]);
  235. }
  236. // 赠送积分
  237. if( $order['order_score'] > 0 ) $CustomScore->trade($order['custom_uid'],$orderId,$order['order_score'],5,1);
  238. // 如果使用了优惠券
  239. if( $usedCoupon ) $CustomCoupon->edit($usedCoupon,['status'=>1,'order_id'=>$orderId]);
  240. // 购物车
  241. if( $isCart ) $ShopCart->query()->where([['custom_uid','=',$uid]])->whereIn('skuid',array_column($buyList,'product_skuid'))->delete();
  242. }
  243. // 自动发放优惠券
  244. $this->autoCoupon($uid);
  245. // 提交数据
  246. DB::commit();
  247. // 返回结果
  248. return json_send(['code'=>'success','msg'=>'下单成功','data'=>['id'=>null]]);
  249. // 返回结果
  250. } catch (\Throwable $th) {
  251. // 回退数据
  252. DB::rollBack();
  253. // 判断结果,如果库存扣减失败的话
  254. if( stripos($th->getMessage(),'UNSIGNED') ) return json_send(['code'=>'error','msg'=>'库存不足','data'=>['error'=>'产品库存扣减失败']]);
  255. // 下单失败提示
  256. return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>$th->getMessage().$th->getLine()]]);
  257. }
  258. }
  259. /**
  260. * 获取产品列表 /api/orders/get_list
  261. *
  262. * @param string $name 产品名称
  263. * @param int $page 页码,默认1
  264. * @param int $limit 每页条数,默认10条
  265. *
  266. * */
  267. public function get_list(Request $request,Model $Model,OrdersProduct $OrdersProduct,Business $Business){
  268. // 接口验签
  269. // $this->verify_sign();
  270. // 验证参数
  271. $request->scene('get_list')->validate();
  272. // 检查登录
  273. $uid = $this->checkLogin();
  274. // 接收参数
  275. $status = request('status',0);
  276. $limit = request('limit',10);
  277. // 显示
  278. $map = [['custom_uid','=',$uid]];
  279. // 查询状态
  280. if( $status ) $map[] = ['status','=',$status];
  281. // 查询
  282. $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']);
  283. // 订单产品
  284. $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();
  285. // 循环处理
  286. foreach ($Paginator as $key => $order) {
  287. // 商品列表
  288. $itemList = [];
  289. // 返回结果
  290. foreach ($productList as $item) {
  291. // 产品图路径
  292. $item['product_thumb'] = path_compat($item['product_thumb']);
  293. // 如果是订单的
  294. if( $item['order_id'] == $order['id'] ) $itemList[] = $item;
  295. }
  296. // 获取子列表
  297. $order['state'] = (string) $Model->getState($order['status'],'state');
  298. // 获取子列表
  299. $order['business_name'] = (string) ($order['business_id'] ? $Business->getOne($order['business_id'],'name') : ($order['weizan_orderid'] ? '微赞订单' : ''));
  300. // 获取子列表
  301. $order['contents_class']= 0;
  302. // 获取子列表
  303. $order['product_list'] = $itemList;
  304. // 重组
  305. $Paginator[$key] = $order;
  306. }
  307. // 获取数据
  308. $data['total'] = $Paginator->total();
  309. $data['current_page'] = $Paginator->currentPage();
  310. $data['per_page'] = $Paginator->perPage();
  311. $data['last_page'] = $Paginator->lastPage();
  312. $data['data'] = $Paginator->items();
  313. // 返回结果
  314. return json_send(['code'=>'success','msg'=>'获取成功','data'=>$data]);
  315. }
  316. /**
  317. * 自动发放优惠券
  318. *
  319. */
  320. private function autoCoupon($uid){
  321. // 模型实例
  322. $Rule = new \App\Models\CouponRewardRule();
  323. // 获取配置列表
  324. $ruleList = $Rule->getList();
  325. // 如果没有信息的话
  326. if( !$ruleList ) return ['success'=>'暂无活动'];
  327. // 其他实例
  328. $RuleProduct = new \App\Models\CouponRewardProduct();
  329. $OrdersProduct = new \App\Models\OrdersProduct();
  330. $Custom = new \App\Models\Custom();
  331. $Coupon = new \App\Models\Coupon();
  332. $CustomCoupon = new \App\Models\CustomCoupon();
  333. // 获取客户城市ID
  334. $customCityId = (int) $Custom->getValue($uid,'city_id');
  335. // 循环配置列表
  336. foreach ( $ruleList as $value ) {
  337. // 如果存在城市范围,并且不在城市范围,不参与这个活动
  338. if( $value['city_ids'] && !in_array($customCityId,explode(',',$value['city_ids'])) ) continue;
  339. // 未到开始时间
  340. if( $value['start_time'] > time() ) continue;
  341. // 通过配置ID获取对应的商品范围
  342. $productList = $RuleProduct->getListByRule($value['id']);
  343. // 如果不存在产品范围,跳过
  344. if( !$productList ) continue;
  345. // 获取客户 规定时段内订单的商品ID以及购买数量
  346. $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();
  347. // 如果没有订单总数
  348. if( !$orderList ) continue;
  349. // 计算商品总量
  350. $total = 0;
  351. // 循环商品范围
  352. foreach ($productList as $scope) {
  353. // 循环订单产品
  354. foreach ($orderList as $order) {
  355. // 如果产品不相等
  356. if( $scope['product_id'] != $order['product_id'] ) continue;
  357. // 相等的计算总量
  358. $total += $scope['product_units'] * $order['buy_num'];
  359. }
  360. }
  361. // 判断总数是不是达标
  362. if( $total < $value['std_num'] ) continue;
  363. // 达标的是否已经发送过优惠券
  364. $havaCoupon = $CustomCoupon->query()->where([['custom_uid','=',$uid],['coupon_id','=',$value['coupon_id']]])->first(['status']);
  365. // 已经发过优惠券的,不发
  366. if( $havaCoupon ) continue;
  367. // 获取优惠券的可用时间
  368. $expTime = $Coupon->query()->where([['id','=',$value['coupon_id']]])->value('exp_time');
  369. // 时间转时间
  370. $expTime = $Coupon->getExpTime($expTime);
  371. // 发送优惠券
  372. $CustomCoupon->add(['coupon_id'=>$value['coupon_id'],'custom_uid'=>$uid,'exp_time'=>$expTime]);
  373. }
  374. // 返回成功
  375. return ['success'=>'操作成功'];
  376. }
  377. /**
  378. * 取消 /api/orders/cancel
  379. *
  380. * */
  381. public function cancel( Request $request, Model $Model,OrdersProduct $OrdersProduct,CustomScore $CustomScore){
  382. // 验证参数
  383. $request->scene('cancel')->validate();
  384. // 检查登录
  385. $uid = $this->checkLogin();
  386. // 接收参数
  387. $id = request('id',0);
  388. $status = 4;
  389. // 获取产品和数量
  390. $oldData = $Model->query()->where([['id','=',$id],['custom_uid','=',$uid]])->first(['id','order_score','custom_uid']);
  391. // 如果用户不存在
  392. if( !$oldData ) return json_send(['code'=>'error','msg'=>'订单不存在']);
  393. // 组合数据,写入订单表,子表
  394. DB::beginTransaction();
  395. try{
  396. // 查询数据
  397. $result = $Model->edit($id,['status'=>$status]);
  398. // 提示新增失败
  399. if( !$result ) {
  400. // 回退数据
  401. DB::rollBack();
  402. // 提示信息
  403. return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>'订单修改失败']]);
  404. }
  405. // 查询数据
  406. $result = $OrdersProduct->query()->where([['order_id','=',$id]])->update(['status'=>$status,'update_time'=>time()]);
  407. // 提示新增失败
  408. if( !$result ) {
  409. // 回退数据
  410. DB::rollBack();
  411. // 提示信息
  412. return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>'子订单修改失败']]);
  413. }
  414. // 如果取消订单
  415. if( $status == 4 ) {
  416. // 赠送积分
  417. if( $oldData['order_score'] > 0 ) {
  418. // 如果扣减失败
  419. $result = $CustomScore->trade($oldData['custom_uid'],$oldData['id'],($oldData['order_score']*-1),6,1);
  420. // 提示新增失败
  421. if( isset($result['error']) ) {
  422. // 回退数据
  423. DB::rollBack();
  424. // 提示信息
  425. return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>$result['error']]]);
  426. }
  427. }
  428. }
  429. // 提交数据
  430. DB::commit();
  431. // 告知结果
  432. return json_send(['code'=>'success','msg'=>'取消成功']);
  433. // 返回结果
  434. } catch (\Throwable $th) {
  435. // 回退数据
  436. DB::rollBack();
  437. // 下单失败提示
  438. return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>$th->getMessage().$th->getLine()]]);
  439. }
  440. }
  441. }