Orders.php 48 KB

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