StoreOrderCreateServices.php 40 KB

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