StoreOrderCreateServices.php 40 KB

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