Orders.php 55 KB

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