Checkout.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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. // 系统设置 TODO: 废弃
  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. public 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. public function getPersonal(): array
  330. {
  331. return [
  332. 'user_id' => $this->user['user_id'],
  333. 'balance' => $this->user['balance'],
  334. 'points' => $this->user['points'],
  335. 'address_id' => $this->user['address_id'],
  336. ];
  337. }
  338. /**
  339. * 当前用户可用的优惠券列表
  340. * @param float $orderTotalPrice 总金额
  341. * @return array|mixed
  342. * @throws \think\db\exception\DbException
  343. */
  344. private function getUserCouponList(float $orderTotalPrice)
  345. {
  346. // 是否开启优惠券折扣
  347. if (!$this->checkoutRule['isCoupon']) {
  348. return [];
  349. }
  350. // 整理当前订单所有商品ID集
  351. $orderGoodsIds = helper::getArrayColumn($this->goodsList, 'goods_id');
  352. // 当前用户可用的优惠券列表
  353. $couponList = UserCouponModel::getUserCouponList($this->user['user_id'], $orderTotalPrice);
  354. // 判断当前优惠券是否满足订单使用条件 (优惠券适用范围)
  355. return UserCouponModel::couponListApplyRange($couponList, $orderGoodsIds);
  356. }
  357. /**
  358. * 验证订单商品的状态
  359. * @return void
  360. */
  361. private function validateGoodsList(): void
  362. {
  363. $Checkout = CheckoutFactory::getFactory(
  364. $this->user,
  365. $this->goodsList,
  366. $this->orderSource['source']
  367. );
  368. $status = $Checkout->validateGoodsList();
  369. $status == false && $this->setError($Checkout->getError());
  370. }
  371. /**
  372. * 设置订单的商品总金额(不含优惠折扣)
  373. */
  374. private function setOrderTotalPrice()
  375. {
  376. // 订单商品的总金额(不含优惠券折扣)
  377. $this->orderData['orderTotalPrice'] = helper::number2(helper::getArrayColumnSum($this->goodsList, 'total_price'));
  378. }
  379. /**
  380. * 设置订单的实际支付金额(含配送费)
  381. */
  382. private function setOrderPayPrice()
  383. {
  384. // 订单金额(含优惠折扣)
  385. $this->orderData['orderPrice'] = helper::number2(helper::getArrayColumnSum($this->goodsList, 'total_pay_price'));
  386. // 订单实付款金额(订单金额 + 运费)
  387. $this->orderData['orderPayPrice'] = helper::number2(helper::bcadd($this->orderData['orderPrice'], $this->orderData['expressPrice']));
  388. }
  389. /**
  390. * 计算订单积分赠送数量
  391. * @return void
  392. * @throws \think\db\exception\DataNotFoundException
  393. * @throws \think\db\exception\DbException
  394. * @throws \think\db\exception\ModelNotFoundException
  395. */
  396. private function setOrderPointsBonus(): void
  397. {
  398. // 初始化商品积分赠送数量
  399. foreach ($this->goodsList as &$goods) {
  400. $goods['points_bonus'] = 0;
  401. }
  402. // 积分设置
  403. $setting = SettingModel::getItem('points');
  404. // 条件:后台开启开启购物送积分
  405. if (!$setting['is_shopping_gift']) {
  406. return;
  407. }
  408. // 设置商品积分赠送数量
  409. foreach ($this->goodsList as &$goods) {
  410. // 积分赠送比例
  411. $ratio = $setting['gift_ratio'] / 100;
  412. // 计算抵扣积分数量
  413. $goods['points_bonus'] = !$goods['is_points_gift'] ? 0 : helper::bcmul($goods['total_pay_price'], $ratio, 0);
  414. }
  415. // 订单积分赠送数量
  416. $this->orderData['pointsBonus'] = helper::getArrayColumnSum($this->goodsList, 'points_bonus');
  417. }
  418. /**
  419. * 计算订单商品的实际付款金额
  420. * @return void
  421. */
  422. private function setOrderGoodsPayPrice(): void
  423. {
  424. // 商品总价 - 优惠抵扣
  425. foreach ($this->goodsList as &$goods) {
  426. // 减去优惠券抵扣金额
  427. $value = helper::bcsub($goods['total_price'], $goods['coupon_money']);
  428. // 减去积分抵扣金额
  429. if ($this->orderData['isAllowPoints'] && $this->orderData['isUsePoints']) {
  430. $value = helper::bcsub($value, $goods['points_money']);
  431. }
  432. $goods['total_pay_price'] = helper::number2($value);
  433. }
  434. }
  435. /**
  436. * 设置订单商品会员折扣价
  437. * @return void
  438. */
  439. private function setOrderGoodsGradeMoney(): void
  440. {
  441. // 设置默认数据
  442. helper::setDataAttribute($this->goodsList, [
  443. // 标记参与会员折扣
  444. 'is_user_grade' => false,
  445. // 会员等级抵扣的金额
  446. 'grade_ratio' => 0,
  447. // 会员折扣的商品单价
  448. 'grade_goods_price' => 0.00,
  449. // 会员折扣的总额差
  450. 'grade_total_money' => 0.00,
  451. ], true);
  452. // 是否开启会员等级折扣
  453. if (!$this->checkoutRule['isUserGrade']) {
  454. return;
  455. }
  456. // 会员等级状态
  457. if (!(
  458. $this->user['grade_id'] > 0 && !empty($this->user['grade'])
  459. && !$this->user['grade']['is_delete'] && $this->user['grade']['status']
  460. )) {
  461. return;
  462. }
  463. // 计算抵扣金额
  464. foreach ($this->goodsList as &$goods) {
  465. // 判断商品是否参与会员折扣
  466. if (!$goods['is_enable_grade']) {
  467. continue;
  468. }
  469. // 商品单独设置了会员折扣
  470. if ($goods['is_alone_grade'] && isset($goods['alone_grade_equity'][$this->user['grade_id']])) {
  471. // 折扣比例
  472. $discountRatio = helper::bcdiv($goods['alone_grade_equity'][$this->user['grade_id']], 10);
  473. } else {
  474. // 折扣比例
  475. $discountRatio = helper::bcdiv($this->user['grade']['equity']['discount'], 10);
  476. }
  477. if ($discountRatio > 0) {
  478. // 会员折扣后的商品总金额
  479. $gradeTotalPrice = max(0.01, helper::bcmul($goods['total_price'], $discountRatio));
  480. helper::setDataAttribute($goods, [
  481. 'is_user_grade' => true,
  482. 'grade_ratio' => $discountRatio,
  483. 'grade_goods_price' => helper::number2(helper::bcmul($goods['goods_price'], $discountRatio), true),
  484. 'grade_total_money' => helper::number2(helper::bcsub($goods['total_price'], $gradeTotalPrice)),
  485. 'total_price' => $gradeTotalPrice,
  486. ], false);
  487. }
  488. }
  489. }
  490. /**
  491. * 设置订单优惠券抵扣信息
  492. * @param array $couponList 当前用户可用的优惠券列表
  493. * @param int $couponId 当前选择的优惠券id
  494. * @return void
  495. * @throws BaseException
  496. */
  497. private function setOrderCouponMoney(array $couponList, int $couponId): void
  498. {
  499. // 设置默认数据:订单信息
  500. helper::setDataAttribute($this->orderData, [
  501. 'couponId' => 0, // 用户优惠券id
  502. 'couponMoney' => 0, // 优惠券抵扣金额
  503. ], false);
  504. // 设置默认数据:订单商品列表
  505. helper::setDataAttribute($this->goodsList, [
  506. 'coupon_money' => 0, // 优惠券抵扣金额
  507. ], true);
  508. // 验证选择的优惠券ID是否合法
  509. if (!$this->verifyOrderCouponId($couponId, $couponList)) {
  510. return;
  511. }
  512. // 获取优惠券信息
  513. $couponInfo = $this->getCouponInfo($couponId, $couponList);
  514. // 计算订单商品优惠券抵扣金额
  515. $goodsListTemp = helper::getArrayColumns($this->goodsList, ['goods_id', 'total_price']);
  516. $CouponMoney = new GoodsDeductService;
  517. $rangeGoodsList = $CouponMoney->setGoodsList($goodsListTemp)
  518. ->setCouponInfo($couponInfo)
  519. ->setGoodsCouponMoney($goodsListTemp, $couponInfo)
  520. ->getRangeGoodsList();
  521. // 分配订单商品优惠券抵扣金额
  522. foreach ($this->goodsList as &$goods) {
  523. if (isset($rangeGoodsList[$goods['goods_id']])) {
  524. $goods['coupon_money'] = $rangeGoodsList[$goods['goods_id']]['coupon_money'] / 100;
  525. }
  526. }
  527. // 记录订单优惠券信息
  528. $this->orderData['couponId'] = $couponId;
  529. $this->orderData['couponMoney'] = helper::number2($CouponMoney->getActualReducedMoney() / 100);
  530. }
  531. /**
  532. * 验证用户选择的优惠券ID是否合法
  533. * @param int $couponId
  534. * @param $couponList
  535. * @return bool
  536. * @throws BaseException
  537. */
  538. private function verifyOrderCouponId(int $couponId, $couponList): bool
  539. {
  540. // 是否开启优惠券折扣
  541. if (!$this->checkoutRule['isCoupon']) {
  542. return false;
  543. }
  544. // 如果没有可用的优惠券,直接返回
  545. if ($couponId <= 0 || empty($couponList)) {
  546. return false;
  547. }
  548. // 判断优惠券是否存在
  549. $couponInfo = $this->getCouponInfo($couponId, $couponList);
  550. if (!$couponInfo) {
  551. throwError('未找到优惠券信息');
  552. }
  553. // 判断优惠券适用范围是否合法
  554. if (!$couponInfo['is_apply']) {
  555. throwError($couponInfo['not_apply_info']);
  556. }
  557. return true;
  558. }
  559. /**
  560. * 查找指定的优惠券信息
  561. * @param int $couponId 优惠券ID
  562. * @param array $couponList 优惠券列表
  563. * @return false|mixed
  564. */
  565. private function getCouponInfo(int $couponId, array $couponList)
  566. {
  567. return helper::getArrayItemByColumn($couponList, 'user_coupon_id', $couponId);
  568. }
  569. /**
  570. * 订单配送-快递配送
  571. * @return void
  572. * @throws \think\db\exception\DataNotFoundException
  573. * @throws \think\db\exception\DbException
  574. * @throws \think\db\exception\ModelNotFoundException
  575. */
  576. private function setOrderExpress(): void
  577. {
  578. // 设置默认数据:配送费用
  579. helper::setDataAttribute($this->goodsList, [
  580. 'expressPrice' => 0,
  581. ], true);
  582. // 当前用户收货城市id
  583. $cityId = $this->user['address_default'] ? (int)$this->user['address_default']['city_id'] : 0;
  584. // 初始化配送服务类
  585. $ExpressService = new ExpressService($cityId, $this->goodsList);
  586. // 验证商品是否在配送范围
  587. $isIntraRegion = $ExpressService->isIntraRegion();
  588. if ($cityId > 0 && $isIntraRegion == false) {
  589. $notInRuleGoodsName = $ExpressService->getNotInRuleGoodsName();
  590. $this->setError("很抱歉,您的收货地址不在商品 [{$notInRuleGoodsName}] 的配送范围内");
  591. }
  592. // 订单总运费金额
  593. $this->orderData['isIntraRegion'] = $isIntraRegion;
  594. $this->orderData['expressPrice'] = $ExpressService->getDeliveryFee();
  595. }
  596. /**
  597. * 创建新订单
  598. * @param array $order 订单信息
  599. * @return bool
  600. */
  601. public function createOrder(array $order): bool
  602. {
  603. // 表单验证
  604. if (!$this->validateOrderForm($order)) {
  605. return false;
  606. }
  607. // 创建新的订单
  608. $status = $this->model->transaction(function () use ($order) {
  609. // 创建订单事件
  610. return $this->createOrderEvent($order);
  611. });
  612. // 余额支付标记订单已支付
  613. if ($status && $order['payType'] == OrderPayTypeEnum::BALANCE) {
  614. return $this->model->onPaymentByBalance($this->model['order_no']);
  615. }
  616. return $status;
  617. }
  618. /**
  619. * 创建订单事件
  620. * @param $order
  621. * @return bool
  622. * @throws BaseException
  623. * @throws \think\db\exception\DataNotFoundException
  624. * @throws \think\db\exception\DbException
  625. * @throws \think\db\exception\ModelNotFoundException
  626. */
  627. private function createOrderEvent($order): bool
  628. {
  629. // 新增订单记录
  630. $status = $this->add($order, $this->param['remark']);
  631. if ($order['delivery'] == DeliveryTypeEnum::EXPRESS) {
  632. // 记录收货地址
  633. $this->saveOrderAddress($order['address']);
  634. }
  635. // 保存订单商品信息
  636. $this->saveOrderGoods($order);
  637. // 更新商品库存 (针对下单减库存的商品)
  638. $this->updateGoodsStockNum($order);
  639. // 设置优惠券使用状态
  640. $order['couponId'] > 0 && UserCouponModel::setIsUse((int)$order['couponId']);
  641. // 积分抵扣情况下扣除用户积分
  642. if ($order['isAllowPoints'] && $order['isUsePoints'] && $order['pointsNum'] > 0) {
  643. $describe = "用户消费:{$this->model['order_no']}";
  644. UserModel::setIncPoints($this->user['user_id'], -$order['pointsNum'], $describe);
  645. }
  646. // 获取订单详情
  647. $detail = OrderModel::getUserOrderDetail((int)$this->model['order_id']);
  648. return $status;
  649. }
  650. /**
  651. * 构建支付请求的参数
  652. * @return array
  653. * @throws BaseException
  654. * @throws \think\db\exception\DataNotFoundException
  655. * @throws \think\db\exception\DbException
  656. * @throws \think\db\exception\ModelNotFoundException
  657. */
  658. public function onOrderPayment(): array
  659. {
  660. return PaymentService::orderPayment($this->model, $this->param['payType']);
  661. }
  662. /**
  663. * 表单验证 (订单提交)
  664. * @param array $order 订单信息
  665. * @return bool
  666. */
  667. private function validateOrderForm(array $order): bool
  668. {
  669. if ($order['delivery'] == DeliveryTypeEnum::EXPRESS) {
  670. if (empty($order['address'])) {
  671. $this->error = '您还没有选择配送地址';
  672. return false;
  673. }
  674. }
  675. // 余额支付时判断用户余额是否足够
  676. if ($order['payType'] == OrderPayTypeEnum::BALANCE) {
  677. if ($this->user['balance'] < $order['orderPayPrice']) {
  678. $this->error = '您的余额不足,无法使用余额支付';
  679. return false;
  680. }
  681. }
  682. return true;
  683. }
  684. /**
  685. * 当前订单是否存在和使用积分抵扣
  686. * @param $order
  687. * @return bool
  688. */
  689. private function isExistPointsDeduction($order): bool
  690. {
  691. return $order['isAllowPoints'] && $order['isUsePoints'];
  692. }
  693. /**
  694. * 新增订单记录
  695. * @param $order
  696. * @param string $remark
  697. * @return bool|false
  698. */
  699. private function add($order, string $remark = ''): bool
  700. {
  701. // 当前订单是否存在和使用积分抵扣
  702. $isExistPointsDeduction = $this->isExistPointsDeduction($order);
  703. // 订单数据
  704. $data = [
  705. 'user_id' => $this->user['user_id'],
  706. 'order_no' => $this->model->orderNo(),
  707. 'total_price' => $order['orderTotalPrice'],
  708. 'order_price' => $order['orderPrice'],
  709. 'coupon_id' => $order['couponId'],
  710. 'coupon_money' => $order['couponMoney'],
  711. 'points_money' => $isExistPointsDeduction ? $order['pointsMoney'] : 0.00,
  712. 'points_num' => $isExistPointsDeduction ? $order['pointsNum'] : 0,
  713. 'pay_price' => $order['orderPayPrice'],
  714. 'delivery_type' => $order['delivery'],
  715. 'pay_type' => $order['payType'],
  716. 'buyer_remark' => trim($remark),
  717. 'order_source' => $this->orderSource['source'],
  718. 'order_source_id' => $this->orderSource['source_id'],
  719. 'points_bonus' => $order['pointsBonus'],
  720. 'order_status' => OrderStatusEnum::NORMAL,
  721. 'platform' => getPlatform(),
  722. 'store_id' => $this->storeId,
  723. ];
  724. if ($order['delivery'] == DeliveryTypeEnum::EXPRESS) {
  725. $data['express_price'] = $order['expressPrice'];
  726. }
  727. // 保存订单记录
  728. return $this->model->save($data);
  729. }
  730. /**
  731. * 保存订单商品信息
  732. * @param $order
  733. * @return void
  734. */
  735. private function saveOrderGoods($order): void
  736. {
  737. // 当前订单是否存在和使用积分抵扣
  738. $isExistPointsDeduction = $this->isExistPointsDeduction($order);
  739. // 订单商品列表
  740. $goodsList = [];
  741. foreach ($order['goodsList'] as $goods) {
  742. /* @var GoodsModel $goods */
  743. $item = [
  744. 'user_id' => $this->user['user_id'],
  745. 'store_id' => $this->storeId,
  746. 'goods_id' => $goods['goods_id'],
  747. 'goods_name' => $goods['goods_name'],
  748. 'goods_no' => $goods['goods_no'] ?: '',
  749. 'image_id' => (int)current($goods['goods_images'])['file_id'],
  750. 'deduct_stock_type' => $goods['deduct_stock_type'],
  751. 'spec_type' => $goods['spec_type'],
  752. 'goods_sku_id' => $goods['skuInfo']['goods_sku_id'],
  753. 'goods_props' => $goods['skuInfo']['goods_props'] ?: '',
  754. 'content' => $goods['content'] ?? '',
  755. 'goods_sku_no' => $goods['skuInfo']['goods_sku_no'] ?: '',
  756. 'goods_price' => $goods['skuInfo']['goods_price'],
  757. 'line_price' => $goods['skuInfo']['line_price'],
  758. 'goods_weight' => $goods['skuInfo']['goods_weight'],
  759. 'is_user_grade' => (int)$goods['is_user_grade'],
  760. 'grade_ratio' => $goods['grade_ratio'],
  761. 'grade_goods_price' => $goods['grade_goods_price'],
  762. 'grade_total_money' => $goods['grade_total_money'],
  763. 'coupon_money' => $goods['coupon_money'],
  764. 'points_money' => $isExistPointsDeduction ? $goods['points_money'] : 0.00,
  765. 'points_num' => $isExistPointsDeduction ? $goods['points_num'] : 0,
  766. 'points_bonus' => $goods['points_bonus'],
  767. 'total_num' => $goods['total_num'],
  768. 'total_price' => $goods['total_price'],
  769. 'total_pay_price' => $goods['total_pay_price']
  770. ];
  771. // 记录订单商品来源id
  772. $item['goods_source_id'] = isset($goods['goods_source_id']) ? $goods['goods_source_id'] : 0;
  773. $goodsList[] = $item;
  774. }
  775. $this->model->goods()->saveAll($goodsList) !== false;
  776. }
  777. /**
  778. * 更新商品库存 (针对下单减库存的商品)
  779. * @param $order
  780. * @return void
  781. */
  782. private function updateGoodsStockNum($order): void
  783. {
  784. StockFactory::getFactory($this->model['order_source'])->updateGoodsStock($order['goodsList']);
  785. }
  786. /**
  787. * 记录收货地址
  788. * @param $address
  789. * @return void
  790. */
  791. private function saveOrderAddress($address): void
  792. {
  793. $this->model->address()->save([
  794. 'user_id' => $this->user['user_id'],
  795. 'store_id' => $this->storeId,
  796. 'name' => $address['name'],
  797. 'phone' => $address['phone'],
  798. 'province_id' => $address['province_id'],
  799. 'city_id' => $address['city_id'],
  800. 'region_id' => $address['region_id'],
  801. 'detail' => $address['detail'],
  802. ]);
  803. }
  804. }