Orders.php 48 KB

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