StoreOrderCreateServices.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2022 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\activity\advance\StoreAdvanceServices;
  13. use app\services\agent\AgentLevelServices;
  14. use app\services\activity\coupon\StoreCouponUserServices;
  15. use app\services\agent\DivisionServices;
  16. use app\services\pay\PayServices;
  17. use app\services\product\product\StoreCategoryServices;
  18. use app\services\shipping\ShippingTemplatesFreeServices;
  19. use app\services\shipping\ShippingTemplatesRegionServices;
  20. use app\services\shipping\ShippingTemplatesServices;
  21. use app\services\wechat\WechatUserServices;
  22. use app\services\BaseServices;
  23. use crmeb\exceptions\ApiException;
  24. use crmeb\services\CacheService;
  25. use app\dao\order\StoreOrderDao;
  26. use app\services\user\UserServices;
  27. use app\services\user\UserBillServices;
  28. use app\services\user\UserAddressServices;
  29. use app\services\activity\bargain\StoreBargainServices;
  30. use app\services\activity\seckill\StoreSeckillServices;
  31. use app\services\system\store\SystemStoreServices;
  32. use app\services\activity\combination\StoreCombinationServices;
  33. use app\services\product\product\StoreProductServices;
  34. use think\facade\Cache;
  35. use think\facade\Log;
  36. /**
  37. * 订单创建
  38. * Class StoreOrderCreateServices
  39. * @package app\services\order
  40. */
  41. class StoreOrderCreateServices extends BaseServices
  42. {
  43. /**
  44. * StoreOrderCreateServices constructor.
  45. * @param StoreOrderDao $dao
  46. */
  47. public function __construct(StoreOrderDao $dao)
  48. {
  49. $this->dao = $dao;
  50. }
  51. /**
  52. * 使用雪花算法生成订单ID
  53. * @return string
  54. * @throws \Exception
  55. */
  56. public function getNewOrderId(string $prefix = 'wx')
  57. {
  58. $snowflake = new \Godruoyi\Snowflake\Snowflake();
  59. $is_callable = function ($currentTime) {
  60. $redis = Cache::store('redis');
  61. $swooleSequenceResolver = new \Godruoyi\Snowflake\RedisSequenceResolver($redis->handler());
  62. return $swooleSequenceResolver->sequence($currentTime);
  63. };
  64. //32位
  65. if (PHP_INT_SIZE == 4) {
  66. $id = abs($snowflake->setSequenceResolver($is_callable)->id());
  67. } else {
  68. $id = $snowflake->setStartTimeStamp(strtotime('2020-06-05') * 1000)->setSequenceResolver($is_callable)->id();
  69. }
  70. return $prefix . $id;
  71. }
  72. /**
  73. * 核销订单生成核销码
  74. * @return false|string
  75. */
  76. public function getStoreCode()
  77. {
  78. list($msec, $sec) = explode(' ', microtime());
  79. $num = time() + mt_rand(10, 999999) . '' . substr($msec, 2, 3);//生成随机数
  80. if (strlen($num) < 12)
  81. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  82. else
  83. $num = substr($num, 0, 12);
  84. if ($this->dao->count(['verify_code' => $num])) {
  85. return $this->getStoreCode();
  86. }
  87. return $num;
  88. }
  89. /**
  90. * 创建订单
  91. * @param $uid
  92. * @param $key
  93. * @param $cartGroup
  94. * @param $userInfo
  95. * @param $addressId
  96. * @param $payType
  97. * @param bool $useIntegral
  98. * @param int $couponId
  99. * @param string $mark
  100. * @param int $combinationId
  101. * @param int $pinkId
  102. * @param int $seckillId
  103. * @param int $bargainId
  104. * @param int $isChannel
  105. * @param int $shippingType
  106. * @param string $real_name
  107. * @param string $phone
  108. * @param int $storeId
  109. * @param bool $news
  110. * @return mixed
  111. * @throws \Psr\SimpleCache\InvalidArgumentException
  112. * @throws \think\db\exception\DataNotFoundException
  113. * @throws \think\db\exception\DbException
  114. * @throws \think\db\exception\ModelNotFoundException
  115. */
  116. 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, $advanceId = 0, $virtual_type = 0, $customForm = [])
  117. {
  118. /** @var StoreOrderComputedServices $computedServices */
  119. $computedServices = app()->make(StoreOrderComputedServices::class);
  120. $priceData = $computedServices->computedOrder($uid, $userInfo, $cartGroup, $addressId, $payType, $useIntegral, $couponId, true, $shippingType);
  121. /** @var WechatUserServices $wechatServices */
  122. $wechatServices = app()->make(WechatUserServices::class);
  123. /** @var UserAddressServices $addressServices */
  124. $addressServices = app()->make(UserAddressServices::class);
  125. if ($shippingType == 1 && $virtual_type == 0) {
  126. if (!$addressId) {
  127. throw new ApiException(410045);
  128. }
  129. if (!$addressInfo = $addressServices->getOne(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]))
  130. throw new ApiException(410046);
  131. $addressInfo = $addressInfo->toArray();
  132. } else {
  133. if ((!$real_name || !$phone) && $virtual_type == 0) {
  134. throw new ApiException(410245);
  135. }
  136. $addressInfo['real_name'] = $real_name;
  137. $addressInfo['phone'] = $phone;
  138. $addressInfo['province'] = '';
  139. $addressInfo['city'] = '';
  140. $addressInfo['district'] = '';
  141. $addressInfo['detail'] = '';
  142. }
  143. $cartInfo = $cartGroup['cartInfo'];
  144. $priceGroup = $cartGroup['priceGroup'];
  145. $cartIds = [];
  146. $totalNum = 0;
  147. $gainIntegral = 0;
  148. foreach ($cartInfo as $cart) {
  149. $cartIds[] = $cart['id'];
  150. $totalNum += $cart['cart_num'];
  151. if (!$seckillId) $seckillId = $cart['seckill_id'];
  152. if (!$bargainId) $bargainId = $cart['bargain_id'];
  153. if (!$combinationId) $combinationId = $cart['combination_id'];
  154. if (!$advanceId) $advanceId = $cart['advance_id'];
  155. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul((string)$cart['cart_num'], (string)$cart['productInfo']['give_integral'], 0) : 0;
  156. $gainIntegral = bcadd((string)$gainIntegral, (string)$cartInfoGainIntegral, 0);
  157. }
  158. if (count($cartInfo) == 1 && isset($cartInfo[0]['productInfo']['presale']) && $cartInfo[0]['productInfo']['presale'] == 1) {
  159. $advance_id = $cartInfo[0]['product_id'];
  160. } else {
  161. $advance_id = 0;
  162. }
  163. $deduction = $seckillId || $bargainId || $combinationId;
  164. if ($deduction) {
  165. $couponId = 0;
  166. $useIntegral = false;
  167. $systemPayType = PayServices::PAY_TYPE;
  168. unset($systemPayType['offline']);
  169. if ($payType != 'pc' && !array_key_exists($payType, $systemPayType)) {
  170. throw new ApiException(410246);
  171. }
  172. }
  173. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  174. $storeSelfMention = sys_config('store_self_mention') ?? 0;
  175. if (!$storeSelfMention) $shippingType = 1;
  176. $orderInfo = [
  177. 'uid' => $uid,
  178. 'order_id' => $this->getNewOrderId('cp'),
  179. 'real_name' => $addressInfo['real_name'],
  180. 'user_phone' => $addressInfo['phone'],
  181. 'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
  182. 'cart_id' => $cartIds,
  183. 'total_num' => $totalNum,
  184. 'total_price' => $priceGroup['totalPrice'],
  185. 'total_postage' => $shippingType == 1 ? $priceGroup['storePostage'] : 0,
  186. 'coupon_id' => $couponId,
  187. 'coupon_price' => $priceData['coupon_price'],
  188. 'pay_price' => $priceData['pay_price'],
  189. 'pay_postage' => $priceData['pay_postage'],
  190. 'deduction_price' => $priceData['deduction_price'],
  191. 'paid' => 0,
  192. 'pay_type' => $payType,
  193. 'use_integral' => $priceData['usedIntegral'],
  194. 'gain_integral' => $gainIntegral,
  195. 'mark' => htmlspecialchars($mark),
  196. 'combination_id' => $combinationId,
  197. 'pink_id' => $pinkId,
  198. 'seckill_id' => $seckillId,
  199. 'bargain_id' => $bargainId,
  200. 'advance_id' => $advance_id,
  201. 'cost' => $priceGroup['costPrice'],
  202. 'is_channel' => $isChannel,
  203. 'add_time' => time(),
  204. 'unique' => $key,
  205. 'shipping_type' => $shippingType,
  206. 'channel_type' => $userInfo['user_type'],
  207. 'province' => strval($userInfo['user_type'] == 'wechat' || $userInfo['user_type'] == 'routine' ? $wechatServices->value(['uid' => $uid, 'user_type' => $userInfo['user_type']], 'province') : ''),
  208. 'spread_uid' => 0,
  209. 'spread_two_uid' => 0,
  210. 'virtual_type' => $virtual_type,
  211. 'pay_uid' => $uid,
  212. 'custom_form' => json_encode($customForm),
  213. 'division_id' => $userInfo['division_id'],
  214. 'agent_id' => $userInfo['agent_id'],
  215. 'staff_id' => $userInfo['staff_id'],
  216. ];
  217. if ($shippingType == 2) {
  218. $orderInfo['verify_code'] = $this->getStoreCode();
  219. /** @var SystemStoreServices $storeServices */
  220. $storeServices = app()->make(SystemStoreServices::class);
  221. $orderInfo['store_id'] = $storeServices->getStoreDispose($storeId, 'id');
  222. if (!$orderInfo['store_id']) {
  223. throw new ApiException(410247);
  224. }
  225. }
  226. /** @var StoreOrderCartInfoServices $cartServices */
  227. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  228. /** @var StoreSeckillServices $seckillServices */
  229. $seckillServices = app()->make(StoreSeckillServices::class);
  230. $priceData['coupon_id'] = $couponId;
  231. $order = $this->transaction(function () use ($cartIds, $orderInfo, $cartInfo, $key, $userInfo, $useIntegral, $priceData, $combinationId, $seckillId, $bargainId, $cartServices, $seckillServices, $uid, $addressId, $advanceId) {
  232. //创建订单
  233. $order = $this->dao->save($orderInfo);
  234. if (!$order) {
  235. throw new ApiException(410200);
  236. }
  237. //记录自提人电话和姓名
  238. /** @var UserServices $userService */
  239. $userService = app()->make(UserServices::class);
  240. $userService->update(['uid' => $uid], ['real_name' => $orderInfo['real_name'], 'record_phone' => $orderInfo['user_phone']]);
  241. //占用库存
  242. $seckillServices->occupySeckillStock($cartInfo, $key);
  243. //积分抵扣
  244. if ($priceData['usedIntegral'] > 0) {
  245. $this->deductIntegral($userInfo, $useIntegral, $priceData, (int)$userInfo['uid'], $order['id']);
  246. }
  247. //扣库存
  248. $this->decGoodsStock($cartInfo, $combinationId, $seckillId, $bargainId, $advanceId);
  249. //保存购物车商品信息
  250. $cartServices->setCartInfo($order['id'], $uid, $cartInfo);
  251. return $order;
  252. });
  253. // 订单创建成功后置事件
  254. event('order.orderCreateAfter', [$order, compact('cartInfo', 'priceData', 'addressId', 'cartIds', 'news'), $uid, $key, $combinationId, $seckillId, $bargainId]);
  255. // 推送订单
  256. event('out.outPush', ['order_create_push', ['order_id' => (int)$order['id']]]);
  257. return $order;
  258. }
  259. /**
  260. * 抵扣积分
  261. * @param array $userInfo
  262. * @param bool $useIntegral
  263. * @param array $priceData
  264. * @param int $uid
  265. * @param string $key
  266. */
  267. public function deductIntegral(array $userInfo, bool $useIntegral, array $priceData, int $uid, $orderId)
  268. {
  269. $res2 = true;
  270. if ($useIntegral && $userInfo['integral'] > 0) {
  271. /** @var UserServices $userServices */
  272. $userServices = app()->make(UserServices::class);
  273. if (!$priceData['SurplusIntegral']) {
  274. $res2 = false !== $userServices->update($uid, ['integral' => 0]);
  275. } else {
  276. $res2 = false !== $userServices->bcDec($userInfo['uid'], 'integral', $priceData['usedIntegral'], 'uid');
  277. }
  278. /** @var UserBillServices $userBillServices */
  279. $userBillServices = app()->make(UserBillServices::class);
  280. $res3 = $userBillServices->income('deduction', $uid, [
  281. 'number' => $priceData['usedIntegral'],
  282. 'deductionPrice' => $priceData['deduction_price']
  283. ], $userInfo['integral'] - $priceData['usedIntegral'], $orderId);
  284. $res2 = $res2 && false != $res3;
  285. }
  286. if (!$res2) {
  287. throw new ApiException(410227);
  288. }
  289. }
  290. /**
  291. * 扣库存
  292. * @param array $cartInfo
  293. * @param int $combinationId
  294. * @param int $seckillId
  295. * @param int $bargainId
  296. */
  297. public function decGoodsStock(array $cartInfo, int $combinationId, int $seckillId, int $bargainId, int $advanceId)
  298. {
  299. $res5 = true;
  300. /** @var StoreProductServices $services */
  301. $services = app()->make(StoreProductServices::class);
  302. /** @var StoreSeckillServices $seckillServices */
  303. $seckillServices = app()->make(StoreSeckillServices::class);
  304. /** @var StoreCombinationServices $pinkServices */
  305. $pinkServices = app()->make(StoreCombinationServices::class);
  306. /** @var StoreBargainServices $bargainServices */
  307. $bargainServices = app()->make(StoreBargainServices::class);
  308. /** @var StoreAdvanceServices $advanceServices */
  309. $advanceServices = app()->make(StoreAdvanceServices::class);
  310. try {
  311. foreach ($cartInfo as $cart) {
  312. //减库存加销量
  313. if ($combinationId) $res5 = $res5 && $pinkServices->decCombinationStock((int)$cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  314. else if ($seckillId) $res5 = $res5 && $seckillServices->decSeckillStock((int)$cart['cart_num'], $seckillId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  315. else if ($bargainId) $res5 = $res5 && $bargainServices->decBargainStock((int)$cart['cart_num'], $bargainId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  316. else if ($advanceId) $res5 = $res5 && $advanceServices->decAdvanceStock((int)$cart['cart_num'], $advanceId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  317. else $res5 = $res5 && $services->decProductStock((int)$cart['cart_num'], (int)$cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  318. }
  319. if (!$res5) {
  320. throw new ApiException(410238);
  321. }
  322. } catch (\Throwable $e) {
  323. throw new ApiException(410238);
  324. }
  325. }
  326. /**
  327. * 订单数据创建之后的商品实际金额计算,佣金计算,优惠折扣计算,设置默认地址,清理购物车
  328. * @param $order
  329. * @param array $group
  330. * @param $activity
  331. */
  332. public function orderCreateAfter($order, array $group, $activity)
  333. {
  334. /** @var UserAddressServices $addressServices */
  335. $addressServices = app()->make(UserAddressServices::class);
  336. //设置用户默认地址
  337. if (!$addressServices->be(['is_default' => 1, 'uid' => $order['uid']])) {
  338. $addressServices->setDefaultAddress($group['addressId'], $order['uid']);
  339. }
  340. //删除购物车
  341. if ($group['news']) {
  342. array_map(function ($key) {
  343. CacheService::delete($key);
  344. }, $group['cartIds']);
  345. } else {
  346. /** @var StoreCartServices $cartServices */
  347. $cartServices = app()->make(StoreCartServices::class);
  348. $cartServices->deleteCartStatus($group['cartIds']);
  349. }
  350. $uid = (int)$order['uid'];
  351. $orderId = (int)$order['id'];
  352. try {
  353. $cartInfo = $group['cartInfo'] ?? [];
  354. $priceData = $group['priceData'] ?? [];
  355. $addressId = $group['addressId'] ?? 0;
  356. $spread_ids = [];
  357. /** @var StoreOrderCreateServices $createService */
  358. $createService = app()->make(StoreOrderCreateServices::class);
  359. if ($cartInfo && $priceData) {
  360. /** @var StoreOrderCartInfoServices $cartServices */
  361. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  362. [$cartInfo, $spread_ids] = $createService->computeOrderProductTruePrice($cartInfo, $priceData, $addressId, $uid, $order);
  363. $cartServices->updateCartInfo($orderId, $cartInfo);
  364. }
  365. $orderData = [];
  366. $spread_uid = $spread_two_uid = 0;
  367. /** @var UserServices $userServices */
  368. $userServices = app()->make(UserServices::class);
  369. if ($spread_ids) {
  370. [$spread_uid, $spread_two_uid] = $spread_ids;
  371. $orderData['spread_uid'] = $spread_uid;
  372. $orderData['spread_two_uid'] = $spread_two_uid;
  373. } else {
  374. $spread_uid = $userServices->getSpreadUid($uid);
  375. $orderData = ['spread_uid' => 0, 'spread_two_uid' => 0];
  376. if ($spread_uid) {
  377. $orderData['spread_uid'] = $spread_uid;
  378. }
  379. if ($spread_uid > 0 && sys_config('brokerage_level') == 2) {
  380. $spread_two_uid = $userServices->getSpreadUid($spread_uid, [], false);
  381. if ($spread_two_uid) {
  382. $orderData['spread_two_uid'] = $spread_two_uid;
  383. }
  384. }
  385. }
  386. $isCommission = 0;
  387. if ($order['combination_id']) {
  388. //检测拼团是否参与返佣
  389. /** @var StoreCombinationServices $combinationServices */
  390. $combinationServices = app()->make(StoreCombinationServices::class);
  391. $isCommission = $combinationServices->value(['id' => $order['combination_id']], 'is_commission');
  392. }
  393. if ($cartInfo && (!$activity || $isCommission)) {
  394. /** @var StoreOrderComputedServices $orderComputed */
  395. $orderComputed = app()->make(StoreOrderComputedServices::class);
  396. if ($userServices->checkUserPromoter($spread_uid)) $orderData['one_brokerage'] = $orderComputed->getOrderSumPrice($cartInfo, 'one_brokerage', false);
  397. if ($userServices->checkUserPromoter($spread_two_uid)) $orderData['two_brokerage'] = $orderComputed->getOrderSumPrice($cartInfo, 'two_brokerage', false);
  398. $orderData['staff_brokerage'] = $orderComputed->getOrderSumPrice($cartInfo, 'staff_brokerage', false);
  399. $orderData['agent_brokerage'] = $orderComputed->getOrderSumPrice($cartInfo, 'agent_brokerage', false);
  400. $orderData['division_brokerage'] = $orderComputed->getOrderSumPrice($cartInfo, 'division_brokerage', false);
  401. }
  402. $createService->update(['id' => $orderId], $orderData);
  403. } catch (\Throwable $e) {
  404. throw new ApiException('计算订单实际优惠、积分、邮费、佣金失败,原因:' . $e->getMessage());
  405. }
  406. }
  407. /**
  408. * 计算订单每个商品真实付款价格
  409. * @param array $cartInfo
  410. * @param array $priceData
  411. * @param $addressId
  412. * @param int $uid
  413. * @return array
  414. */
  415. public function computeOrderProductTruePrice(array $cartInfo, array $priceData, $addressId, int $uid, $orderInfo)
  416. {
  417. //统一放入默认数据
  418. foreach ($cartInfo as &$cart) {
  419. $cart['use_integral'] = 0;
  420. $cart['integral_price'] = 0.00;
  421. $cart['coupon_price'] = 0.00;
  422. }
  423. try {
  424. [$cartInfo, $spread_ids] = $this->computeOrderProductBrokerage($uid, $cartInfo, $orderInfo);
  425. $cartInfo = $this->computeOrderProductCoupon($cartInfo, $priceData);
  426. $cartInfo = $this->computeOrderProductIntegral($cartInfo, $priceData);
  427. // $cartInfo = $this->computeOrderProductPostage($cartInfo, $priceData, $addressId);
  428. } catch (\Throwable $e) {
  429. Log::error('订单商品结算失败,File:' . $e->getFile() . ',Line:' . $e->getLine() . ',Message:' . $e->getMessage());
  430. throw new ApiException(410248);
  431. }
  432. //truePice实际支付单价(存在)
  433. //几件商品总体优惠 以及积分抵扣金额
  434. foreach ($cartInfo as &$cart) {
  435. $coupon_price = $cart['coupon_price'] ?? 0;
  436. $integral_price = $cart['integral_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. }
  449. return [$cartInfo, $spread_ids];
  450. }
  451. /**
  452. * 计算每个商品实际支付运费
  453. * @param array $cartInfo
  454. * @param array $priceData
  455. * @return array
  456. */
  457. public function computeOrderProductPostage(array $cartInfo, array $priceData, $addressId)
  458. {
  459. $storePostage = $priceData['pay_postage'] ?? 0;
  460. if ($storePostage) {
  461. /** @var UserAddressServices $addressServices */
  462. $addressServices = app()->make(UserAddressServices::class);
  463. $addr = $addressServices->getAddress($addressId);
  464. if ($addr) {
  465. $addr = $addr->toArray();
  466. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  467. $cityId = $addr['city_id'] ?? 0;
  468. $tempIds[] = 1;
  469. foreach ($cartInfo as $key_c => $item_c) {
  470. $tempIds[] = $item_c['productInfo']['temp_id'];
  471. }
  472. $tempIds = array_unique($tempIds);
  473. /** @var ShippingTemplatesServices $shippServices */
  474. $shippServices = app()->make(ShippingTemplatesServices::class);
  475. $temp = $shippServices->getShippingColumn(['id' => $tempIds], 'type,appoint', 'id');
  476. /** @var ShippingTemplatesRegionServices $regionServices */
  477. $regionServices = app()->make(ShippingTemplatesRegionServices::class);
  478. $regions = $regionServices->getTempRegionList($tempIds, [$cityId, 0], 'temp_id,first,first_price,continue,continue_price', 'temp_id');
  479. $temp_num = [];
  480. foreach ($cartInfo as $cart) {
  481. $tempId = $cart['productInfo']['temp_id'] ?? 1;
  482. $type = $temp[$tempId]['type'] ?? $temp[1]['type'];
  483. if ($type == 1) {
  484. $num = $cart['cart_num'];
  485. } elseif ($type == 2) {
  486. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  487. } else {
  488. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  489. }
  490. $region = $regions[$tempId] ?? $regions[1];
  491. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  492. $temp_num[$cart['productInfo']['temp_id']]['cart_id'][] = $cart['id'];
  493. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  494. $temp_num[$cart['productInfo']['temp_id']]['type'] = $type;
  495. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  496. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  497. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  498. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  499. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  500. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  501. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
  502. } else {
  503. $temp_num[$cart['productInfo']['temp_id']]['cart_id'][] = $cart['id'];
  504. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  505. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  506. }
  507. }
  508. $cartInfo = array_combine(array_column($cartInfo, 'id'), $cartInfo);
  509. /** @var ShippingTemplatesFreeServices $freeServices */
  510. $freeServices = app()->make(ShippingTemplatesFreeServices::class);
  511. foreach ($temp_num as $k => $v) {
  512. if (isset($temp[$v['temp_id']]['appoint']) && $temp[$v['temp_id']]['appoint']) {
  513. if ($freeServices->isFree($v['temp_id'], $v['city_id'], $v['number'], $v['price'], $v['type'])) {
  514. //免运费
  515. foreach ($v['cart_id'] as $c_id) {
  516. if (isset($cartInfo[$c_id])) $cartInfo[$c_id]['postage_price'] = 0.00;
  517. }
  518. }
  519. }
  520. }
  521. $count = 0;
  522. $compute_price = 0.00;
  523. $total_price = 0;
  524. $postage_price = 0.00;
  525. foreach ($cartInfo as &$cart) {
  526. if (isset($cart['postage_price'])) {//免运费
  527. continue;
  528. }
  529. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  530. $count++;
  531. }
  532. foreach ($cartInfo as &$cart) {
  533. if (isset($cart['postage_price'])) {//免运费
  534. continue;
  535. }
  536. if ($count > 1) {
  537. $postage_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$storePostage, 2);
  538. $compute_price = bcadd((string)$compute_price, (string)$postage_price, 2);
  539. } else {
  540. $postage_price = bcsub((string)$storePostage, $compute_price, 2);
  541. }
  542. $cart['postage_price'] = $postage_price;
  543. $count--;
  544. }
  545. $cartInfo = array_merge($cartInfo);
  546. }
  547. }
  548. //保证不进运费模版计算的购物车商品postage_price字段有值
  549. foreach ($cartInfo as &$item) {
  550. if (!isset($item['postage_price'])) $item['postage_price'] = 0.00;
  551. }
  552. return $cartInfo;
  553. }
  554. /**
  555. * 计算订单商品积分实际抵扣金额
  556. * @param array $cartInfo
  557. * @param array $priceData
  558. * @return array
  559. */
  560. public function computeOrderProductIntegral(array $cartInfo, array $priceData)
  561. {
  562. $usedIntegral = $priceData['usedIntegral'] ?? 0;
  563. $deduction_price = $priceData['deduction_price'] ?? 0;
  564. if ($deduction_price) {
  565. $count = 0;
  566. $total_price = 0.00;
  567. $compute_price = 0.00;
  568. $integral_price = 0.00;
  569. $use_integral = 0;
  570. $compute_integral = 0;
  571. foreach ($cartInfo as $cart) {
  572. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  573. $count++;
  574. }
  575. foreach ($cartInfo as &$cart) {
  576. if ($count > 1) {
  577. $integral_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$deduction_price, 2);
  578. $compute_price = bcadd((string)$compute_price, (string)$integral_price, 2);
  579. $use_integral = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$usedIntegral, 0);
  580. $compute_integral = bcadd((string)$compute_integral, $use_integral, 0);
  581. } else {
  582. $integral_price = bcsub((string)$deduction_price, $compute_price, 2);
  583. $use_integral = bcsub((string)$usedIntegral, $compute_integral, 0);
  584. }
  585. $count--;
  586. $cart['integral_price'] = $integral_price;
  587. $cart['use_integral'] = $use_integral;
  588. }
  589. }
  590. return $cartInfo;
  591. }
  592. /**
  593. * 计算订单商品优惠券实际抵扣金额
  594. * @param array $cartInfo
  595. * @param array $priceData
  596. * @return array
  597. */
  598. public function computeOrderProductCoupon(array $cartInfo, array $priceData)
  599. {
  600. if ($priceData['coupon_id'] && $priceData['coupon_price'] ?? 0) {
  601. $count = 0;
  602. $total_price = 0.00;
  603. $compute_price = 0.00;
  604. $coupon_price = 0.00;
  605. /** @var StoreCouponUserServices $couponServices */
  606. $couponServices = app()->make(StoreCouponUserServices::class);
  607. $couponInfo = $couponServices->getOne(['id' => $priceData['coupon_id']], '*', ['issue']);
  608. if ($couponInfo) {
  609. $type = $couponInfo['applicable_type'] ?? 0;
  610. $counpon_id = $couponInfo['id'];
  611. switch ($type) {
  612. case 0:
  613. case 3:
  614. foreach ($cartInfo as $cart) {
  615. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  616. $count++;
  617. }
  618. foreach ($cartInfo as &$cart) {
  619. if ($count > 1) {
  620. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  621. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  622. } else {
  623. $coupon_price = bcsub((string)$couponInfo['coupon_price'], $compute_price, 2);
  624. }
  625. $cart['coupon_price'] = $coupon_price;
  626. $cart['coupon_id'] = $counpon_id;
  627. $count--;
  628. }
  629. break;
  630. case 1://品类券
  631. /** @var StoreCategoryServices $storeCategoryServices */
  632. $storeCategoryServices = app()->make(StoreCategoryServices::class);
  633. $coupon_category = explode(',', (string)$couponInfo['category_id']);
  634. $category_ids = $storeCategoryServices->getAllById($coupon_category);
  635. if ($category_ids) {
  636. $cateIds = array_column($category_ids, 'id');
  637. foreach ($cartInfo as $cart) {
  638. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  639. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  640. $count++;
  641. }
  642. }
  643. foreach ($cartInfo as &$cart) {
  644. $cart['coupon_id'] = 0;
  645. $cart['coupon_price'] = 0;
  646. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  647. if ($count > 1) {
  648. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  649. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  650. } else {
  651. $coupon_price = bcsub((string)$couponInfo['coupon_price'], $compute_price, 2);
  652. }
  653. $cart['coupon_id'] = $counpon_id;
  654. $cart['coupon_price'] = $coupon_price;
  655. $count--;
  656. }
  657. }
  658. }
  659. break;
  660. case 2://商品劵
  661. foreach ($cartInfo as $cart) {
  662. if (isset($cart['product_id']) && in_array($cart['product_id'], explode(',', $couponInfo['product_id']))) {
  663. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  664. $count++;
  665. }
  666. }
  667. foreach ($cartInfo as &$cart) {
  668. $cart['coupon_id'] = 0;
  669. $cart['coupon_price'] = 0;
  670. if (isset($cart['product_id']) && in_array($cart['product_id'], explode(',', $couponInfo['product_id']))) {
  671. if ($count > 1) {
  672. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  673. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  674. } else {
  675. $coupon_price = bcsub((string)$couponInfo['coupon_price'], $compute_price, 2);
  676. }
  677. $cart['coupon_id'] = $counpon_id;
  678. $cart['coupon_price'] = $coupon_price;
  679. $count--;
  680. }
  681. }
  682. break;
  683. }
  684. }
  685. }
  686. return $cartInfo;
  687. }
  688. /**
  689. * 计算实际佣金
  690. * @param int $uid
  691. * @param array $cartInfo
  692. * @return array
  693. * @throws \think\db\exception\DataNotFoundException
  694. * @throws \think\db\exception\DbException
  695. * @throws \think\db\exception\ModelNotFoundException
  696. */
  697. public function computeOrderProductBrokerage(int $uid, array $cartInfo, $orderInfo)
  698. {
  699. /** @var AgentLevelServices $agentLevelServices */
  700. $agentLevelServices = app()->make(AgentLevelServices::class);
  701. [$one_brokerage_up, $two_brokerage_up, $spread_one_uid, $spread_two_uid] = $agentLevelServices->getAgentLevelBrokerage($uid);
  702. $BrokerageOne = sys_config('store_brokerage_ratio') != '' ? sys_config('store_brokerage_ratio') : 0;
  703. $BrokerageTwo = sys_config('store_brokerage_two') != '' ? sys_config('store_brokerage_two') : 0;
  704. $storeBrokerageRatio = $BrokerageOne + (($BrokerageOne * $one_brokerage_up) / 100);
  705. $storeBrokerageTwo = $BrokerageTwo + (($BrokerageTwo * $two_brokerage_up) / 100);
  706. if (sys_config('brokerage_level') == 1) {
  707. $storeBrokerageTwo = $spread_two_uid = 0;
  708. }
  709. /** @var DivisionServices $divisionService */
  710. $divisionService = app()->make(DivisionServices::class);
  711. [$storeBrokerageRatio, $storeBrokerageTwo, $staffPercent, $agentPercent, $divisionPercent] = $divisionService->getDivisionPercent($uid, $storeBrokerageRatio, $storeBrokerageTwo, sys_config('is_self_brokerage', 0));
  712. foreach ($cartInfo as &$cart) {
  713. $oneBrokerage = '0';//一级返佣金额
  714. $twoBrokerage = '0';//二级返佣金额
  715. $staffBrokerage = '0';//店员返佣金额
  716. $agentBrokerage = '0';//代理商返佣金额
  717. $divisionBrokerage = '0';//事业部返佣金额
  718. $cartNum = (string)$cart['cart_num'] ?? '0';
  719. if (isset($cart['productInfo'])) {
  720. $productInfo = $cart['productInfo'];
  721. //计算商品金额
  722. if (isset($productInfo['attrInfo'])) {
  723. $price = bcmul((string)($productInfo['attrInfo']['price'] ?? '0'), $cartNum, 4);
  724. } else {
  725. $price = bcmul((string)($productInfo['price'] ?? '0'), $cartNum, 4);
  726. }
  727. $staffBrokerage = bcmul((string)$price, (string)bcdiv($staffPercent, 100, 4), 2);
  728. $agentBrokerage = bcmul((string)$price, (string)bcdiv($agentPercent, 100, 4), 2);
  729. $divisionBrokerage = bcmul((string)$price, (string)bcdiv($divisionPercent, 100, 4), 2);
  730. //指定返佣金额
  731. if (isset($productInfo['is_sub']) && $productInfo['is_sub'] == 1) {
  732. $oneBrokerage = $storeBrokerageRatio > 0 ? bcmul((string)($productInfo['attrInfo']['brokerage'] ?? '0'), $cartNum, 2) : 0;
  733. $twoBrokerage = $storeBrokerageTwo > 0 ? bcmul((string)($productInfo['attrInfo']['brokerage_two'] ?? '0'), $cartNum, 2) : 0;
  734. } else {
  735. if ($price) {
  736. //一级返佣比例 小于等于零时直接返回 不返佣
  737. if ($storeBrokerageRatio > 0) {
  738. //计算获取一级返佣比例
  739. $brokerageRatio = bcdiv($storeBrokerageRatio, 100, 4);
  740. $oneBrokerage = bcmul((string)$price, (string)$brokerageRatio, 2);
  741. }
  742. //二级返佣比例小于等于0 直接返回
  743. if ($storeBrokerageTwo > 0) {
  744. //计算获取二级返佣比例
  745. $brokerageTwo = bcdiv($storeBrokerageTwo, 100, 4);
  746. $twoBrokerage = bcmul((string)$price, (string)$brokerageTwo, 2);
  747. }
  748. }
  749. }
  750. }
  751. $cart['one_brokerage'] = $oneBrokerage;
  752. $cart['two_brokerage'] = $twoBrokerage;
  753. $cart['staff_brokerage'] = $staffBrokerage;
  754. $cart['agent_brokerage'] = $agentBrokerage;
  755. $cart['division_brokerage'] = $divisionBrokerage;
  756. }
  757. return [$cartInfo, [$spread_one_uid, $spread_two_uid]];
  758. }
  759. }