OrderLogic.php 62 KB

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