Orders.php 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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. if ($value['coupon_id']){
  472. $couponIdArray = explode(',',$value['coupon_id']);
  473. foreach ($couponIdArray as $couponId) {
  474. // 达标的是否已经发送过优惠券
  475. $havaCoupon = $CustomCoupon->query()->where([['custom_uid','=',$uid],['coupon_id','=',$couponId]])->first(['status']);
  476. // 已经发过优惠券的,不发
  477. if( $havaCoupon ) continue;
  478. // 获取优惠券的可用时间
  479. $expTime = $Coupon->query()->where([['id','=',$couponId]])->value('exp_time');
  480. // 时间转时间
  481. $expTime = $Coupon->getExpTime($expTime);
  482. // 发送优惠券
  483. $CustomCoupon->add(['coupon_id'=>$couponId,'custom_uid'=>$uid,'exp_time'=>$expTime]);
  484. }
  485. }
  486. }
  487. // 返回成功
  488. return ['success'=>'操作成功'];
  489. }
  490. /**
  491. * 取消 /api/orders/cancel
  492. *
  493. * */
  494. public function cancel( Request $request, Model $Model,OrdersProduct $OrdersProduct,CustomScore $CustomScore){
  495. // 验证参数
  496. $request->scene('cancel')->validate();
  497. // 检查登录
  498. $uid = $this->checkLogin();
  499. // 接收参数
  500. $id = request('id',0);
  501. $status = 4;
  502. // 获取产品和数量
  503. $oldData = $Model->query()->where([['id','=',$id],['custom_uid','=',$uid]])->first(['id','order_score','status','custom_uid','insert_time']);
  504. // 如果用户不存在
  505. if( !$oldData ) return json_send(['code'=>'error','msg'=>'订单不存在']);
  506. // 如果已经取消
  507. if( $oldData['status'] == 4 ) return json_send(['code'=>'error','msg'=>'订单已取消']);
  508. // 组合数据,写入订单表,子表
  509. DB::beginTransaction();
  510. try{
  511. // 查询数据
  512. $result = $Model->setOrderStatus($id,$status,$OrdersProduct);
  513. // 提示新增失败
  514. if( isset($result['error']) ) {
  515. // 回退数据
  516. DB::rollBack();
  517. // 提示信息
  518. return json_send(['code'=>'error','msg'=>$result['error'],'data'=>['error'=>$result['error']]]);
  519. }
  520. if( $status == 4 ){
  521. // 取消积分
  522. if( $oldData['order_score'] > 0 ) {
  523. // 如果扣减失败
  524. $result = $CustomScore->trade($oldData['custom_uid'],$oldData['id'],($oldData['order_score']*-1),6,1);
  525. // 提示新增失败
  526. if( isset($result['error']) ) {
  527. // 回退数据
  528. DB::rollBack();
  529. // 提示信息
  530. return json_send(['code'=>'error','msg'=>'取消赠送积分失败','data'=>['error'=>$result['error']]]);
  531. }
  532. }
  533. // 取消关联订单
  534. $result = $Model->cancelRelate($oldData['insert_time'],$oldData['custom_uid'],$OrdersProduct,$CustomScore);
  535. // 提示新增失败
  536. if( isset($result['error']) ) {
  537. // 回退数据
  538. DB::rollBack();
  539. // 提示信息
  540. return json_send(['code'=>'error','msg'=>'取消关联订单失败','data'=>['error'=>$result['error']]]);
  541. }
  542. }
  543. // 提交数据
  544. DB::commit();
  545. // 告知结果
  546. return json_send(['code'=>'success','msg'=>'取消成功']);
  547. // 返回结果
  548. } catch (\Throwable $th) {
  549. // 回退数据
  550. DB::rollBack();
  551. // 下单失败提示
  552. return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>$th->getMessage().$th->getLine()]]);
  553. }
  554. }
  555. /**
  556. * 获取订单子数据 /api/orders/get_item
  557. *
  558. * @param string $name 产品名称
  559. * @param int $page 页码,默认1
  560. * @param int $limit 每页条数,默认10条
  561. *
  562. * */
  563. public function get_item(Request $request, Model $Model, OrdersProduct $OrdersProduct, Business $Business){
  564. // 接口验签
  565. // $this->verify_sign();
  566. // 验证参数
  567. $request->scene('get_item')->validate();
  568. // 检查登录
  569. $uid = $this->checkLogin();
  570. // 接收参数
  571. $id = request('id',0);
  572. // 查询
  573. $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']);
  574. // 如果用户不存在
  575. if( !$orderInfo ) return json_send(['code'=>'error','msg'=>'订单不存在']);
  576. // 转数组
  577. $orderInfo = $orderInfo->toArray();
  578. // 订单产品
  579. $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();
  580. // 循环处理
  581. foreach ($orderInfo['product_list'] as $key => $item) {
  582. // 产品图路径
  583. $item['product_thumb'] = path_compat($item['product_thumb']);
  584. // 重组
  585. $orderInfo['product_list'][$key] = $item;
  586. }
  587. // 获取子列表
  588. $orderInfo['state'] = (string) $Model->getState($orderInfo['status'],'state');
  589. // 获取子列表
  590. $orderInfo['business_name'] = (string) ($orderInfo['business_id'] ? $Business->getOne($orderInfo['business_id'],'name') : ($orderInfo['weizan_orderid'] ? '微赞订单' : ''));
  591. // 返回结果
  592. return json_send(['code'=>'success','msg'=>'获取成功','data'=>$orderInfo]);
  593. }
  594. /**
  595. * 创建拼团订单 /api/orders/create_regiment
  596. *
  597. * */
  598. public function create_regiment(Request $request,Custom $Custom,City $City,Model $Model,WeiBanTags $WeiBanTags,OrdersAddr $OrdersAddr,OrdersProduct $OrdersProduct,Product $Product,CustomAddr $CustomAddr,CustomScore $CustomScore){
  599. // 接口验签
  600. // $this->verify_sign();
  601. // 验证参数
  602. $request->scene('create')->validate();
  603. // 检查登录
  604. $uid = $this->checkLogin();
  605. // 接收参数
  606. $isCart = request('is_cart',0);
  607. $productList = request('product_list','[]');
  608. $customCouponId = request('custom_coupon_id',0);
  609. $addrId = request('addr_id',0);
  610. $regimentId = request('regiment_id',0);
  611. $regimentActiveId = request('regiment_active_id',0);
  612. $btnType = request('btn_type',0);
  613. // 如果不存在数据
  614. if( !$addrId ) return json_send(['code'=>'error','msg'=>'请选择收货地址','data'=>['error'=>'请选择收货地址']]);
  615. // 解码购买信息
  616. $buyList = json_decode($productList,true);
  617. // 如果不存在数据
  618. if( empty($buyList) ) return json_send(['code'=>'error','msg'=>'没有需下单的产品','data'=>['error'=>'产品列表为空']]);
  619. $time = time();
  620. // 选择地址
  621. $addr = $CustomAddr->getOne($addrId);
  622. // 如果不存在数据
  623. if( !$addr ) return json_send(['code'=>'error','msg'=>'地址有误,请核对','data'=>['error'=>'没有找到对应的地址']]);
  624. // 重组数据
  625. $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']];
  626. // 获取客户城市ID
  627. $custom = $Custom->getOne($uid);
  628. // 如果不存在的话
  629. if( !$custom ) return json_send(['code'=>'no_login','msg'=>'用户不存在,请重新登录','data'=>['error'=>'用户不存在,请重新登录']]);
  630. // 如果不存在的话
  631. if( !$custom['city_id'] ) return json_send(['code'=>'error','msg'=>'请选择所在城市后下单','data'=>['error'=>'请选择所在城市后下单']]);
  632. // 获取城市ID
  633. $cityId = $custom['city_id'];
  634. $cityName = $City->getOne($cityId,'name');
  635. $pid = $City->getOne($cityId,'pid');
  636. $province = $City->getOne($pid,'name');
  637. // 判断选择的城市名称是不是一致
  638. if( $cityName != $addr['contact_city'] ) return json_send(['code'=>'error','msg'=>'收货地址请选择'.$province.'/'.$cityName,'data'=>['error'=>'收货地址需与您所选城市一致']]);
  639. //获取团活动信息
  640. $regimentActiveInfo = RegimentActive::query()
  641. ->where([['id','=',$regimentActiveId],['status','=',1],['start_time','<=',$time],['end_time','>=',$time]])
  642. ->first();
  643. if (!$regimentActiveInfo) return json_send(['code'=>'error','msg'=>'拼团活动不存在','data'=>['error'=>'拼团活动不存在']]);
  644. //是否符合开团条件
  645. if($btnType == 3){
  646. if ($regimentActiveInfo['open_people'] == 1){
  647. if ($custom['insert_time'] > $regimentActiveInfo['start_time']) return json_send(['code'=>'error','msg'=>'此活动只允许老用户开团','data'=>['error'=>'此活动只允许老用户开团']]);
  648. }
  649. if ($regimentActiveInfo['open_people'] == 2){
  650. if ($custom['insert_time'] < $regimentActiveInfo['start_time']) return json_send(['code'=>'error','msg'=>'此活动只允许新用户开团','data'=>['error'=>'此活动只允许新用户开团']]);
  651. }
  652. }
  653. //是否符合参团条件
  654. if($btnType == 4){
  655. if ($regimentActiveInfo['partake_people'] == 1){
  656. if ($custom['insert_time'] > $regimentActiveInfo['start_time']) return json_send(['code'=>'error','msg'=>'此活动只允许老用户参与','data'=>['error'=>'此活动只允许老用户开团']]);
  657. }
  658. if ($regimentActiveInfo['partake_people'] == 2){
  659. if ($custom['insert_time'] < $regimentActiveInfo['start_time']) return json_send(['code'=>'error','msg'=>'此活动只允许新用户参与','data'=>['error'=>'此活动只允许新用户开团']]);
  660. }
  661. //查询团信息
  662. $regimentInfo = Regiment::query()
  663. ->where([['id','=',$regimentId],['status','=',0],['start_time','<=',$time],['end_time','>=',$time]])
  664. ->first();
  665. if (!$regimentInfo) return json_send(['code'=>'error','msg'=>'拼团活动不存在','data'=>['error'=>'拼团活动不存在']]);
  666. $regimentRecordres = RegimentRecord::query()
  667. ->where([['custom_uid','=',$uid],['regiment_id','=',$regimentId]])
  668. ->first();
  669. if ($regimentRecordres) return json_send(['code'=>'error','msg'=>'您已参与此拼团','data'=>['error'=>'您已参与此拼团']]);
  670. }
  671. //查询用户参团记录
  672. $regimentRecordCount = RegimentRecord::query()
  673. ->where([['custom_uid','=',$uid],['active_id','=',$regimentActiveInfo['id']]])
  674. ->count('id');
  675. if ($regimentRecordCount >= $regimentActiveInfo['participation_number']) return json_send(['code'=>'error','msg'=>'该活动每人仅限参与'.$regimentActiveInfo['participation_number'].'次','data'=>['error'=>'该活动每人仅限参与'.$regimentActiveInfo['participation_number'].'次']]);
  676. $tags = $WeiBanTags->getListByWeibanExtid($custom['weiban_extid']);
  677. // 查询产品信息
  678. $productList = $Product->getListByIds(array_column($buyList,'product_id'));
  679. // 当前时间
  680. $time = time();
  681. // 产品以店铺分组,方便写入订单
  682. $orderProduct = [];
  683. // 产品价格同级,用于优惠券计算
  684. $productPrice = [];
  685. $priceTotal = 0;
  686. $payTotal = 0;
  687. $buyInfo = $buyList[0];
  688. if ($buyInfo){
  689. if( empty($productList[$buyInfo['product_id']]) ) return json_send(['code'=>'error','msg'=>'产品不存在或已下架','data'=>['error'=>'产品不存在或已下架=>'.$buyInfo['product_id']]]);
  690. // 获取产信息
  691. $productInfo = $productList[$buyInfo['product_id']];
  692. // 判断是不是可以参与
  693. if( $productInfo['tag_scope'] ) {
  694. // 解析数组
  695. $productInfo['tag_scope'] = explode(',',$productInfo['tag_scope']);
  696. // 标签范围限定时,默认不能参与
  697. $allowJoin = 0;
  698. // 判断标签是不是存在
  699. foreach ($tags as $value) {
  700. // 标签范围内,允许参加
  701. if( in_array($value['name'],$productInfo['tag_scope']) ) $allowJoin = 1;
  702. }
  703. // 如果不能参与
  704. if( !$allowJoin ) return json_send(['code'=>'error','msg'=>'不在 '.$productInfo['product_name'].' 参与范围','data'=>['error'=>'不在标签范围内']]);
  705. }
  706. // 判断是不是可以参与
  707. if( $productInfo['tag_exclude'] ) {
  708. // 解析数组
  709. $productInfo['tag_exclude'] = explode(',',$productInfo['tag_exclude']);
  710. // 判断标签是不是存在
  711. foreach ($tags as $value) {
  712. // 标签排除范围内,不允许参加
  713. if( in_array($value['name'],$productInfo['tag_exclude']) ) return json_send(['code'=>'error','msg'=>'不在 '.$productInfo['product_name'].' 可参与范围','data'=>['error'=>'用户在标签排除范围']]);
  714. }
  715. }
  716. //拼团活动限购
  717. if ($regimentActiveInfo['quota']){
  718. if ($buyInfo['buy_num'] > $regimentActiveInfo['quota']) return json_send(['code'=>'error','msg'=>'超过拼团限购','data'=>['error'=>'拼团限购=>'.$buyInfo['product_id']]]);
  719. }
  720. // 如果产品限购
  721. if( $productInfo['quota'] ) {
  722. // 是否在限购时间,当前时间大于开始时间,并且小于结束时间
  723. if( $productInfo['quota_start'] <= $time && $time <= $productInfo['quota_end'] ){
  724. // 通过时间查询商品的购买总数
  725. $total = $OrdersProduct->query()->where([['custom_uid','=',$uid],['product_id','=',$productInfo['id']],['insert_time','>=',$productInfo['quota_start']],['insert_time','<=',$productInfo['quota_end']]])->sum('buy_num');
  726. // 判断限购数量
  727. $total = $buyInfo['buy_num'] + $total;
  728. // 如果超过数量
  729. if( $total > $productInfo['quota'] ) return json_send(['code'=>'error','msg'=>'限购'.$productInfo['quota'].'单-'.$productInfo['product_name'],'data'=>['error'=>'已超限=>'.($total - $productInfo['quota'])]]);
  730. }
  731. }
  732. // 需要扣除的库存
  733. $productList[$buyInfo['product_id']]['decr'] = $buyInfo['buy_num'];
  734. // 判断库存
  735. if( $productInfo['stock'] < $productList[$buyInfo['product_id']]['decr'] ) return json_send(['code'=>'error','msg'=>$productInfo['product_name'].'-库存不足','data'=>['error'=>'产品库存不足=>'.$buyInfo['product_id']]]);
  736. // 计算价值
  737. $priceTotal = $buyInfo['buy_num'] * $productInfo['price'];
  738. $payTotal = $buyInfo['buy_num'] * $regimentActiveInfo['regiment_price'];
  739. }
  740. $orderInfo = [
  741. 'custom_uid' => $uid,
  742. 'status' => 10,
  743. 'insert_time' => $time,
  744. 'update_time' => $time,
  745. 'pay_total' => $payTotal,
  746. 'price_total' => $priceTotal,
  747. 'business_id' => $productList[$buyInfo['product_id']]['business_id'],
  748. ];
  749. // 赠送积分
  750. $orderInfo['order_score'] = (config('order_score_send',0) && floor( $orderInfo['pay_total'] * 1 ) > 0 ) ? floor( $orderInfo['pay_total'] * 1 ) : 0;
  751. $orderProductInfo = [
  752. 'product_name' => $productList[$buyInfo['product_id']]['product_name'],
  753. 'sku_attr_names' => $productList[$buyInfo['product_id']]['sku_attr_names'],
  754. 'product_thumb' => $productList[$buyInfo['product_id']]['product_thumb'],
  755. 'buy_num' => $buyInfo['buy_num'],
  756. 'price_total' => $priceTotal,
  757. 'pay_total' => $buyInfo['buy_num'] * $productList[$buyInfo['product_id']]['price'],
  758. 'product_id' => $buyInfo['product_id'],
  759. 'custom_uid' => $uid,
  760. 'business_id' => $productList[$buyInfo['product_id']]['business_id'],
  761. 'insert_time' => $time,
  762. 'update_time' => $time,
  763. 'status' => 10,
  764. ];
  765. // 组合数据,写入订单表,子表
  766. DB::beginTransaction();
  767. // 写入数据
  768. try {
  769. // 扣减商品库存
  770. foreach ($productList as $key => $value) {
  771. // 扣减库存
  772. $result = $Product->edit($value['id'],['stock'=>DB::raw('stock+-'.$value['decr'])]);
  773. // 判断结果
  774. if( !$result ) {
  775. // 回退数据
  776. DB::rollBack();
  777. // 错误提示
  778. return json_send(['code'=>'error','msg'=>'库存扣减失败','data'=>['error'=>'库存扣减失败']]);
  779. }
  780. }
  781. //创建拼团
  782. if($btnType == 3){
  783. $regimentInfo = [
  784. 'custom_uid' => $uid,
  785. 'active_id' => $regimentActiveInfo['id'],
  786. 'product_id' => $buyInfo['product_id'],
  787. 'people_number' => 1,
  788. 'status' => 0,
  789. 'start_time' => $time,
  790. 'end_time' => $time + $regimentActiveInfo['expiration']*3600,
  791. 'update_time' => $time,
  792. 'insert_time' => $time,
  793. ];
  794. $regimentId = Regiment::query()->insertGetId($regimentInfo);
  795. if( !$regimentId ) {
  796. // 回退数据
  797. DB::rollBack();
  798. // 提示信息
  799. return json_send(['code'=>'error','msg'=>'创建拼团失败','data'=>['error'=>'创建拼团失败']]);
  800. }
  801. }
  802. $orderInfo['regiment_id'] = $regimentId;
  803. // 创建总订单
  804. $orderId = $Model->add($orderInfo);
  805. // 如果订单写入失败
  806. if( !$orderId ) {
  807. // 回退数据
  808. DB::rollBack();
  809. // 错误提示
  810. return json_send(['code'=>'error','msg'=>'下单失败','data'=>['error'=>'订单创建失败']]);
  811. }
  812. $orderProductInfo['order_id'] = $orderId;
  813. // 写入子表
  814. $result = $OrdersProduct->query()->insert($orderProductInfo);
  815. // 如果扣减失败
  816. if( !$result ) {
  817. // 回退数据
  818. DB::rollBack();
  819. // 提示信息
  820. return json_send(['code'=>'error','msg'=>'子订单创建失败','data'=>['error'=>'子订单创建失败']]);
  821. }
  822. // 写入订单地址表
  823. $addr['order_id'] = $orderId;
  824. // 写入订单地址表
  825. $result = $OrdersAddr->add($addr);
  826. // 地址写入失败
  827. if( !$result ) {
  828. // 回退数据
  829. DB::rollBack();
  830. // 提示信息
  831. return json_send(['code'=>'error','msg'=>'地址写入失败','data'=>['error'=>'地址写入失败']]);
  832. }
  833. if($btnType == 4){
  834. // 拼团人数加1
  835. $inc = Regiment::query()->where('id','=',$regimentId)->increment('people_number',1);
  836. if( !$inc ) {
  837. // 回退数据
  838. DB::rollBack();
  839. // 提示信息
  840. return json_send(['code'=>'error','msg'=>'创建拼团失败','data'=>['error'=>'创建拼团失败']]);
  841. }
  842. //团满
  843. if ((($regimentInfo['people_number'] + 1) == $regimentActiveInfo['number']) && $regimentActiveInfo['exceed_people'] == 1) {
  844. $res = regiment::query()->where('id','=',$regimentId)->update(['status'=>3]);
  845. if( !$res ) {
  846. // 回退数据
  847. DB::rollBack();
  848. // 提示信息
  849. return json_send(['code'=>'error','msg'=>'创建拼团失败','data'=>['error'=>'创建拼团失败']]);
  850. }
  851. //修改订单
  852. $orderRes = $Model::query()->where('regiment_id','=',$regimentId)->update(['status'=>'1']);
  853. if( !$orderRes ) {
  854. // 回退数据
  855. DB::rollBack();
  856. // 提示信息
  857. return json_send(['code'=>'error','msg'=>'创建拼团失败','data'=>['error'=>'创建拼团失败']]);
  858. }
  859. //赠送积分
  860. $orderList = $Model::query()->where('regiment_id','=',$regimentId)->get();
  861. foreach ($orderList as $key => $value) {
  862. if( $value['order_score'] > 0 ) $CustomScore->trade($orderInfo['custom_uid'],$value['id'],$value['order_score'],5,1);
  863. }
  864. }
  865. }
  866. //拼团记录
  867. $regimentRecordInfo = [
  868. 'custom_uid' => $uid,
  869. 'regiment_id' => $regimentId,
  870. 'active_id' => $regimentActiveInfo['id'],
  871. 'product_id' => $buyInfo['product_id'],
  872. 'order_id' => $orderId,
  873. 'update_time' => $time,
  874. 'insert_time' => $time,
  875. ];
  876. $result = RegimentRecord::query()->insert($regimentRecordInfo);
  877. if( !$result ) {
  878. // 回退数据
  879. DB::rollBack();
  880. // 提示信息
  881. return json_send(['code'=>'error','msg'=>'创建拼团记录失败','data'=>['error'=>'创建拼团记录失败']]);
  882. }
  883. // 提交数据
  884. DB::commit();
  885. // 返回结果
  886. return json_send(['code'=>'success','msg'=>'下单成功','data'=>['id'=>null]]);
  887. // 返回结果
  888. } catch (\Throwable $th) {
  889. // 回退数据
  890. DB::rollBack();
  891. // 判断结果,如果库存扣减失败的话
  892. if( stripos($th->getMessage(),'UNSIGNED') ) return json_send(['code'=>'error','msg'=>'库存不足','data'=>['error'=>'产品库存扣减失败']]);
  893. // 下单失败提示
  894. return json_send(['code'=>'error','msg'=>'系统异常,请稍后再试','data'=>['error'=>$th->getMessage().$th->getLine()]]);
  895. }
  896. }
  897. /**
  898. * 取消拼团 /api/orders/cancel_regiment
  899. *
  900. * */
  901. public function cancel_regiment( Request $request, Model $Model,OrdersProduct $OrdersProduct){
  902. // 验证参数
  903. $request->scene('cancel')->validate();
  904. // 检查登录
  905. $uid = $this->checkLogin();
  906. // 接收参数
  907. $id = request('id',0);
  908. $status = 12;
  909. // 获取产品和数量
  910. $oldData = $Model->query()->where([['id','=',$id],['custom_uid','=',$uid]])->first(['id','order_score','status','custom_uid','insert_time','regiment_id']);
  911. // 如果用户不存在
  912. if( !$oldData ) return json_send(['code'=>'error','msg'=>'订单不存在']);
  913. // 如果已经取消
  914. if( $oldData['status'] == 12 ) return json_send(['code'=>'error','msg'=>'订单已取消']);
  915. // 如果团不存在
  916. if( !$oldData['regiment_id'] ) return json_send(['code'=>'error','msg'=>'拼团不存在']);
  917. //查询团信息
  918. $regimentInfo = Regiment::query()->find($oldData['regiment_id']);
  919. if( !$regimentInfo ) return json_send(['code'=>'error','msg'=>'拼团不存在']);
  920. // 组合数据,写入订单表,子表
  921. DB::beginTransaction();
  922. try{
  923. // 查询数据
  924. $result = $Model->setOrderStatus($id,$status,$OrdersProduct);
  925. // 提示新增失败
  926. if( isset($result['error']) ) {
  927. // 回退数据
  928. DB::rollBack();
  929. // 提示信息
  930. return json_send(['code'=>'error','msg'=>$result['error'],'data'=>['error'=>$result['error']]]);
  931. }
  932. //开团用户取消团订单
  933. if ($regimentInfo['people_number'] > 1 && $regimentInfo['custom_uid'] == $uid){
  934. //查询团记录
  935. $regimentRecordInfo = RegimentRecord::query()->where([['order_id','<>',$oldData['id']],['regiment_id','=',$regimentInfo['id']],['status','=',0]])->first();
  936. if ($regimentRecordInfo){
  937. //将参团成员中的第一个用户变成开团人
  938. $result = Regiment::query()->where('id','=',$regimentRecordInfo['regiment_id'])->update(['custom_uid'=>$regimentRecordInfo['custom_uid']]);
  939. if (!$result) {
  940. DB::rollBack();
  941. return json_send(['code'=>'error','msg'=>'取消拼团,改变开团人失败']);
  942. }
  943. }
  944. //扣减加入团人数
  945. $regimentRes = Regiment::query()->where('id','=',$oldData['regiment_id'])->decrement('people_number',1);
  946. if( !$regimentRes ) {
  947. // 回退数据
  948. DB::rollBack();
  949. // 提示信息
  950. return json_send(['code'=>'error','msg'=>'取消拼团失败']);
  951. }
  952. }else{
  953. $regimentRes = Regiment::query()->where('id','=',$oldData['regiment_id'])->update(['status'=>1]);
  954. if (!$regimentRes){
  955. DB::rollBack();
  956. return json_send(['code'=>'error','msg'=>'取消拼团失败']);
  957. }
  958. }
  959. //修改拼团记录
  960. $regimentRes = RegimentRecord::query()->where([['order_id','=',$oldData['id'],]])->update(['status'=>'1']);
  961. if( !$regimentRes ) {
  962. // 回退数据
  963. DB::rollBack();
  964. // 提示信息
  965. return json_send(['code'=>'error','msg'=>'取消拼团失败']);
  966. }
  967. // 提交数据
  968. DB::commit();
  969. // 告知结果
  970. return json_send(['code'=>'success','msg'=>'取消成功']);
  971. // 返回结果
  972. } catch (\Throwable $th) {
  973. // 回退数据
  974. DB::rollBack();
  975. // 下单失败提示
  976. return json_send(['code'=>'error','msg'=>'取消失败','data'=>['error'=>$th->getMessage().$th->getLine()]]);
  977. }
  978. }
  979. /**
  980. * 订单详情
  981. *
  982. * @pamam int $id 订单ID
  983. *
  984. * */
  985. public function get_detail( Request $request, Model $Model,OrdersProduct $OrdersProduct,Business $Business,OrdersAddr $OrdersAddr){
  986. // 验证参数
  987. $request->scene('get_detail')->validate();
  988. // 接受参数
  989. $id = request('id',0);
  990. // 查询数据
  991. $order = $Model->query()->find($id,['id','pay_total','status','price_total','coupon_total','business_id','pay_total','weizan_orderid','insert_time']);
  992. // 查询不到订单
  993. if( !$order ) return json_send(['code'=>'error','msg'=>'订单不存在']);
  994. // 数据转换
  995. $order = $order->toArray();
  996. // id转编号
  997. $order['insert_time'] = date('Y-m-d H:i:s',$order['insert_time']);
  998. $order['business_name'] = (string) $Business->getOne($order['business_id'],'name');
  999. $order['order_code'] = $Model->idToCode($order['id']);
  1000. $order['state'] = $Model->getState($order['status'],'state');
  1001. // 查询子订单数据
  1002. $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();
  1003. // 处理缩略图
  1004. foreach ($order['order_items'] as $key => $value) {
  1005. $order['order_items'][$key]['product_thumb'] = $value['product_thumb'] ? path_compat($value['product_thumb']) : '';
  1006. }
  1007. // 地址
  1008. $order['order_addr'] = $OrdersAddr->query()->where([['order_id','=',$id]])->first(['contact_name','contact_phone','contact_province','contact_city','contact_area','contact_addr','contact_shop']);
  1009. // 加载模板
  1010. return json_send(['code'=>'success','msg'=>'获取成功','data'=>$order]);
  1011. }
  1012. }