StoreOrderCreateServices.php 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  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\jobs\activity\StorePromotionsJob;
  13. use app\services\activity\discounts\StoreDiscountsServices;
  14. use app\services\activity\newcomer\StoreNewcomerServices;
  15. use app\services\agent\AgentLevelServices;
  16. use app\services\activity\coupon\StoreCouponUserServices;
  17. use app\services\other\CityAreaServices;
  18. use app\services\pay\PayServices;
  19. use app\services\product\branch\StoreBranchProductServices;
  20. use app\services\product\brand\StoreBrandServices;
  21. use app\services\product\category\StoreProductCategoryServices;
  22. use app\services\product\shipping\ShippingTemplatesFreeServices;
  23. use app\services\product\shipping\ShippingTemplatesRegionServices;
  24. use app\services\product\shipping\ShippingTemplatesServices;
  25. use app\services\wechat\WechatUserServices;
  26. use app\services\BaseServices;
  27. use crmeb\services\CacheService;
  28. use app\dao\order\StoreOrderDao;
  29. use app\services\user\UserServices;
  30. use crmeb\traits\ServicesTrait;
  31. use think\exception\ValidateException;
  32. use app\services\user\UserBillServices;
  33. use app\services\user\UserAddressServices;
  34. use app\services\activity\bargain\StoreBargainServices;
  35. use app\services\activity\seckill\StoreSeckillServices;
  36. use app\services\store\SystemStoreServices;
  37. use app\services\activity\combination\StoreCombinationServices;
  38. use app\services\product\product\StoreProductServices;
  39. use app\services\activity\collage\UserCollageServices;
  40. use app\services\activity\collage\UserCollagePartakeServices;
  41. use think\facade\Cache;
  42. use think\facade\Log;
  43. /**
  44. * 订单创建
  45. * Class StoreOrderCreateServices
  46. * @package app\services\order
  47. * @mixin StoreOrderDao
  48. */
  49. class StoreOrderCreateServices extends BaseServices
  50. {
  51. use ServicesTrait;
  52. /**
  53. * StoreOrderCreateServices constructor.
  54. * @param StoreOrderDao $dao
  55. */
  56. public function __construct(StoreOrderDao $dao)
  57. {
  58. $this->dao = $dao;
  59. }
  60. /**
  61. * 使用雪花算法生成订单ID
  62. * @return string
  63. * @throws \Exception
  64. */
  65. public function getNewOrderId(string $prefix = 'wx')
  66. {
  67. $snowflake = new \Godruoyi\Snowflake\Snowflake();
  68. $is_callable = function ($currentTime) {
  69. // if (is_win()) {
  70. $redis = Cache::store('redis');
  71. $swooleSequenceResolver = new \Godruoyi\Snowflake\RedisSequenceResolver($redis->handler());
  72. return $swooleSequenceResolver->sequence($currentTime);
  73. // } else {
  74. // $swooleSequenceResolver = new \Godruoyi\Snowflake\SwooleSequenceResolver();
  75. // return $swooleSequenceResolver->sequence($currentTime);
  76. // }
  77. };
  78. //32位
  79. if (PHP_INT_SIZE == 4) {
  80. $id = abs($snowflake->setSequenceResolver($is_callable)->id());
  81. } else {
  82. $id = $snowflake->setStartTimeStamp(strtotime('2020-06-05') * 1000)->setSequenceResolver($is_callable)->id();
  83. }
  84. return $prefix . $id;
  85. }
  86. /**
  87. * 核销订单生成核销码
  88. * @return false|string
  89. */
  90. public function getStoreCode()
  91. {
  92. mt_srand();
  93. [$msec, $sec] = explode(' ', microtime());
  94. $num = time() + mt_rand(10, 999999) . '' . substr($msec, 2, 3);//生成随机数
  95. if (strlen($num) < 12)
  96. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  97. else
  98. $num = substr($num, 0, 12);
  99. if ($this->dao->count(['verify_code' => $num])) {
  100. return $this->getStoreCode();
  101. }
  102. return $num;
  103. }
  104. /**
  105. * 创建订单
  106. * @param int $uid
  107. * @param string $key
  108. * @param array $cartGroup
  109. * @param int $addressId
  110. * @param string $payType
  111. * @param array $addressInfo
  112. * @param array $userInfo
  113. * @param bool $useIntegral
  114. * @param int $couponId
  115. * @param string $mark
  116. * @param int $pinkId
  117. * @param int $isChannel
  118. * @param int $shippingType
  119. * @param int $storeId
  120. * @param false $news
  121. * @param array $customForm
  122. * @param int $invoice_id
  123. * @param string $from
  124. * @return mixed
  125. * @throws \think\db\exception\DataNotFoundException
  126. * @throws \think\db\exception\DbException
  127. * @throws \think\db\exception\ModelNotFoundException
  128. */
  129. public function createOrder(int $uid, string $key, array $cartGroup, int $addressId, string $payType, array $addressInfo, array $userInfo = [], bool $useIntegral = false, $couponId = 0, $mark = '', $pinkId = 0, $isChannel = 0, $shippingType = 1, $storeId = 0, $news = false, $customForm = [], int $invoice_id = 0, string $from = '', int $collate_code_id = 0)
  130. {
  131. /** @var StoreOrderComputedServices $computedServices */
  132. $computedServices = app()->make(StoreOrderComputedServices::class);
  133. $priceData = $computedServices->computedOrder($uid, $userInfo, $cartGroup, $addressId, $payType, $useIntegral, $couponId, $shippingType);
  134. $cartInfo = $cartGroup['cartInfo'];
  135. $priceGroup = $cartGroup['priceGroup'];
  136. $cartIds = [];
  137. $totalNum = 0;
  138. $gainIntegral = 0;
  139. foreach ($cartInfo as $cart) {
  140. $cartIds[] = $cart['id'];
  141. $totalNum += $cart['cart_num'];
  142. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul((string)$cart['cart_num'], (string)$cart['productInfo']['give_integral'], 0) : 0;
  143. $gainIntegral = bcadd((string)$gainIntegral, (string)$cartInfoGainIntegral, 0);
  144. }
  145. $deduction = $cartGroup['deduction'];
  146. $other = $cartGroup['other'];
  147. $promotions_give = [
  148. 'give_integral' => $other['give_integral'] ?? 0,
  149. 'give_coupon' => $other['give_coupon'] ?? [],
  150. 'give_product' => $other['give_product'] ?? [],
  151. 'promotions' => $other['promotions'] ?? []
  152. ];
  153. $type = (int)$deduction['type'] ?? 0;
  154. $activity_id = (int)$deduction['activity_id'] ?? 0;
  155. $collateCodeId = (int)$deduction['collate_code_id'] ?? 0;
  156. $product_type = (int)$deduction['product_type'] ?? 0;
  157. /** @var UserCollageServices $collageServices */
  158. $collageServices = app()->make(UserCollageServices::class);
  159. if (in_array($type, [1, 2, 3, 5])) {
  160. $couponId = 0;
  161. if ($type != 5) $useIntegral = false;
  162. $systemPayType = PayServices::PAY_TYPE;
  163. unset($systemPayType['offline']);
  164. if ($from != 'pc' && !array_key_exists($payType, $systemPayType)) {
  165. throw new ValidateException('营销商品不能使用线下支付!');
  166. }
  167. } else if ($type == 8) {
  168. $gainIntegral = 0;
  169. } else if ($type == 9 || $type == 10) {
  170. if ($collateCodeId != $collate_code_id) throw new ValidateException('拼单/桌码ID有误!');
  171. $status = $collageServices->value(['id' => $collate_code_id], 'status');
  172. if ($status >= 2) throw new ValidateException($type == 10 ? '桌码' : '拼单' . '已生成订单!');
  173. $activity_id = $collate_code_id;
  174. }
  175. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  176. if (!sys_config('store_func_status', 1) || !sys_config('store_self_mention', 1)) $shippingType = 1;
  177. $userAddress = $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['street'] . ' ' . $addressInfo['detail'];
  178. $userLocation = $addressInfo['longitude'] . ' ' . $addressInfo['latitude'];
  179. $orderInfo = [
  180. 'uid' => $uid,
  181. 'type' => $type,
  182. 'order_id' => $this->getNewOrderId(),
  183. 'real_name' => $addressInfo['real_name'],
  184. 'user_phone' => $addressInfo['phone'],
  185. 'user_address' => $userAddress,
  186. 'user_location' => $userLocation,
  187. 'cart_id' => $cartIds,
  188. 'total_num' => $totalNum,
  189. 'total_price' => $priceGroup['sumPrice'] ?? $priceGroup['totalPrice'],
  190. 'total_postage' => $priceData['total_postage'] ?? $priceGroup['storePostage'],
  191. 'coupon_id' => $couponId,
  192. 'coupon_price' => $priceData['coupon_price'],
  193. 'first_order_price' => $priceData['first_order_price'],
  194. 'promotions_price' => $priceData['promotions_price'],
  195. 'pay_price' => $priceData['pay_price'],
  196. 'pay_postage' => $priceData['pay_postage'],
  197. 'deduction_price' => $priceData['deduction_price'],
  198. 'paid' => 0,
  199. 'pay_type' => $payType,
  200. 'use_integral' => $priceData['usedIntegral'],
  201. 'gain_integral' => $gainIntegral,
  202. 'mark' => htmlspecialchars($mark),
  203. 'product_type' => $product_type,
  204. 'activity_id' => $activity_id,
  205. 'pink_id' => $pinkId,
  206. 'cost' => $priceGroup['costPrice'],
  207. 'is_channel' => $isChannel,
  208. 'add_time' => time(),
  209. 'unique' => $key,
  210. 'shipping_type' => $shippingType,
  211. 'channel_type' => $userInfo['user_type'],
  212. 'province' => '',
  213. 'spread_uid' => 0,
  214. 'spread_two_uid' => 0,
  215. 'custom_form' => json_encode($customForm),
  216. 'promotions_give' => json_encode($promotions_give),
  217. 'give_integral' => $promotions_give['give_integral'] ?? 0,
  218. 'give_coupon' => implode(',', $promotions_give['give_coupon'] ?? []),
  219. 'store_id' => $storeId
  220. ];
  221. if ($userInfo['user_type'] == 'wechat' || $userInfo['user_type'] == 'routine') {
  222. /** @var WechatUserServices $wechatServices */
  223. $wechatServices = app()->make(WechatUserServices::class);
  224. $orderInfo['province'] = $wechatServices->value(['uid' => $uid, 'user_type' => $userInfo['user_type']], 'province') ?: '';
  225. }
  226. if ($shippingType == 2) {
  227. $orderInfo['verify_code'] = $this->getStoreCode();
  228. /** @var SystemStoreServices $storeServices */
  229. $storeServices = app()->make(SystemStoreServices::class);
  230. $orderInfo['store_id'] = $storeServices->getStoreDisposeCache($storeId, 'id');
  231. if (!$orderInfo['store_id']) {
  232. throw new ValidateException('暂无门店无法选择门店自提');
  233. }
  234. }
  235. $priceData['coupon_id'] = $couponId;
  236. $order = $this->transaction(function () use ($cartIds, $couponId, $orderInfo, $cartInfo, $key, $userInfo, $useIntegral, $priceData, $type, $activity_id, $uid, $addressId, $promotions_give, $storeId) {
  237. //创建订单
  238. $order = $this->dao->save($orderInfo);
  239. if ($couponId) {
  240. /** @var StoreCouponUserServices $couponServices */
  241. $couponServices = app()->make(StoreCouponUserServices::class);
  242. $couponServices->useCoupon($couponId, (int)$userInfo['uid'], $cartInfo, [], $storeId);
  243. }
  244. //抵扣积分
  245. $this->deductIntegral($userInfo, $useIntegral, $priceData, (int)$userInfo['uid'], $key);
  246. //扣库存
  247. $this->decGoodsStock($cartInfo, $type, $activity_id, $orderInfo['store_id'] ?? 0);
  248. //保存购物车商品信息
  249. /** @var StoreOrderCartInfoServices $cartServices */
  250. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  251. $cartServices->setCartInfo($order['id'], $cartInfo, (int)$uid, $promotions_give['promotions'] ?? []);
  252. return $order;
  253. });
  254. if (in_array($type, [9, 10]) && $collate_code_id > 0 && $order) {
  255. //关联订单和拼单、桌码
  256. $collageServices->update($collate_code_id, ['oid' => $order['id'], 'status' => 2]);
  257. /** @var UserCollagePartakeServices $partakeService */
  258. $partakeService = app()->make(UserCollagePartakeServices::class);
  259. $partakeService->update(['collate_code_id' => $collate_code_id, 'is_settle' => 0], ['status' => 0]);
  260. }
  261. //保存购物车商品信息
  262. // StoreCartJob::dispatch([$order['id'], $cartInfo, $uid, $promotions_give['promotions'] ?? []]);
  263. //扣除优惠活动赠品限量
  264. StorePromotionsJob::dispatchDo('changeGiveLimit', [$promotions_give]);
  265. //订单创建事件
  266. event('order.create', [$order, $userInfo, compact('cartInfo', 'priceData', 'addressId', 'cartIds', 'news'), compact('type', 'activity_id'), $invoice_id]);
  267. return $order;
  268. }
  269. /**
  270. * 抵扣积分
  271. * @param array $userInfo
  272. * @param bool $useIntegral
  273. * @param array $priceData
  274. * @param int $uid
  275. * @param string $key
  276. */
  277. public function deductIntegral(array $userInfo, bool $useIntegral, array $priceData, int $uid, string $key)
  278. {
  279. $res2 = true;
  280. if (sys_config('integral_ratio_status', 1) && $userInfo && $useIntegral && $userInfo['integral'] > 0) {
  281. /** @var UserServices $userServices */
  282. $userServices = app()->make(UserServices::class);
  283. if (!$priceData['SurplusIntegral']) {
  284. $integral = 0;
  285. } else {
  286. $integral = bcsub((string)$userInfo['integral'], (string)$priceData['usedIntegral']);
  287. }
  288. $res2 = false !== $userServices->update($uid, ['integral' => $integral]);
  289. /** @var UserBillServices $userBillServices */
  290. $userBillServices = app()->make(UserBillServices::class);
  291. $res3 = $userBillServices->income('deduction', $uid, [
  292. 'number' => (int)$priceData['usedIntegral'],
  293. 'deductionPrice' => $priceData['deduction_price']
  294. ], $integral, $key);
  295. $res2 = $res2 && false != $res3;
  296. }
  297. if (!$res2) {
  298. throw new ValidateException('使用积分抵扣失败!');
  299. }
  300. }
  301. /**
  302. * 扣库存
  303. * @param array $cartInfo
  304. * @param int $type
  305. * @param int $activity_id
  306. * @param int $store_id
  307. */
  308. public function decGoodsStock(array $cartInfo, int $type, int $activity_id, int $store_id = 0)
  309. {
  310. $res5 = true;
  311. /** @var StoreProductServices $services */
  312. $services = app()->make(StoreProductServices::class);
  313. /** @var StoreSeckillServices $seckillServices */
  314. $seckillServices = app()->make(StoreSeckillServices::class);
  315. /** @var StoreCombinationServices $pinkServices */
  316. $pinkServices = app()->make(StoreCombinationServices::class);
  317. /** @var StoreBargainServices $bargainServices */
  318. $bargainServices = app()->make(StoreBargainServices::class);
  319. /** @var StoreDiscountsServices $discountServices */
  320. $discountServices = app()->make(StoreDiscountsServices::class);
  321. /** @var StoreNewcomerServices $storeNewcomerServices */
  322. $storeNewcomerServices = app()->make(StoreNewcomerServices::class);
  323. try {
  324. foreach ($cartInfo as $cart) {
  325. $unique = isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '';
  326. $cart_num = (int)$cart['cart_num'];
  327. //减库存加销量
  328. switch ($type) {
  329. case 0://普通
  330. case 6://预售
  331. case 8://抽奖
  332. case 9://拼单
  333. case 10://桌码
  334. $res5 = $res5 && $services->decProductStock($cart_num, (int)$cart['productInfo']['id'], $unique, $store_id);
  335. break;
  336. case 1://秒杀
  337. $res5 = $res5 && $seckillServices->decSeckillStock($cart_num, $activity_id, $unique, $store_id);
  338. break;
  339. case 2://砍价
  340. $res5 = $res5 && $bargainServices->decBargainStock($cart_num, $activity_id, $unique, $store_id);
  341. break;
  342. case 3://拼团
  343. $res5 = $res5 && $pinkServices->decCombinationStock($cart_num, $activity_id, $unique, $store_id);
  344. break;
  345. case 5://套餐
  346. $res5 = $res5 && $discountServices->decDiscountStock($cart_num, $activity_id, (int)($cart['discount_product_id'] ?? 0), (int)($cart['product_id'] ?? 0), $unique, $store_id);
  347. break;
  348. case 7://新人专享
  349. $res5 = $res5 && $storeNewcomerServices->decNewcomerStock($cart_num, $activity_id, $unique, $store_id);
  350. break;
  351. default:
  352. $res5 = $res5 && $services->decProductStock($cart_num, (int)$cart['productInfo']['id'], $unique, $store_id);
  353. break;
  354. }
  355. }
  356. if ($type == 5 && $activity_id) {
  357. //改变套餐限量
  358. $res5 = $res5 && $discountServices->changeDiscountLimit($activity_id);
  359. }
  360. if (!$res5) {
  361. throw new ValidateException('库存不足!');
  362. }
  363. } catch (\Throwable $e) {
  364. throw new ValidateException('库存不足!');
  365. }
  366. }
  367. /**
  368. * 订单创建后的后置事件
  369. * @param UserAddressServices $addressServices
  370. * @param $order
  371. * @param array $group
  372. */
  373. public function orderCreateAfter($order, array $group)
  374. {
  375. /** @var UserAddressServices $addressServices */
  376. $addressServices = app()->make(UserAddressServices::class);
  377. //设置用户默认地址
  378. if ($order['uid'] && isset($group['addressId']) && $group['addressId'] && !$addressServices->be(['is_default' => 1, 'uid' => $order['uid']])) {
  379. $addressServices->setDefaultAddress($group['addressId'], $order['uid']);
  380. }
  381. //删除购物车
  382. if (isset($group['news']) && $group['news']) {
  383. array_map(function ($key) {
  384. CacheService::redisHandler()->delete($key);
  385. }, $group['cartIds']);
  386. } else {
  387. if (!isset($group['delCart']) || (isset($group['delCart']) && $group['delCart'] !== false)) {
  388. /** @var StoreCartServices $cartServices */
  389. $cartServices = app()->make(StoreCartServices::class);
  390. $cartServices->deleteCartStatus($group['cartIds'] ?? []);
  391. }
  392. }
  393. }
  394. /**
  395. * 计算订单每个商品真实付款价格
  396. * @param array $orderInfo
  397. * @param array $cartInfo
  398. * @param array $priceData
  399. * @param $addressId
  400. * @param int $uid
  401. * @param $userInfo
  402. * @return array
  403. */
  404. public function computeOrderProductTruePrice($orderInfo, array $cartInfo, array $priceData, $addressId, int $uid, $userInfo)
  405. {
  406. //统一放入默认数据
  407. foreach ($cartInfo as &$cart) {
  408. $cart['use_integral'] = 0;
  409. $cart['integral_price'] = 0.00;
  410. if (!isset($cart['coupon_price'])) {
  411. $cart['coupon_price'] = 0.00;
  412. }
  413. $cart['first_order_price'] = 0.00;
  414. $cart['one_brokerage'] = 0.00;
  415. $cart['two_brokerage'] = 0.00;
  416. }
  417. try {
  418. $promotionsGice = isset($orderInfo['promotions_give']) ? (is_string($orderInfo['promotions_give']) ? json_decode($orderInfo['promotions_give'], true) : $orderInfo['promotions_give']) : [];
  419. $promotions = [];
  420. if (isset($promotionsGice['promotions']) && $promotionsGice['promotions']) {
  421. $promotions = $promotionsGice['promotions'];
  422. }
  423. //$cartInfo = $this->computeOrderProductCoupon($cartInfo, $priceData, $promotions);
  424. $cartInfo = $this->computeOrderProductIntegral($cartInfo, $priceData);
  425. // $cartInfo = $this->computeOrderProductPostage($cartInfo, $priceData);
  426. $cartInfo = $this->computeOrderProductFirstDiscount($cartInfo, $priceData);
  427. } catch (\Throwable $e) {
  428. Log::error('订单商品结算失败,File:' . $e->getFile() . ',Line:' . $e->getLine() . ',Message:' . $e->getMessage());
  429. throw new ValidateException('订单商品结算失败');
  430. }
  431. //truePice实际支付单价(存在)
  432. //几件商品总体优惠 以及积分抵扣金额
  433. foreach ($cartInfo as &$cart) {
  434. $coupon_price = $cart['coupon_price'] ?? 0;
  435. $integral_price = $cart['integral_price'] ?? 0;
  436. $first_order_price = $cart['first_order_price'] ?? 0;
  437. $cart['sum_true_price'] = bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 2);
  438. if ($coupon_price) {
  439. $cart['sum_true_price'] = bcsub((string)$cart['sum_true_price'], (string)$coupon_price, 2);
  440. $uni_coupon_price = (string)bcdiv((string)$coupon_price, (string)$cart['cart_num'], 4);
  441. $cart['truePrice'] = $cart['truePrice'] > $uni_coupon_price ? bcsub((string)$cart['truePrice'], $uni_coupon_price, 2) : 0;
  442. }
  443. if ($integral_price) {
  444. $cart['sum_true_price'] = bcsub((string)$cart['sum_true_price'], (string)$integral_price, 2);
  445. $uni_integral_price = (string)bcdiv((string)$integral_price, (string)$cart['cart_num'], 4);
  446. $cart['truePrice'] = $cart['truePrice'] > $uni_integral_price ? bcsub((string)$cart['truePrice'], $uni_integral_price, 2) : 0;
  447. }
  448. if ($first_order_price) {
  449. $cart['sum_true_price'] = bcsub((string)$cart['sum_true_price'], (string)$first_order_price, 2);
  450. $uni_first_order_price = (string)bcdiv((string)$first_order_price, (string)$cart['cart_num'], 4);
  451. $cart['truePrice'] = $cart['truePrice'] > $uni_first_order_price ? bcsub((string)$cart['truePrice'], $uni_first_order_price, 2) : 0;
  452. }
  453. }
  454. //计算佣金:1售价2实际支付金额
  455. [$cartInfo, $spread_ids] = $this->computeOrderProductBrokerage($uid, $cartInfo, $userInfo);
  456. return [$cartInfo, $spread_ids];
  457. }
  458. /**
  459. * 计算每个商品实际支付运费
  460. * @param array $cartInfo
  461. * @param array $priceData
  462. * @return array
  463. */
  464. public function computeOrderProductPostage(array $cartInfo, array $priceData, $addressId)
  465. {
  466. $storePostage = $priceData['pay_postage'] ?? 0;
  467. if ($storePostage) {
  468. /** @var UserAddressServices $addressServices */
  469. $addressServices = app()->make(UserAddressServices::class);
  470. $addr = $addressServices->getAdderssCache($addressId);
  471. if ($addr) {
  472. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  473. $cityId = $addr['city_id'] ?? 0;
  474. $ids = [];
  475. if ($cityId) {
  476. /** @var CityAreaServices $cityAreaServices */
  477. $cityAreaServices = app()->make(CityAreaServices::class);
  478. $ids = $cityAreaServices->getRelationCityIds($cityId);
  479. }
  480. $cityIds = array_merge([0], $ids);
  481. $tempIds[] = 1;
  482. foreach ($cartInfo as $key_c => $item_c) {
  483. $tempIds[] = $item_c['productInfo']['temp_id'];
  484. }
  485. $tempIds = array_unique($tempIds);
  486. /** @var ShippingTemplatesServices $shippServices */
  487. $shippServices = app()->make(ShippingTemplatesServices::class);
  488. $temp = $shippServices->getShippingColumn(['id' => $tempIds], 'type,appoint', 'id');
  489. /** @var ShippingTemplatesRegionServices $regionServices */
  490. $regionServices = app()->make(ShippingTemplatesRegionServices::class);
  491. $regions = $regionServices->getTempRegionList($tempIds, $cityIds, 'temp_id,first,first_price,continue,continue_price', 'temp_id');
  492. $temp_num = [];
  493. foreach ($cartInfo as $cart) {
  494. $tempId = $cart['productInfo']['temp_id'] ?? 1;
  495. $type = isset($temp[$tempId]['type']) ? $temp[$tempId]['type'] : $temp[1]['type'];
  496. if ($type == 1) {
  497. $num = $cart['cart_num'];
  498. } elseif ($type == 2) {
  499. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  500. } else {
  501. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  502. }
  503. $region = isset($regions[$tempId]) ? $regions[$tempId] : $regions[1];
  504. if (!isset($temp_num[$tempId])) {
  505. $temp_num[$tempId] = [
  506. 'cart_id' => [$cart['id']],
  507. 'number' => $num,
  508. 'type' => $type,
  509. 'price' => bcmul($cart['cart_num'], $cart['truePrice'], 2),
  510. 'first' => $region['first'],
  511. 'first_price' => $region['first_price'],
  512. 'continue' => $region['continue'],
  513. 'continue_price' => $region['continue_price'],
  514. 'temp_id' => $tempId
  515. ];
  516. } else {
  517. $temp_num[$tempId]['cart_id'][] = $cart['id'];
  518. $temp_num[$tempId]['number'] += $num;
  519. $temp_num[$tempId]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  520. }
  521. }
  522. $cartInfo = array_combine(array_column($cartInfo, 'id'), $cartInfo);
  523. /** @var ShippingTemplatesFreeServices $freeServices */
  524. $freeServices = app()->make(ShippingTemplatesFreeServices::class);
  525. $freeList = $freeServices->isFreeList($tempIds, $cityIds, 0, 'temp_id,number,price', 'temp_id');
  526. if ($freeList) {
  527. foreach ($temp_num as $k => $v) {
  528. if (isset($temp[$v['temp_id']]['appoint']) && $temp[$v['temp_id']]['appoint'] && isset($freeList[$v['temp_id']])) {
  529. $free = $freeList[$v['temp_id']];
  530. $condition = $free['number'] <= $v['number'];
  531. if ($free['price'] <= $v['price'] && $condition) {
  532. //免运费
  533. foreach ($v['cart_id'] as $c_id) {
  534. if (isset($cartInfo[$c_id])) $cartInfo[$c_id]['postage_price'] = 0.00;
  535. }
  536. }
  537. }
  538. }
  539. }
  540. $count = 0;
  541. $compute_price = 0.00;
  542. $total_price = 0;
  543. $postage_price = 0.00;
  544. foreach ($cartInfo as $cart) {
  545. if (isset($cart['postage_price'])) {//免运费
  546. continue;
  547. }
  548. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  549. continue;
  550. }
  551. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  552. $count++;
  553. }
  554. foreach ($cartInfo as &$cart) {
  555. if (isset($cart['postage_price'])) {//免运费
  556. continue;
  557. }
  558. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  559. continue;
  560. }
  561. if ($count > 1) {
  562. $postage_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$storePostage, 2);
  563. $compute_price = bcadd((string)$compute_price, (string)$postage_price, 2);
  564. } else {
  565. $postage_price = bcsub((string)$storePostage, $compute_price, 2);
  566. }
  567. $cart['postage_price'] = $postage_price;
  568. $count--;
  569. }
  570. $cartInfo = array_merge($cartInfo);
  571. }
  572. }
  573. return $cartInfo;
  574. }
  575. /**
  576. * 计算订单商品积分实际抵扣金额
  577. * @param array $cartInfo
  578. * @param array $priceData
  579. * @return array
  580. */
  581. public function computeOrderProductIntegral(array $cartInfo, array $priceData)
  582. {
  583. $usedIntegral = $priceData['usedIntegral'] ?? 0;
  584. $deduction_price = $priceData['deduction_price'] ?? 0;
  585. if ($deduction_price) {
  586. $count = 0;
  587. $total_price = 0.00;
  588. $compute_price = 0.00;
  589. $integral_price = 0.00;
  590. $use_integral = 0;
  591. $compute_integral = 0;
  592. foreach ($cartInfo as $cart) {
  593. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  594. continue;
  595. }
  596. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  597. $count++;
  598. }
  599. if ($total_price == $deduction_price) {
  600. $ratio = 1;
  601. } else {
  602. $ratio = bcdiv((string)$deduction_price, (string)$total_price, 4);
  603. }
  604. foreach ($cartInfo as &$cart) {
  605. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  606. continue;
  607. }
  608. if ($count > 1) {
  609. $integral_price = bcmul((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$ratio, 2);
  610. $compute_price = bcadd((string)$compute_price, (string)$integral_price, 2);
  611. $use_integral = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$usedIntegral, 0);
  612. $compute_integral = bcadd((string)$compute_integral, $use_integral, 0);
  613. } else {
  614. $integral_price = bcsub((string)$deduction_price, $compute_price, 2);
  615. $use_integral = bcsub((string)$usedIntegral, $compute_integral, 0);
  616. }
  617. $count--;
  618. $cart['integral_price'] = $integral_price;
  619. $cart['use_integral'] = $use_integral;
  620. }
  621. }
  622. return $cartInfo;
  623. }
  624. /**
  625. * 计算订单商品优惠券实际抵扣金额
  626. * @param array $cartInfo
  627. * @param array $priceData
  628. * @return array
  629. */
  630. public function computeOrderProductCoupon(array $cartInfo, array $priceData, array $promotions = [], int $store_id = 0)
  631. {
  632. if ($priceData['coupon_id'] && $priceData['coupon_price'] ?? 0) {
  633. $count = 0;
  634. $total_price = 0.00;
  635. $compute_price = 0.00;
  636. $coupon_price = 0.00;
  637. /** @var StoreCouponUserServices $couponServices */
  638. $couponServices = app()->make(StoreCouponUserServices::class);
  639. $couponInfo = $couponServices->getOne(['id' => $priceData['coupon_id']], '*', ['issue']);
  640. if ($couponInfo) {
  641. //验证是否适用门店
  642. if ($store_id && isset($couponInfo['applicable_type']) && isset($couponInfo['applicable_store_id'])) {
  643. $applicable_store_id = is_array($couponInfo['applicable_store_id']) ? $couponInfo['applicable_store_id'] : explode(',', $couponInfo['applicable_store_id']);
  644. //活动不适用该门店
  645. if ($couponInfo['applicable_type'] == 0 || ($couponInfo['applicable_type'] == 2 && !in_array($store_id, $applicable_store_id))) {
  646. return [[], 0];
  647. }
  648. }
  649. $promotionsList = [];
  650. if ($promotions) {
  651. $promotionsList = array_combine(array_column($promotions, 'id'), $promotions);
  652. }
  653. $isOverlay = function ($cart) use ($promotionsList) {
  654. $productInfo = $cart['productInfo'] ?? [];
  655. if (!$productInfo) {
  656. return false;
  657. }
  658. //门店独立商品 不使用优惠券
  659. $isBranchProduct = isset($productInfo['type']) && isset($productInfo['pid']) && $productInfo['type'] == 1 && !$productInfo['pid'];
  660. if ($isBranchProduct) {
  661. return false;
  662. }
  663. if (isset($cart['promotions_id']) && $cart['promotions_id']) {
  664. foreach ($cart['promotions_id'] as $key => $promotions_id) {
  665. $promotions = $promotionsList[$promotions_id] ?? [];
  666. if ($promotions && $promotions['promotions_type'] != 4) {
  667. $overlay = is_string($promotions['overlay']) ? explode(',', $promotions['overlay']) : $promotions['overlay'];
  668. if (!in_array(5, $overlay)) {
  669. return false;
  670. }
  671. }
  672. }
  673. }
  674. return true;
  675. };
  676. $type = $couponInfo['applicable_type'] ?? 0;
  677. $counpon_id = $couponInfo['id'];
  678. switch ($type) {
  679. case 0:
  680. foreach ($cartInfo as $cart) {
  681. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  682. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  683. $count++;
  684. }
  685. foreach ($cartInfo as &$cart) {
  686. $cart['coupon_id'] = 0;
  687. $cart['coupon_price'] = 0;
  688. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  689. if ($count > 1) {
  690. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$priceData['coupon_price'], 2);
  691. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  692. } else {
  693. $coupon_price = bcsub((string)$priceData['coupon_price'], $compute_price, 2);
  694. }
  695. $cart['coupon_price'] = $coupon_price;
  696. $cart['coupon_id'] = $counpon_id;
  697. $count--;
  698. }
  699. break;
  700. case 1://品类券
  701. /** @var StoreProductCategoryServices $storeCategoryServices */
  702. $storeCategoryServices = app()->make(StoreProductCategoryServices::class);
  703. $cateGorys = $storeCategoryServices->getAllById((int)$couponInfo['category_id']);
  704. if ($cateGorys) {
  705. $cateIds = array_column($cateGorys, 'id');
  706. foreach ($cartInfo as $cart) {
  707. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  708. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  709. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  710. $count++;
  711. }
  712. }
  713. foreach ($cartInfo as &$cart) {
  714. $cart['coupon_id'] = 0;
  715. $cart['coupon_price'] = 0;
  716. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  717. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  718. if ($count > 1) {
  719. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$priceData['coupon_price'], 2);
  720. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  721. } else {
  722. $coupon_price = bcsub((string)$priceData['coupon_price'], $compute_price, 2);
  723. }
  724. $cart['coupon_id'] = $counpon_id;
  725. $cart['coupon_price'] = $coupon_price;
  726. $count--;
  727. }
  728. }
  729. }
  730. break;
  731. case 2://商品劵
  732. foreach ($cartInfo as $cart) {
  733. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  734. $product_id = isset($cart['productInfo']['pid']) && $cart['productInfo']['pid'] ? $cart['productInfo']['pid'] : ($cart['product_id'] ?? 0);
  735. if ($product_id && in_array($product_id, explode(',', $couponInfo['product_id']))) {
  736. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  737. $count++;
  738. }
  739. }
  740. foreach ($cartInfo as &$cart) {
  741. $cart['coupon_id'] = 0;
  742. $cart['coupon_price'] = 0;
  743. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  744. $product_id = isset($cart['productInfo']['pid']) && $cart['productInfo']['pid'] ? $cart['productInfo']['pid'] : ($cart['product_id'] ?? 0);
  745. if ($product_id && in_array($product_id, explode(',', $couponInfo['product_id']))) {
  746. if ($count > 1) {
  747. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$priceData['coupon_price'], 2);
  748. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  749. } else {
  750. $coupon_price = bcsub((string)$priceData['coupon_price'], $compute_price, 2);
  751. }
  752. $cart['coupon_id'] = $counpon_id;
  753. $cart['coupon_price'] = $coupon_price;
  754. $count--;
  755. }
  756. }
  757. break;
  758. case 3://品牌券
  759. /** @var StoreBrandServices $storeBrandServices */
  760. $storeBrandServices = app()->make(StoreBrandServices::class);
  761. $brands = $storeBrandServices->getAllById((int)$couponInfo['brand_id']);
  762. if ($brands) {
  763. $brandIds = array_column($brands, 'id');
  764. foreach ($cartInfo as $cart) {
  765. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  766. if (isset($cart['productInfo']['brand_id']) && in_array($cart['productInfo']['brand_id'], $brandIds)) {
  767. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  768. $count++;
  769. }
  770. }
  771. foreach ($cartInfo as &$cart) {
  772. $cart['coupon_id'] = 0;
  773. $cart['coupon_price'] = 0;
  774. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  775. if (isset($cart['productInfo']['brand_id']) && in_array($cart['productInfo']['brand_id'], $brandIds)) {
  776. if ($count > 1) {
  777. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$priceData['coupon_price'], 2);
  778. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  779. } else {
  780. $coupon_price = bcsub((string)$priceData['coupon_price'], $compute_price, 2);
  781. }
  782. $cart['coupon_id'] = $counpon_id;
  783. $cart['coupon_price'] = $coupon_price;
  784. $count--;
  785. }
  786. }
  787. }
  788. break;
  789. }
  790. }
  791. }
  792. return $cartInfo;
  793. }
  794. /**
  795. * 计算实际佣金
  796. * @param int $uid
  797. * @param array $cartInfo
  798. * @param $userInfo
  799. * @return array
  800. * @throws \think\db\exception\DataNotFoundException
  801. * @throws \think\db\exception\DbException
  802. * @throws \think\db\exception\ModelNotFoundException
  803. */
  804. public function computeOrderProductBrokerage(int $uid, array $cartInfo, $userInfo)
  805. {
  806. //获取后台一级返佣比例
  807. $storeBrokerageRatio = sys_config('store_brokerage_ratio');
  808. //获取二级返佣比例
  809. $storeBrokerageTwo = sys_config('store_brokerage_two');
  810. //佣金计算方式
  811. $brokerageComputeType = sys_config('brokerage_compute_type', 1);
  812. /** @var AgentLevelServices $agentLevelServices */
  813. $agentLevelServices = app()->make(AgentLevelServices::class);
  814. [$one_brokerage_up, $two_brokerage_up, $spread_uid, $spread_two_uid] = $agentLevelServices->getAgentLevelBrokerage($uid, $userInfo);
  815. // 二级分销开关
  816. if (sys_config('brokerage_level', 2) == 1) {
  817. $storeBrokerageTwo = $spread_two_uid = 0;
  818. }
  819. foreach ($cartInfo as &$cart) {
  820. $oneBrokerage = '0';//一级返佣金额
  821. $twoBrokerage = '0';//二级返佣金额
  822. $cartNum = (string)$cart['cart_num'] ?? '0';
  823. if (isset($cart['productInfo']) && isset($cart['is_gift']) && $cart['is_gift'] == 0) {
  824. $productInfo = $cart['productInfo'];
  825. //指定返佣金额
  826. if (isset($productInfo['is_sub']) && $productInfo['is_sub'] == 1) {
  827. $oneBrokerage = bcmul((string)($productInfo['attrInfo']['brokerage'] ?? '0'), $cartNum, 2);
  828. $twoBrokerage = bcmul((string)($productInfo['attrInfo']['brokerage_two'] ?? '0'), $cartNum, 2);
  829. } else {//比例返佣
  830. $price = 0;
  831. switch ($brokerageComputeType) {
  832. case 1://售价
  833. if (isset($productInfo['attrInfo'])) {
  834. $price = bcmul((string)($productInfo['attrInfo']['price'] ?? '0'), $cartNum, 4);
  835. } else {
  836. $price = bcmul((string)($productInfo['price'] ?? '0'), $cartNum, 4);
  837. }
  838. break;
  839. case 2://实付金额
  840. $price = bcmul((string)($cart['truePrice'] ?? 0), $cartNum, 4);
  841. break;
  842. case 3://商品利润
  843. $price = bcmul(bcsub((string)($cart['truePrice'] ?? 0), (string)($cart['costPrice'] ?? 0), 2), $cartNum, 4);
  844. break;
  845. }
  846. if ($price > 0) {
  847. //一级返佣比例 小于等于零时直接返回 不返佣
  848. if ($storeBrokerageRatio > 0) {
  849. //计算获取一级返佣比例
  850. $brokerageRatio = bcdiv($storeBrokerageRatio, 100, 4);
  851. $oneBrokerage = bcmul((string)$price, (string)$brokerageRatio, 2);
  852. }
  853. //二级返佣比例小于等于0 直接返回
  854. if ($storeBrokerageTwo > 0) {
  855. //计算获取二级返佣比例
  856. $brokerageTwo = bcdiv($storeBrokerageTwo, 100, 4);
  857. $twoBrokerage = bcmul((string)$price, (string)$brokerageTwo, 2);
  858. }
  859. }
  860. }
  861. }
  862. //分销等级上浮佣金
  863. if ($one_brokerage_up) $oneBrokerage = bcadd((string)$oneBrokerage, (string)bcmul((string)$oneBrokerage, (string)bcdiv((string)$one_brokerage_up, '100', 2), 4), 2);
  864. if ($two_brokerage_up) $twoBrokerage = bcadd((string)$twoBrokerage, (string)bcmul((string)$twoBrokerage, (string)bcdiv((string)$two_brokerage_up, '100', 2), 4), 2);
  865. $cart['one_brokerage'] = $oneBrokerage;
  866. $cart['two_brokerage'] = $twoBrokerage;
  867. }
  868. return [$cartInfo, [$spread_uid, $spread_two_uid]];
  869. }
  870. /**
  871. * 计算订单商品信任首单优惠实际抵扣金额
  872. * @param array $cartInfo
  873. * @param array $priceData
  874. * @return array
  875. */
  876. public function computeOrderProductFirstDiscount(array $cartInfo, array $priceData)
  877. {
  878. $first_order_price = $priceData['first_order_price'] ?? 0;
  879. if ($first_order_price) {
  880. $count = 0;
  881. $total_price = 0.00;
  882. $compute_price = 0.00;
  883. $discount_price = 0.00;
  884. foreach ($cartInfo as $cart) {
  885. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  886. continue;
  887. }
  888. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  889. $count++;
  890. }
  891. if ($total_price == $first_order_price) {
  892. $ratio = 1;
  893. } else {
  894. $ratio = bcdiv((string)$first_order_price, (string)$total_price, 4);
  895. }
  896. foreach ($cartInfo as &$cart) {
  897. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  898. continue;
  899. }
  900. if ($count > 1) {
  901. $discount_price = bcmul((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$ratio, 2);
  902. $compute_price = bcadd((string)$compute_price, (string)$discount_price, 2);
  903. } else {
  904. $discount_price = bcsub((string)$first_order_price, $compute_price, 2);
  905. }
  906. $count--;
  907. $cart['first_order_price'] = $discount_price;
  908. }
  909. }
  910. return $cartInfo;
  911. }
  912. }