StoreOrderCreateServices.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\order;
  12. use app\services\coupon\StoreCouponUserServices;
  13. use app\services\pay\PayServices;
  14. use app\services\product\product\StoreCategoryServices;
  15. use app\services\wechat\WechatUserServices;
  16. use app\jobs\OrderCreateAfterJob;
  17. use app\jobs\ProductLogJob;
  18. use crmeb\utils\Arr;
  19. use app\services\BaseServices;
  20. use app\jobs\UnpaidOrderSend;
  21. use crmeb\services\CacheService;
  22. use app\dao\order\StoreOrderDao;
  23. use app\services\user\UserServices;
  24. use app\jobs\UnpaidOrderCancelJob;
  25. use think\exception\ValidateException;
  26. use crmeb\services\SystemConfigService;
  27. use app\services\user\UserBillServices;
  28. use app\services\user\UserAddressServices;
  29. use app\services\activity\StoreBargainServices;
  30. use app\services\activity\StoreSeckillServices;
  31. use app\services\system\store\SystemStoreServices;
  32. use app\services\activity\StoreCombinationServices;
  33. use app\services\product\product\StoreProductServices;
  34. /**
  35. * 订单创建
  36. * Class StoreOrderCreateServices
  37. * @package app\services\order
  38. */
  39. class StoreOrderCreateServices extends BaseServices
  40. {
  41. /**
  42. * StoreOrderCreateServices constructor.
  43. * @param StoreOrderDao $dao
  44. */
  45. public function __construct(StoreOrderDao $dao)
  46. {
  47. $this->dao = $dao;
  48. }
  49. /**
  50. * 使用雪花算法生成订单ID
  51. * @return string
  52. * @throws \Exception
  53. */
  54. public function getNewOrderId(string $prefix = 'wx')
  55. {
  56. $snowflake = new \Godruoyi\Snowflake\Snowflake();
  57. //32位
  58. if (PHP_INT_SIZE == 4) {
  59. $id = abs($snowflake->id());
  60. } else {
  61. $id = $snowflake->setStartTimeStamp(strtotime('2020-06-05') * 1000)->id();
  62. }
  63. return $prefix . $id;
  64. }
  65. /**
  66. * 核销订单生成核销码
  67. * @return false|string
  68. */
  69. public function getStoreCode()
  70. {
  71. list($msec, $sec) = explode(' ', microtime());
  72. $num = time() + mt_rand(10, 999999) . '' . substr($msec, 2, 3);//生成随机数
  73. if (strlen($num) < 12)
  74. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  75. else
  76. $num = substr($num, 0, 12);
  77. if ($this->dao->count(['verify_code' => $num])) {
  78. return $this->getStoreCode();
  79. }
  80. return $num;
  81. }
  82. /**
  83. * 创建订单
  84. * @param $uid
  85. * @param $key
  86. * @param $cartGroup
  87. * @param $userInfo
  88. * @param $addressId
  89. * @param $payType
  90. * @param bool $useIntegral
  91. * @param int $couponId
  92. * @param string $mark
  93. * @param int $combinationId
  94. * @param int $pinkId
  95. * @param int $seckillId
  96. * @param int $bargainId
  97. * @param int $isChannel
  98. * @param int $shippingType
  99. * @param string $real_name
  100. * @param string $phone
  101. * @param int $storeId
  102. * @param bool $news
  103. * @return mixed
  104. * @throws \Psr\SimpleCache\InvalidArgumentException
  105. * @throws \think\db\exception\DataNotFoundException
  106. * @throws \think\db\exception\DbException
  107. * @throws \think\db\exception\ModelNotFoundException
  108. */
  109. public function createOrder($uid, $key, $cartGroup, $userInfo, $addressId, $payType, $useIntegral = false, $couponId = 0, $mark = '', $combinationId = 0, $pinkId = 0, $seckillId = 0, $bargainId = 0, $isChannel = 0, $shippingType = 1, $real_name = '', $phone = '', $storeId = 0, $news = false)
  110. {
  111. /** @var StoreOrderComputedServices $computedServices */
  112. $computedServices = app()->make(StoreOrderComputedServices::class);
  113. $priceData = $computedServices->computedOrder($uid, $key, $cartGroup, $addressId, $payType, $useIntegral, $couponId, true, $shippingType);
  114. /** @var WechatUserServices $wechatServices */
  115. $wechatServices = app()->make(WechatUserServices::class);
  116. /** @var UserAddressServices $addressServices */
  117. $addressServices = app()->make(UserAddressServices::class);
  118. if ($shippingType === 1) {
  119. if (!$addressId) {
  120. throw new ValidateException('请选择收货地址!');
  121. }
  122. if (!$addressInfo = $addressServices->getOne(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]))
  123. throw new ValidateException('地址选择有误!');
  124. $addressInfo = $addressInfo->toArray();
  125. } else {
  126. if ((!$real_name || !$phone)) {
  127. throw new ValidateException('请填写姓名和电话');
  128. }
  129. $addressInfo['real_name'] = $real_name;
  130. $addressInfo['phone'] = $phone;
  131. $addressInfo['province'] = '';
  132. $addressInfo['city'] = '';
  133. $addressInfo['district'] = '';
  134. $addressInfo['detail'] = '';
  135. }
  136. $cartInfo = $cartGroup['cartInfo'];
  137. $priceGroup = $cartGroup['priceGroup'];
  138. $cartIds = [];
  139. $totalNum = 0;
  140. $gainIntegral = 0;
  141. foreach ($cartInfo as $cart) {
  142. $cartIds[] = $cart['id'];
  143. $totalNum += $cart['cart_num'];
  144. if (!$seckillId) $seckillId = $cart['seckill_id'];
  145. if (!$bargainId) $bargainId = $cart['bargain_id'];
  146. if (!$combinationId) $combinationId = $cart['combination_id'];
  147. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul((string)$cart['cart_num'], (string)$cart['productInfo']['give_integral'], 0) : 0;
  148. $gainIntegral = bcadd((string)$gainIntegral, (string)$cartInfoGainIntegral, 0);
  149. }
  150. $deduction = $seckillId || $bargainId || $combinationId;
  151. if ($deduction) {
  152. $couponId = 0;
  153. $useIntegral = false;
  154. $systemPayType = PayServices::PAY_TYPE;
  155. unset($systemPayType['offline']);
  156. if ($payType != 'pc' && !array_key_exists($payType, $systemPayType)) {
  157. throw new ValidateException('营销商品不能使用线下支付!');
  158. }
  159. }
  160. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  161. $storeSelfMention = sys_config('store_self_mention') ?? 0;
  162. if (!$storeSelfMention) $shippingType = 1;
  163. $orderInfo = [
  164. 'uid' => $uid,
  165. 'order_id' => $this->getNewOrderId(),
  166. 'real_name' => $addressInfo['real_name'],
  167. 'user_phone' => $addressInfo['phone'],
  168. 'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
  169. 'cart_id' => $cartIds,
  170. 'total_num' => $totalNum,
  171. 'total_price' => $priceGroup['totalPrice'],
  172. 'total_postage' => $priceGroup['storePostage'],
  173. 'coupon_id' => $couponId,
  174. 'coupon_price' => $priceData['coupon_price'],
  175. 'pay_price' => $priceData['pay_price'],
  176. 'pay_postage' => $priceData['pay_postage'],
  177. 'deduction_price' => $priceData['deduction_price'],
  178. 'paid' => 0,
  179. 'pay_type' => $payType,
  180. 'use_integral' => $priceData['usedIntegral'],
  181. 'gain_integral' => $gainIntegral,
  182. 'mark' => htmlspecialchars($mark),
  183. 'combination_id' => $combinationId,
  184. 'pink_id' => $pinkId,
  185. 'seckill_id' => $seckillId,
  186. 'bargain_id' => $bargainId,
  187. 'cost' => $priceGroup['costPrice'],
  188. 'is_channel' => $isChannel,
  189. 'add_time' => time(),
  190. 'unique' => $key,
  191. 'shipping_type' => $shippingType,
  192. 'channel_type' => $userInfo['user_type'],
  193. 'province' => $userInfo['user_type'] == 'wecaht' || $userInfo['user_type'] == 'routine' ? $wechatServices->value(['uid' => $uid, 'user_type' => $userInfo['user_type']], 'province') : ''
  194. ];
  195. if ($shippingType === 2) {
  196. $orderInfo['verify_code'] = $this->getStoreCode();
  197. /** @var SystemStoreServices $storeServices */
  198. $storeServices = app()->make(SystemStoreServices::class);
  199. $orderInfo['store_id'] = $storeServices->getStoreDispose($storeId, 'id');
  200. if (!$orderInfo['store_id']) {
  201. throw new ValidateException('暂无门店无法选择门店自提');
  202. }
  203. }
  204. /** @var StoreOrderCartInfoServices $cartServices */
  205. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  206. /** @var StoreSeckillServices $seckillServices */
  207. $seckillServices = app()->make(StoreSeckillServices::class);
  208. $priceData['coupon_id'] = $couponId;
  209. $order = $this->transaction(function () use ($cartIds, $orderInfo, $cartInfo, $key, $userInfo, $useIntegral, $priceData, $combinationId, $seckillId, $bargainId, $cartServices, $seckillServices, $uid) {
  210. //创建订单
  211. $order = $this->dao->save($orderInfo);
  212. if (!$order) {
  213. throw new ValidateException('订单生成失败!');
  214. }
  215. //记录自提人电话和姓名
  216. /** @var UserServices $userService */
  217. $userService = app()->make(UserServices::class);
  218. $userService->update(['uid' => $uid], ['real_name' => $orderInfo['real_name'], 'record_phone' => $orderInfo['user_phone']]);
  219. //占用库存
  220. $seckillServices->occupySeckillStock($cartInfo, $key);
  221. //积分抵扣
  222. $this->deductIntegral($userInfo, $useIntegral, $priceData, (int)$userInfo['uid'], $key);
  223. //扣库存
  224. $this->decGoodsStock($cartInfo, $combinationId, $seckillId, $bargainId);
  225. //保存购物车商品信息
  226. $cartServices->setCartInfo($order['id'], $this->computeOrderProductTruePrice($cartInfo, $priceData));
  227. return $order;
  228. });
  229. //订单创建成功后置事件
  230. event('order.orderCreateAfter', [$order, compact('cartInfo', 'addressId', 'cartIds', 'news'), $uid, $key, $combinationId, $seckillId, $bargainId]);
  231. return $order;
  232. }
  233. /**
  234. * 抵扣积分
  235. * @param array $userInfo
  236. * @param bool $useIntegral
  237. * @param array $priceData
  238. * @param int $uid
  239. * @param string $key
  240. */
  241. public function deductIntegral(array $userInfo, bool $useIntegral, array $priceData, int $uid, string $key)
  242. {
  243. $res2 = true;
  244. if ($useIntegral && $userInfo['integral'] > 0) {
  245. /** @var UserServices $userServices */
  246. $userServices = app()->make(UserServices::class);
  247. if (!$priceData['SurplusIntegral']) {
  248. $res2 = false !== $userServices->update($uid, ['integral' => 0]);
  249. } else {
  250. $res2 = false !== $userServices->bcDec($userInfo['uid'], 'integral', $priceData['usedIntegral'], 'uid');
  251. }
  252. /** @var UserBillServices $userBillServices */
  253. $userBillServices = app()->make(UserBillServices::class);
  254. $res3 = $userBillServices->income('deduction', $uid, [
  255. 'number' => $priceData['usedIntegral'],
  256. 'deductionPrice' => $priceData['deduction_price']
  257. ], $userInfo['integral'], $key);
  258. $res2 = $res2 && false != $res3;
  259. }
  260. if (!$res2) {
  261. throw new ValidateException('使用积分抵扣失败!');
  262. }
  263. }
  264. /**
  265. * 扣库存
  266. * @param array $cartInfo
  267. * @param int $combinationId
  268. * @param int $seckillId
  269. * @param int $bargainId
  270. */
  271. public function decGoodsStock(array $cartInfo, int $combinationId, int $seckillId, int $bargainId)
  272. {
  273. $res5 = true;
  274. /** @var StoreProductServices $services */
  275. $services = app()->make(StoreProductServices::class);
  276. /** @var StoreSeckillServices $seckillServices */
  277. $seckillServices = app()->make(StoreSeckillServices::class);
  278. /** @var StoreCombinationServices $pinkServices */
  279. $pinkServices = app()->make(StoreCombinationServices::class);
  280. /** @var StoreBargainServices $bargainServices */
  281. $bargainServices = app()->make(StoreBargainServices::class);
  282. foreach ($cartInfo as $cart) {
  283. //减库存加销量
  284. if ($combinationId) $res5 = $res5 && $pinkServices->decCombinationStock((int)$cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  285. else if ($seckillId) $res5 = $res5 && $seckillServices->decSeckillStock((int)$cart['cart_num'], $seckillId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  286. else if ($bargainId) $res5 = $res5 && $bargainServices->decBargainStock((int)$cart['cart_num'], $bargainId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  287. else $res5 = $res5 && $services->decProductStock((int)$cart['cart_num'], (int)$cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  288. }
  289. if (!$res5) {
  290. throw new ValidateException('扣库存失败!');
  291. }
  292. }
  293. /**
  294. * 订单创建后的后置事件
  295. * @param UserAddressServices $addressServices
  296. * @param $order
  297. * @param array $group
  298. */
  299. public function orderCreateAfter($order, array $group)
  300. {
  301. /** @var UserAddressServices $addressServices */
  302. $addressServices = app()->make(UserAddressServices::class);
  303. //设置用户默认地址
  304. if (!$addressServices->be(['is_default' => 1, 'uid' => $order['uid']])) {
  305. $addressServices->setDefaultAddress($group['addressId'], $order['uid']);
  306. }
  307. //删除购物车
  308. if ($group['news']) {
  309. array_map(function ($key) {
  310. CacheService::redisHandler()->delete($key);
  311. }, $group['cartIds']);
  312. } else {
  313. /** @var StoreCartServices $cartServices */
  314. $cartServices = app()->make(StoreCartServices::class);
  315. $cartServices->deleteCartStatus($group['cartIds']);
  316. }
  317. }
  318. /**
  319. * 计算订单每个商品真实付款价格
  320. * @param array $cartInfo
  321. * @param array $priceData
  322. * @return array
  323. */
  324. public function computeOrderProductTruePrice(array $cartInfo, array $priceData)
  325. {
  326. $cartInfo = $this->computeOrderProductCoupon($cartInfo, $priceData);
  327. $cartInfo = $this->computeOrderProductIntegral($cartInfo, $priceData);
  328. foreach ($cartInfo as &$cart) {
  329. $coupon_price = $cart['coupon_price'] ?? 0;
  330. $integral_price = $cart['integral_price'] ?? 0;
  331. if ($coupon_price) {
  332. $cart['truePrice'] = $cart['truePrice'] > $coupon_price ? bcsub((string)$cart['truePrice'], (string)$coupon_price, 2) : 0;
  333. }
  334. if ($integral_price) {
  335. $cart['truePrice'] = $cart['truePrice'] > $integral_price ? bcsub((string)$cart['truePrice'], (string)$integral_price, 2) : 0;
  336. }
  337. }
  338. return $cartInfo;
  339. }
  340. /**
  341. * 计算订单商品积分实际抵扣金额
  342. * @param array $cartInfo
  343. * @param array $priceData
  344. */
  345. public function computeOrderProductIntegral(array $cartInfo, array $priceData)
  346. {
  347. $total_price = 0.00;
  348. $compute_price = 0.00;
  349. $integral_price = 0.00;
  350. $count = 0;
  351. $where = $priceData['deduction_price'] ? true : false;
  352. if ($where) {
  353. foreach ($cartInfo as $cart) {
  354. $total_price += bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 2);
  355. $count++;
  356. }
  357. }
  358. foreach ($cartInfo as &$cart) {
  359. if ($where) {
  360. if ($count > 1) {
  361. $integral_price = bcmul((string)bcdiv((string)$cart['truePrice'], (string)$total_price, 4), (string)$priceData['deduction_price'], 2);
  362. $compute_price += bcmul((string)$integral_price, (string)$cart['cart_num'], 2);
  363. } else {
  364. $integral_price = bcdiv((string)bcsub((string)$priceData['deduction_price'], $compute_price, 2), $cart['cart_num'], 2);
  365. }
  366. $count--;
  367. }
  368. $cart['integral_price'] = $integral_price;
  369. }
  370. return $cartInfo;
  371. }
  372. /**
  373. * 计算订单商品优惠券实际抵扣金额
  374. * @param array $cartInfo
  375. * @param array $priceData
  376. */
  377. public function computeOrderProductCoupon(array $cartInfo, array $priceData)
  378. {
  379. $count = 0;
  380. $total_price = 0.00;
  381. $compute_price = 0.00;
  382. $coupon_price = 0.00;
  383. $where = false;
  384. if ($priceData['coupon_id'] && $priceData['coupon_price']) {
  385. /** @var StoreCouponUserServices $couponServices */
  386. $couponServices = app()->make(StoreCouponUserServices::class);
  387. $couponInfo = $couponServices->getOne(['id' => $priceData['coupon_id']], '*', ['issue']);
  388. if ($couponInfo) {
  389. $type = $couponInfo['applicable_type'] ?? 0;
  390. switch ($type) {
  391. case 0:
  392. case 3:
  393. foreach ($cartInfo as $cart) {
  394. $total_price += bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 2);
  395. $count++;
  396. }
  397. foreach ($cartInfo as &$cart) {
  398. if ($count > 1) {
  399. $coupon_price = bcmul((string)bcdiv((string)$cart['truePrice'], (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  400. $compute_price += bcmul((string)$coupon_price, (string)$cart['cart_num'], 2);
  401. } else {
  402. $coupon_price = bcdiv((string)bcsub((string)$couponInfo['coupon_price'], $compute_price, 2), $cart['cart_num'], 2);
  403. }
  404. $count--;
  405. $cart['coupon_price'] = $coupon_price;
  406. }
  407. break;
  408. case 1://品类券
  409. /** @var StoreCategoryServices $storeCategoryServices */
  410. $storeCategoryServices = app()->make(StoreCategoryServices::class);
  411. $cateGorys = $storeCategoryServices->getAllById((int)$couponInfo['category_id']);
  412. if ($cateGorys) {
  413. $cateIds = array_column($cateGorys, 'id');
  414. foreach ($cartInfo as $cart) {
  415. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  416. $total_price += bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 2);
  417. $count++;
  418. }
  419. }
  420. foreach ($cartInfo as &$cart) {
  421. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  422. if ($count > 1) {
  423. $coupon_price = bcmul((string)bcdiv((string)$cart['truePrice'], (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  424. $compute_price += bcmul((string)$coupon_price, (string)$cart['cart_num'], 2);
  425. } else {
  426. $coupon_price = bcdiv((string)bcsub((string)$couponInfo['coupon_price'], $compute_price, 2), $cart['cart_num'], 2);
  427. }
  428. $count--;
  429. } else {
  430. $coupon_price = 0;
  431. }
  432. $cart['coupon_price'] = $coupon_price;
  433. }
  434. }
  435. break;
  436. case 2:
  437. foreach ($cartInfo as $cart) {
  438. if (isset($cart['product_id']) && in_array($cart['product_id'], explode(',', $couponInfo['product_id']))) {
  439. $total_price += bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 2);
  440. $count++;
  441. }
  442. }
  443. foreach ($cartInfo as &$cart) {
  444. if (isset($cart['product_id']) && in_array($cart['product_id'], explode(',', $couponInfo['product_id']))) {
  445. if ($count > 1) {
  446. $coupon_price = bcmul((string)bcdiv((string)$cart['truePrice'], (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  447. $compute_price += bcmul((string)$coupon_price, (string)$cart['cart_num'], 2);
  448. } else {
  449. $coupon_price = bcdiv((string)bcsub((string)$couponInfo['coupon_price'], $compute_price, 2), $cart['cart_num'], 2);
  450. }
  451. $count--;
  452. } else {
  453. $coupon_price = 0;
  454. }
  455. $cart['coupon_price'] = $coupon_price;
  456. }
  457. break;
  458. }
  459. }
  460. }
  461. return $cartInfo;
  462. }
  463. }