Orders.php 47 KB

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