Checkout.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. <?php
  2. namespace app\api\service\sharing\order;
  3. use app\api\model\sharing\Order as OrderModel;
  4. use app\api\model\User as UserModel;
  5. use app\api\model\Setting as SettingModel;
  6. use app\api\model\sharing\Goods as GoodsModel;
  7. use app\api\model\sharing\GoodsSku as GoodsSkuModel;
  8. use app\api\model\sharing\Active as ActiveModel;
  9. use app\api\model\sharing\Setting as SharingSettingModel;
  10. use app\api\model\store\Shop as ShopModel;
  11. use app\api\model\UserCoupon as UserCouponModel;
  12. use app\api\model\dealer\Order as DealerOrderModel;
  13. use app\api\service\User as UserService;
  14. use app\api\service\Payment as PaymentService;
  15. use app\api\service\coupon\GoodsDeduct as GoodsDeductService;
  16. use app\api\service\points\GoodsDeduct as PointsDeductService;
  17. use app\common\library\helper;
  18. use app\common\enum\OrderType as OrderTypeEnum;
  19. use app\common\enum\order\PayType as PayTypeEnum;
  20. use app\common\enum\DeliveryType as DeliveryTypeEnum;
  21. use app\common\enum\order\OrderSource as OrderSourceEnum;
  22. use app\common\service\delivery\Express as ExpressService;
  23. use app\common\exception\BaseException;
  24. /**
  25. * 订单结算台服务类
  26. * Class Checkout
  27. * @package app\api\service\order
  28. */
  29. class Checkout
  30. {
  31. /* $model OrderModel 订单模型 */
  32. public $model;
  33. // 当前小程序id
  34. private $wxapp_id;
  35. /* @var UserModel $user 当前用户信息 */
  36. private $user;
  37. // 订单结算商品列表
  38. private $goodsList = [];
  39. // 错误信息
  40. protected $error;
  41. /**
  42. * 订单结算api参数
  43. * @var array
  44. */
  45. private $param = [
  46. 'active_id' => 0, // 参与的拼单id
  47. 'delivery' => null, // 配送方式
  48. 'shop_id' => 0, // 自提门店id
  49. 'linkman' => '', // 自提联系人
  50. 'phone' => '', // 自提联系电话
  51. 'coupon_id' => 0, // 优惠券id
  52. 'is_use_points' => 0, // 是否使用积分抵扣
  53. 'remark' => '', // 买家留言
  54. 'pay_type' => PayTypeEnum::WECHAT, // 支付方式
  55. 'order_type' => 20, // 下单类型 10 => 单独购买,20 => 拼团
  56. ];
  57. /**
  58. * 订单结算的规则
  59. * @var array
  60. */
  61. private $checkoutRule = [
  62. 'is_user_grade' => true, // 会员等级折扣
  63. 'is_coupon' => true, // 优惠券抵扣
  64. 'is_use_points' => true, // 是否使用积分抵扣
  65. 'is_dealer' => true, // 是否开启分销
  66. ];
  67. /**
  68. * 订单来源
  69. * @var array
  70. */
  71. private $orderSource = [
  72. 'source' => OrderSourceEnum::MASTER,
  73. 'source_id' => 0,
  74. ];
  75. /**
  76. * 订单结算数据
  77. * @var array
  78. */
  79. private $orderData = [];
  80. /**
  81. * 构造函数
  82. * Checkout constructor.
  83. */
  84. public function __construct()
  85. {
  86. $this->model = new OrderModel;
  87. $this->wxapp_id = OrderModel::$wxapp_id;
  88. }
  89. /**
  90. * 设置结算台请求的参数
  91. * @param $param
  92. * @return array
  93. */
  94. public function setParam($param)
  95. {
  96. $this->param = array_merge($this->param, $param);
  97. return $this->getParam();
  98. }
  99. /**
  100. * 获取结算台请求的参数
  101. * @return array
  102. */
  103. public function getParam()
  104. {
  105. return $this->param;
  106. }
  107. /**
  108. * 订单结算的规则
  109. * @param $data
  110. */
  111. public function setCheckoutRule($data)
  112. {
  113. $this->checkoutRule = array_merge($this->checkoutRule, $data);
  114. }
  115. /**
  116. * 设置订单来源(普通订单、砍价订单)
  117. * @param $data
  118. */
  119. public function setOrderSource($data)
  120. {
  121. $this->orderSource = array_merge($this->orderSource, $data);
  122. }
  123. /**
  124. * 订单确认-砍价活动
  125. * @param $user
  126. * @param $goodsList
  127. * @return array
  128. * @throws BaseException
  129. * @throws \think\Exception
  130. * @throws \think\db\exception\DataNotFoundException
  131. * @throws \think\db\exception\ModelNotFoundException
  132. * @throws \think\exception\DbException
  133. */
  134. public function onCheckout($user, $goodsList)
  135. {
  136. $this->user = $user;
  137. $this->goodsList = $goodsList;
  138. // 订单确认-立即购买
  139. return $this->checkout();
  140. }
  141. /**
  142. * 订单结算台
  143. * @return array
  144. * @throws BaseException
  145. * @throws \think\Exception
  146. * @throws \think\db\exception\DataNotFoundException
  147. * @throws \think\db\exception\ModelNotFoundException
  148. * @throws \think\exception\DbException
  149. */
  150. private function checkout()
  151. {
  152. // 整理订单数据
  153. $this->orderData = $this->getOrderData();
  154. // 验证商品状态, 是否允许购买
  155. $this->validateGoodsList();
  156. // 订单商品总数量
  157. $orderTotalNum = helper::getArrayColumnSum($this->goodsList, 'total_num');
  158. // 设置订单商品会员折扣价
  159. $this->setOrderGoodsGradeMoney();
  160. // 设置订单商品总金额(不含优惠折扣)
  161. $this->setOrderTotalPrice();
  162. // 计算可用积分抵扣
  163. $this->setOrderPoints();
  164. // 当前用户可用的优惠券列表
  165. $couponList = $this->getUserCouponList($this->orderData['order_total_price']);
  166. // 计算优惠券抵扣
  167. $this->setOrderCouponMoney($couponList, $this->param['coupon_id']);
  168. // 计算订单商品的实际付款金额
  169. $this->setOrderGoodsPayPrice();
  170. // 设置默认配送方式
  171. !$this->param['delivery'] && $this->param['delivery'] = current(SettingModel::getItem('store')['delivery_type']);
  172. // 处理配送方式
  173. if ($this->param['delivery'] == DeliveryTypeEnum::EXPRESS) {
  174. $this->setOrderExpress();
  175. } elseif ($this->param['delivery'] == DeliveryTypeEnum::EXTRACT) {
  176. $this->param['shop_id'] > 0 && $this->orderData['extract_shop'] = ShopModel::detail($this->param['shop_id']);
  177. }
  178. // 计算订单最终金额
  179. $this->setOrderPayPrice();
  180. // 计算订单积分赠送数量
  181. $this->setOrderPointsBonus();
  182. // 返回订单数据
  183. return array_merge([
  184. 'goods_list' => array_values($this->goodsList), // 商品信息
  185. 'order_total_num' => $orderTotalNum, // 商品总数量
  186. 'coupon_list' => array_values($couponList), // 优惠券列表
  187. 'has_error' => $this->hasError(),
  188. 'error_msg' => $this->getError(),
  189. ], $this->orderData);
  190. }
  191. /**
  192. * 计算订单可用积分抵扣
  193. * @return bool
  194. */
  195. private function setOrderPoints()
  196. {
  197. // 设置默认的商品积分抵扣信息
  198. $this->setDefaultGoodsPoints();
  199. // 积分设置
  200. $setting = SettingModel::getItem('points');
  201. // 条件:后台开启下单使用积分抵扣
  202. if (!$setting['is_shopping_discount'] || !$this->checkoutRule['is_use_points']) {
  203. return false;
  204. }
  205. // 条件:订单金额满足[?]元
  206. if (helper::bccomp($setting['discount']['full_order_price'], $this->orderData['order_total_price']) === 1) {
  207. return false;
  208. }
  209. // 计算订单商品最多可抵扣的积分数量
  210. $this->setOrderGoodsMaxPointsNum();
  211. // 订单最多可抵扣的积分总数量
  212. $maxPointsNumCount = helper::getArrayColumnSum($this->goodsList, 'max_points_num');
  213. // 实际可抵扣的积分数量
  214. $actualPointsNum = min($maxPointsNumCount, $this->user['points']);
  215. if ($actualPointsNum < 1) {
  216. return false;
  217. }
  218. // 计算订单商品实际抵扣的积分数量和金额
  219. $GoodsDeduct = new PointsDeductService($this->goodsList);
  220. $GoodsDeduct->setGoodsPoints($maxPointsNumCount, $actualPointsNum);
  221. // 积分抵扣总金额
  222. $orderPointsMoney = helper::getArrayColumnSum($this->goodsList, 'points_money');
  223. $this->orderData['points_money'] = helper::number2($orderPointsMoney);
  224. // 积分抵扣总数量
  225. $this->orderData['points_num'] = $actualPointsNum;
  226. // 允许积分抵扣
  227. $this->orderData['is_allow_points'] = true;
  228. return true;
  229. }
  230. /**
  231. * 计算订单商品最多可抵扣的积分数量
  232. * @return bool
  233. */
  234. private function setOrderGoodsMaxPointsNum()
  235. {
  236. // 积分设置
  237. $setting = SettingModel::getItem('points');
  238. foreach ($this->goodsList as &$goods) {
  239. // 商品不允许积分抵扣
  240. if (!$goods['is_points_discount']) continue;
  241. // 积分抵扣比例
  242. $deductionRatio = helper::bcdiv($setting['discount']['max_money_ratio'], 100);
  243. // 最多可抵扣的金额
  244. $maxPointsMoney = helper::bcmul($goods['total_price'], $deductionRatio);
  245. // 最多可抵扣的积分数量
  246. $goods['max_points_num'] = helper::bcdiv($maxPointsMoney, $setting['discount']['discount_ratio'], 0);
  247. }
  248. return true;
  249. }
  250. /**
  251. * 设置默认的商品积分抵扣信息
  252. * @return bool
  253. */
  254. private function setDefaultGoodsPoints()
  255. {
  256. foreach ($this->goodsList as &$goods) {
  257. // 最多可抵扣的积分数量
  258. $goods['max_points_num'] = 0;
  259. // 实际抵扣的积分数量
  260. $goods['points_num'] = 0;
  261. // 实际抵扣的金额
  262. $goods['points_money'] = 0.00;
  263. }
  264. return true;
  265. }
  266. /**
  267. * 整理订单数据(结算台初始化)
  268. * @return array
  269. */
  270. private function getOrderData()
  271. {
  272. // 系统支持的配送方式 (后台设置)
  273. $deliveryType = SettingModel::getItem('store')['delivery_type'];
  274. // 积分设置
  275. $pointsSetting = SettingModel::getItem('points');
  276. return [
  277. // 订单类型
  278. 'order_type' => $this->param['order_type'],
  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. 'points_money' => 0.00,
  297. // 赠送的积分数量
  298. 'points_bonus' => 0,
  299. // 支付方式
  300. 'pay_type' => $this->param['pay_type'],
  301. // 系统设置
  302. 'setting' => [
  303. 'delivery' => $deliveryType, // 支持的配送方式
  304. 'points_name' => $pointsSetting['points_name'], // 积分名称
  305. 'points_describe' => $pointsSetting['describe'], // 积分说明
  306. ],
  307. // 记忆的自提联系方式
  308. 'last_extract' => UserService::getLastExtract($this->user['user_id']),
  309. // todo: 兼容处理
  310. 'deliverySetting' => $deliveryType,
  311. ];
  312. }
  313. /**
  314. * 当前用户可用的优惠券列表
  315. * @param $orderTotalPrice
  316. * @return mixed
  317. * @throws \think\db\exception\DataNotFoundException
  318. * @throws \think\db\exception\ModelNotFoundException
  319. * @throws \think\exception\DbException
  320. */
  321. private function getUserCouponList($orderTotalPrice)
  322. {
  323. // 是否开启优惠券折扣
  324. if (!$this->checkoutRule['is_coupon'] && SharingSettingModel::getItem('basic')['is_coupon']) {
  325. return [];
  326. }
  327. return UserCouponModel::getUserCouponList($this->user['user_id'], $orderTotalPrice);
  328. }
  329. /**
  330. * 验证订单商品的状态
  331. */
  332. private function validateGoodsList()
  333. {
  334. foreach ($this->goodsList as $goods) {
  335. // 判断商品是否下架
  336. if ($goods['goods_status']['value'] != 10) {
  337. $this->setError("很抱歉,商品 [{$goods['goods_name']}] 已下架");
  338. }
  339. // 判断商品库存
  340. if ($goods['total_num'] > $goods['goods_sku']['stock_num']) {
  341. $this->setError("很抱歉,商品 [{$goods['goods_name']}] 库存不足");
  342. }
  343. }
  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'] ? helper::bcmul($goods['total_pay_price'], $ratio, 0) : 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. */
  512. private function setOrderExpress()
  513. {
  514. // 设置默认数据:配送费用
  515. helper::setDataAttribute($this->goodsList, [
  516. 'express_price' => 0,
  517. ], true);
  518. // 当前用户收货城市id
  519. $cityId = $this->user['address_default'] ? $this->user['address_default']['city_id'] : null;
  520. // 初始化配送服务类
  521. $ExpressService = new ExpressService($cityId, $this->goodsList, OrderTypeEnum::SHARING);
  522. // 验证商品是否在配送范围
  523. if (!$isIntraRegion = $ExpressService->isIntraRegion()) {
  524. $notInRuleGoodsName = $ExpressService->getNotInRuleGoodsName();
  525. $this->setError("很抱歉,您的收货地址不在商品 [{$notInRuleGoodsName}] 的配送范围内");
  526. }
  527. // 订单总运费金额
  528. $this->orderData['intra_region'] = $isIntraRegion;
  529. $this->orderData['express_price'] = $ExpressService->getDeliveryFee();
  530. return true;
  531. }
  532. /**
  533. * 创建新订单
  534. * @param array $order 订单信息
  535. * @return bool
  536. * @throws \Exception
  537. */
  538. public function createOrder($order)
  539. {
  540. // 如果是参与拼单,则记录拼单id
  541. $order['active_id'] = $this->param['active_id'];
  542. // 表单验证
  543. if (!$this->validateOrderForm($order, $this->param['linkman'], $this->param['phone'])) {
  544. return false;
  545. }
  546. // 创建新的订单
  547. $status = $this->model->transaction(function () use ($order) {
  548. // 创建订单事件
  549. return $this->createOrderEvent($order);
  550. });
  551. // 余额支付标记订单已支付
  552. if ($status && $order['pay_type'] == PayTypeEnum::BALANCE) {
  553. return $this->model->onPaymentByBalance($this->model['order_no']);
  554. }
  555. return $status;
  556. }
  557. /**
  558. * 创建订单事件
  559. * @param $order
  560. * @return bool
  561. * @throws BaseException
  562. * @throws \think\exception\DbException
  563. * @throws \Exception
  564. */
  565. private function createOrderEvent($order)
  566. {
  567. // 新增订单记录
  568. $status = $this->add($order, $this->param['remark']);
  569. if ($order['delivery'] == DeliveryTypeEnum::EXPRESS) {
  570. // 记录收货地址
  571. $this->saveOrderAddress($order['address']);
  572. } elseif ($order['delivery'] == DeliveryTypeEnum::EXTRACT) {
  573. // 记录自提信息
  574. $this->saveOrderExtract($this->param['linkman'], $this->param['phone']);
  575. }
  576. // 保存订单商品信息
  577. $this->saveOrderGoods($order);
  578. // 更新商品库存 (针对下单减库存的商品)
  579. $this->updateGoodsStockNum($order['goods_list']);
  580. // 设置优惠券使用状态
  581. UserCouponModel::setIsUse($this->param['coupon_id']);
  582. // 积分抵扣情况下扣除用户积分
  583. if ($order['is_allow_points'] && $order['is_use_points'] && $order['points_num'] > 0) {
  584. $describe = "用户消费:{$this->model['order_no']}";
  585. $this->user->setIncPoints(-$order['points_num'], $describe);
  586. }
  587. // 获取订单详情
  588. $detail = OrderModel::getUserOrderDetail($this->model['order_id'], $this->user['user_id']);
  589. // 记录分销商订单
  590. if ($this->checkoutRule['is_dealer'] && SharingSettingModel::getItem('basic')['is_dealer']) {
  591. DealerOrderModel::createOrder($detail, OrderTypeEnum::SHARING);
  592. }
  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. * @throws \think\exception\DbException
  612. */
  613. private function validateOrderForm(&$order, $linkman, $phone)
  614. {
  615. if ($order['delivery'] == DeliveryTypeEnum::EXPRESS) {
  616. if (empty($order['address'])) {
  617. $this->error = '您还没有选择配送地址';
  618. return false;
  619. }
  620. }
  621. if ($order['delivery'] == DeliveryTypeEnum::EXTRACT) {
  622. if (empty($order['extract_shop'])) {
  623. $this->error = '您还没有选择自提门店';
  624. return false;
  625. }
  626. if (empty($linkman) || empty($phone)) {
  627. $this->error = '您还没有填写联系人和电话';
  628. return false;
  629. }
  630. }
  631. // 余额支付时判断用户余额是否足够
  632. if ($order['pay_type'] == PayTypeEnum::BALANCE) {
  633. if ($this->user['balance'] < $order['order_pay_price']) {
  634. $this->error = '您的余额不足,无法使用余额支付';
  635. return false;
  636. }
  637. }
  638. // 验证拼单id是否合法
  639. if ($order['active_id'] > 0) {
  640. // 拼单详情
  641. $detail = ActiveModel::detail($order['active_id']);
  642. if (empty($detail)) {
  643. $this->error = '很抱歉,拼单不存在';
  644. return false;
  645. }
  646. // 验证当前拼单是否允许加入新成员
  647. if (!$detail->checkAllowJoin()) {
  648. $this->error = $detail->getError();
  649. return false;
  650. }
  651. }
  652. return true;
  653. }
  654. /**
  655. * 当前订单是否存在和使用积分抵扣
  656. * @param $order
  657. * @return bool
  658. */
  659. private function isExistPointsDeduction($order)
  660. {
  661. return $order['is_allow_points'] && $order['is_use_points'];
  662. }
  663. /**
  664. * 新增订单记录
  665. * @param $order
  666. * @param string $remark
  667. * @return false|int
  668. */
  669. private function add(&$order, $remark = '')
  670. {
  671. // 当前订单是否存在和使用积分抵扣
  672. $isExistPointsDeduction = $this->isExistPointsDeduction($order);
  673. // 订单数据
  674. $data = [
  675. 'user_id' => $this->user['user_id'],
  676. 'order_type' => $order['order_type'],
  677. 'active_id' => $order['active_id'],
  678. 'order_no' => $this->model->orderNo(),
  679. 'total_price' => $order['order_total_price'],
  680. 'order_price' => $order['order_price'],
  681. 'coupon_id' => $order['coupon_id'],
  682. 'coupon_money' => $order['coupon_money'],
  683. 'points_money' => $isExistPointsDeduction ? $order['points_money'] : 0.00,
  684. 'points_num' => $isExistPointsDeduction ? $order['points_num'] : 0,
  685. 'pay_price' => $order['order_pay_price'],
  686. 'delivery_type' => $order['delivery'],
  687. 'pay_type' => $order['pay_type'],
  688. 'buyer_remark' => trim($remark),
  689. // 'order_source' => $this->orderSource['source'],
  690. // 'order_source_id' => $this->orderSource['source_id'],
  691. 'points_bonus' => $order['points_bonus'],
  692. 'wxapp_id' => $this->wxapp_id,
  693. ];
  694. if ($order['delivery'] == DeliveryTypeEnum::EXPRESS) {
  695. $data['express_price'] = $order['express_price'];
  696. } elseif ($order['delivery'] == DeliveryTypeEnum::EXTRACT) {
  697. $data['extract_shop_id'] = $order['extract_shop']['shop_id'];
  698. }
  699. // 保存订单记录
  700. return $this->model->save($data);
  701. }
  702. /**
  703. * 保存订单商品信息
  704. * @param $order
  705. * @return int
  706. */
  707. private function saveOrderGoods(&$order)
  708. {
  709. // 当前订单是否存在和使用积分抵扣
  710. $isExistPointsDeduction = $this->isExistPointsDeduction($order);
  711. // 订单商品列表
  712. $goodsList = [];
  713. foreach ($order['goods_list'] as $goods) {
  714. /* @var GoodsModel $goods */
  715. $goodsList[] = [
  716. 'user_id' => $this->user['user_id'],
  717. 'wxapp_id' => $this->wxapp_id,
  718. 'goods_id' => $goods['goods_id'],
  719. 'goods_name' => $goods['goods_name'],
  720. 'image_id' => $goods['image'][0]['image_id'],
  721. 'people' => $goods['people'],
  722. 'group_time' => $goods['group_time'],
  723. 'is_alone' => $goods['is_alone'],
  724. 'deduct_stock_type' => $goods['deduct_stock_type'],
  725. 'spec_type' => $goods['spec_type'],
  726. 'spec_sku_id' => $goods['goods_sku']['spec_sku_id'],
  727. 'goods_sku_id' => $goods['goods_sku']['goods_sku_id'],
  728. 'goods_attr' => $goods['goods_sku']['goods_attr'],
  729. 'content' => $goods['content'],
  730. 'goods_no' => $goods['goods_sku']['goods_no'],
  731. 'goods_price' => $goods['goods_sku']['goods_price'],
  732. 'line_price' => $goods['goods_sku']['line_price'],
  733. 'goods_weight' => $goods['goods_sku']['goods_weight'],
  734. 'is_user_grade' => (int)$goods['is_user_grade'],
  735. 'grade_ratio' => $goods['grade_ratio'],
  736. 'grade_goods_price' => $goods['grade_goods_price'],
  737. 'grade_total_money' => $goods['grade_total_money'],
  738. 'coupon_money' => $goods['coupon_money'],
  739. 'points_money' => $isExistPointsDeduction ? $goods['points_money'] : 0.00,
  740. 'points_num' => $isExistPointsDeduction ? $goods['points_num'] : 0,
  741. 'points_bonus' => $goods['points_bonus'],
  742. 'total_num' => $goods['total_num'],
  743. 'total_price' => $goods['total_price'],
  744. 'total_pay_price' => $goods['total_pay_price'],
  745. 'is_ind_dealer' => $goods['is_ind_dealer'],
  746. 'dealer_money_type' => $goods['dealer_money_type'],
  747. 'first_money' => $goods['first_money'],
  748. 'second_money' => $goods['second_money'],
  749. 'third_money' => $goods['third_money'],
  750. ];
  751. }
  752. return $this->model->goods()->saveAll($goodsList);
  753. }
  754. /**
  755. * 更新商品库存 (针对下单减库存的商品)
  756. * @param $goods_list
  757. * @throws \Exception
  758. */
  759. private function updateGoodsStockNum($goods_list)
  760. {
  761. $deductStockData = [];
  762. foreach ($goods_list as $goods) {
  763. // 下单减库存
  764. $goods['deduct_stock_type'] == 10 && $deductStockData[] = [
  765. 'goods_sku_id' => $goods['goods_sku']['goods_sku_id'],
  766. 'stock_num' => ['dec', $goods['total_num']]
  767. ];
  768. }
  769. !empty($deductStockData) && (new GoodsSkuModel)->isUpdate()->saveAll($deductStockData);
  770. }
  771. /**
  772. * 记录收货地址
  773. * @param $address
  774. * @return false|\think\Model
  775. */
  776. private function saveOrderAddress($address)
  777. {
  778. if ($address['region_id'] == 0 && !empty($address['district'])) {
  779. $address['detail'] = $address['district'] . ' ' . $address['detail'];
  780. }
  781. return $this->model->address()->save([
  782. 'user_id' => $this->user['user_id'],
  783. 'wxapp_id' => $this->wxapp_id,
  784. 'name' => $address['name'],
  785. 'phone' => $address['phone'],
  786. 'province_id' => $address['province_id'],
  787. 'city_id' => $address['city_id'],
  788. 'region_id' => $address['region_id'],
  789. 'detail' => $address['detail'],
  790. ]);
  791. }
  792. /**
  793. * 保存上门自提联系人
  794. * @param $linkman
  795. * @param $phone
  796. * @return false|\think\Model
  797. */
  798. private function saveOrderExtract($linkman, $phone)
  799. {
  800. // 记忆上门自提联系人(缓存),用于下次自动填写
  801. UserService::setLastExtract($this->model['user_id'], trim($linkman), trim($phone));
  802. // 保存上门自提联系人(数据库)
  803. return $this->model->extract()->save([
  804. 'linkman' => trim($linkman),
  805. 'phone' => trim($phone),
  806. 'user_id' => $this->model['user_id'],
  807. 'wxapp_id' => $this->wxapp_id,
  808. ]);
  809. }
  810. /**
  811. * 设置错误信息
  812. * @param $error
  813. */
  814. protected function setError($error)
  815. {
  816. empty($this->error) && $this->error = $error;
  817. }
  818. /**
  819. * 获取错误信息
  820. * @return mixed
  821. */
  822. public function getError()
  823. {
  824. return $this->error;
  825. }
  826. /**
  827. * 是否存在错误
  828. * @return bool
  829. */
  830. public function hasError()
  831. {
  832. return !empty($this->error);
  833. }
  834. }