Checkout.php 30 KB

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