OrderLogic.php 61 KB

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