Orders.php 48 KB

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