Checkout.php 30 KB

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