Orders.php 52 KB

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