Orders.php 55 KB

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