Orders.php 50 KB

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