Checkout.php 31 KB

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