Checkout.php 31 KB

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