Orders.php 53 KB

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