Orders.php 50 KB

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