Checkout.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\api\service\order;
  13. use app\api\model\User as UserModel;
  14. use app\api\model\Goods as GoodsModel;
  15. use app\api\model\Order as OrderModel;
  16. use app\api\model\Setting as SettingModel;
  17. use app\api\model\UserCoupon as UserCouponModel;
  18. use app\api\service\User as UserService;
  19. use app\api\service\user\Grade as UserGradeService;
  20. use app\api\service\coupon\GoodsDeduct as GoodsDeductService;
  21. use app\api\service\points\GoodsDeduct as PointsDeductService;
  22. use app\api\service\order\source\checkout\Factory as CheckoutFactory;
  23. use app\common\enum\Setting as SettingEnum;
  24. use app\common\enum\DiscountType as DiscountTypeEnum;
  25. use app\common\enum\order\OrderType as OrderTypeEnum;
  26. use app\common\enum\order\OrderStatus as OrderStatusEnum;
  27. use app\common\enum\order\OrderSource as OrderSourceEnum;
  28. use app\common\enum\order\DeliveryType as DeliveryTypeEnum;
  29. use app\common\service\BaseService;
  30. use app\common\service\delivery\Express as ExpressService;
  31. use app\common\service\goods\source\Factory as StockFactory;
  32. use app\common\library\helper;
  33. use cores\exception\BaseException;
  34. /**
  35. * 订单结算台服务类
  36. * Class Checkout
  37. * @package app\api\service\order
  38. */
  39. class Checkout extends BaseService
  40. {
  41. /* $model OrderModel 订单模型 */
  42. public OrderModel $model;
  43. /* @var UserModel $user 当前用户信息 */
  44. private $user;
  45. // 订单结算商品列表
  46. private $goodsList;
  47. /**
  48. * 订单结算api参数
  49. * @var array
  50. */
  51. private array $param = [
  52. 'delivery' => null, // 配送方式
  53. 'couponId' => 0, // 用户的优惠券ID
  54. 'isUsePoints' => 0, // 是否使用积分抵扣
  55. 'remark' => '', // 买家留言
  56. ];
  57. /**
  58. * 订单结算的规则
  59. * @var array
  60. */
  61. private array $checkoutRule = [
  62. 'isUserGrade' => true, // 会员等级折扣
  63. 'isCoupon' => true, // 优惠券折扣
  64. 'isUsePoints' => true, // 积分抵扣
  65. ];
  66. /**
  67. * 订单来源
  68. * @var array
  69. */
  70. private array $orderSource = [
  71. 'source' => OrderSourceEnum::MAIN,
  72. 'sourceId' => 0,
  73. 'sourceData' => [],
  74. ];
  75. /**
  76. * 订单结算数据
  77. * @var array
  78. */
  79. private array $orderData = [];
  80. /**
  81. * 构造函数
  82. * Checkout constructor.
  83. * @throws BaseException
  84. */
  85. public function __construct()
  86. {
  87. parent::__construct();
  88. $this->user = UserService::getCurrentLoginUser(true);
  89. $this->model = new OrderModel;
  90. $this->storeId = $this->getStoreId();
  91. }
  92. /**
  93. * 设置结算台请求的参数
  94. * @param $param
  95. * @return array
  96. */
  97. public function setParam($param): array
  98. {
  99. $this->param = array_merge($this->param, $param);
  100. return $this->getParam();
  101. }
  102. /**
  103. * 获取结算台请求的参数
  104. * @return array
  105. */
  106. public function getParam(): array
  107. {
  108. return $this->param;
  109. }
  110. /**
  111. * 订单结算的规则
  112. * @param $data
  113. * @return $this
  114. */
  115. public function setCheckoutRule($data): Checkout
  116. {
  117. $this->checkoutRule = array_merge($this->checkoutRule, $data);
  118. return $this;
  119. }
  120. /**
  121. * 设置订单来源(普通订单)
  122. * @param $data
  123. * @return $this
  124. */
  125. public function setOrderSource($data): Checkout
  126. {
  127. $this->orderSource = array_merge($this->orderSource, $data);
  128. return $this;
  129. }
  130. /**
  131. * 订单确认-结算台
  132. * @param $goodsList
  133. * @return array
  134. * @throws BaseException
  135. * @throws \think\db\exception\DataNotFoundException
  136. * @throws \think\db\exception\DbException
  137. * @throws \think\db\exception\ModelNotFoundException
  138. */
  139. public function onCheckout($goodsList): array
  140. {
  141. // 订单确认-立即购买
  142. $this->goodsList = $goodsList;
  143. return $this->checkout();
  144. }
  145. /**
  146. * 订单结算台
  147. * @return array
  148. * @throws BaseException
  149. * @throws \think\db\exception\DataNotFoundException
  150. * @throws \think\db\exception\DbException
  151. * @throws \think\db\exception\ModelNotFoundException
  152. */
  153. private function checkout(): array
  154. {
  155. // 整理订单数据
  156. $this->orderData = $this->getOrderData();
  157. // 验证商品状态, 是否允许购买
  158. $this->validateGoodsList();
  159. // 订单商品总数量
  160. $orderTotalNum = (int)helper::getArrayColumnSum($this->goodsList, 'total_num');
  161. // 设置订单商品会员折扣价
  162. $this->setOrderGoodsGradeMoney();
  163. // 设置订单商品总金额(不含优惠折扣)
  164. $this->setOrderTotalPrice();
  165. // 当前用户可用的优惠券列表
  166. $couponList = $this->getCouponListByOrder((float)$this->orderData['orderTotalPrice']);
  167. // 计算优惠券抵扣
  168. $this->setOrderCouponMoney($couponList, (int)$this->param['couponId']);
  169. // 计算可用积分抵扣
  170. $this->setOrderPoints();
  171. // 计算订单商品的实际付款金额
  172. $this->setOrderGoodsPayPrice();
  173. // 设置订单配送信息
  174. $this->setDelivery();
  175. // 计算订单最终金额
  176. $this->setOrderPayPrice();
  177. // 计算订单积分赠送数量
  178. $this->setOrderPointsBonus();
  179. // 返回订单数据
  180. return array_merge([
  181. 'goodsList' => $this->goodsList, // 商品信息
  182. 'orderTotalNum' => $orderTotalNum, // 商品总数量
  183. 'couponList' => array_values($couponList), // 优惠券列表
  184. 'hasError' => $this->hasError(),
  185. 'errorMsg' => $this->getError(),
  186. ], $this->orderData);
  187. }
  188. /**
  189. * 设置订单配送信息
  190. * @throws \think\db\exception\DataNotFoundException
  191. * @throws \think\db\exception\DbException
  192. * @throws \think\db\exception\ModelNotFoundException
  193. */
  194. private function setDelivery()
  195. {
  196. // 设置默认配送方式
  197. if (!$this->param['delivery']) {
  198. $deliveryType = SettingModel::getItem(SettingEnum::DELIVERY)['delivery_type'];
  199. $this->param['delivery'] = current($deliveryType);
  200. }
  201. // 处理配送方式
  202. if ($this->param['delivery'] == DeliveryTypeEnum::EXPRESS) {
  203. $this->setOrderExpress();
  204. }
  205. // 判断商品是否支持配送
  206. $deliveryName = DeliveryTypeEnum::data()[$this->param['delivery']]['name'];
  207. foreach ($this->goodsList as $goods) {
  208. if ($goods['is_ind_delivery_type'] && !in_array($this->param['delivery'], $goods['delivery_type'])) {
  209. $this->setError("很抱歉,商品 [{$goods['goods_name']}] 不支持{$deliveryName}");
  210. }
  211. }
  212. }
  213. /**
  214. * 计算订单可用积分抵扣
  215. * @return void
  216. * @throws \think\db\exception\DataNotFoundException
  217. * @throws \think\db\exception\DbException
  218. * @throws \think\db\exception\ModelNotFoundException
  219. */
  220. private function setOrderPoints(): void
  221. {
  222. // 设置默认的商品积分抵扣信息
  223. $this->setDefaultGoodsPoints();
  224. // 积分设置
  225. $setting = SettingModel::getItem('points');
  226. // 条件:后台开启下单使用积分抵扣
  227. if (
  228. !$this->checkoutRule['isUsePoints']
  229. || !$setting['is_shopping_discount']
  230. ) {
  231. return;
  232. }
  233. // 条件:订单金额满足[?]元
  234. if (helper::bccomp($setting['discount']['full_order_price'], $this->orderData['orderTotalPrice']) === 1) {
  235. return;
  236. }
  237. // 计算订单商品最多可抵扣的积分数量
  238. $this->setOrderGoodsMaxPointsNum();
  239. // 订单最多可抵扣的积分总数量
  240. $maxPointsNumCount = (int)helper::getArrayColumnSum($this->goodsList, 'max_points_num');
  241. // 实际可抵扣的积分数量
  242. $actualPointsNum = min($maxPointsNumCount, $this->user['points']);
  243. if ($actualPointsNum < 1) {
  244. return;
  245. }
  246. // 计算订单商品实际抵扣的积分数量和金额
  247. $GoodsDeduct = new PointsDeductService($this->goodsList);
  248. $GoodsDeduct->setGoodsPoints($maxPointsNumCount, $actualPointsNum);
  249. // 积分抵扣总金额
  250. $orderPointsMoney = helper::getArrayColumnSum($this->goodsList, 'points_money');
  251. $this->orderData['pointsMoney'] = helper::number2($orderPointsMoney);
  252. // 积分抵扣总数量
  253. $this->orderData['pointsNum'] = $actualPointsNum;
  254. // 允许积分抵扣
  255. $this->orderData['isAllowPoints'] = true;
  256. }
  257. /**
  258. * 计算订单商品最多可抵扣的积分数量
  259. * @return void
  260. * @throws \think\db\exception\DataNotFoundException
  261. * @throws \think\db\exception\DbException
  262. * @throws \think\db\exception\ModelNotFoundException
  263. */
  264. private function setOrderGoodsMaxPointsNum(): void
  265. {
  266. // 积分设置
  267. $setting = SettingModel::getItem('points');
  268. foreach ($this->goodsList as &$goods) {
  269. // 商品不允许积分抵扣
  270. if (!$goods['is_points_discount']) continue;
  271. // 积分抵扣比例
  272. $deductionRatio = helper::bcdiv($setting['discount']['max_money_ratio'], 100);
  273. // 最多可抵扣的金额
  274. $totalPayPrice = helper::bcsubs([$goods['total_price'], $goods['coupon_money']]);
  275. $maxPointsMoney = helper::bcmul($totalPayPrice, $deductionRatio);
  276. // 最多可抵扣的积分数量
  277. $goods['max_points_num'] = helper::bcdiv($maxPointsMoney, $setting['discount']['discount_ratio'], 0);
  278. }
  279. }
  280. /**
  281. * 设置默认的商品积分抵扣信息
  282. * @return void
  283. */
  284. private function setDefaultGoodsPoints(): void
  285. {
  286. foreach ($this->goodsList as &$goods) {
  287. // 最多可抵扣的积分数量
  288. $goods['max_points_num'] = 0;
  289. // 实际抵扣的积分数量
  290. $goods['points_num'] = 0;
  291. // 实际抵扣的金额
  292. $goods['points_money'] = 0;
  293. }
  294. }
  295. /**
  296. * 整理订单数据(结算台初始化)
  297. * @return array
  298. * @throws \think\db\exception\DataNotFoundException
  299. * @throws \think\db\exception\DbException
  300. * @throws \think\db\exception\ModelNotFoundException
  301. */
  302. private function getOrderData(): array
  303. {
  304. return [
  305. // 当前订单类型
  306. 'orderType' => $this->getOrderType(),
  307. // 当前配送方式
  308. 'delivery' => $this->getDeliveryType(),
  309. // 默认地址
  310. 'address' => $this->user['address_default'],
  311. // 是否存在收货地址
  312. 'existAddress' => $this->user['address_id'] > 0,
  313. // 配送费用
  314. 'expressPrice' => '0.00',
  315. // 当前用户收货城市是否存在配送规则中
  316. 'isIntraRegion' => true,
  317. // 是否允许使用积分抵扣
  318. 'isAllowPoints' => false,
  319. // 是否使用积分抵扣
  320. 'isUsePoints' => (bool)$this->param['isUsePoints'],
  321. // 积分抵扣金额
  322. 'pointsMoney' => '0.00',
  323. // 赠送的积分数量
  324. 'pointsBonus' => 0,
  325. ];
  326. }
  327. /**
  328. * 获取当前配送方式
  329. * @return int|mixed
  330. * @throws \think\db\exception\DataNotFoundException
  331. * @throws \think\db\exception\DbException
  332. * @throws \think\db\exception\ModelNotFoundException
  333. */
  334. private function getDeliveryType()
  335. {
  336. // 系统默认的配送方式
  337. $setting = SettingModel::getItem(SettingEnum::DELIVERY)['delivery_type'];
  338. // 配送方式:实物订单
  339. if ($this->getOrderType() == OrderTypeEnum::PHYSICAL) {
  340. return $this->param['delivery'] > 0 ? $this->param['delivery'] : $setting[0];
  341. }
  342. // 配送方式:无需配送
  343. return DeliveryTypeEnum::NOTHING;
  344. }
  345. /**
  346. * 获取订单类型
  347. * @return mixed
  348. */
  349. private function getOrderType()
  350. {
  351. return $this->goodsList[0]['goods_type'];
  352. }
  353. /**
  354. * 获取订单页面中使用到的系统设置
  355. * @return array
  356. * @throws \think\db\exception\DataNotFoundException
  357. * @throws \think\db\exception\DbException
  358. * @throws \think\db\exception\ModelNotFoundException
  359. */
  360. public function getSetting(): array
  361. {
  362. // 系统支持的配送方式 (后台设置)
  363. $deliveryType = SettingModel::getItem(SettingEnum::DELIVERY)['delivery_type'];
  364. // 积分设置
  365. $pointsSetting = SettingModel::getItem(SettingEnum::POINTS);
  366. return [
  367. 'deliveryType' => $deliveryType, // 支持的配送方式
  368. 'points_name' => $pointsSetting['points_name'], // 积分名称
  369. 'points_describe' => $pointsSetting['describe'], // 积分说明
  370. ];
  371. }
  372. /**
  373. * 获取订单结算时的个人信息
  374. * @return array
  375. */
  376. public function getPersonal(): array
  377. {
  378. return [
  379. 'user_id' => $this->user['user_id'],
  380. 'balance' => $this->user['balance'],
  381. 'points' => $this->user['points'],
  382. 'address_id' => $this->user['address_id'],
  383. ];
  384. }
  385. /**
  386. * 当前用户可用的优惠券列表
  387. * @param float $orderTotalPrice 订单商品总金额
  388. * @return array
  389. * @throws \think\db\exception\DbException
  390. */
  391. private function getCouponListByOrder(float $orderTotalPrice): array
  392. {
  393. // 是否开启优惠券折扣
  394. if (!$this->checkoutRule['isCoupon']) {
  395. return [];
  396. }
  397. // 整理当前订单所有商品ID集
  398. $orderGoodsIds = helper::getArrayColumn($this->goodsList, 'goods_id');
  399. // 当前用户可用的优惠券列表
  400. $couponList = UserCouponModel::getListByOrder($this->user['user_id'], $orderTotalPrice);
  401. // 判断当前优惠券是否满足订单使用条件 (优惠券适用范围)
  402. return UserCouponModel::couponListApplyRange($couponList, $orderGoodsIds);
  403. }
  404. /**
  405. * 验证订单商品的状态
  406. * @return void
  407. */
  408. private function validateGoodsList(): void
  409. {
  410. $Checkout = CheckoutFactory::getFactory(
  411. $this->user,
  412. $this->goodsList,
  413. $this->orderSource['source']
  414. );
  415. if (!$Checkout->validateGoodsList()) {
  416. $this->setError($Checkout->getError());
  417. }
  418. }
  419. /**
  420. * 设置订单的商品总金额(不含优惠折扣)
  421. */
  422. private function setOrderTotalPrice()
  423. {
  424. // 订单商品的总金额(不含优惠券折扣)
  425. $this->orderData['orderTotalPrice'] = helper::number2(helper::getArrayColumnSum($this->goodsList, 'total_price'));
  426. }
  427. /**
  428. * 设置订单的实际支付金额(含配送费)
  429. */
  430. private function setOrderPayPrice()
  431. {
  432. // 订单金额(含优惠折扣)
  433. $this->orderData['orderPrice'] = helper::number2(helper::getArrayColumnSum($this->goodsList, 'total_pay_price'));
  434. // 订单实付款金额(订单金额 + 运费)
  435. $this->orderData['orderPayPrice'] = helper::number2(helper::bcadd($this->orderData['orderPrice'], $this->orderData['expressPrice']));
  436. }
  437. /**
  438. * 计算订单积分赠送数量
  439. * @return void
  440. * @throws \think\db\exception\DataNotFoundException
  441. * @throws \think\db\exception\DbException
  442. * @throws \think\db\exception\ModelNotFoundException
  443. */
  444. private function setOrderPointsBonus(): void
  445. {
  446. // 初始化商品积分赠送数量
  447. foreach ($this->goodsList as &$goods) {
  448. $goods['points_bonus'] = 0;
  449. }
  450. // 积分设置
  451. $setting = SettingModel::getItem('points');
  452. // 条件:后台开启开启购物送积分
  453. if (!$setting['is_shopping_gift']) {
  454. return;
  455. }
  456. // 设置商品积分赠送数量
  457. foreach ($this->goodsList as &$goods) {
  458. // 积分赠送比例
  459. $ratio = helper::bcdiv($setting['gift_ratio'], 100);
  460. // 计算抵扣积分数量
  461. $goods['points_bonus'] = !$goods['is_points_gift'] ? 0 : helper::bcmul($goods['total_pay_price'], $ratio, 0);
  462. }
  463. // 订单积分赠送数量
  464. $this->orderData['pointsBonus'] = (int)helper::getArrayColumnSum($this->goodsList, 'points_bonus');
  465. }
  466. /**
  467. * 计算订单商品的实际付款金额
  468. * @return void
  469. */
  470. private function setOrderGoodsPayPrice(): void
  471. {
  472. // 商品总价 - 优惠抵扣
  473. foreach ($this->goodsList as &$goods) {
  474. // 减去优惠券抵扣金额
  475. $value = helper::bcsubs([$goods['total_price'], $goods['coupon_money']]);
  476. // 减去积分抵扣金额
  477. if ($this->orderData['isAllowPoints'] && $this->orderData['isUsePoints']) {
  478. $value = helper::bcsub($value, $goods['points_money']);
  479. }
  480. // 订单商品的实际付款金额
  481. $goods['total_pay_price'] = helper::number2($value);
  482. }
  483. }
  484. /**
  485. * 设置订单商品会员折扣价
  486. * @return void
  487. * @throws BaseException
  488. * @throws \think\db\exception\DataNotFoundException
  489. * @throws \think\db\exception\DbException
  490. * @throws \think\db\exception\ModelNotFoundException
  491. */
  492. private function setOrderGoodsGradeMoney(): void
  493. {
  494. // 设置默认数据
  495. helper::setDataAttribute($this->goodsList, [
  496. // 标记参与会员折扣
  497. 'is_user_grade' => false,
  498. // 会员等级抵扣的金额
  499. 'grade_ratio' => 0,
  500. // 会员折扣的商品单价
  501. 'grade_goods_price' => 0,
  502. // 会员折扣的总额差
  503. 'grade_total_money' => 0,
  504. ], true);
  505. // 是否开启会员等级折扣
  506. if (!$this->checkoutRule['isUserGrade']) {
  507. return;
  508. }
  509. // 获取当前登录用户的会员等级信息
  510. $gradeInfo = UserGradeService::getCurrentGradeInfo();
  511. // 判断商品是否参与会员折扣
  512. if (empty($gradeInfo)) {
  513. return;
  514. }
  515. // 计算抵扣金额
  516. foreach ($this->goodsList as &$goods) {
  517. // 判断商品是否参与会员折扣
  518. if (!$goods['is_enable_grade']) {
  519. continue;
  520. }
  521. // 折扣比例
  522. $discountRatio = $gradeInfo['equity']['discount'];
  523. // 商品单独设置了会员折扣
  524. if ($goods['is_alone_grade'] && isset($goods['alone_grade_equity'][$this->user['grade_id']])) {
  525. $discountRatio = $goods['alone_grade_equity'][$gradeInfo['grade_id']];
  526. }
  527. if (empty($discountRatio)) {
  528. continue;
  529. }
  530. // 会员折扣后的商品总金额
  531. $gradeTotalPrice = UserGradeService::getDiscountPrice($goods['total_price'], $discountRatio);
  532. helper::setDataAttribute($goods, [
  533. 'is_user_grade' => true,
  534. 'grade_ratio' => $discountRatio,
  535. 'grade_goods_price' => UserGradeService::getDiscountPrice($goods['goods_price'], $discountRatio),
  536. 'grade_total_money' => helper::bcsub($goods['total_price'], $gradeTotalPrice),
  537. 'total_price' => $gradeTotalPrice,
  538. ], false);
  539. }
  540. }
  541. /**
  542. * 设置订单优惠券抵扣信息
  543. * @param array $couponList 当前用户可用的优惠券列表
  544. * @param int $userCouponId 当前选择的优惠券ID
  545. * @return void
  546. * @throws BaseException
  547. */
  548. private function setOrderCouponMoney(array $couponList, int $userCouponId): void
  549. {
  550. // 设置默认数据:订单信息
  551. helper::setDataAttribute($this->orderData, [
  552. 'couponId' => 0, // 用户的优惠券ID
  553. 'couponMoney' => 0, // 优惠券抵扣金额
  554. ], false);
  555. // 设置默认数据:订单商品列表
  556. helper::setDataAttribute($this->goodsList, [
  557. 'coupon_money' => 0, // 优惠券抵扣金额
  558. ], true);
  559. // 验证选择的优惠券ID是否合法
  560. if (!$this->verifyOrderCouponId($userCouponId, $couponList)) {
  561. return;
  562. }
  563. // 获取优惠券信息
  564. $couponInfo = $this->getCouponInfo($userCouponId, $couponList);
  565. // 商品列表信息格式化
  566. $goodsListTemp = helper::getArrayColumns($this->goodsList, ['goods_id', 'goods_sku_id', 'total_price']);
  567. // 计算订单商品优惠券抵扣金额
  568. $CouponMoney = new GoodsDeductService;
  569. $rangeGoodsList = $CouponMoney->setGoodsList($goodsListTemp)
  570. ->setCouponInfo($couponInfo)
  571. ->setGoodsCouponMoney()
  572. ->getRangeGoodsList();
  573. // 分配订单商品优惠券抵扣金额
  574. foreach ($this->goodsList as &$goods) {
  575. $goodsKey = "{$goods['goods_id']}-{$goods['goods_sku_id']}";
  576. if (isset($rangeGoodsList[$goodsKey])) {
  577. $goods['coupon_money'] = helper::bcdiv($rangeGoodsList[$goodsKey]['coupon_money'], 100);
  578. }
  579. }
  580. // 记录订单优惠券信息
  581. $this->orderData['couponId'] = $userCouponId;
  582. $this->orderData['couponMoney'] = helper::number2(helper::bcdiv($CouponMoney->getActualReducedMoney(), 100));
  583. }
  584. /**
  585. * 验证用户选择的优惠券ID是否合法
  586. * @param int $userCouponId
  587. * @param $couponList
  588. * @return bool
  589. * @throws BaseException
  590. */
  591. private function verifyOrderCouponId(int $userCouponId, $couponList): bool
  592. {
  593. // 是否开启优惠券折扣
  594. if (!$this->checkoutRule['isCoupon']) {
  595. return false;
  596. }
  597. // 如果没有可用的优惠券,直接返回
  598. if ($userCouponId <= 0 || empty($couponList)) {
  599. return false;
  600. }
  601. // 判断优惠券是否存在
  602. $couponInfo = $this->getCouponInfo($userCouponId, $couponList);
  603. if (!$couponInfo) {
  604. throwError('未找到优惠券信息');
  605. }
  606. // 判断优惠券适用范围是否合法
  607. if (!$couponInfo['is_apply']) {
  608. throwError($couponInfo['not_apply_info']);
  609. }
  610. return true;
  611. }
  612. /**
  613. * 查找指定的优惠券信息
  614. * @param int $userCouponId 用户优惠券ID
  615. * @param array $couponList 优惠券列表
  616. * @return false|mixed
  617. */
  618. private function getCouponInfo(int $userCouponId, array $couponList)
  619. {
  620. return helper::getArrayItemByColumn($couponList, 'user_coupon_id', $userCouponId);
  621. }
  622. /**
  623. * 订单配送-快递配送
  624. * @return void
  625. * @throws \think\db\exception\DataNotFoundException
  626. * @throws \think\db\exception\DbException
  627. * @throws \think\db\exception\ModelNotFoundException
  628. */
  629. private function setOrderExpress(): void
  630. {
  631. // 设置默认数据:配送费用
  632. helper::setDataAttribute($this->goodsList, [
  633. 'expressPrice' => 0,
  634. ], true);
  635. // 当前用户收货城市ID
  636. $cityId = $this->user['address_default'] ? (int)$this->user['address_default']['city_id'] : 0;
  637. // 初始化配送服务类
  638. $ExpressService = new ExpressService($cityId, $this->goodsList);
  639. // 验证商品是否在配送范围
  640. $isIntraRegion = $ExpressService->isIntraRegion();
  641. if ($cityId > 0 && !$isIntraRegion) {
  642. $notInRuleGoodsName = $ExpressService->getNotInRuleGoodsName();
  643. $this->setError("很抱歉,您的收货地址不在商品 [{$notInRuleGoodsName}] 的配送范围内");
  644. }
  645. // 订单总运费金额
  646. $this->orderData['isIntraRegion'] = $isIntraRegion;
  647. $this->orderData['expressPrice'] = $ExpressService->getDeliveryFee(true);
  648. }
  649. /**
  650. * 创建新订单
  651. * @param array $order 订单信息
  652. * @return bool
  653. */
  654. public function createOrder(array $order): bool
  655. {
  656. // 表单验证
  657. if (!$this->validateOrderForm($order)) {
  658. return false;
  659. }
  660. // 创建新的订单
  661. return $this->model->transaction(function () use ($order) {
  662. return $this->createOrderEvent($order);
  663. });
  664. }
  665. /**
  666. * 创建订单事件
  667. * @param $order
  668. * @return bool
  669. * @throws BaseException
  670. * @throws \think\db\exception\DataNotFoundException
  671. * @throws \think\db\exception\DbException
  672. * @throws \think\db\exception\ModelNotFoundException
  673. */
  674. private function createOrderEvent($order): bool
  675. {
  676. // 新增订单记录
  677. $this->add($order, $this->param['remark']);
  678. // 保存订单数据 (根据订单类型)
  679. $order['orderType'] == OrderTypeEnum::PHYSICAL && $this->saveOrderByPhysical($order);
  680. // 保存订单商品信息
  681. $this->saveOrderGoods($order);
  682. // 更新商品库存 (针对下单减库存的商品)
  683. $this->updateGoodsStockNum($order);
  684. // 设置优惠券使用状态
  685. $order['couponId'] > 0 && UserCouponModel::setIsUse((int)$order['couponId']);
  686. // 积分抵扣情况下扣除用户积分
  687. if ($order['isAllowPoints'] && $order['isUsePoints'] && $order['pointsNum'] > 0) {
  688. $describe = "用户消费:{$this->model['order_no']}";
  689. UserModel::setIncPoints($this->user['user_id'], -$order['pointsNum'], $describe);
  690. }
  691. // 获取订单详情
  692. $detail = OrderModel::getDetail((int)$this->model['order_id'], ['goods']);
  693. return true;
  694. }
  695. /**
  696. * 保存订单数据 (实物商品)
  697. * @param $order
  698. * @return void
  699. */
  700. private function saveOrderByPhysical($order)
  701. {
  702. if ($order['delivery'] == DeliveryTypeEnum::EXPRESS) {
  703. // 记录收货地址
  704. $this->saveOrderAddress($order['address']);
  705. }
  706. }
  707. /**
  708. * 表单验证 (订单提交)
  709. * @param array $order 订单信息
  710. * @return bool
  711. */
  712. private function validateOrderForm(array $order): bool
  713. {
  714. if ($order['orderType'] == OrderTypeEnum::PHYSICAL) {
  715. return $this->validateOrderFormByPhysical($order);
  716. }
  717. return true;
  718. }
  719. /**
  720. * 表单验证:实物订单
  721. * @param array $order
  722. * @return bool
  723. */
  724. private function validateOrderFormByPhysical(array $order): bool
  725. {
  726. if ($order['delivery'] == DeliveryTypeEnum::EXPRESS) {
  727. if (empty($order['address'])) {
  728. $this->error = '您还没有选择配送地址';
  729. return false;
  730. }
  731. }
  732. return true;
  733. }
  734. /**
  735. * 当前订单是否存在和使用积分抵扣
  736. * @param $order
  737. * @return bool
  738. */
  739. private function isExistPointsDeduction($order): bool
  740. {
  741. return $order['isAllowPoints'] && $order['isUsePoints'];
  742. }
  743. /**
  744. * 新增订单记录
  745. * @param $order
  746. * @param string $remark
  747. * @return void
  748. */
  749. private function add($order, string $remark = ''): void
  750. {
  751. // 当前订单是否存在和使用积分抵扣
  752. $isExistPointsDeduction = $this->isExistPointsDeduction($order);
  753. // 订单数据
  754. $data = [
  755. 'user_id' => $this->user['user_id'],
  756. 'order_no' => $this->model->orderNo(),
  757. 'order_type' => $order['orderType'],
  758. 'total_price' => $order['orderTotalPrice'],
  759. 'order_price' => $order['orderPrice'],
  760. 'coupon_id' => $order['couponId'],
  761. 'coupon_money' => $order['couponMoney'],
  762. 'points_money' => $isExistPointsDeduction ? $order['pointsMoney'] : 0,
  763. 'points_num' => $isExistPointsDeduction ? $order['pointsNum'] : 0,
  764. 'pay_price' => $order['orderPayPrice'],
  765. 'delivery_type' => $order['delivery'],
  766. 'buyer_remark' => trim($remark),
  767. 'order_source' => $this->orderSource['source'],
  768. 'order_source_id' => $this->orderSource['sourceId'],
  769. 'order_source_data' => $this->orderSource['sourceData'],
  770. 'points_bonus' => $order['pointsBonus'],
  771. 'order_status' => OrderStatusEnum::NORMAL,
  772. 'platform' => getPlatform(),
  773. 'store_id' => $this->storeId,
  774. ];
  775. if ($order['delivery'] == DeliveryTypeEnum::EXPRESS) {
  776. $data['express_price'] = $order['expressPrice'];
  777. }
  778. // 保存订单记录
  779. $this->model->save($data);
  780. }
  781. /**
  782. * 保存订单商品信息
  783. * @param $order
  784. * @return void
  785. */
  786. private function saveOrderGoods($order): void
  787. {
  788. // 当前订单是否存在和使用积分抵扣
  789. $isExistPointsDeduction = $this->isExistPointsDeduction($order);
  790. // 订单商品列表
  791. $goodsList = [];
  792. foreach ($order['goodsList'] as $goods) {
  793. /* @var GoodsModel $goods */
  794. $item = [
  795. 'user_id' => $this->user['user_id'],
  796. 'store_id' => $this->storeId,
  797. 'goods_id' => $goods['goods_id'],
  798. 'goods_type' => $goods['goods_type'],
  799. 'goods_name' => $goods['goods_name'],
  800. 'goods_no' => $goods['goods_no'] ?: '',
  801. 'image_id' => $this->getGoodsImageId($goods),
  802. 'deduct_stock_type' => $goods['deduct_stock_type'],
  803. 'spec_type' => $goods['spec_type'],
  804. 'goods_sku_id' => $goods['skuInfo']['goods_sku_id'],
  805. 'goods_props' => $goods['skuInfo']['goods_props'] ?: '',
  806. 'content' => $goods['content'] ?? '',
  807. 'goods_sku_no' => $goods['skuInfo']['goods_sku_no'] ?: '',
  808. 'goods_price' => $goods['skuInfo']['goods_price'],
  809. 'line_price' => $goods['skuInfo']['line_price'],
  810. 'goods_weight' => $goods['skuInfo']['goods_weight'],
  811. 'is_user_grade' => (int)$goods['is_user_grade'],
  812. 'grade_ratio' => $goods['grade_ratio'],
  813. 'grade_goods_price' => $goods['grade_goods_price'],
  814. 'grade_total_money' => $goods['grade_total_money'],
  815. 'coupon_money' => $goods['coupon_money'],
  816. 'points_money' => $isExistPointsDeduction ? $goods['points_money'] : 0,
  817. 'points_num' => $isExistPointsDeduction ? $goods['points_num'] : 0,
  818. 'points_bonus' => $goods['points_bonus'],
  819. 'total_num' => $goods['total_num'],
  820. 'total_price' => $goods['total_price'],
  821. 'total_pay_price' => $goods['total_pay_price'],
  822. ];
  823. // 记录订单商品来源ID
  824. $item['goods_source_id'] = isset($goods['goods_source_id']) ? $goods['goods_source_id'] : 0;
  825. $goodsList[] = $item;
  826. }
  827. $this->model->goods()->saveAll($goodsList) !== false;
  828. }
  829. /**
  830. * 获取订单商品的封面图(优先sku封面图)
  831. * @param $goods
  832. * @return int
  833. */
  834. private function getGoodsImageId($goods): int
  835. {
  836. return $goods['skuInfo']['image_id'] ?: (int)current($goods['goods_images'])['file_id'];
  837. }
  838. /**
  839. * 更新商品库存 (针对下单减库存的商品)
  840. * @param $order
  841. * @return void
  842. */
  843. private function updateGoodsStockNum($order): void
  844. {
  845. StockFactory::getFactory($this->model['order_source'])->updateGoodsStock($order['goodsList']);
  846. }
  847. /**
  848. * 记录收货地址
  849. * @param $address
  850. * @return void
  851. */
  852. private function saveOrderAddress($address): void
  853. {
  854. $this->model->address()->save([
  855. 'user_id' => $this->user['user_id'],
  856. 'store_id' => $this->storeId,
  857. 'name' => $address['name'],
  858. 'phone' => $address['phone'],
  859. 'province_id' => $address['province_id'],
  860. 'city_id' => $address['city_id'],
  861. 'region_id' => $address['region_id'],
  862. 'detail' => $address['detail'],
  863. ]);
  864. }
  865. }