OrderLogic.php 61 KB

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