Orders.php 50 KB

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