StoreOrderCreateServices.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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', (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 UserAddressServices $addressServices
  329. * @param $order
  330. * @param array $group
  331. */
  332. public function orderCreateAfter($order, array $group)
  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::redisHandler()->delete($key);
  344. }, $group['cartIds']);
  345. } else {
  346. /** @var StoreCartServices $cartServices */
  347. $cartServices = app()->make(StoreCartServices::class);
  348. $cartServices->deleteCartStatus($group['cartIds']);
  349. }
  350. }
  351. /**
  352. * 计算订单每个商品真实付款价格
  353. * @param array $cartInfo
  354. * @param array $priceData
  355. * @param $addressId
  356. * @param int $uid
  357. * @return array
  358. */
  359. public function computeOrderProductTruePrice(array $cartInfo, array $priceData, $addressId, int $uid, $orderInfo)
  360. {
  361. //统一放入默认数据
  362. foreach ($cartInfo as &$cart) {
  363. $cart['use_integral'] = 0;
  364. $cart['integral_price'] = 0.00;
  365. $cart['coupon_price'] = 0.00;
  366. }
  367. try {
  368. [$cartInfo, $spread_ids] = $this->computeOrderProductBrokerage($uid, $cartInfo, $orderInfo);
  369. $cartInfo = $this->computeOrderProductCoupon($cartInfo, $priceData);
  370. $cartInfo = $this->computeOrderProductIntegral($cartInfo, $priceData);
  371. // $cartInfo = $this->computeOrderProductPostage($cartInfo, $priceData, $addressId);
  372. } catch (\Throwable $e) {
  373. Log::error('订单商品结算失败,File:' . $e->getFile() . ',Line:' . $e->getLine() . ',Message:' . $e->getMessage());
  374. throw new ApiException(410248);
  375. }
  376. //truePice实际支付单价(存在)
  377. //几件商品总体优惠 以及积分抵扣金额
  378. foreach ($cartInfo as &$cart) {
  379. $coupon_price = $cart['coupon_price'] ?? 0;
  380. $integral_price = $cart['integral_price'] ?? 0;
  381. $cart['sum_true_price'] = bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 2);
  382. if ($coupon_price) {
  383. $cart['sum_true_price'] = bcsub((string)$cart['sum_true_price'], (string)$coupon_price, 2);
  384. $uni_coupon_price = (string)bcdiv((string)$coupon_price, (string)$cart['cart_num'], 4);
  385. $cart['truePrice'] = $cart['truePrice'] > $uni_coupon_price ? bcsub((string)$cart['truePrice'], $uni_coupon_price, 2) : 0;
  386. }
  387. if ($integral_price) {
  388. $cart['sum_true_price'] = bcsub((string)$cart['sum_true_price'], (string)$integral_price, 2);
  389. $uni_integral_price = (string)bcdiv((string)$integral_price, (string)$cart['cart_num'], 4);
  390. $cart['truePrice'] = $cart['truePrice'] > $uni_integral_price ? bcsub((string)$cart['truePrice'], $uni_integral_price, 2) : 0;
  391. }
  392. }
  393. return [$cartInfo, $spread_ids];
  394. }
  395. /**
  396. * 计算每个商品实际支付运费
  397. * @param array $cartInfo
  398. * @param array $priceData
  399. * @return array
  400. */
  401. public function computeOrderProductPostage(array $cartInfo, array $priceData, $addressId)
  402. {
  403. $storePostage = $priceData['pay_postage'] ?? 0;
  404. if ($storePostage) {
  405. /** @var UserAddressServices $addressServices */
  406. $addressServices = app()->make(UserAddressServices::class);
  407. $addr = $addressServices->getAddress($addressId);
  408. if ($addr) {
  409. $addr = $addr->toArray();
  410. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  411. $cityId = $addr['city_id'] ?? 0;
  412. $tempIds[] = 1;
  413. foreach ($cartInfo as $key_c => $item_c) {
  414. $tempIds[] = $item_c['productInfo']['temp_id'];
  415. }
  416. $tempIds = array_unique($tempIds);
  417. /** @var ShippingTemplatesServices $shippServices */
  418. $shippServices = app()->make(ShippingTemplatesServices::class);
  419. $temp = $shippServices->getShippingColumn(['id' => $tempIds], 'type,appoint', 'id');
  420. /** @var ShippingTemplatesRegionServices $regionServices */
  421. $regionServices = app()->make(ShippingTemplatesRegionServices::class);
  422. $regions = $regionServices->getTempRegionList($tempIds, [$cityId, 0], 'temp_id,first,first_price,continue,continue_price', 'temp_id');
  423. $temp_num = [];
  424. foreach ($cartInfo as $cart) {
  425. $tempId = $cart['productInfo']['temp_id'] ?? 1;
  426. $type = $temp[$tempId]['type'] ?? $temp[1]['type'];
  427. if ($type == 1) {
  428. $num = $cart['cart_num'];
  429. } elseif ($type == 2) {
  430. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  431. } else {
  432. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  433. }
  434. $region = $regions[$tempId] ?? $regions[1];
  435. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  436. $temp_num[$cart['productInfo']['temp_id']]['cart_id'][] = $cart['id'];
  437. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  438. $temp_num[$cart['productInfo']['temp_id']]['type'] = $type;
  439. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  440. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  441. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  442. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  443. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  444. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  445. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
  446. } else {
  447. $temp_num[$cart['productInfo']['temp_id']]['cart_id'][] = $cart['id'];
  448. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  449. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  450. }
  451. }
  452. $cartInfo = array_combine(array_column($cartInfo, 'id'), $cartInfo);
  453. /** @var ShippingTemplatesFreeServices $freeServices */
  454. $freeServices = app()->make(ShippingTemplatesFreeServices::class);
  455. foreach ($temp_num as $k => $v) {
  456. if (isset($temp[$v['temp_id']]['appoint']) && $temp[$v['temp_id']]['appoint']) {
  457. if ($freeServices->isFree($v['temp_id'], $v['city_id'], $v['number'], $v['price'], $v['type'])) {
  458. //免运费
  459. foreach ($v['cart_id'] as $c_id) {
  460. if (isset($cartInfo[$c_id])) $cartInfo[$c_id]['postage_price'] = 0.00;
  461. }
  462. }
  463. }
  464. }
  465. $count = 0;
  466. $compute_price = 0.00;
  467. $total_price = 0;
  468. $postage_price = 0.00;
  469. foreach ($cartInfo as &$cart) {
  470. if (isset($cart['postage_price'])) {//免运费
  471. continue;
  472. }
  473. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  474. $count++;
  475. }
  476. foreach ($cartInfo as &$cart) {
  477. if (isset($cart['postage_price'])) {//免运费
  478. continue;
  479. }
  480. if ($count > 1) {
  481. $postage_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$storePostage, 2);
  482. $compute_price = bcadd((string)$compute_price, (string)$postage_price, 2);
  483. } else {
  484. $postage_price = bcsub((string)$storePostage, $compute_price, 2);
  485. }
  486. $cart['postage_price'] = $postage_price;
  487. $count--;
  488. }
  489. $cartInfo = array_merge($cartInfo);
  490. }
  491. }
  492. //保证不进运费模版计算的购物车商品postage_price字段有值
  493. foreach ($cartInfo as &$item) {
  494. if (!isset($item['postage_price'])) $item['postage_price'] = 0.00;
  495. }
  496. return $cartInfo;
  497. }
  498. /**
  499. * 计算订单商品积分实际抵扣金额
  500. * @param array $cartInfo
  501. * @param array $priceData
  502. * @return array
  503. */
  504. public function computeOrderProductIntegral(array $cartInfo, array $priceData)
  505. {
  506. $usedIntegral = $priceData['usedIntegral'] ?? 0;
  507. $deduction_price = $priceData['deduction_price'] ?? 0;
  508. if ($deduction_price) {
  509. $count = 0;
  510. $total_price = 0.00;
  511. $compute_price = 0.00;
  512. $integral_price = 0.00;
  513. $use_integral = 0;
  514. $compute_integral = 0;
  515. foreach ($cartInfo as $cart) {
  516. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  517. $count++;
  518. }
  519. foreach ($cartInfo as &$cart) {
  520. if ($count > 1) {
  521. $integral_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$deduction_price, 2);
  522. $compute_price = bcadd((string)$compute_price, (string)$integral_price, 2);
  523. $use_integral = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$usedIntegral, 0);
  524. $compute_integral = bcadd((string)$compute_integral, $use_integral, 0);
  525. } else {
  526. $integral_price = bcsub((string)$deduction_price, $compute_price, 2);
  527. $use_integral = bcsub((string)$usedIntegral, $compute_integral, 0);
  528. }
  529. $count--;
  530. $cart['integral_price'] = $integral_price;
  531. $cart['use_integral'] = $use_integral;
  532. }
  533. }
  534. return $cartInfo;
  535. }
  536. /**
  537. * 计算订单商品优惠券实际抵扣金额
  538. * @param array $cartInfo
  539. * @param array $priceData
  540. * @return array
  541. */
  542. public function computeOrderProductCoupon(array $cartInfo, array $priceData)
  543. {
  544. if ($priceData['coupon_id'] && $priceData['coupon_price'] ?? 0) {
  545. $count = 0;
  546. $total_price = 0.00;
  547. $compute_price = 0.00;
  548. $coupon_price = 0.00;
  549. /** @var StoreCouponUserServices $couponServices */
  550. $couponServices = app()->make(StoreCouponUserServices::class);
  551. $couponInfo = $couponServices->getOne(['id' => $priceData['coupon_id']], '*', ['issue']);
  552. if ($couponInfo) {
  553. $type = $couponInfo['applicable_type'] ?? 0;
  554. $counpon_id = $couponInfo['id'];
  555. switch ($type) {
  556. case 0:
  557. case 3:
  558. foreach ($cartInfo as $cart) {
  559. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  560. $count++;
  561. }
  562. foreach ($cartInfo as &$cart) {
  563. if ($count > 1) {
  564. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  565. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  566. } else {
  567. $coupon_price = bcsub((string)$couponInfo['coupon_price'], $compute_price, 2);
  568. }
  569. $cart['coupon_price'] = $coupon_price;
  570. $cart['coupon_id'] = $counpon_id;
  571. $count--;
  572. }
  573. break;
  574. case 1://品类券
  575. /** @var StoreCategoryServices $storeCategoryServices */
  576. $storeCategoryServices = app()->make(StoreCategoryServices::class);
  577. $cateGorys = $storeCategoryServices->getAllById((int)$couponInfo['category_id']);
  578. if ($cateGorys) {
  579. $cateIds = array_column($cateGorys, 'id');
  580. foreach ($cartInfo as $cart) {
  581. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  582. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  583. $count++;
  584. }
  585. }
  586. foreach ($cartInfo as &$cart) {
  587. $cart['coupon_id'] = 0;
  588. $cart['coupon_price'] = 0;
  589. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  590. if ($count > 1) {
  591. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  592. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  593. } else {
  594. $coupon_price = bcsub((string)$couponInfo['coupon_price'], $compute_price, 2);
  595. }
  596. $cart['coupon_id'] = $counpon_id;
  597. $cart['coupon_price'] = $coupon_price;
  598. $count--;
  599. }
  600. }
  601. }
  602. break;
  603. case 2://商品劵
  604. foreach ($cartInfo as $cart) {
  605. if (isset($cart['product_id']) && in_array($cart['product_id'], explode(',', $couponInfo['product_id']))) {
  606. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  607. $count++;
  608. }
  609. }
  610. foreach ($cartInfo as &$cart) {
  611. $cart['coupon_id'] = 0;
  612. $cart['coupon_price'] = 0;
  613. if (isset($cart['product_id']) && in_array($cart['product_id'], explode(',', $couponInfo['product_id']))) {
  614. if ($count > 1) {
  615. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  616. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  617. } else {
  618. $coupon_price = bcsub((string)$couponInfo['coupon_price'], $compute_price, 2);
  619. }
  620. $cart['coupon_id'] = $counpon_id;
  621. $cart['coupon_price'] = $coupon_price;
  622. $count--;
  623. }
  624. }
  625. break;
  626. }
  627. }
  628. }
  629. return $cartInfo;
  630. }
  631. /**
  632. * 计算实际佣金
  633. * @param int $uid
  634. * @param array $cartInfo
  635. * @return array
  636. * @throws \think\db\exception\DataNotFoundException
  637. * @throws \think\db\exception\DbException
  638. * @throws \think\db\exception\ModelNotFoundException
  639. */
  640. public function computeOrderProductBrokerage(int $uid, array $cartInfo, $orderInfo)
  641. {
  642. /** @var AgentLevelServices $agentLevelServices */
  643. $agentLevelServices = app()->make(AgentLevelServices::class);
  644. [$one_brokerage_up, $two_brokerage_up, $spread_one_uid, $spread_two_uid] = $agentLevelServices->getAgentLevelBrokerage($uid);
  645. $BrokerageOne = sys_config('store_brokerage_ratio') != '' ? sys_config('store_brokerage_ratio') : 0;
  646. $BrokerageTwo = sys_config('store_brokerage_two') != '' ? sys_config('store_brokerage_two') : 0;
  647. $storeBrokerageRatio = $BrokerageOne + (($BrokerageOne * $one_brokerage_up) / 100);
  648. $storeBrokerageTwo = $BrokerageTwo + (($BrokerageTwo * $two_brokerage_up) / 100);
  649. if (sys_config('brokerage_level') == 1) {
  650. $storeBrokerageTwo = $spread_two_uid = 0;
  651. }
  652. /** @var DivisionServices $divisionService */
  653. $divisionService = app()->make(DivisionServices::class);
  654. [$storeBrokerageRatio, $storeBrokerageTwo, $staffPercent, $agentPercent, $divisionPercent] = $divisionService->getDivisionPercent($uid, $storeBrokerageRatio, $storeBrokerageTwo, sys_config('is_self_brokerage', 0));
  655. foreach ($cartInfo as &$cart) {
  656. $oneBrokerage = '0';//一级返佣金额
  657. $twoBrokerage = '0';//二级返佣金额
  658. $staffBrokerage = '0';//店员返佣金额
  659. $agentBrokerage = '0';//代理商返佣金额
  660. $divisionBrokerage = '0';//事业部返佣金额
  661. $cartNum = (string)$cart['cart_num'] ?? '0';
  662. if (isset($cart['productInfo'])) {
  663. $productInfo = $cart['productInfo'];
  664. //计算商品金额
  665. if (isset($productInfo['attrInfo'])) {
  666. $price = bcmul((string)($productInfo['attrInfo']['price'] ?? '0'), $cartNum, 4);
  667. } else {
  668. $price = bcmul((string)($productInfo['price'] ?? '0'), $cartNum, 4);
  669. }
  670. $staffBrokerage = bcmul((string)$price, (string)bcdiv($staffPercent, 100, 4), 2);
  671. $agentBrokerage = bcmul((string)$price, (string)bcdiv($agentPercent, 100, 4), 2);
  672. $divisionBrokerage = bcmul((string)$price, (string)bcdiv($divisionPercent, 100, 4), 2);
  673. //指定返佣金额
  674. if (isset($productInfo['is_sub']) && $productInfo['is_sub'] == 1) {
  675. $oneBrokerage = $storeBrokerageRatio > 0 ? bcmul((string)($productInfo['attrInfo']['brokerage'] ?? '0'), $cartNum, 2) : 0;
  676. $twoBrokerage = $storeBrokerageTwo > 0 ? bcmul((string)($productInfo['attrInfo']['brokerage_two'] ?? '0'), $cartNum, 2) : 0;
  677. } else {
  678. if ($price) {
  679. //一级返佣比例 小于等于零时直接返回 不返佣
  680. if ($storeBrokerageRatio > 0) {
  681. //计算获取一级返佣比例
  682. $brokerageRatio = bcdiv($storeBrokerageRatio, 100, 4);
  683. $oneBrokerage = bcmul((string)$price, (string)$brokerageRatio, 2);
  684. }
  685. //二级返佣比例小于等于0 直接返回
  686. if ($storeBrokerageTwo > 0) {
  687. //计算获取二级返佣比例
  688. $brokerageTwo = bcdiv($storeBrokerageTwo, 100, 4);
  689. $twoBrokerage = bcmul((string)$price, (string)$brokerageTwo, 2);
  690. }
  691. }
  692. }
  693. }
  694. $cart['one_brokerage'] = $oneBrokerage;
  695. $cart['two_brokerage'] = $twoBrokerage;
  696. $cart['staff_brokerage'] = $staffBrokerage;
  697. $cart['agent_brokerage'] = $agentBrokerage;
  698. $cart['division_brokerage'] = $divisionBrokerage;
  699. }
  700. return [$cartInfo, [$spread_one_uid, $spread_two_uid]];
  701. }
  702. }