Checkout.php 32 KB

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