Checkout.php 31 KB

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