Orders.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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\City;
  9. use App\Models\Custom;
  10. use App\Models\CustomAddr;
  11. use App\Models\CustomCoupon;
  12. use App\Models\CustomScore;
  13. use App\Models\OrdersAddr;
  14. use App\Models\OrdersProduct;
  15. use App\Models\Regiment;
  16. use App\Models\RegimentActive;
  17. use App\Models\RegimentRecord;
  18. use App\Models\ShopCart;
  19. use Illuminate\Support\Facades\DB;
  20. use App\Models\WeiBan\Tags as WeiBanTags;
  21. use App\Models\PromoProduct as PromoProduct;
  22. /**
  23. * 订单接口
  24. *
  25. * @author 刘相欣
  26. *
  27. * */
  28. class Orders extends Api{
  29. /**
  30. * 创建订单 /api/orders/create
  31. *
  32. * */
  33. public function create(Request $request,Custom $Custom,City $City,Model $Model,WeiBanTags $WeiBanTags,OrdersAddr $OrdersAddr,OrdersProduct $OrdersProduct,Product $Product,ProductSkus $ProductSkus,CustomCoupon $CustomCoupon,ShopCart $ShopCart,CustomAddr $CustomAddr,CustomScore $CustomScore,PromoProduct $PromoProduct){
  34. // 接口验签
  35. // $this->verify_sign();
  36. // 验证参数
  37. $request->scene('create')->validate();
  38. // 检查登录
  39. $uid = $this->checkLogin();
  40. // 接收参数
  41. $isCart = request('is_cart',0);
  42. $productList = request('product_list','[]');
  43. $customCouponId = request('custom_coupon_id',0);
  44. $addrId = request('addr_id',0);
  45. // 如果不存在数据
  46. if( !$addrId ) return json_send(['code'=>'error','msg'=>'请选择收货地址','data'=>['error'=>'请选择收货地址']]);
  47. // 解码购买信息
  48. $buyList = json_decode($productList,true);
  49. // 如果不存在数据
  50. if( empty($buyList) ) return json_send(['code'=>'error','msg'=>'没有需下单的产品','data'=>['error'=>'产品列表为空']]);
  51. // 选择地址
  52. $addr = $CustomAddr->getOne($addrId);
  53. // 如果不存在数据
  54. if( !$addr ) return json_send(['code'=>'error','msg'=>'地址有误,请核对','data'=>['error'=>'没有找到对应的地址']]);
  55. // 如果不存在的话
  56. if( !$addr['contact_shop'] ) return json_send(['code'=>'error','msg'=>'请在店铺名称处填写具体药店名称','data'=>['error'=>'所用地址请补充店铺名称']]);
  57. // 重组数据
  58. $addr = ['contact_name'=>$addr['contact_name'],'contact_shop'=>$addr['contact_shop'],'shop_type'=>$addr['shop_type'],'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']];
  59. // 获取客户城市ID
  60. $custom = $Custom->getOne($uid);
  61. // 如果不存在的话
  62. if( !$custom ) return json_send(['code'=>'no_login','msg'=>'用户不存在,请重新登录','data'=>['error'=>'用户不存在,请重新登录']]);
  63. // 如果不存在的话
  64. if( !$custom['city_id'] ) return json_send(['code'=>'error','msg'=>'请选择所在城市后下单','data'=>['error'=>'请选择所在城市后下单']]);
  65. // 获取城市ID
  66. $cityId = $custom['city_id'];
  67. $cityName = $City->getOne($cityId,'name');
  68. $pid = $City->getOne($cityId,'pid');
  69. $province = $City->getOne($pid,'name');
  70. // 如果不是海南,
  71. if( $province != '海南省' ) {
  72. // 判断选择的城市名称是不是一致
  73. if( trim($cityName) != trim($addr['contact_city']) ) return json_send(['code'=>'error','msg'=>'收货地址请选择'.($province=='直辖县级'?$cityName:$province).'/'.$cityName,'data'=>['error'=>'收货地址需与您所选城市一致']]);
  74. }else{
  75. if( trim($addr['contact_province']) != trim($province) ) return json_send(['code'=>'error','msg'=>'收货地址请选择海南范围','data'=>['error'=>'收货地址需与您所选城市一致']]);
  76. }
  77. // 商品购买数量
  78. $buyNum = [];
  79. // 循环购买信息
  80. foreach ($buyList as $key => $value) {
  81. // 获取每个商品的总量
  82. $buyNum[$value['product_id']] = isset($buyNum[$value['product_id']]) ? ($buyNum[$value['product_id']] + $value['buy_num']) : $value['buy_num'];
  83. }
  84. // 查询用户标签
  85. $tags = $WeiBanTags->getListByWeibanExtid($custom['weiban_extid']);
  86. // 查询产品信息
  87. $productList = $Product->getListByIds(array_column($buyList,'product_id'),[1,$cityId]);
  88. $skusList = $ProductSkus->getListByIds(array_column($buyList,'product_skuid'));
  89. // 当前时间
  90. $time = time();
  91. // 产品以店铺分组,方便写入订单
  92. $orderProduct = [];
  93. // 产品价格同级,用于优惠券计算
  94. $productPrice = [];
  95. // 循环处理购买信息
  96. foreach ($buyList as $buyInfo) {
  97. // 如果产品不存在
  98. if( empty($productList[$buyInfo['product_id']]) ) return json_send(['code'=>'error','msg'=>'产品不存在或已下架','data'=>['error'=>'产品不存在或已下架=>'.$buyInfo['product_id']]]);
  99. // 获取产信息
  100. $productInfo = $productList[$buyInfo['product_id']];
  101. // 判断是不是可以参与
  102. if( $productInfo['tag_scope'] ) {
  103. // 解析数组
  104. $productInfo['tag_scope'] = explode(',',$productInfo['tag_scope']);
  105. // 标签范围限定时,默认不能参与
  106. $allowJoin = 0;
  107. // 判断标签是不是存在
  108. foreach ($tags as $value) {
  109. // 标签范围内,允许参加
  110. if( in_array($value['name'],$productInfo['tag_scope']) ) $allowJoin = 1;
  111. }
  112. // 如果不能参与
  113. if( !$allowJoin ) return json_send(['code'=>'error','msg'=>'不在 '.$productInfo['product_name'].' 参与范围','data'=>['error'=>'不在标签范围内']]);
  114. }
  115. // 判断是不是可以参与
  116. if( $productInfo['tag_exclude'] ) {
  117. // 解析数组
  118. $productInfo['tag_exclude'] = explode(',',$productInfo['tag_exclude']);
  119. // 判断标签是不是存在
  120. foreach ($tags as $value) {
  121. // 标签排除范围内,不允许参加
  122. if( in_array($value['name'],$productInfo['tag_exclude']) ) return json_send(['code'=>'error','msg'=>'不在 '.$productInfo['product_name'].' 可参与范围','data'=>['error'=>'用户在标签排除范围']]);
  123. }
  124. }
  125. // 如果产品限购
  126. if( $productInfo['quota'] ) {
  127. // 是否在限购时间,当前时间大于开始时间,并且小于结束时间
  128. if( $productInfo['quota_start'] <= $time && $time <= $productInfo['quota_end'] ){
  129. // 通过时间查询商品的购买总数
  130. $total = $OrdersProduct->query()->whereIn('status',[0,1,2,3,8,9])->where([['custom_uid','=',$uid],['is_rebate','=',0],['product_id','=',$productInfo['id']],['insert_time','>=',$productInfo['quota_start']],['insert_time','<=',$productInfo['quota_end']]])->sum('buy_num');
  131. // 判断限购数量
  132. $total = $buyNum[$buyInfo['product_id']] + $total;
  133. // 如果超过数量
  134. if( $total > $productInfo['quota'] ) return json_send(['code'=>'error','msg'=>'限购'.$productInfo['quota'].'单-'.$productInfo['product_name'],'data'=>['error'=>'已超限=>'.($total - $productInfo['quota'])]]);
  135. }
  136. }
  137. // 如果有限制产品的SKU起购规则是与
  138. if( $productInfo['sku_min_quota_and'] ){
  139. // 查询该产品的所有SKU
  140. $skuMin = $ProductSkus->getListByProductId($productInfo['id']);
  141. // 循环产品的SKU
  142. foreach ($skuMin as $key => $value) {
  143. // 如果SKU不限制起购数量,跳过
  144. if( !$value['min_quota'] ) continue;
  145. // 如果限购的SKU不在购买列表中
  146. if( !in_array($value['id'],array_column($buyList,'product_skuid')) ) return json_send(['code'=>'error','msg'=>'请搭配'.$productInfo['product_name'].'【'.$value['attr_names'].'】下单','data'=>['error'=>'最少购买'.$value['min_quota'].'单-'.$productInfo['product_name']]]);;
  147. // 如果购买数量小于最低起购数量
  148. foreach ($buyList as $item) {
  149. // 如果SKU不匹配,跳过
  150. if( $item['product_skuid'] != $value['id'] ) continue;
  151. // 如果购买数量小于最低起购数量
  152. if( $item['buy_num'] < $value['min_quota'] ) return json_send(['code'=>'error','msg'=>'最少购买'.$value['min_quota'].'单-'.$productInfo['product_name'].'【'.$value['attr_names'].'】','data'=>['error'=>'最少购买'.$value['min_quota'].'单-'.$productInfo['product_name']]]);
  153. }
  154. }
  155. }
  156. // 如果存在SKU
  157. if( $buyInfo['product_skuid'] ) {
  158. // 判断SKU信息存不存在
  159. if( empty($skusList[$buyInfo['product_skuid']]) ) return json_send(['code'=>'error','msg'=>'该产品规格不存在或已下架','data'=>['error'=>'SKU不存在或已下架=>'.$buyInfo['product_skuid']]]);
  160. // 产品ID不匹配的话
  161. if( $skusList[$buyInfo['product_skuid']]['product_id'] != $buyInfo['product_id'] ) return json_send(['code'=>'error','msg'=>'该产品规格不存在或已下架','data'=>['error'=>'SKU不匹配=>'.$buyInfo['product_skuid']]]);
  162. // SKU信息
  163. $skuInfo = $skusList[$buyInfo['product_skuid']];
  164. // 如果产品有最低起购
  165. if( $skuInfo['min_quota'] ) {
  166. // 如果购买数量小于最低起购数量
  167. if( $buyInfo['buy_num'] < $skuInfo['min_quota'] ){
  168. // 如果超过数量
  169. return json_send(['code'=>'error','msg'=>'最少购买'.$skuInfo['min_quota'].'单-'.$productInfo['product_name'].'【'.$skuInfo['sku_attr_names'].'】','data'=>['error'=>'最少购买'.$skuInfo['min_quota'].'单-'.$productInfo['product_name']]]);
  170. }
  171. }
  172. // 如果SKU限购
  173. if( $skuInfo['quota'] ) {
  174. // 是否在限购时间,当前时间大于开始时间,并且小于结束时间
  175. if( $productInfo['quota_start'] <= $time && $time <= $productInfo['quota_end'] ){
  176. // 通过时间查询商品的购买总数
  177. $total = $OrdersProduct->query()->whereIn('status',[0,1,2,3,8,9])->where([['custom_uid','=',$uid],['is_rebate','=',0],['product_id','=',$productInfo['id']],['sku_attr_names','=',$skuInfo['sku_attr_names']],['insert_time','>=',$productInfo['quota_start']],['insert_time','<=',$productInfo['quota_end']]])->sum('buy_num');
  178. // 判断限购数量
  179. $total = $buyInfo['buy_num'] + $total;
  180. // 如果超过数量
  181. if( $total > $skuInfo['quota'] ) return json_send(['code'=>'error','msg'=>'限购'.$skuInfo['quota'].'单-'.$productInfo['product_name'].'【'.$skuInfo['sku_attr_names'].'】','data'=>['error'=>'已超限=>'.($total - $skuInfo['quota'])]]);
  182. }
  183. }
  184. // 删除起购字段,避免影响后续产品最低起购的判定
  185. unset($skuInfo['min_quota']);
  186. // 如果SKU存在,合并产品信息
  187. $productInfo = array_merge($productInfo,$skuInfo);
  188. // 需要扣除的库存
  189. $skusList[$buyInfo['product_skuid']]['decr'] = empty($skusList[$buyInfo['product_skuid']]['decr']) ? $buyInfo['buy_num'] : $skusList[$buyInfo['product_skuid']]['decr'] + $buyInfo['buy_num'];
  190. }
  191. // 如果产品有最低起购
  192. if( $productInfo['min_quota'] ) {
  193. // 如果购买数量小于最低起购数量
  194. if( $buyNum[$buyInfo['product_id']] < $productInfo['min_quota'] ){
  195. // 如果超过数量
  196. return json_send(['code'=>'error','msg'=>'最少购买'.$productInfo['min_quota'].'单-'.$productInfo['product_name'],'data'=>['error'=>'最少购买'.$productInfo['min_quota'].'单-'.$productInfo['product_name']]]);
  197. }
  198. }
  199. // 需要扣除的库存
  200. $productList[$buyInfo['product_id']]['decr'] = empty($productList[$buyInfo['product_id']]['decr']) ? $buyInfo['buy_num'] : $productList[$buyInfo['product_id']]['decr'] + $buyInfo['buy_num'];
  201. // 判断库存
  202. if( $productInfo['stock'] < $productList[$buyInfo['product_id']]['decr'] ) return json_send(['code'=>'error','msg'=>$productInfo['product_name'].'-库存不足','data'=>['error'=>'产品库存不足=>'.$buyInfo['product_id']]]);
  203. // 计算价值
  204. $priceTotal = $buyInfo['buy_num'] * $productInfo['price'];
  205. // 购买信息
  206. $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']];
  207. // 获取信息
  208. 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'=>[]];
  209. // 订单产品
  210. $orderProduct[$buyInfo['business_id']]['price_total'] += $buyInfo['price_total'];
  211. $orderProduct[$buyInfo['business_id']]['pay_total'] += $buyInfo['price_total'];
  212. $orderProduct[$buyInfo['business_id']]['product_list'][] = $buyInfo;
  213. // 商品优惠信息不存在,创建
  214. if( !isset($productPrice[$buyInfo['product_id']]) ) $productPrice[$buyInfo['product_id']] = ['price_total'=>0,'rebate_price'=>0];
  215. // 计算总价
  216. $productPrice[$buyInfo['product_id']]['price_total'] = $productPrice[$buyInfo['product_id']]['price_total'] + $priceTotal;
  217. }
  218. // 优惠券数据
  219. $couponRebate = $CustomCoupon->getRebatePrice($customCouponId,$uid,$productPrice);
  220. // 判断是否使用了优惠券
  221. $usedCoupon = $couponRebate['is_used'];
  222. // 获取优惠券扣减金额
  223. $productPrice = $couponRebate['product_price'];
  224. // 获取优惠券赠品信息
  225. $rebateProduct = $couponRebate['rebate_product'];
  226. /*活动优惠数据*/
  227. $promoList = $PromoProduct->getRebatePrice(array_column($buyList,'product_id'),$uid,$productPrice,$cityId,$tags);
  228. $promoProductPrice = $promoList['product_price'];
  229. $promoRebateProduct = $promoList['rebate_product'];
  230. // 组合订单数据
  231. foreach ($orderProduct as $key => $order) {
  232. // 判断哪一家的赠品
  233. if( isset($rebateProduct[$order['business_id']]) ){
  234. // 循环赠品
  235. foreach ( $rebateProduct[$order['business_id']] as $value) {
  236. // 没有对应的产品
  237. if( !isset($productList[$value['product_id']]) ) $productList[$value['product_id']] = ['id'=>$value['id'],'stock'=>$value['stock']];
  238. // 判断库存,如果库存不足,只赠送最后的库存
  239. if( $productList[$value['product_id']]['stock'] <= $value['buy_num'] ) $value['buy_num'] = $productList[$value['product_id']]['stock'];
  240. // 库存扣减
  241. $productList[$value['product_id']]['decr'] = empty($productList[$value['product_id']]['decr']) ? $value['buy_num'] : $productList[$value['product_id']]['decr'] + $value['buy_num'];
  242. // 追加到订单表
  243. $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']];
  244. }
  245. }
  246. // 促销活动判断哪一家的赠品
  247. if( isset($promoRebateProduct[$order['business_id']]) ){
  248. // 循环赠品
  249. foreach ( $promoRebateProduct[$order['business_id']] as $value) {
  250. // 没有对应的产品
  251. if( !isset($productList[$value['product_id']]) ) $productList[$value['product_id']] = ['id'=>$value['product_id'],'stock'=>$value['stock']];
  252. // 判断库存,如果库存不足,只赠送最后的库存
  253. if( $productList[$value['product_id']]['stock'] <= $value['buy_num'] ) $value['buy_num'] = $productList[$value['product_id']]['stock'];
  254. // 库存扣减
  255. $productList[$value['product_id']]['decr'] = empty($productList[$value['product_id']]['decr']) ? $value['buy_num'] : $productList[$value['product_id']]['decr'] + $value['buy_num'];
  256. // 追加到订单表
  257. $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'],'sku_attr_names'=>$value['sku_attr_names'],'product_name'=>$value['name'],'product_thumb'=>$value['thumb']];
  258. }
  259. }
  260. // 计算总价格
  261. foreach ($order['product_list'] as $k=>$product) {
  262. //促销活动扣减
  263. if (isset($promoProductPrice[$product['product_id']]['promo_rebate_price']) && $promoProductPrice[$product['product_id']]['promo_rebate_price']> 0){
  264. // 当前商品的优惠折扣计算
  265. $product['coupon_total'] = number_format( $promoProductPrice[$product['product_id']]['rebate_price'] * ($product['price_total'] / $promoProductPrice[$product['product_id']]['price_total']) , 2 , '.' ,'');
  266. // 总优惠增加
  267. $order['coupon_total'] = $order['coupon_total'] + $product['coupon_total'];
  268. // 成交小计
  269. $product['pay_total'] = $product['pay_total'] - $product['coupon_total'];
  270. }
  271. // 商品不存在,不进行扣减
  272. if( empty($productPrice[$product['product_id']]['rebate_price']) ) {
  273. // 重组
  274. $order['product_list'][$k] = $product;
  275. continue;
  276. }
  277. // 当前商品的优惠折扣计算
  278. $product['coupon_total'] = number_format( $productPrice[$product['product_id']]['rebate_price'] * ($product['price_total'] / $productPrice[$product['product_id']]['price_total']) , 2 , '.' ,'');
  279. // 总优惠增加
  280. $order['coupon_total'] = $order['coupon_total'] + $product['coupon_total'];
  281. // 成交小计
  282. $product['pay_total'] = $product['pay_total'] - $product['coupon_total'];
  283. // 重组
  284. $order['product_list'][$k] = $product;
  285. }
  286. // 成交总价
  287. $order['pay_total'] = $order['pay_total'] - $order['coupon_total'];
  288. // 赠送积分
  289. $order['order_score'] = (config('order_score_send',0) && floor( $order['pay_total'] * 1 ) > 0 ) ? floor( $order['pay_total'] * 1 ) : 0;
  290. // 成交总价
  291. $order['custom_uid'] = $uid;
  292. // 重组
  293. $orderProduct[$key] = $order;
  294. }
  295. // 组合数据,写入订单表,子表
  296. DB::beginTransaction();
  297. // 写入数据
  298. try {
  299. // 扣减商品库存
  300. foreach ($productList as $key => $value) {
  301. // 扣减库存
  302. $result = $Product->edit($value['id'],['stock'=>DB::raw('stock+-'.$value['decr'])]);
  303. // 判断结果
  304. if( !$result ) {
  305. // 回退数据
  306. DB::rollBack();
  307. // 错误提示
  308. return json_send(['code'=>'error','msg'=>'库存扣减失败','data'=>['error'=>'库存扣减失败']]);
  309. }
  310. }
  311. // 扣减商品库存
  312. foreach ($skusList as $key => $value) {
  313. // 扣减库存
  314. $result = $ProductSkus->edit($value['sku_id'],['stock'=>DB::raw('stock+-'.$value['decr'])]);
  315. // 判断结果
  316. if( !$result ) {
  317. // 回退数据
  318. DB::rollBack();
  319. // 错误提示
  320. return json_send(['code'=>'error','msg'=>'库存扣减失败','data'=>['error'=>'库存扣减失败']]);
  321. }
  322. }
  323. // 循环订单数据
  324. foreach ($orderProduct as $order) {
  325. // 先获取产品列表,并去除key
  326. $productItem = array_values($order['product_list']);
  327. // 删除非必要数据
  328. unset($order['product_list']);
  329. // 创建总订单
  330. $orderId = $Model->add($order);
  331. // 如果订单写入失败
  332. if( !$orderId ) {
  333. // 回退数据
  334. DB::rollBack();
  335. // 错误提示
  336. return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'订单创建失败']]);
  337. }
  338. // 创建子订单
  339. foreach ($productItem as $key=>$value) {
  340. // 增加订单ID
  341. $value['order_id'] = $orderId;
  342. // 增加订单ID
  343. $value['insert_time']= $time;
  344. $value['update_time']= $time;
  345. // 结果
  346. $productItem[$key] = $value;
  347. }
  348. // 写入子表
  349. $result = $OrdersProduct->query()->insert($productItem);
  350. // 如果扣减失败
  351. if( !$result ) {
  352. // 回退数据
  353. DB::rollBack();
  354. // 提示信息
  355. return json_send(['code'=>'error','msg'=>'子订单创建失败','data'=>['error'=>'子订单创建失败']]);
  356. }
  357. // 写入订单地址表
  358. $addr['order_id'] = $orderId;
  359. // 写入订单地址表
  360. $result = $OrdersAddr->add($addr);
  361. // 地址写入失败
  362. if( !$result ) {
  363. // 回退数据
  364. DB::rollBack();
  365. // 提示信息
  366. return json_send(['code'=>'error','msg'=>'地址写入失败','data'=>['error'=>'地址写入失败']]);
  367. }
  368. // 赠送积分
  369. if( $order['order_score'] > 0 ) $CustomScore->trade($order['custom_uid'],$orderId,$order['order_score'],5,1);
  370. // 如果使用了优惠券
  371. if( $usedCoupon ) $CustomCoupon->edit($usedCoupon,['status'=>1,'order_id'=>$orderId]);
  372. // 购物车
  373. if( $isCart ) $ShopCart->query()->where([['custom_uid','=',$uid]])->whereIn('skuid',array_column($buyList,'product_skuid'))->delete();
  374. }
  375. // 自动发放优惠券
  376. $this->autoCoupon($uid);
  377. // 提交数据
  378. DB::commit();
  379. // 返回结果
  380. return json_send(['code'=>'success','msg'=>'下单成功','data'=>['id'=>null]]);
  381. // 返回结果
  382. } catch (\Throwable $th) {
  383. // 回退数据
  384. DB::rollBack();
  385. // 判断结果,如果库存扣减失败的话
  386. if( stripos($th->getMessage(),'UNSIGNED') ) return json_send(['code'=>'error','msg'=>'库存不足','data'=>['error'=>'产品库存扣减失败']]);
  387. // 下单失败提示
  388. return json_send(['code'=>'error','msg'=>'系统异常,请稍后再试','data'=>['error'=>$th->getMessage().$th->getLine()]]);
  389. }
  390. }
  391. /**
  392. * 获取列表 /api/orders/get_list
  393. *
  394. * @param string $name 产品名称
  395. * @param int $page 页码,默认1
  396. * @param int $limit 每页条数,默认10条
  397. *
  398. * */
  399. public function get_list(Request $request, Model $Model, OrdersProduct $OrdersProduct, Business $Business){
  400. // 接口验签
  401. // $this->verify_sign();
  402. // 验证参数
  403. $request->scene('get_list')->validate();
  404. // 检查登录
  405. $uid = $this->checkLogin();
  406. // 接收参数
  407. $status = request('status',0);
  408. $limit = request('limit',10);
  409. // 显示
  410. $map = [['custom_uid','=',$uid]];
  411. // 查询状态
  412. if( $status ) $map[] = ['status','=',$status];
  413. // 查询
  414. $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']);
  415. // 订单产品
  416. $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();
  417. // 循环处理
  418. foreach ($Paginator as $key => $order) {
  419. // 商品列表
  420. $itemList = [];
  421. // 返回结果
  422. foreach ($productList as $item) {
  423. // 产品图路径
  424. $item['product_thumb'] = path_compat($item['product_thumb']);
  425. // 如果是订单的
  426. if( $item['order_id'] == $order['id'] ) $itemList[] = $item;
  427. }
  428. // 获取子列表
  429. $order['state'] = (string) $Model->getState($order['status'],'state');
  430. // 获取子列表
  431. $order['business_name'] = (string) ($order['business_id'] ? $Business->getOne($order['business_id'],'name') : ($order['weizan_orderid'] ? '微赞订单' : ''));
  432. // 获取子列表
  433. $order['contents_class']= 0;
  434. // 获取子列表
  435. $order['product_list'] = $itemList;
  436. // 重组
  437. $Paginator[$key] = $order;
  438. }
  439. // 获取数据
  440. $data['total'] = $Paginator->total();
  441. $data['current_page'] = $Paginator->currentPage();
  442. $data['per_page'] = $Paginator->perPage();
  443. $data['last_page'] = $Paginator->lastPage();
  444. $data['data'] = $Paginator->items();
  445. // 返回结果
  446. return json_send(['code'=>'success','msg'=>'获取成功','data'=>$data]);
  447. }
  448. /**
  449. * 自动发放优惠券
  450. *
  451. */
  452. private function autoCoupon($uid){
  453. // 模型实例
  454. $Rule = new \App\Models\CouponRewardRule();
  455. // 获取配置列表
  456. $ruleList = $Rule->getList();
  457. // 如果没有信息的话
  458. if( !$ruleList ) return ['success'=>'暂无活动'];
  459. // 其他实例
  460. $RuleProduct = new \App\Models\CouponRewardProduct();
  461. $OrdersProduct = new \App\Models\OrdersProduct();
  462. $Custom = new \App\Models\Custom();
  463. $Coupon = new \App\Models\Coupon();
  464. $CustomCoupon = new \App\Models\CustomCoupon();
  465. // 获取客户城市ID
  466. $customCityId = (int) $Custom->getValue($uid,'city_id');
  467. // 循环配置列表
  468. foreach ( $ruleList as $value ) {
  469. // 如果存在城市范围,并且不在城市范围,不参与这个活动
  470. if( $value['city_ids'] && !in_array($customCityId,explode(',',$value['city_ids'])) ) continue;
  471. // 未到开始时间
  472. if( $value['start_time'] > time() ) continue;
  473. // 通过配置ID获取对应的商品范围
  474. $productList = $RuleProduct->getListByRule($value['id']);
  475. // 如果不存在产品范围,跳过
  476. if( !$productList ) continue;
  477. // 获取客户 规定时段内订单的商品ID以及购买数量
  478. $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();
  479. // 如果没有订单总数
  480. if( !$orderList ) continue;
  481. // 计算商品总量
  482. $total = 0;
  483. // 循环商品范围
  484. foreach ($productList as $scope) {
  485. // 循环订单产品
  486. foreach ($orderList as $order) {
  487. // 如果产品不相等
  488. if( $scope['product_id'] != $order['product_id'] ) continue;
  489. // 相等的计算总量
  490. $total += $scope['product_units'] * $order['buy_num'];
  491. }
  492. }
  493. // 判断总数是不是达标
  494. if( $total < $value['std_num'] ) continue;
  495. if ($value['coupon_id']){
  496. $couponIdArray = explode(',',$value['coupon_id']);
  497. foreach ($couponIdArray as $couponId) {
  498. // 达标的是否已经发送过优惠券
  499. $havaCoupon = $CustomCoupon->query()->where([['custom_uid','=',$uid],['coupon_id','=',$couponId]])->first(['status']);
  500. // 已经发过优惠券的,不发
  501. if( $havaCoupon ) continue;
  502. // 获取优惠券的可用时间
  503. $expTime = $Coupon->query()->where([['id','=',$couponId]])->value('exp_time');
  504. // 时间转时间
  505. $expTime = $Coupon->getExpTime($expTime);
  506. // 发送优惠券
  507. $CustomCoupon->add(['coupon_id'=>$couponId,'custom_uid'=>$uid,'exp_time'=>$expTime]);
  508. }
  509. }
  510. }
  511. // 返回成功
  512. return ['success'=>'操作成功'];
  513. }
  514. /**
  515. * 取消 /api/orders/cancel
  516. *
  517. * */
  518. public function cancel( Request $request, Model $Model,OrdersProduct $OrdersProduct,CustomScore $CustomScore){
  519. // 验证参数
  520. $request->scene('cancel')->validate();
  521. // 检查登录
  522. $uid = $this->checkLogin();
  523. // 接收参数
  524. $id = request('id',0);
  525. $status = 4;
  526. // 获取产品和数量
  527. $oldData = $Model->query()->where([['id','=',$id],['custom_uid','=',$uid]])->first(['id','order_score','status','custom_uid','insert_time']);
  528. // 如果用户不存在
  529. if( !$oldData ) return json_send(['code'=>'error','msg'=>'订单不存在']);
  530. // 如果已经取消
  531. if( $oldData['status'] == 4 ) return json_send(['code'=>'error','msg'=>'订单已取消']);
  532. // 组合数据,写入订单表,子表
  533. DB::beginTransaction();
  534. try{
  535. // 查询数据
  536. $result = $Model->setOrderStatus($id,$status,$OrdersProduct);
  537. // 提示新增失败
  538. if( isset($result['error']) ) {
  539. // 回退数据
  540. DB::rollBack();
  541. // 提示信息
  542. return json_send(['code'=>'error','msg'=>$result['error'],'data'=>['error'=>$result['error']]]);
  543. }
  544. if( $status == 4 ){
  545. // 取消积分
  546. if( $oldData['order_score'] > 0 ) {
  547. // 如果扣减失败
  548. $result = $CustomScore->trade($oldData['custom_uid'],$oldData['id'],($oldData['order_score']*-1),6,1);
  549. // 提示新增失败
  550. if( isset($result['error']) ) {
  551. // 回退数据
  552. DB::rollBack();
  553. // 提示信息
  554. return json_send(['code'=>'error','msg'=>'取消赠送积分失败','data'=>['error'=>$result['error']]]);
  555. }
  556. }
  557. // 取消关联订单
  558. $result = $Model->cancelRelate($oldData['insert_time'],$oldData['custom_uid'],$OrdersProduct,$CustomScore);
  559. // 提示新增失败
  560. if( isset($result['error']) ) {
  561. // 回退数据
  562. DB::rollBack();
  563. // 提示信息
  564. return json_send(['code'=>'error','msg'=>'取消关联订单失败','data'=>['error'=>$result['error']]]);
  565. }
  566. }
  567. // 提交数据
  568. DB::commit();
  569. // 告知结果
  570. return json_send(['code'=>'success','msg'=>'取消成功']);
  571. // 返回结果
  572. } catch (\Throwable $th) {
  573. // 回退数据
  574. DB::rollBack();
  575. // 下单失败提示
  576. return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>$th->getMessage().$th->getLine()]]);
  577. }
  578. }
  579. /**
  580. * 获取订单子数据 /api/orders/get_item
  581. *
  582. * @param string $name 产品名称
  583. * @param int $page 页码,默认1
  584. * @param int $limit 每页条数,默认10条
  585. *
  586. * */
  587. public function get_item(Request $request, Model $Model, OrdersProduct $OrdersProduct, Business $Business){
  588. // 接口验签
  589. // $this->verify_sign();
  590. // 验证参数
  591. $request->scene('get_item')->validate();
  592. // 检查登录
  593. $uid = $this->checkLogin();
  594. // 接收参数
  595. $id = request('id',0);
  596. // 查询
  597. $orderInfo = $Model->query()->where([['id','=',$id],['custom_uid','=',$uid]])->first(['id','pay_total','status','price_total','coupon_total','business_id','pay_total','weizan_orderid','insert_time']);
  598. // 如果用户不存在
  599. if( !$orderInfo ) return json_send(['code'=>'error','msg'=>'订单不存在']);
  600. // 转数组
  601. $orderInfo = $orderInfo->toArray();
  602. // 订单产品
  603. $orderInfo['product_list'] = $OrdersProduct->query()->where([['order_id','=',$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();
  604. // 循环处理
  605. foreach ($orderInfo['product_list'] as $key => $item) {
  606. // 产品图路径
  607. $item['product_thumb'] = path_compat($item['product_thumb']);
  608. // 重组
  609. $orderInfo['product_list'][$key] = $item;
  610. }
  611. // 获取子列表
  612. $orderInfo['state'] = (string) $Model->getState($orderInfo['status'],'state');
  613. // 获取子列表
  614. $orderInfo['business_name'] = (string) ($orderInfo['business_id'] ? $Business->getOne($orderInfo['business_id'],'name') : ($orderInfo['weizan_orderid'] ? '微赞订单' : ''));
  615. // 返回结果
  616. return json_send(['code'=>'success','msg'=>'获取成功','data'=>$orderInfo]);
  617. }
  618. /**
  619. * 创建拼团订单 /api/orders/create_regiment
  620. *
  621. * */
  622. public function create_regiment(Request $request,Custom $Custom,City $City,Model $Model,WeiBanTags $WeiBanTags,OrdersAddr $OrdersAddr,OrdersProduct $OrdersProduct,Product $Product,CustomAddr $CustomAddr,CustomScore $CustomScore){
  623. // 接口验签
  624. // $this->verify_sign();
  625. // 验证参数
  626. $request->scene('create')->validate();
  627. // 检查登录
  628. $uid = $this->checkLogin();
  629. // 接收参数
  630. $isCart = request('is_cart',0);
  631. $productList = request('product_list','[]');
  632. $customCouponId = request('custom_coupon_id',0);
  633. $addrId = request('addr_id',0);
  634. $regimentId = request('regiment_id',0);
  635. $regimentActiveId = request('regiment_active_id',0);
  636. $btnType = request('btn_type',0);
  637. // 如果不存在数据
  638. if( !$addrId ) return json_send(['code'=>'error','msg'=>'请选择收货地址','data'=>['error'=>'请选择收货地址']]);
  639. // 解码购买信息
  640. $buyList = json_decode($productList,true);
  641. // 如果不存在数据
  642. if( empty($buyList) ) return json_send(['code'=>'error','msg'=>'没有需下单的产品','data'=>['error'=>'产品列表为空']]);
  643. $time = time();
  644. // 选择地址
  645. $addr = $CustomAddr->getOne($addrId);
  646. // 如果不存在数据
  647. if( !$addr ) return json_send(['code'=>'error','msg'=>'地址有误,请核对','data'=>['error'=>'没有找到对应的地址']]);
  648. // 重组数据
  649. $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']];
  650. // 获取客户城市ID
  651. $custom = $Custom->getOne($uid);
  652. // 如果不存在的话
  653. if( !$custom ) return json_send(['code'=>'no_login','msg'=>'用户不存在,请重新登录','data'=>['error'=>'用户不存在,请重新登录']]);
  654. // 如果不存在的话
  655. if( !$custom['city_id'] ) return json_send(['code'=>'error','msg'=>'请选择所在城市后下单','data'=>['error'=>'请选择所在城市后下单']]);
  656. // 获取城市ID
  657. $cityId = $custom['city_id'];
  658. $cityName = $City->getOne($cityId,'name');
  659. $pid = $City->getOne($cityId,'pid');
  660. $province = $City->getOne($pid,'name');
  661. // 如果不是海南,
  662. if( $province != '海南省' ) {
  663. // 判断选择的城市名称是不是一致
  664. if( $cityName != $addr['contact_city'] ) return json_send(['code'=>'error','msg'=>'收货地址请选择'.$province.'/'.$cityName,'data'=>['error'=>'收货地址需与您所选城市一致']]);
  665. }else{
  666. if( trim($addr['contact_province']) != trim($province) ) return json_send(['code'=>'error','msg'=>'收货地址请选择海南范围','data'=>['error'=>'收货地址需与您所选城市一致']]);
  667. }
  668. //获取团活动信息
  669. $regimentActiveInfo = RegimentActive::query()
  670. ->where([['id','=',$regimentActiveId],['status','=',1],['start_time','<=',$time],['end_time','>=',$time]])
  671. ->first();
  672. if (!$regimentActiveInfo) return json_send(['code'=>'error','msg'=>'拼团活动不存在','data'=>['error'=>'拼团活动不存在']]);
  673. //是否符合开团条件
  674. if($btnType == 3){
  675. if ($regimentActiveInfo['open_people'] == 1){
  676. if ($custom['insert_time'] > $regimentActiveInfo['start_time']) return json_send(['code'=>'error','msg'=>'此活动只允许老用户开团','data'=>['error'=>'此活动只允许老用户开团']]);
  677. }
  678. if ($regimentActiveInfo['open_people'] == 2){
  679. if ($custom['insert_time'] < $regimentActiveInfo['start_time']) return json_send(['code'=>'error','msg'=>'此活动只允许新用户开团','data'=>['error'=>'此活动只允许新用户开团']]);
  680. }
  681. }
  682. //是否符合参团条件
  683. if($btnType == 4){
  684. if ($regimentActiveInfo['partake_people'] == 1){
  685. if ($custom['insert_time'] > $regimentActiveInfo['start_time']) return json_send(['code'=>'error','msg'=>'此活动只允许老用户参与','data'=>['error'=>'此活动只允许老用户开团']]);
  686. }
  687. if ($regimentActiveInfo['partake_people'] == 2){
  688. if ($custom['insert_time'] < $regimentActiveInfo['start_time']) return json_send(['code'=>'error','msg'=>'此活动只允许新用户参与','data'=>['error'=>'此活动只允许新用户开团']]);
  689. }
  690. //查询团信息
  691. $regimentInfo = Regiment::query()
  692. ->where([['id','=',$regimentId],['status','=',0],['start_time','<=',$time],['end_time','>=',$time]])
  693. ->first();
  694. if (!$regimentInfo) return json_send(['code'=>'error','msg'=>'拼团活动不存在','data'=>['error'=>'拼团活动不存在']]);
  695. $regimentRecordres = RegimentRecord::query()
  696. ->where([['custom_uid','=',$uid],['regiment_id','=',$regimentId]])
  697. ->first();
  698. if ($regimentRecordres) return json_send(['code'=>'error','msg'=>'您已参与此拼团','data'=>['error'=>'您已参与此拼团']]);
  699. }
  700. //查询用户参团记录
  701. $regimentRecordCount = RegimentRecord::query()
  702. ->where([['custom_uid','=',$uid],['active_id','=',$regimentActiveInfo['id']]])
  703. ->count('id');
  704. if ($regimentRecordCount >= $regimentActiveInfo['participation_number']) return json_send(['code'=>'error','msg'=>'该活动每人仅限参与'.$regimentActiveInfo['participation_number'].'次','data'=>['error'=>'该活动每人仅限参与'.$regimentActiveInfo['participation_number'].'次']]);
  705. $tags = $WeiBanTags->getListByWeibanExtid($custom['weiban_extid']);
  706. // 查询产品信息
  707. $productList = $Product->getListByIds(array_column($buyList,'product_id'));
  708. // 当前时间
  709. $time = time();
  710. // 产品以店铺分组,方便写入订单
  711. $orderProduct = [];
  712. // 产品价格同级,用于优惠券计算
  713. $productPrice = [];
  714. $priceTotal = 0;
  715. $payTotal = 0;
  716. $buyInfo = $buyList[0];
  717. if ($buyInfo){
  718. if( empty($productList[$buyInfo['product_id']]) ) return json_send(['code'=>'error','msg'=>'产品不存在或已下架','data'=>['error'=>'产品不存在或已下架=>'.$buyInfo['product_id']]]);
  719. // 获取产信息
  720. $productInfo = $productList[$buyInfo['product_id']];
  721. // 判断是不是可以参与
  722. if( $productInfo['tag_scope'] ) {
  723. // 解析数组
  724. $productInfo['tag_scope'] = explode(',',$productInfo['tag_scope']);
  725. // 标签范围限定时,默认不能参与
  726. $allowJoin = 0;
  727. // 判断标签是不是存在
  728. foreach ($tags as $value) {
  729. // 标签范围内,允许参加
  730. if( in_array($value['name'],$productInfo['tag_scope']) ) $allowJoin = 1;
  731. }
  732. // 如果不能参与
  733. if( !$allowJoin ) return json_send(['code'=>'error','msg'=>'不在 '.$productInfo['product_name'].' 参与范围','data'=>['error'=>'不在标签范围内']]);
  734. }
  735. // 判断是不是可以参与
  736. if( $productInfo['tag_exclude'] ) {
  737. // 解析数组
  738. $productInfo['tag_exclude'] = explode(',',$productInfo['tag_exclude']);
  739. // 判断标签是不是存在
  740. foreach ($tags as $value) {
  741. // 标签排除范围内,不允许参加
  742. if( in_array($value['name'],$productInfo['tag_exclude']) ) return json_send(['code'=>'error','msg'=>'不在 '.$productInfo['product_name'].' 可参与范围','data'=>['error'=>'用户在标签排除范围']]);
  743. }
  744. }
  745. //拼团活动限购
  746. if ($regimentActiveInfo['quota']){
  747. if ($buyInfo['buy_num'] > $regimentActiveInfo['quota']) return json_send(['code'=>'error','msg'=>'超过拼团限购','data'=>['error'=>'拼团限购=>'.$buyInfo['product_id']]]);
  748. }
  749. // 如果产品限购
  750. if( $productInfo['quota'] ) {
  751. // 是否在限购时间,当前时间大于开始时间,并且小于结束时间
  752. if( $productInfo['quota_start'] <= $time && $time <= $productInfo['quota_end'] ){
  753. // 通过时间查询商品的购买总数
  754. $total = $OrdersProduct->query()->where([['custom_uid','=',$uid],['product_id','=',$productInfo['id']],['insert_time','>=',$productInfo['quota_start']],['insert_time','<=',$productInfo['quota_end']]])->sum('buy_num');
  755. // 判断限购数量
  756. $total = $buyInfo['buy_num'] + $total;
  757. // 如果超过数量
  758. if( $total > $productInfo['quota'] ) return json_send(['code'=>'error','msg'=>'限购'.$productInfo['quota'].'单-'.$productInfo['product_name'],'data'=>['error'=>'已超限=>'.($total - $productInfo['quota'])]]);
  759. }
  760. }
  761. // 需要扣除的库存
  762. $productList[$buyInfo['product_id']]['decr'] = $buyInfo['buy_num'];
  763. // 判断库存
  764. if( $productInfo['stock'] < $productList[$buyInfo['product_id']]['decr'] ) return json_send(['code'=>'error','msg'=>$productInfo['product_name'].'-库存不足','data'=>['error'=>'产品库存不足=>'.$buyInfo['product_id']]]);
  765. // 计算价值
  766. $priceTotal = $buyInfo['buy_num'] * $productInfo['price'];
  767. $payTotal = $buyInfo['buy_num'] * $regimentActiveInfo['regiment_price'];
  768. }
  769. $orderInfo = [
  770. 'custom_uid' => $uid,
  771. 'status' => 10,
  772. 'insert_time' => $time,
  773. 'update_time' => $time,
  774. 'pay_total' => $payTotal,
  775. 'price_total' => $priceTotal,
  776. 'business_id' => $productList[$buyInfo['product_id']]['business_id'],
  777. ];
  778. // 赠送积分
  779. $orderInfo['order_score'] = (config('order_score_send',0) && floor( $orderInfo['pay_total'] * 1 ) > 0 ) ? floor( $orderInfo['pay_total'] * 1 ) : 0;
  780. $orderProductInfo = [
  781. 'product_name' => $productList[$buyInfo['product_id']]['product_name'],
  782. 'sku_attr_names' => $productList[$buyInfo['product_id']]['sku_attr_names'],
  783. 'product_thumb' => $productList[$buyInfo['product_id']]['product_thumb'],
  784. 'buy_num' => $buyInfo['buy_num'],
  785. 'price_total' => $priceTotal,
  786. 'pay_total' => $buyInfo['buy_num'] * $productList[$buyInfo['product_id']]['price'],
  787. 'product_id' => $buyInfo['product_id'],
  788. 'custom_uid' => $uid,
  789. 'business_id' => $productList[$buyInfo['product_id']]['business_id'],
  790. 'insert_time' => $time,
  791. 'update_time' => $time,
  792. 'status' => 10,
  793. ];
  794. // 组合数据,写入订单表,子表
  795. DB::beginTransaction();
  796. // 写入数据
  797. try {
  798. // 扣减商品库存
  799. foreach ($productList as $key => $value) {
  800. // 扣减库存
  801. $result = $Product->edit($value['id'],['stock'=>DB::raw('stock+-'.$value['decr'])]);
  802. // 判断结果
  803. if( !$result ) {
  804. // 回退数据
  805. DB::rollBack();
  806. // 错误提示
  807. return json_send(['code'=>'error','msg'=>'库存扣减失败','data'=>['error'=>'库存扣减失败']]);
  808. }
  809. }
  810. //创建拼团
  811. if($btnType == 3){
  812. $regimentInfo = [
  813. 'custom_uid' => $uid,
  814. 'active_id' => $regimentActiveInfo['id'],
  815. 'product_id' => $buyInfo['product_id'],
  816. 'people_number' => 1,
  817. 'status' => 0,
  818. 'start_time' => $time,
  819. 'end_time' => $time + $regimentActiveInfo['expiration']*3600,
  820. 'update_time' => $time,
  821. 'insert_time' => $time,
  822. ];
  823. $regimentId = Regiment::query()->insertGetId($regimentInfo);
  824. if( !$regimentId ) {
  825. // 回退数据
  826. DB::rollBack();
  827. // 提示信息
  828. return json_send(['code'=>'error','msg'=>'创建拼团失败','data'=>['error'=>'创建拼团失败']]);
  829. }
  830. }
  831. $orderInfo['regiment_id'] = $regimentId;
  832. // 创建总订单
  833. $orderId = $Model->add($orderInfo);
  834. // 如果订单写入失败
  835. if( !$orderId ) {
  836. // 回退数据
  837. DB::rollBack();
  838. // 错误提示
  839. return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'订单创建失败']]);
  840. }
  841. $orderProductInfo['order_id'] = $orderId;
  842. // 写入子表
  843. $result = $OrdersProduct->query()->insert($orderProductInfo);
  844. // 如果扣减失败
  845. if( !$result ) {
  846. // 回退数据
  847. DB::rollBack();
  848. // 提示信息
  849. return json_send(['code'=>'error','msg'=>'子订单创建失败','data'=>['error'=>'子订单创建失败']]);
  850. }
  851. // 写入订单地址表
  852. $addr['order_id'] = $orderId;
  853. // 写入订单地址表
  854. $result = $OrdersAddr->add($addr);
  855. // 地址写入失败
  856. if( !$result ) {
  857. // 回退数据
  858. DB::rollBack();
  859. // 提示信息
  860. return json_send(['code'=>'error','msg'=>'地址写入失败','data'=>['error'=>'地址写入失败']]);
  861. }
  862. if($btnType == 4){
  863. // 拼团人数加1
  864. $inc = Regiment::query()->where('id','=',$regimentId)->increment('people_number',1);
  865. if( !$inc ) {
  866. // 回退数据
  867. DB::rollBack();
  868. // 提示信息
  869. return json_send(['code'=>'error','msg'=>'创建拼团失败','data'=>['error'=>'创建拼团失败']]);
  870. }
  871. //团满
  872. if ((($regimentInfo['people_number'] + 1) == $regimentActiveInfo['number']) && $regimentActiveInfo['exceed_people'] == 1) {
  873. $res = regiment::query()->where('id','=',$regimentId)->update(['status'=>3]);
  874. if( !$res ) {
  875. // 回退数据
  876. DB::rollBack();
  877. // 提示信息
  878. return json_send(['code'=>'error','msg'=>'创建拼团失败','data'=>['error'=>'创建拼团失败']]);
  879. }
  880. //修改订单
  881. $orderRes = $Model::query()->where('regiment_id','=',$regimentId)->update(['status'=>'1']);
  882. if( !$orderRes ) {
  883. // 回退数据
  884. DB::rollBack();
  885. // 提示信息
  886. return json_send(['code'=>'error','msg'=>'创建拼团失败','data'=>['error'=>'创建拼团失败']]);
  887. }
  888. //赠送积分
  889. $orderList = $Model::query()->where('regiment_id','=',$regimentId)->get();
  890. foreach ($orderList as $key => $value) {
  891. if( $value['order_score'] > 0 ) $CustomScore->trade($orderInfo['custom_uid'],$value['id'],$value['order_score'],5,1);
  892. }
  893. }
  894. }
  895. //拼团记录
  896. $regimentRecordInfo = [
  897. 'custom_uid' => $uid,
  898. 'regiment_id' => $regimentId,
  899. 'active_id' => $regimentActiveInfo['id'],
  900. 'product_id' => $buyInfo['product_id'],
  901. 'order_id' => $orderId,
  902. 'update_time' => $time,
  903. 'insert_time' => $time,
  904. ];
  905. $result = RegimentRecord::query()->insert($regimentRecordInfo);
  906. if( !$result ) {
  907. // 回退数据
  908. DB::rollBack();
  909. // 提示信息
  910. return json_send(['code'=>'error','msg'=>'创建拼团记录失败','data'=>['error'=>'创建拼团记录失败']]);
  911. }
  912. // 提交数据
  913. DB::commit();
  914. // 返回结果
  915. return json_send(['code'=>'success','msg'=>'下单成功','data'=>['id'=>null]]);
  916. // 返回结果
  917. } catch (\Throwable $th) {
  918. // 回退数据
  919. DB::rollBack();
  920. // 判断结果,如果库存扣减失败的话
  921. if( stripos($th->getMessage(),'UNSIGNED') ) return json_send(['code'=>'error','msg'=>'库存不足','data'=>['error'=>'产品库存扣减失败']]);
  922. // 下单失败提示
  923. return json_send(['code'=>'error','msg'=>'系统异常,请稍后再试','data'=>['error'=>$th->getMessage().$th->getLine()]]);
  924. }
  925. }
  926. /**
  927. * 取消拼团 /api/orders/cancel_regiment
  928. *
  929. * */
  930. public function cancel_regiment( Request $request, Model $Model,OrdersProduct $OrdersProduct){
  931. // 验证参数
  932. $request->scene('cancel')->validate();
  933. // 检查登录
  934. $uid = $this->checkLogin();
  935. // 接收参数
  936. $id = request('id',0);
  937. $status = 12;
  938. // 获取产品和数量
  939. $oldData = $Model->query()->where([['id','=',$id],['custom_uid','=',$uid]])->first(['id','order_score','status','custom_uid','insert_time','regiment_id']);
  940. // 如果用户不存在
  941. if( !$oldData ) return json_send(['code'=>'error','msg'=>'订单不存在']);
  942. // 如果已经取消
  943. if( $oldData['status'] == 12 ) return json_send(['code'=>'error','msg'=>'订单已取消']);
  944. // 如果团不存在
  945. if( !$oldData['regiment_id'] ) return json_send(['code'=>'error','msg'=>'拼团不存在']);
  946. //查询团信息
  947. $regimentInfo = Regiment::query()->find($oldData['regiment_id']);
  948. if( !$regimentInfo ) return json_send(['code'=>'error','msg'=>'拼团不存在']);
  949. // 组合数据,写入订单表,子表
  950. DB::beginTransaction();
  951. try{
  952. // 查询数据
  953. $result = $Model->setOrderStatus($id,$status,$OrdersProduct);
  954. // 提示新增失败
  955. if( isset($result['error']) ) {
  956. // 回退数据
  957. DB::rollBack();
  958. // 提示信息
  959. return json_send(['code'=>'error','msg'=>$result['error'],'data'=>['error'=>$result['error']]]);
  960. }
  961. //开团用户取消团订单
  962. if ($regimentInfo['people_number'] > 1 && $regimentInfo['custom_uid'] == $uid){
  963. //查询团记录
  964. $regimentRecordInfo = RegimentRecord::query()->where([['order_id','<>',$oldData['id']],['regiment_id','=',$regimentInfo['id']],['status','=',0]])->first();
  965. if ($regimentRecordInfo){
  966. //将参团成员中的第一个用户变成开团人
  967. $result = Regiment::query()->where('id','=',$regimentRecordInfo['regiment_id'])->update(['custom_uid'=>$regimentRecordInfo['custom_uid']]);
  968. if (!$result) {
  969. DB::rollBack();
  970. return json_send(['code'=>'error','msg'=>'取消拼团,改变开团人失败']);
  971. }
  972. }
  973. //扣减加入团人数
  974. $regimentRes = Regiment::query()->where('id','=',$oldData['regiment_id'])->decrement('people_number',1);
  975. if( !$regimentRes ) {
  976. // 回退数据
  977. DB::rollBack();
  978. // 提示信息
  979. return json_send(['code'=>'error','msg'=>'取消拼团失败']);
  980. }
  981. }else{
  982. $regimentRes = Regiment::query()->where('id','=',$oldData['regiment_id'])->update(['status'=>1]);
  983. if (!$regimentRes){
  984. DB::rollBack();
  985. return json_send(['code'=>'error','msg'=>'取消拼团失败']);
  986. }
  987. }
  988. //修改拼团记录
  989. $regimentRes = RegimentRecord::query()->where([['order_id','=',$oldData['id'],]])->update(['status'=>'1']);
  990. if( !$regimentRes ) {
  991. // 回退数据
  992. DB::rollBack();
  993. // 提示信息
  994. return json_send(['code'=>'error','msg'=>'取消拼团失败']);
  995. }
  996. // 提交数据
  997. DB::commit();
  998. // 告知结果
  999. return json_send(['code'=>'success','msg'=>'取消成功']);
  1000. // 返回结果
  1001. } catch (\Throwable $th) {
  1002. // 回退数据
  1003. DB::rollBack();
  1004. // 下单失败提示
  1005. return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>$th->getMessage().$th->getLine()]]);
  1006. }
  1007. }
  1008. /**
  1009. * 订单详情
  1010. *
  1011. * @pamam int $id 订单ID
  1012. *
  1013. * */
  1014. public function get_detail( Request $request, Model $Model,OrdersProduct $OrdersProduct,Business $Business,OrdersAddr $OrdersAddr){
  1015. // 验证参数
  1016. $request->scene('get_detail')->validate();
  1017. // 接受参数
  1018. $id = request('id',0);
  1019. // 查询数据
  1020. $order = $Model->query()->find($id,['id','pay_total','status','price_total','coupon_total','business_id','pay_total','weizan_orderid','insert_time']);
  1021. // 查询不到订单
  1022. if( !$order ) return json_send(['code'=>'error','msg'=>'订单不存在']);
  1023. // 数据转换
  1024. $order = $order->toArray();
  1025. // id转编号
  1026. $order['insert_time'] = date('Y-m-d H:i:s',$order['insert_time']);
  1027. $order['business_name'] = (string) $Business->getOne($order['business_id'],'name');
  1028. $order['order_code'] = $Model->idToCode($order['id']);
  1029. $order['state'] = $Model->getState($order['status'],'state');
  1030. // 查询子订单数据
  1031. $order['order_items'] = $OrdersProduct->query()->where([['order_id','=',$id]])->select(['id as item_id','order_id','product_id','buy_num','pay_total','is_rebate','sku_attr_names as product_spec','product_name','product_thumb'])->get()->toArray();
  1032. // 处理缩略图
  1033. foreach ($order['order_items'] as $key => $value) {
  1034. $order['order_items'][$key]['product_thumb'] = $value['product_thumb'] ? path_compat($value['product_thumb']) : '';
  1035. }
  1036. // 地址
  1037. $order['order_addr'] = $OrdersAddr->query()->where([['order_id','=',$id]])->first(['contact_name','contact_phone','contact_province','contact_city','contact_area','contact_addr','contact_shop']);
  1038. // 加载模板
  1039. return json_send(['code'=>'success','msg'=>'获取成功','data'=>$order]);
  1040. }
  1041. }