OrderLogic.php 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LikeShop有特色的全开源社交分销电商系统
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 商业用途务必购买系统授权,以免引起不必要的法律纠纷
  7. // | 禁止对系统程序代码以任何目的,任何形式的再发布
  8. // | 微信公众号:好象科技
  9. // | 访问官网:http://www.likemarket.net
  10. // | 访问社区:http://bbs.likemarket.net
  11. // | 访问手册:http://doc.likemarket.net
  12. // | 好象科技开发团队 版权所有 拥有最终解释权
  13. // +----------------------------------------------------------------------
  14. // | Author: LikeShopTeam-段誉
  15. // +----------------------------------------------------------------------
  16. namespace app\shopapi\logic\Order;
  17. use app\common\enum\AfterSaleEnum;
  18. use app\common\enum\AfterSaleLogEnum;
  19. use app\common\enum\BargainEnum;
  20. use app\common\enum\CouponEnum;
  21. use app\common\enum\DeliveryEnum;
  22. use app\common\enum\FreeShippingEnum;
  23. use app\common\enum\GoodsEnum;
  24. use app\common\enum\OrderEnum;
  25. use app\common\enum\OrderLogEnum;
  26. use app\common\enum\PayEnum;
  27. use app\common\enum\PresellEnum;
  28. use app\common\enum\TeamEnum;
  29. use app\common\enum\YesNoEnum;
  30. use app\common\logic\CommonPresellLogic;
  31. use app\common\logic\DiscountLogic;
  32. use app\common\model\AddressLibrary;
  33. use app\common\model\AfterSale;
  34. use app\common\model\AfterSaleGoods;
  35. use app\common\model\BargainInitiate;
  36. use app\common\model\Cart;
  37. use app\common\model\CouponList;
  38. use app\common\model\Delivery;
  39. use app\common\model\Express;
  40. use app\common\model\FreeShipping;
  41. use app\common\model\FreeShippingOrder;
  42. use app\common\model\Goods;
  43. use app\common\model\GoodsItem;
  44. use app\common\model\LuckyDrawRecord;
  45. use app\common\model\Order;
  46. use app\common\model\OrderGoods;
  47. use app\common\model\OrderLog;
  48. use app\common\model\PresellGoodsItem;
  49. use app\common\model\Region;
  50. use app\common\model\SeckillGoodsItem;
  51. use app\common\model\SelffetchShop;
  52. use app\common\model\TeamActivity;
  53. use app\common\model\TeamFound;
  54. use app\common\model\TeamGoods;
  55. use app\common\model\TeamGoodsItem;
  56. use app\common\model\TeamJoin;
  57. use app\common\model\User;
  58. use app\common\logic\BaseLogic;
  59. use app\common\model\UserAddress;
  60. use app\common\service\after_sale\AfterSaleService;
  61. use app\common\service\ConfigService;
  62. use app\common\service\FileService;
  63. use app\shopapi\logic\BargainLogic;
  64. use app\shopapi\logic\TeamLogic;
  65. use expressage\Kd100;
  66. use expressage\Kdniao;
  67. use think\Exception;
  68. use think\facade\Db;
  69. use think\facade\Validate;
  70. /**
  71. * 订单逻辑
  72. * Class OrderLogic
  73. * @package app\shopapi\logic
  74. */
  75. class OrderLogic extends BaseLogic
  76. {
  77. /**
  78. * 下单用户
  79. * @var
  80. */
  81. protected static $user;
  82. /**
  83. * 订单类型
  84. * @var int
  85. */
  86. protected static $OrderType = OrderEnum::NORMAL_ORDER;
  87. /**
  88. * 订单数量
  89. * @var int
  90. */
  91. protected static $totalNum = 0;
  92. /**
  93. * 订单金额
  94. * @var array
  95. */
  96. protected static $orderPrice = [
  97. 'total_goods_price' => 0,//订单商品金额
  98. 'express_price' => 0,//运费
  99. 'total_amount' => 0,//订单金额
  100. 'order_amount' => 0,//订单实付金额
  101. 'discount_amount' => 0,//优惠金额
  102. 'member_amount' => 0,//会员折扣价
  103. 'total_goods_original_price' => 0,//订单商品原价总价
  104. ];
  105. /**
  106. * 失效商品列表
  107. * @var array
  108. */
  109. protected static array $disabledGoods = [];
  110. /**
  111. * @notes 当前下单用户
  112. * @param $userId
  113. * @return array
  114. * @author 段誉
  115. * @date 2021/7/23 15:52
  116. */
  117. public static function setOrderUser($userId)
  118. {
  119. self::$user = User::findOrEmpty($userId)->toArray();
  120. return self::$user;
  121. }
  122. /**
  123. * @notes 订单结算详情
  124. * @param $params
  125. * @return array|bool
  126. * @author 段誉
  127. * @date 2021/7/23 15:52
  128. */
  129. public static function settlement($params)
  130. {
  131. try {
  132. //设置订单类型
  133. self::$OrderType = $params['order_type'];
  134. //设置用户信息
  135. $user = self::setOrderUser($params['user_id']);
  136. outFileLog($params,'order_submit','params');
  137. outFileLog($user,'order_submit','$user');
  138. //判断PC端邀请人信息是否存在。不存在的话需要相伴i的那个邀请人才能下单
  139. if($params['terminal'] ==4){
  140. if(!$user['inviter_id']){
  141. self::$error = '您未绑定推荐码,请联系商店管理员绑定推荐码后再次下单!';
  142. return false;
  143. }
  144. }
  145. //设置用户地址
  146. $userAddress = UserAddress::getOneAddress($params['user_id'], $params['address_id'] ?? 0);
  147. //获取商品信息
  148. $goodsLists = self::getOrderGoodsData($params);
  149. //判断是否需要地址
  150. $is_address = 1;
  151. foreach ($goodsLists as $goods) {
  152. //非虚拟商品必填地址
  153. if ($goods['type'] != GoodsEnum::GOODS_VIRTUAL) {
  154. break;
  155. }
  156. $is_address = $goods['is_address'];
  157. }
  158. if ($is_address == 0) {
  159. $userAddress = [];
  160. }
  161. //计算运费(自提订单不需要运费)
  162. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) {
  163. self::$orderPrice['express_price'] = 0;
  164. } else {
  165. $express_data = FreightLogic::calculateFreight($goodsLists, $userAddress);
  166. self::$orderPrice['express_price'] = $express_data['express_price'];
  167. $goodsLists = $express_data['goods'];
  168. }
  169. // 普通订单、虚拟订单可使用优惠券
  170. if (!empty($params['coupon_list_id']) && in_array(self::$OrderType, [OrderEnum::NORMAL_ORDER, OrderEnum::VIRTUAL_ORDER])) {
  171. $discountData = OrderCouponLogic::calculateCouponDiscount($goodsLists, $params['coupon_list_id']);
  172. self::$orderPrice['discount_amount'] = $discountData['discount'];
  173. self::$orderPrice['order_amount'] -= $discountData['discount'];
  174. $goodsLists = $discountData['goods'];
  175. }
  176. // 订单金额
  177. self::$orderPrice['total_amount'] += self::$orderPrice['express_price'];
  178. //订单应付金额
  179. self::$orderPrice['order_amount'] += self::$orderPrice['express_price'];
  180. $result = [
  181. 'terminal' => $params['terminal'],
  182. 'delivery_type' => intval($params['delivery_type']),
  183. 'delivery_type_desc' => DeliveryEnum::getDeliveryTypeDesc($params['delivery_type']),
  184. 'cart_id' => $params['cart_id'] ?? [],
  185. 'order_type' => self::$OrderType,
  186. 'coupon_list_id' => intval($params['coupon_list_id'] ?? 0),
  187. 'total_num' => self::$totalNum,
  188. 'total_goods_price' => bcadd(0, self::$orderPrice['total_goods_price'], 2),
  189. 'total_amount' => bcadd(0, self::$orderPrice['total_amount'], 2),
  190. 'order_amount' => bcadd(0, self::$orderPrice['order_amount'], 2),
  191. 'discount_amount' => bcadd(0, self::$orderPrice['discount_amount'], 2),
  192. 'member_amount' => bcadd(0, self::$orderPrice['member_amount'],2),
  193. 'express_price' => bcadd(0, self::$orderPrice['express_price'], 2),
  194. 'total_goods_original_price' => bcadd(0, self::$orderPrice['total_goods_original_price'], 2),
  195. 'user_id' => $user['id'],
  196. 'user_money' => $user['user_money'],
  197. 'user_remark' => $params['user_remark'] ?? '',
  198. 'address' => $userAddress,
  199. 'goods' => $goodsLists,
  200. 'goods_disabled' => static::$disabledGoods,
  201. 'selffetch_shop_id' => $params['selffetch_shop_id'] ?? '',
  202. 'selffetch_info' => [],
  203. 'contact' => $params['contact'] ?? '',
  204. 'mobile' => $params['mobile'] ?? '',
  205. 'is_address' => $is_address,
  206. 'draw_record_id' => $params['draw_record_id'] ?? 0,
  207. ];
  208. //门店自提显示上次提货人信息
  209. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) {
  210. $selffetch_info = Order::where(['user_id' => $user['id'], 'delivery_type' => DeliveryEnum::SELF_DELIVERY])
  211. ->field('address,selffetch_shop_id')
  212. ->order('id desc')
  213. ->findOrEmpty()->toArray();
  214. //上一次提货人
  215. if ($selffetch_info) {
  216. $selffetch_field = [
  217. 'id', 'name', 'image', 'contact', 'mobile',
  218. 'province', 'city', 'district', 'longitude', 'address', 'latitude',
  219. 'business_start_time', 'business_end_time', 'weekdays', 'remark',
  220. 'status',
  221. ];
  222. $result['selffetch_info'] = [
  223. 'selffetch_shop_id' => $selffetch_info['selffetch_shop_id'] ?? '',
  224. 'contact' => $selffetch_info['address']->contact ?? '',
  225. 'mobile' => $selffetch_info['address']->mobile ?? '',
  226. 'selffetch_shop' => SelffetchShop::where('status', 1)
  227. ->field($selffetch_field)
  228. ->append([ 'detailed_address' ])
  229. ->find($selffetch_info['selffetch_shop_id'] ?? 0),
  230. ];
  231. }
  232. }
  233. // 营销活动附加参数: 秒杀、拼团、砍价
  234. switch ($params['order_type']) {
  235. // 拼团
  236. case OrderEnum::TEAM_ORDER:
  237. $result['team_id'] = $params['team_id'];
  238. $result['found_id'] = $params['found_id'] ?? null;
  239. $teamFound = (new TeamFound())
  240. ->where(['id' => $result['found_id'], 'user_id' => $params['user_id']])
  241. ->findOrEmpty();
  242. if (!$teamFound->isEmpty()) {
  243. self::$error = '不允许参与自己开的团';
  244. return false;
  245. }
  246. break;
  247. // 秒杀
  248. case OrderEnum::SECKILL_ORDER:
  249. $result['seckill_id'] = $params['seckill_id'];
  250. break;
  251. // 砍价
  252. case OrderEnum::BARGAIN_ORDER:
  253. $result['initiate_id'] = $params['initiate_id'];
  254. break;
  255. // 预售
  256. case OrderEnum::PRESELL_ORDER:
  257. $result['presell_id'] = $params['presell_id'];
  258. break;
  259. // 抽奖
  260. case OrderEnum::DRAW_ORDER:
  261. //订单金额等于运费
  262. $result['order_amount'] = $result['express_price'];
  263. $result['total_amount'] = $result['express_price'];
  264. break;
  265. }
  266. // 判断是否符合包邮活动条件
  267. if (self::isFreeShipping($result)) {
  268. $result['order_amount'] = $result['order_amount'] - $result['express_price'];
  269. $result['total_amount'] = $result['total_amount'] - $result['express_price'];
  270. $result['express_price'] = 0;
  271. // 商品的运费也清0
  272. foreach ($goodsLists as &$goodsList) {
  273. $goodsList['express_price'] = 0;
  274. $goodsList['express_money'] = 0;
  275. }
  276. $result['goods'] = $goodsLists;
  277. }
  278. $result['total_goods_price'] = bcadd($result['total_goods_price'], 0, 2);
  279. $result['total_amount'] = bcadd($result['total_amount'], 0, 2);
  280. $result['order_amount'] = bcadd($result['order_amount'], 0, 2);
  281. $result['discount_amount'] = bcadd($result['discount_amount'], 0, 2);
  282. $result['member_amount'] = bcadd($result['member_amount'], 0, 2);
  283. $result['express_price'] = bcadd($result['express_price'], 0, 2);
  284. $result['total_goods_original_price'] = bcadd($result['total_goods_original_price'], 0, 2);
  285. return $result;
  286. } catch (\Exception $e) {
  287. self::$error = $e->getMessage();
  288. return false;
  289. }
  290. }
  291. /**
  292. * @notes 是否符合包邮活动条件
  293. */
  294. public static function isFreeShipping(&$params) {
  295. $params['is_free_shipping'] = false;
  296. if (empty($params['address'])) {
  297. return false;
  298. }
  299. // 获取当前时间进行中的包邮活动
  300. $activity = FreeShipping::where([
  301. ['start_time', '<=', time()],
  302. ['end_time', '>', time()],
  303. ['status', '=', FreeShippingEnum::ING],
  304. ])->find();
  305. if (!$activity) {
  306. // 没有包邮活动
  307. return false;
  308. }
  309. if ($activity->getData('condition_type') == FreeShippingEnum::BY_AMOUNT) {
  310. // 去除优惠金额
  311. $threshold = $params['total_goods_price'] - $params['discount_amount'];
  312. } else {
  313. $threshold = $params['total_num'];
  314. }
  315. $nationThreshold = 0;
  316. foreach($activity->region as $item) {
  317. if ($item->region_id == "100000") {
  318. // 全国区域留在最后判断
  319. $nationThreshold = $item->threshold;
  320. continue;
  321. }
  322. if (strpos($item->region_id, $params['address']->district_id) !== false) {
  323. if ($threshold >= $item->threshold) {
  324. $params['is_free_shipping'] = true;
  325. $params['free_shipping_id'] = $activity->id;
  326. return true;
  327. } else {
  328. return false;
  329. }
  330. }
  331. if (strpos($item->region_id, $params['address']->city_id) !== false) {
  332. if ($threshold >= $item->threshold) {
  333. $params['is_free_shipping'] = true;
  334. $params['free_shipping_id'] = $activity->id;
  335. return true;
  336. } else {
  337. return false;
  338. }
  339. }
  340. if (strpos($item->region_id, $params['address']->province_id) !== false) {
  341. if ($threshold >= $item->threshold) {
  342. $params['is_free_shipping'] = true;
  343. $params['free_shipping_id'] = $activity->id;
  344. return true;
  345. } else {
  346. return false;
  347. }
  348. }
  349. }
  350. if ($threshold >= $nationThreshold) {
  351. $params['is_free_shipping'] = true;
  352. $params['free_shipping_id'] = $activity->id;
  353. return true;
  354. }
  355. return false;
  356. }
  357. /**
  358. * @notes 提交订单前验证
  359. * @param $params
  360. * @throws \Exception
  361. * @author 段誉
  362. * @date 2021/7/23 15:53
  363. */
  364. public static function submitBeforeCheck($params)
  365. {
  366. // 商品检测
  367. if (empty($params['goods'])) {
  368. throw new \Exception('提交的商品已不能购买,请重新选择商品');
  369. }
  370. //配送方式为快递配送时,检测地址
  371. if (empty($params['address']) && $params['delivery_type'] == DeliveryEnum::EXPRESS_DELIVERY && $params['is_address'] == 1) {
  372. throw new \Exception('请选择收货地址');
  373. }
  374. //配送方式为门店自提时
  375. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY && empty($params['selffetch_shop_id'])) {
  376. throw new \Exception('自提门店不能为空');
  377. }
  378. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY && !empty($params['selffetch_shop_id'])) {
  379. $selffetch_shop = SelffetchShop::where('id', $params['selffetch_shop_id'])->findOrEmpty();
  380. if ($selffetch_shop->isEmpty()) {
  381. throw new \Exception('自提门店不存在');
  382. }
  383. }
  384. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY && empty($params['contact'])) {
  385. throw new \Exception('取货人不能为空');
  386. }
  387. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY && empty($params['mobile'])) {
  388. throw new \Exception('联系电话不能为空');
  389. }
  390. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY && !Validate::mobile($params['mobile'])) {
  391. throw new \Exception('联系电话格式不正确');
  392. }
  393. // 校验商品数量
  394. $limit_arr = [];
  395. foreach ($params['goods'] as $goods) {
  396. if ($goods['goods_num'] <= 0) {
  397. throw new \Exception('请选择商品' . ($goods['goods_name'] ?? '') . '数量');
  398. }
  399. $limit_arr[$goods['goods_id']]['goods_num'] = ($limit_arr[$goods['goods_id']]['goods_num'] ?? 0) + $goods['goods_num'];
  400. $limit_arr[$goods['goods_id']]['limit_type'] = $goods['limit_type'];
  401. $limit_arr[$goods['goods_id']]['limit_value'] = $goods['limit_value'];
  402. $limit_arr[$goods['goods_id']]['goods_name'] = $goods['goods_name'];
  403. $limit_arr[$goods['goods_id']]['goods_id'] = $goods['goods_id'];
  404. }
  405. //校验限购商品
  406. foreach ($limit_arr as $limit_val) {
  407. if (static::isOutBuyNum($limit_val, $limit_val['goods_num'], $params['user_id'])) {
  408. throw new \Exception('商品:' . ($limit_val['goods_name'] ?? '') . ' 超过限购数量');
  409. }
  410. }
  411. //验证订单商品是否支持对应的配送方式
  412. $is_express = ConfigService::get('delivery_type', 'is_express', 1);
  413. $is_selffetch = ConfigService::get('delivery_type', 'is_selffetch', 0);
  414. $item_ids = implode(',', array_column($params['goods'], 'item_id'));
  415. $goods_ids = implode(',', GoodsItem::where('id', 'in', $item_ids)->column('goods_id'));
  416. $goods = Goods::where('id', 'in', $goods_ids)->select();
  417. $goods_name = [];
  418. //门店自提
  419. if ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) {
  420. if ($is_selffetch == 0) {
  421. throw new \Exception('系统未开启门店自提配送方式');
  422. }
  423. foreach ($goods as $val) {
  424. //虚拟商品不支持门店自提
  425. if (GoodsEnum::GOODS_VIRTUAL == $val['type']) {
  426. throw new \Exception($val['name'] . '不支持门店自提');
  427. }
  428. if ($val['is_selffetch'] == 0) {
  429. $goods_name[] = $val['name'];
  430. }
  431. }
  432. } elseif ($params['delivery_type'] == DeliveryEnum::EXPRESS_DELIVERY) { //快递配送
  433. if ($is_express == 0) {
  434. throw new \Exception('系统未开启快递配送方式');
  435. }
  436. foreach ($goods as $val) {
  437. //实物商品且不支持物流
  438. if ($val['is_express'] == 0 && GoodsEnum::GOODS_REALITY == $val['type']) {
  439. $goods_name[] = $val['name'];
  440. }
  441. }
  442. }
  443. if (!empty($goods_name)) {
  444. throw new \Exception(implode('、', $goods_name) . '不支持' . DeliveryEnum::getDeliveryTypeDesc($params['delivery_type']) . ',请重新选择配送方式');
  445. }
  446. }
  447. /**
  448. * @notes 提交订单
  449. * @param $params
  450. * @return array|bool
  451. * @author 段誉
  452. * @date 2021/7/23 15:53
  453. */
  454. public static function submitOrder($params)
  455. {
  456. Db::startTrans();
  457. try {
  458. //提交前验证
  459. self::submitBeforeCheck($params);
  460. //删除购物车
  461. self::delCartByOrder($params);
  462. //下单扣除库存
  463. self::decStock($params['goods']);
  464. //提交订单
  465. $order = self::addOrder($params, self::$user['id']);
  466. //下单增加商品销量
  467. self::incSale($params['goods']);
  468. //有使用优惠券时更新coupon_list
  469. if ($params['coupon_list_id'] > 0) {
  470. self::handleCouponByOrder($params['coupon_list_id'], $order['id']);
  471. }
  472. // 营销活动下单后的操作
  473. switch ($params['order_type']) {
  474. // 拼团
  475. case OrderEnum::TEAM_ORDER:
  476. self::teamAfter($params, $order);
  477. break;
  478. // 秒杀
  479. case OrderEnum::SECKILL_ORDER:
  480. self::seckillAfter($params, $order);
  481. break;
  482. // 砍价
  483. case OrderEnum::BARGAIN_ORDER:
  484. self::bargainAfter($params, $order);
  485. break;
  486. // 预售
  487. case OrderEnum::PRESELL_ORDER:
  488. self::presellAfter($params, $order);
  489. break;
  490. }
  491. // 判断是否为包邮活动订单
  492. if ($params['is_free_shipping']) {
  493. FreeShippingOrder::create([
  494. 'free_shpping_id' => $params['free_shipping_id'],
  495. 'order_id' => $order['id'],
  496. 'amount' => $order['order_amount']
  497. ]);
  498. }
  499. //订单日志
  500. (new OrderLog())->record([
  501. 'type' => OrderLogEnum::TYPE_USER,
  502. 'channel' => OrderLogEnum::USER_ADD_ORDER,
  503. 'order_id' => $order['id'],
  504. 'operator_id' => self::$user['id'],
  505. ]);
  506. //抽奖记录结算
  507. LuckyDrawRecord::update([
  508. 'id' => $params['draw_record_id'] ?? 0,
  509. 'is_send' => YesNoEnum::YES,
  510. 'send_time' => time(),
  511. ]);
  512. //提交事务
  513. Db::commit();
  514. return ['order_id' => $order['id'], 'type' => 'order'];
  515. } catch (\Exception $e) {
  516. Db::rollback();
  517. self::$error = $e->getMessage();
  518. return false;
  519. }
  520. }
  521. /**
  522. * @notes 更新订单优惠券状态
  523. * @param $coupon_list_id
  524. * @param $order_id
  525. * @throws \think\db\exception\DataNotFoundException
  526. * @throws \think\db\exception\DbException
  527. * @throws \think\db\exception\ModelNotFoundException
  528. * @author ljj
  529. * @date 2021/9/14 11:39 上午
  530. */
  531. public static function handleCouponByOrder($coupon_list_id, $order_id)
  532. {
  533. $coupon_list = CouponList::find($coupon_list_id);
  534. $coupon_list->order_id = $order_id;
  535. $coupon_list->status = CouponEnum::USE_STATUS_OK;
  536. $coupon_list->use_time = time();
  537. $coupon_list->update_time = time();
  538. $coupon_list->save();
  539. }
  540. /**
  541. * @notes 扣减库存
  542. * @param $goodLists
  543. * @throws \Exception
  544. * @author 段誉
  545. * @date 2021/8/9 17:47
  546. */
  547. public static function decStock($goodLists)
  548. {
  549. foreach ($goodLists as $goods) {
  550. $goodsItem = GoodsItem::where(['id' => $goods['item_id']])->findOrEmpty()->toArray();
  551. if ($goodsItem['stock'] < $goods['goods_num']) {
  552. throw new \Exception('商品库存不足');
  553. }
  554. //更新商品总库存
  555. Goods::update(['total_stock' => ['dec', $goods['goods_num']]], ['id' => $goods['goods_id']]);
  556. //更新规格库存
  557. GoodsItem::update(['stock' => ['dec', $goods['goods_num']]], ['id' => $goods['item_id']]);
  558. }
  559. }
  560. /**
  561. * @notes 下单增加销量
  562. * @param $goodLists
  563. * @throws \Exception
  564. * @author ljj
  565. * @date 2021/9/22 5:30 下午
  566. */
  567. public static function incSale($goodLists)
  568. {
  569. foreach ($goodLists as $goods) {
  570. Goods::update(['sales_num' => ['inc', $goods['goods_num']]], ['id' => $goods['goods_id']]);
  571. }
  572. }
  573. /**
  574. * @notes 删除购物车(购物车下单情况)
  575. * @param $params
  576. * @author 段誉
  577. * @date 2021/7/23 15:54
  578. */
  579. public static function delCartByOrder($params)
  580. {
  581. if (!empty($params['cart_id'])) {
  582. Cart::where(['id' => $params['cart_id'], 'user_id' => self::$user['id']])->delete();
  583. }
  584. }
  585. /**
  586. * @notes 添加订单
  587. * @param $params
  588. * @param $user_id
  589. * @author 段誉
  590. * @date 2021/8/9 17:42
  591. */
  592. public static function addOrder($params, $user_id)
  593. {
  594. $order = Order::create([
  595. 'sn' => generate_sn((new Order()), 'sn'),
  596. 'order_type' => $params['order_type'],
  597. 'user_id' => $user_id,
  598. 'order_terminal' => $params['terminal'],
  599. 'coupon_list_id' => $params['coupon_list_id'],
  600. 'total_num' => $params['total_num'],
  601. 'total_amount' => $params['total_amount'],
  602. 'goods_price' => $params['total_goods_price'],
  603. 'order_amount' => $params['order_amount'],
  604. 'express_price' => $params['express_price'],
  605. 'discount_amount' => $params['discount_amount'],
  606. 'member_amount' => $params['member_amount'],
  607. 'user_remark' => $params['user_remark'],
  608. 'address' => [
  609. 'contact' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? $params['contact'] : ($params['address']['contact'] ?? ''),
  610. 'province' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? '' : ($params['address']['province_id'] ?? ''),
  611. 'city' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? '' : ($params['address']['city_id'] ?? ''),
  612. 'district' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? '' : ($params['address']['district_id'] ?? ''),
  613. 'address' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? '' : ($params['address']['address'] ?? ''),
  614. 'mobile' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? $params['mobile'] : ($params['address']['mobile'] ?? ''),
  615. ],
  616. 'delivery_type' => OrderEnum::VIRTUAL_ORDER == $params['order_type'] ? DeliveryEnum::DELIVERY_VIRTUAL : $params['delivery_type'],
  617. 'pickup_code' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? create_number_sn((new Order()), 'pickup_code', 6) : null,
  618. 'selffetch_shop_id' => ($params['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? $params['selffetch_shop_id'] : 0,
  619. 'draw_record_id' => $params['draw_record_id'] ?? 0,
  620. ]);
  621. $goodsData = [];
  622. foreach ($params['goods'] as $goods) {
  623. //商品实付价格
  624. $totalPayPrice = $goods['sub_price'] - ($goods['discount_price'] ?? 0) + ($goods['express_price'] ?? 0);
  625. $totalPayPrice = $totalPayPrice <= 0 ? 0 : $totalPayPrice;
  626. $goodsData[] = [
  627. 'order_id' => $order['id'],
  628. 'goods_id' => $goods['goods_id'],
  629. 'item_id' => $goods['item_id'],
  630. 'goods_name' => $goods['goods_name'],
  631. 'goods_num' => $goods['goods_num'],
  632. 'goods_price' => $goods['sell_price'],//商品价格单价(未扣减优惠和积分价格)
  633. 'total_price' => $goods['sub_price'],
  634. 'total_pay_price' => $totalPayPrice,//实际支付商品金额(扣除优惠金额、加上运费)
  635. 'spec_value_ids' => $goods['spec_value_ids'],
  636. 'discount_price' => $goods['discount_price'] ?? 0,//优惠券优惠金额
  637. 'original_price' => $goods['original_price'] ?? 0,//商品原始价格
  638. 'member_price' => $goods['member_price'] ?? 0,//商品会员价格
  639. 'goods_snap' => $goods,
  640. 'express_price' => $goods['express_price'] ?? 0,//运费
  641. ];
  642. }
  643. (new OrderGoods())->saveAll($goodsData);
  644. return $order;
  645. }
  646. /**
  647. * @notes 商品信息
  648. * @param $params
  649. * @return array
  650. * @author 段誉
  651. * @date 2021/7/23 15:54
  652. */
  653. public static function getOrderGoodsData($params)
  654. {
  655. // 购物车下单
  656. if ($params['source'] == 'cart') {
  657. $params['goods'] = Cart::where([
  658. ['id', 'in', $params['cart_id']],
  659. ['user_id', '=', $params['user_id']],
  660. ])->field('item_id,goods_id,goods_num')->select()->toArray();
  661. }
  662. // 砍价商品信息提取
  663. if ($params['order_type'] == OrderEnum::BARGAIN_ORDER) {
  664. $params['goods'] = self::initiateGoods($params);
  665. }
  666. $itemIds = array_column($params['goods'], 'item_id');
  667. $field = [
  668. 'gi.id', 'gi.id' => 'item_id', 'gi.image' => 'item_image',
  669. 'gi.spec_value_str', 'spec_value_ids', 'gi.sell_price',
  670. 'gi.volume', 'gi.stock', 'gi.weight', 'gi.bar_code', 'g.id' => 'goods_id',
  671. 'g.name' => 'goods_name', 'g.type', 'g.status', 'g.delete_time', 'g.image',
  672. 'g.express_type', 'g.express_money', 'g.express_template_id',
  673. 'g.is_express', 'g.is_selffetch', 'g.is_express', 'g.is_virtualdelivery',
  674. 'g.after_pay', 'g.after_delivery', 'g.delivery_content', 'g.delivery_type','g.delivery_template_id',
  675. 'g.code', 'g.is_address', 'g.limit_type', 'g.limit_value'
  676. ];
  677. $goodsData = (new Goods())->alias('g')
  678. ->join('goods_item gi', 'gi.goods_id = g.id')
  679. ->with([ 'goods_category_index2', 'delivery_template' ])
  680. ->where('gi.id', 'in', $itemIds)
  681. ->field($field)
  682. ->select()->toArray();
  683. $goodsData = array_column($goodsData, null, 'id');
  684. //处理图片路径
  685. foreach ($goodsData as &$val) {
  686. $val['item_image'] = trim($val['item_image']) ? FileService::getFileUrl($val['item_image']) : '';
  687. }
  688. return self::getOrderGoodsLists($params, $goodsData);
  689. }
  690. /**
  691. * @notes 结算商品列表
  692. * @param $goods
  693. * @param $goodsData
  694. * @return array
  695. * @author 段誉
  696. * @date 2021/7/23 15:55
  697. */
  698. public static function getOrderGoodsLists($params, $goodsData)
  699. {
  700. $goods = $params['goods'];
  701. $goodsIds = array_column($goodsData, 'goods_id');
  702. $levelGoodsItem = DiscountLogic::getGoodsDiscount(self::$user['id'], $goodsIds);
  703. $goodsLists = [];
  704. foreach ($goods as $k => $item) {
  705. //删除没找到商品信息的商品
  706. if (!isset($goodsData[$item['item_id']])) {
  707. unset($goods[$k]);
  708. static::$disabledGoods[] = [
  709. 'msg' => '找不到商品',
  710. 'goods' => $goodsData[$item['item_id']] ?? [],
  711. ];
  712. continue;
  713. }
  714. //组装商品数据
  715. $goodsInfo = $goodsData[$item['item_id']];
  716. $goodsInfo['goods_num'] = intval($item['goods_num'] ?? 0);
  717. //记录原价
  718. $goodsInfo['original_price'] = $goodsInfo['sell_price'];
  719. $goodsInfo['sub_price'] = round($goodsInfo['sell_price'] * $item['goods_num'], 2);
  720. //当前商品是否被删除或下架
  721. if ($goodsInfo['delete_time'] > 0 || $goodsInfo['status'] != 1) {
  722. unset($goods[$k]);
  723. static::$disabledGoods[] = [
  724. 'msg' => '商品不能购买',
  725. 'goods' => $goodsInfo,
  726. ];
  727. continue;
  728. }
  729. //当前库存是否足够
  730. if ($item['goods_num'] > $goodsInfo['stock']) {
  731. unset($goods[$k]);
  732. static::$disabledGoods[] = [
  733. 'msg' => '商品库存不足',
  734. 'goods' => $goodsInfo,
  735. ];
  736. continue;
  737. }
  738. // 是否限购
  739. if (static::isOutBuyNum($goodsInfo, $item['goods_num'], $params['user_id'])) {
  740. unset($goods[$k]);
  741. static::$disabledGoods[] = [
  742. 'msg' => '超过购买限制',
  743. 'goods' => $goodsInfo,
  744. ];
  745. continue;
  746. }
  747. $goodsInfo['member_price'] = 0;
  748. if(in_array(self::$OrderType,[OrderEnum::NORMAL_ORDER,OrderEnum::VIRTUAL_ORDER])){
  749. //会员折扣
  750. $goodsInfo['member_price'] = $levelGoodsItem[$goodsInfo['goods_id']][$goodsInfo['item_id']]['discount_price'] ?? '';
  751. }
  752. // 获取不同订单类型的规格单价
  753. $goodsInfo['sell_price'] = self::getSellPrice($params, $goodsInfo);
  754. $goodsInfo['sub_price'] = round($goodsInfo['sell_price'] * $item['goods_num'], 2);
  755. $goodsInfo['total_original_price'] = round($goodsInfo['original_price'] * $goodsInfo['goods_num'], 2);//商品原价合计
  756. $goodsLists[] = $goodsInfo;
  757. self::$totalNum += $item['goods_num'];
  758. self::$orderPrice['total_goods_price'] += $goodsInfo['sub_price'];
  759. //普通商品,计算折扣金额
  760. if(in_array(self::$OrderType,[OrderEnum::NORMAL_ORDER,OrderEnum::VIRTUAL_ORDER])){
  761. $memberAmount = round(($goodsInfo['original_price'] - $goodsInfo['sell_price']) * $item['goods_num'],2);
  762. self::$orderPrice['member_amount'] += $memberAmount;
  763. }
  764. //订单商品原价总价
  765. self::$orderPrice['total_goods_original_price'] += $goodsInfo['total_original_price'];
  766. }
  767. //订单金额
  768. self::$orderPrice['total_amount'] = self::$orderPrice['total_goods_price'] + self::$orderPrice['member_amount'];
  769. //订单应付金额
  770. self::$orderPrice['order_amount'] = self::$orderPrice['total_goods_price'];
  771. return $goodsLists;
  772. }
  773. /**
  774. * @notes 是否超出 购买限制
  775. * @param $goods
  776. * @param $num
  777. * @param $userId
  778. * @return bool
  779. * @author lbzy
  780. * @datetime 2023-08-16 15:13:47
  781. */
  782. static function isOutBuyNum($goods, $num, $userId) : bool
  783. {
  784. if ($goods['limit_type'] == GoodsEnum::LIMIT_TYPE_USER) {
  785. $order_goods_num = OrderGoods::alias('og')
  786. ->join('order o', 'o.id = og.order_id')
  787. ->where([
  788. 'og.goods_id'=>$goods['goods_id'],
  789. 'o.order_status'=>[
  790. OrderEnum::STATUS_WAIT_PAY,
  791. OrderEnum::STATUS_WAIT_DELIVERY,
  792. OrderEnum::STATUS_WAIT_RECEIVE,
  793. OrderEnum::STATUS_FINISH
  794. ],
  795. 'o.user_id' => $userId,
  796. 'o.order_type' => [ OrderEnum::NORMAL_ORDER, OrderEnum::VIRTUAL_ORDER] ]
  797. )
  798. ->sum('og.goods_num');
  799. return ($order_goods_num + $goods['goods_num']) > $goods['limit_value'];
  800. }
  801. if ($goods['limit_type'] == GoodsEnum::LIMIT_TYPE_ORDER) {
  802. return $num > $goods['limit_value'];
  803. }
  804. return false;
  805. }
  806. /**
  807. * @notes 订单详情
  808. * @param $params
  809. * @return array
  810. * @author 段誉
  811. * @date 2021/8/2 20:59
  812. */
  813. public static function getDetail($params)
  814. {
  815. $result = (new Order())->with(['order_goods' => function ($query) {
  816. $query->field([
  817. 'id', 'order_id', 'goods_id', 'item_id', 'goods_snap', 'original_price',
  818. 'goods_name', 'goods_price', 'goods_num', 'total_price', 'total_pay_price', 'express_price', 'change_price', 'discount_price', 'discount_price'=>'coupon_discount', 'member_price', 'integral_price'
  819. ])->append(['goods_image', 'spec_value_str','original_price'])->hidden(['goods_snap']);
  820. }])
  821. ->where(['id' => $params['id'], 'user_id' => $params['user_id']])
  822. ->append(['btn', 'delivery_address', 'cancel_unpaid_orders_time', 'show_pickup_code'])
  823. ->hidden(['user_id', 'order_terminal', 'delete_time', 'update_time'])
  824. ->findOrEmpty()->toArray();
  825. //订单类型
  826. $result['order_type_desc'] = ($result['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? '自提订单' : OrderEnum::getOrderTypeDesc($result['order_type']);
  827. //订单状态描述
  828. $result['order_status_desc'] = ($result['order_status'] == OrderEnum::STATUS_WAIT_DELIVERY && $result['delivery_type'] == DeliveryEnum::SELF_DELIVERY) ? '待取货' : OrderEnum::getOrderStatusDesc($result['order_status']);
  829. if ($result['order_type'] == OrderEnum::TEAM_ORDER && $result['is_team_success'] != TeamEnum::TEAM_FOUND_SUCCESS) {
  830. $result['order_status_desc'] = ($result['order_status'] == OrderEnum::STATUS_WAIT_DELIVERY) ? TeamEnum::getStatusDesc($result['is_team_success']) : OrderEnum::getOrderStatusDesc($result['order_status']);
  831. }
  832. // 预售信息
  833. if ($result['order_type'] == OrderEnum::PRESELL_ORDER) {
  834. $result['presell'] = CommonPresellLogic::orderInfo($result);
  835. }
  836. //自提门店
  837. $result['selffetch_shop'] = SelffetchShop::where('id', $result['selffetch_shop_id'])
  838. ->append(['detailed_address'])
  839. ->hidden([ 'create_time', 'update_time', 'delete_time' ])
  840. ->find();
  841. //地址 省市区分隔开
  842. $result['address']->province = Region::where('id', $result['address']->province)->value('name');
  843. $result['address']->city = Region::where('id', $result['address']->city)->value('name');
  844. $result['address']->district = Region::where('id', $result['address']->district)->value('name');
  845. //订单商品原价总价
  846. $result['total_original_price'] = 0;
  847. //订单商品售后按钮处理
  848. foreach ($result['order_goods'] as &$goods) {
  849. $goods['after_sale_btn'] = 0;//售后按钮关闭
  850. $after_sale = AfterSale::where(['order_goods_id' => $goods['id'], 'order_id' => $params['id']])->findOrEmpty();
  851. $after_sale_goods = AfterSaleGoods::where(['order_goods_id' => $goods['id'], 'after_sale_id' => $after_sale['id']])->findOrEmpty();
  852. $goods['after_sale_id'] = $after_sale_goods['id'] ?? 0;
  853. if ($result['order_status'] == OrderEnum::STATUS_FINISH && $result['after_sale_deadline'] > time() && $after_sale->isEmpty()) {
  854. $goods['after_sale_btn'] = 1;//售后按钮开启
  855. }
  856. if ($result['order_status'] == OrderEnum::STATUS_FINISH && $result['after_sale_deadline'] > time() && $after_sale['status'] == AfterSaleEnum::STATUS_ING) {
  857. $goods['after_sale_btn'] = 2;//售后中
  858. }
  859. if ($result['order_status'] == OrderEnum::STATUS_FINISH && $result['after_sale_deadline'] > time() && $after_sale['status'] == AfterSaleEnum::STATUS_SUCCESS) {
  860. $goods['after_sale_btn'] = 3;//售后成功
  861. }
  862. if ($result['order_status'] == OrderEnum::STATUS_FINISH && $result['after_sale_deadline'] > time() && $after_sale['status'] == AfterSaleEnum::STATUS_FAIL) {
  863. $goods['after_sale_btn'] = 4;//售后失败
  864. }
  865. //批量下单后,过了取消订单的时间,可对其中一件商品进行退款操作
  866. if (in_array($result['order_status'],[OrderEnum::STATUS_WAIT_DELIVERY,OrderEnum::STATUS_WAIT_RECEIVE])) {
  867. $ableCancelOrder = ConfigService::get('transaction', 'cancel_unshipped_orders');
  868. if ($ableCancelOrder == YesNoEnum::NO) {
  869. $goods['after_sale_btn'] = 1;//售后按钮开启
  870. }
  871. if ($ableCancelOrder == YesNoEnum::YES) {
  872. $configTime = ConfigService::get('transaction', 'cancel_unshipped_orders_times');
  873. $ableCancelTime = strtotime($result['pay_time']) + ($configTime * 60);
  874. if (time() > $ableCancelTime) {
  875. $goods['after_sale_btn'] = 1;//售后按钮开启
  876. }
  877. }
  878. if (isset($after_sale['status']) && $after_sale['status'] == AfterSaleEnum::STATUS_ING) {
  879. $goods['after_sale_btn'] = 2;//售后中
  880. }
  881. if (isset($after_sale['status']) && $after_sale['status'] == AfterSaleEnum::STATUS_SUCCESS) {
  882. $goods['after_sale_btn'] = 3;//售后成功
  883. }
  884. if (isset($after_sale['status']) && $after_sale['status'] == AfterSaleEnum::STATUS_FAIL) {
  885. $goods['after_sale_btn'] = 4;//售后失败
  886. }
  887. }
  888. //商品原价总价
  889. $goods['total_original_price'] = $goods['original_price'] * $goods['goods_num'];
  890. $result['total_original_price'] += $goods['original_price'] * $goods['goods_num'];
  891. //会员价优惠
  892. $goods['member_discount'] = 0;
  893. if($goods['member_price'] > 0){
  894. $goods['member_discount'] = round(($goods['original_price'] - $goods['member_price']) * $goods['goods_num'],2);
  895. }
  896. // unset($goods['member_price']);
  897. //积分优惠
  898. $goods['integral_discount'] = round($goods['integral_price'] * $goods['goods_num'],2);
  899. // unset($goods['integral_price']);
  900. //售后状态
  901. $goods['after_sale_status_desc'] = '无售后';
  902. if (!$after_sale->isEmpty()) {
  903. $goods['after_sale_status_desc'] = AfterSaleEnum::getStatusDesc($after_sale->status);
  904. }
  905. //订单商品总的优惠
  906. $goods['total_discount'] = round($goods['member_discount']+ $goods['coupon_discount'] +$goods['integral_discount'],2);
  907. }
  908. //订单商品原价总价
  909. $result['total_original_price'] = round($result['total_original_price'],2);
  910. //订单总优惠金额
  911. $result['total_discount'] = $result['discount_amount'] + $result['member_amount'] + $result['integral_amount'];
  912. // unset($result['discount_amount']);unset($result['member_amount']);unset($result['integral_amount']);
  913. //商品详情屏蔽查看内容按钮
  914. $result['btn']['content_btn'] = OrderEnum::BTN_HIDE;
  915. return $result;
  916. }
  917. static function wxReceiveDetail($id, $user_id)
  918. {
  919. $order = Order::where('id', $id)->where('user_id', $user_id)->findOrEmpty()->toArray();
  920. return [
  921. 'transaction_id' => $order['transaction_id'] ?? '',
  922. ];
  923. }
  924. /**
  925. * @notes 取消订单
  926. * @param $params
  927. * @return bool
  928. * @author 段誉
  929. * @date 2021/8/2 15:08
  930. */
  931. public static function cancelOrder($params)
  932. {
  933. Db::startTrans();
  934. try {
  935. $order = (new Order())->getUserOrderById($params['id'], $params['user_id']);
  936. // 如果是拼团订单特别处理
  937. if ($order['order_type'] == OrderEnum::TEAM_ORDER) {
  938. TeamLogic::signFailTeam($order['id']);
  939. } else {
  940. //处于已支付状态的发起整单售后
  941. if ($order['pay_status'] == PayEnum::ISPAID) {
  942. AfterSaleService::orderRefund([
  943. 'order_id' => $params['id'],
  944. 'scene' => AfterSaleLogEnum::BUYER_CANCEL_ORDER
  945. ]);
  946. }
  947. //更新订单为已关闭
  948. Order::update([
  949. 'order_status' => OrderEnum::STATUS_CLOSE,
  950. 'cancel_time' => time()
  951. ], ['id' => $order['id']]);
  952. $returnInventory = ConfigService::get('transaction', 'return_inventory');
  953. if ($returnInventory) {
  954. // 需退还库存
  955. AfterSaleService::returnInventory(['order_id' => $order['id']]);
  956. }
  957. $returnCoupon = ConfigService::get('transaction', 'return_coupon');
  958. if ($returnCoupon) {
  959. // 需退还优惠券
  960. AfterSaleService::returnCoupon($order);
  961. }
  962. //订单日志
  963. (new OrderLog())->record([
  964. 'type' => OrderLogEnum::TYPE_USER,
  965. 'channel' => OrderLogEnum::USER_CANCEL_ORDER,
  966. 'order_id' => $params['id'],
  967. 'operator_id' => $params['user_id'],
  968. ]);
  969. }
  970. Db::commit();
  971. return true;
  972. } catch (\Exception $e) {
  973. Db::rollback();
  974. self::$error = $e->getMessage();
  975. return false;
  976. }
  977. }
  978. /**
  979. * @notes 确认订单
  980. * @param $params
  981. * @author 段誉
  982. * @date 2021/8/2 14:59
  983. */
  984. public static function confirmOrder($params)
  985. {
  986. //更新订单状态
  987. Order::update([
  988. 'order_status' => OrderEnum::STATUS_FINISH,
  989. 'confirm_take_time' => time(),
  990. 'after_sale_deadline' => self::getAfterSaleDeadline(), //售后截止时间
  991. ], ['id' => $params['id'], 'user_id' => $params['user_id']]);
  992. //订单日志
  993. (new OrderLog())->record([
  994. 'type' => OrderLogEnum::TYPE_USER,
  995. 'channel' => OrderLogEnum::USER_CONFIRM_ORDER,
  996. 'order_id' => $params['id'],
  997. 'operator_id' => $params['user_id']
  998. ]);
  999. }
  1000. /**
  1001. * @notes 获取当前售后
  1002. * @return float|int
  1003. * @author 段誉
  1004. * @date 2021/8/2 17:02
  1005. */
  1006. public static function getAfterSaleDeadline()
  1007. {
  1008. //是否关闭维权
  1009. $afterSale = ConfigService::get('transaction', 'after_sales');
  1010. //可维权时间
  1011. $afterSaleDays = ConfigService::get('transaction', 'after_sales_days');
  1012. if ($afterSale == YesNoEnum::NO) {
  1013. $afterSaleDeadline = time();
  1014. } else {
  1015. $afterSaleDeadline = ($afterSaleDays * 24 * 60 * 60) + time();
  1016. }
  1017. return $afterSaleDeadline;
  1018. }
  1019. /**
  1020. * @notes 查看物流
  1021. * @param $params
  1022. * @return array[]
  1023. * @author ljj
  1024. * @date 2021/8/13 6:07 下午
  1025. */
  1026. public static function orderTraces($params)
  1027. {
  1028. //订单信息
  1029. $order = Order::field('id,sn,pay_time,address,order_type,express_status,order_status')
  1030. ->append(['delivery_address'])
  1031. ->where('id',$params['id'])
  1032. ->find()
  1033. ->toArray();
  1034. //物流配置
  1035. $express_type = ConfigService::get('logistics_config', 'express_type', '');
  1036. $express_bird = unserialize(ConfigService::get('logistics_config', 'express_bird', ''));
  1037. $express_hundred = unserialize(ConfigService::get('logistics_config', 'express_hundred', ''));
  1038. $parcelInfo = Delivery::field('id,order_id,order_goods_info,express_name,express_id,invoice_no,send_type,remark,create_time,delivery_address_info,return_address_info')
  1039. ->where(['order_id'=>$order['id']])
  1040. ->append(['send_type_desc'])
  1041. ->select()->toArray();
  1042. foreach ($parcelInfo as $key=>$parcel) {
  1043. //查询物流信息
  1044. $logisticsInfo = [];
  1045. if ($parcel['send_type'] == DeliveryEnum::NO_EXPRESS) {
  1046. $logisticsInfo['traces'] = ['无需物流'];
  1047. } else {
  1048. if (empty($express_type)) {
  1049. $logisticsInfo['traces'] = ['暂无物流信息'];
  1050. }
  1051. //快递配置设置为快递鸟时
  1052. if($express_type === 'express_bird') {
  1053. $expressage = (new Kdniao($express_bird['ebussiness_id'], $express_bird['app_key']));
  1054. $express_field = 'codebird';
  1055. } elseif($express_type === 'express_hundred') {
  1056. $expressage = (new Kd100($express_hundred['customer'], $express_hundred['app_key']));
  1057. $express_field = 'code100';
  1058. }
  1059. //快递编码
  1060. $express_code = Express::where('id',$parcel['express_id'])->value($express_field);
  1061. //获取物流轨迹
  1062. if (in_array(strtolower($express_code), [ 'sf', 'shunfeng' ])) {
  1063. if ($express_type === 'express_bird') {
  1064. $expressage->logistics($express_code, $parcel['invoice_no'], substr($order['address']->mobile, -4));
  1065. } else {
  1066. $expressage->logistics($express_code, $parcel['invoice_no'], $order['address']->mobile);
  1067. }
  1068. }else {
  1069. $expressage->logistics($express_code, $parcel['invoice_no']);
  1070. }
  1071. $logisticsInfo['traces'] = $expressage->logisticsFormat();
  1072. if ($logisticsInfo['traces'] == false) {
  1073. $logisticsInfo['traces'] = ['暂无物流信息'];
  1074. } else {
  1075. foreach ($logisticsInfo['traces'] as &$item) {
  1076. $item = array_values(array_unique($item));
  1077. }
  1078. }
  1079. }
  1080. $parcelInfo[$key]['logistics_info'] = $logisticsInfo;
  1081. $parcelInfo[$key]['express_icon'] = Express::where('id',$parcel['express_id'])->value('icon');
  1082. }
  1083. $deliveryAddressInfo = !empty($parcelInfo[0]['delivery_address_info']) ? json_decode($parcelInfo[0]['delivery_address_info'],true) : '';
  1084. $returnAddressInfo = !empty($parcelInfo[0]['return_address_info']) ? json_decode($parcelInfo[0]['return_address_info'],true) : '';
  1085. //待发货商品
  1086. $waitDeliveryGoods = OrderGoods::where(['order_id'=>$order['id'],'express_status'=>[DeliveryEnum::NOT_SHIPPED,DeliveryEnum::PART_SHIPPED]])
  1087. ->field('id,goods_name,goods_num,goods_price,delivery_num,goods_snap')
  1088. ->append(['spec_value_str','goods_image'])
  1089. ->hidden(['goods_snap'])->select()->toArray();
  1090. foreach ($waitDeliveryGoods as $key=>$goods) {
  1091. $afterSale = AfterSale::where(['order_goods_id'=>$goods['id'],'status'=>AfterSaleEnum::STATUS_SUCCESS])->findOrEmpty();
  1092. if (!$afterSale->isEmpty()) {
  1093. unset($waitDeliveryGoods[$key]);
  1094. }
  1095. }
  1096. $waitDeliveryGoods = empty($waitDeliveryGoods) ? [] : array_values($waitDeliveryGoods);
  1097. return [
  1098. 'order_id' => $order['id'],
  1099. 'order_sn' => $order['sn'],
  1100. 'order_type' => $order['order_type'],
  1101. 'order_status' => $order['order_status'],
  1102. 'express_status' => $order['express_status'],
  1103. 'pay_time' => $order['pay_time'],
  1104. 'receipt_address_info' => [
  1105. 'addresss' => $order['delivery_address'],
  1106. 'contact' => $order['address']->contact,
  1107. 'mobile' => $order['address']->mobile,
  1108. ],
  1109. 'delivery_address_info' => [
  1110. 'addresss' => $deliveryAddressInfo['complete_address'] ?? '',
  1111. 'contact' => $deliveryAddressInfo['contact'] ?? '',
  1112. 'mobile' => $deliveryAddressInfo['mobile'] ?? '',
  1113. ],
  1114. 'return_address_info' => [
  1115. 'addresss' => $returnAddressInfo['complete_address'] ?? '',
  1116. 'contact' => $returnAddressInfo['contact'] ?? '',
  1117. 'mobile' => $returnAddressInfo['mobile'] ?? '',
  1118. ],
  1119. 'remark' => $parcelInfo[0]['remark'],
  1120. 'parcel_info' => $parcelInfo,
  1121. 'wait_delivery_goods' => $waitDeliveryGoods
  1122. ];
  1123. }
  1124. /**
  1125. * @notes 获取配送方式
  1126. * @return array
  1127. * @author ljj
  1128. * @date 2021/8/27 2:32 下午
  1129. */
  1130. public function getDeliveryType()
  1131. {
  1132. return [
  1133. 'express' => [
  1134. 'is_express' => ConfigService::get('delivery_type', 'is_express', 1),
  1135. 'express_name' => ConfigService::get('delivery_type', 'express_name', '快递发货'),
  1136. ],
  1137. 'selffetch' => [
  1138. 'is_selffetch' => ConfigService::get('delivery_type', 'is_selffetch', 0),
  1139. 'selffetch_name' => ConfigService::get('delivery_type', 'selffetch_name', '上门自提'),
  1140. ],
  1141. ];
  1142. }
  1143. /**
  1144. * @notes 删除订单
  1145. * @param $params
  1146. * @return bool
  1147. * @author ljj
  1148. * @date 2021/8/31 2:38 下午
  1149. */
  1150. public function del($params)
  1151. {
  1152. return Order::destroy($params['id']);
  1153. }
  1154. /**
  1155. * @notes 提取砍价商品信息
  1156. * @param $params
  1157. * @return array
  1158. * @author Tab
  1159. * @date 2021/10/9 11:13
  1160. */
  1161. public static function initiateGoods($params)
  1162. {
  1163. $bargainInitiate = BargainInitiate::findOrEmpty($params['initiate_id'])->toArray();
  1164. // 返回二维数组
  1165. return [
  1166. [
  1167. 'item_id' => $bargainInitiate['goods_snapshot']['item_id'],
  1168. 'goods_num' => $bargainInitiate['goods_snapshot']['goods_num'],
  1169. ]
  1170. ];
  1171. }
  1172. /**
  1173. * @notes 获取不同类型订单的规格单价
  1174. * @param $params
  1175. * @author Tab
  1176. * @date 2021/10/9 11:23
  1177. */
  1178. public static function getSellPrice($params, $goodsInfo)
  1179. {
  1180. switch ($params['order_type']) {
  1181. // 普通订单 虚拟订单 抽奖订单
  1182. case OrderEnum::VIRTUAL_ORDER:
  1183. case OrderEnum::NORMAL_ORDER:
  1184. case OrderEnum::DRAW_ORDER:
  1185. return self::getGoodsSellPrice($goodsInfo);
  1186. // 拼团订单
  1187. case OrderEnum::TEAM_ORDER:
  1188. return self::getTeamActivityPrice($params);
  1189. // 秒杀订单
  1190. case OrderEnum::SECKILL_ORDER:
  1191. return self::getSeckillActivityPrice($params);
  1192. // 砍价订单
  1193. case OrderEnum::BARGAIN_ORDER:
  1194. return self::getBargainActivityPrice($params);
  1195. // 预售订单
  1196. case OrderEnum::PRESELL_ORDER:
  1197. return self::getPresellActivityPrice($params);
  1198. }
  1199. }
  1200. /**
  1201. * @notes 获取预售价
  1202. * @param $params
  1203. * @return mixed
  1204. * @author lbzy
  1205. * @datetime 2024-04-26 16:33:58
  1206. */
  1207. static function getPresellActivityPrice($params)
  1208. {
  1209. return PresellGoodsItem::alias('pgi')
  1210. ->where('pgi.item_id', $params['goods'][0]['item_id'])
  1211. ->where('pgi.presell_id', $params['presell_id'])
  1212. ->value('price');
  1213. }
  1214. /**
  1215. * @notes 获取商品售价
  1216. * @param $params
  1217. * @return mixed
  1218. * @author cjhao
  1219. * @date 2022/5/7 18:40
  1220. */
  1221. public static function getGoodsSellPrice($params)
  1222. {
  1223. //会员价允许为零
  1224. if($params['member_price'] >= 0 && $params['member_price'] <= $params['sell_price']){
  1225. return $params['member_price'];
  1226. }
  1227. return $params['sell_price'];
  1228. }
  1229. /**
  1230. * @notes 获取砍价活动价格
  1231. * @param $params
  1232. * @return mixed|void
  1233. * @author Tab
  1234. * @date 2021/10/9 11:30
  1235. */
  1236. public static function getBargainActivityPrice($params)
  1237. {
  1238. $bargainInitiate = BargainInitiate::findOrEmpty($params['initiate_id'])->toArray();
  1239. // 任意金额可购买
  1240. if ($params['buy_condition'] == 'random') {
  1241. return $bargainInitiate['current_price'];
  1242. }
  1243. // 底价购买
  1244. if ($params['buy_condition'] == 'floor') {
  1245. return $bargainInitiate['floor_price'];
  1246. }
  1247. }
  1248. /**
  1249. * @notes 获取秒杀活动价格
  1250. * @param $params
  1251. * @return mixed
  1252. * @author Tab
  1253. * @date 2021/10/9 16:00
  1254. */
  1255. public static function getSeckillActivityPrice($params)
  1256. {
  1257. return SeckillGoodsItem::where([
  1258. 'seckill_id' => $params['seckill_id'],
  1259. 'item_id' => $params['goods'][0]['item_id'],
  1260. ])->value('seckill_price');
  1261. }
  1262. /**
  1263. * @notes 获取拼团活动价格
  1264. * @param $params
  1265. * @author Tab
  1266. * @date 2021/10/9 16:31
  1267. */
  1268. public static function getTeamActivityPrice($params)
  1269. {
  1270. return TeamGoodsItem::where([
  1271. 'team_id' => $params['team_id'],
  1272. 'item_id' => $params['goods'][0]['item_id'],
  1273. ])->value('team_price');
  1274. }
  1275. /**
  1276. * @notes 砍价下单后的操作
  1277. * @param $params
  1278. * @param $order
  1279. * @author Tab
  1280. * @date 2021/10/9 11:52
  1281. */
  1282. public static function bargainAfter($params, $order)
  1283. {
  1284. // 更新砍价记录
  1285. $bargainInitiate = BargainInitiate::findOrEmpty($params['initiate_id']);
  1286. $bargainInitiate->order_id = $order['id'];
  1287. // 标识砍价成功避免任意金额可下单的情况用户继续发起帮助砍价
  1288. $bargainInitiate->status = BargainEnum::STATUS_SUCCESS;
  1289. $bargainInitiate->save();
  1290. }
  1291. /**
  1292. * @notes 拼团下单后的操作
  1293. * @param $params
  1294. * @param $order
  1295. * @author Tab
  1296. * @date 2021/10/9 16:35
  1297. */
  1298. public static function teamAfter($params, $order)
  1299. {
  1300. $time = time();
  1301. $news_found_id = null;
  1302. $teamActivity = TeamActivity::findOrEmpty($params['team_id'])->toArray();
  1303. $teamGoods = TeamGoods::where([
  1304. 'team_id' => $params['team_id'],
  1305. 'goods_id' => $params['goods'][0]['goods_id'],
  1306. ])->findOrEmpty()->toArray();
  1307. $teamGoodsItem = TeamGoodsItem::where([
  1308. 'team_id' => $params['team_id'],
  1309. 'item_id' => $params['goods'][0]['item_id'],
  1310. ])->findOrEmpty()->toArray();
  1311. $goodsSnap = $teamGoods['goods_snap'];
  1312. $itemSnap = $teamGoodsItem['item_snap'];
  1313. $goodsInfo = [
  1314. 'id' => intval($params['goods'][0]['goods_id']),
  1315. 'item_id' => intval($params['goods'][0]['item_id']),
  1316. 'spec_value_ids' => $params['goods'][0]['spec_value_ids'],
  1317. 'name' => $goodsSnap['name'],
  1318. 'image' => $itemSnap['image'] ? FileService::getFileUrl($itemSnap['image']) : FileService::getFileUrl($goodsSnap['image']),
  1319. 'spec_value_str' => $itemSnap['spec_value_str'],
  1320. 'cost_price' => $teamGoodsItem['sell_price'],
  1321. 'sell_price' => $teamGoodsItem['team_price'],
  1322. 'total_price' => round($teamGoodsItem['team_price'] * $params['goods'][0]['goods_num'], 2),
  1323. 'count' => intval($params['goods'][0]['goods_num']),
  1324. 'goods_snap' => $goodsSnap,
  1325. ];
  1326. // 开团
  1327. if (!isset($params['found_id']) || empty($params['found_id'])) {
  1328. $found = TeamFound::create([
  1329. 'found_sn' => generate_sn((new TeamFound()), 'found_sn'),
  1330. 'team_id' => $params['team_id'],
  1331. 'user_id' => $params['user_id'],
  1332. 'order_id' => $order['id'],
  1333. 'people' => $teamActivity['people_num'],
  1334. 'join' => 0,
  1335. 'status' => 0,
  1336. 'goods_snap' => json_encode([
  1337. 'id' => $params['goods'][0]['goods_id'],
  1338. 'name' => $params['goods'][0]['goods_name'],
  1339. 'image' => $params['goods'][0]['image']
  1340. ], JSON_UNESCAPED_UNICODE),
  1341. 'kaituan_time' => $time,
  1342. 'invalid_time' => ($teamActivity['effective_time'] * 60) + time()
  1343. ]);
  1344. $news_found_id = $found['id'];
  1345. }
  1346. // 参团
  1347. TeamJoin::create([
  1348. 'join_sn' => generate_sn((new TeamJoin()), 'join_sn'),
  1349. 'team_id' => $params['team_id'],
  1350. 'found_id' => $news_found_id ?: $params['found_id'],
  1351. 'identity' => $news_found_id ? 1 : 2,
  1352. 'user_id' => $params['user_id'],
  1353. 'order_id' => $order['id'],
  1354. 'status' => 0,
  1355. 'team_snap' => json_encode($teamActivity, JSON_UNESCAPED_UNICODE),
  1356. 'goods_snap' => json_encode($goodsInfo, JSON_UNESCAPED_UNICODE),
  1357. 'invalid_time' => ($teamActivity['effective_time'] * 60) + time(),
  1358. 'create_time' => $time,
  1359. 'update_time' => $time
  1360. ]);
  1361. // 更新数据
  1362. TeamFound::update(['join' => ['inc', 1]], ['id' => $news_found_id ?: $params['found_id']]);
  1363. TeamActivity::update(['partake_number' => ['inc', 1]], ['id' => $params['team_id']]);
  1364. Order::update(['team_found_id' => $news_found_id ?: $params['found_id']], ['id' => $order['id']]);
  1365. }
  1366. /**
  1367. * @notes 秒杀下单后操作
  1368. * @param $params
  1369. * @param $order
  1370. * @author Tab
  1371. * @date 2021/10/13 14:49
  1372. */
  1373. public static function seckillAfter($params, $order)
  1374. {
  1375. Order::update([
  1376. 'id' => $order['id'],
  1377. 'seckill_id' => $params['seckill_id']
  1378. ]);
  1379. }
  1380. /**
  1381. * @notes 预售下单后操作
  1382. * @param $params
  1383. * @param $order
  1384. * @return void
  1385. * @author lbzy
  1386. * @datetime 2024-04-26 16:43:00
  1387. */
  1388. static function presellAfter($params, $order)
  1389. {
  1390. Order::update([
  1391. 'id' => $order['id'],
  1392. 'presell_id' => $params['presell_id']
  1393. ]);
  1394. }
  1395. }