Orders.php 48 KB

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