StoreOrderCreateServices.php 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\order;
  12. use app\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\services\CacheService;
  24. use app\dao\order\StoreOrderDao;
  25. use app\services\user\UserServices;
  26. use think\exception\ValidateException;
  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 ValidateException('请选择收货地址!');
  128. }
  129. if (!$addressInfo = $addressServices->getOne(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]))
  130. throw new ValidateException('地址选择有误!');
  131. $addressInfo = $addressInfo->toArray();
  132. } else {
  133. if ((!$real_name || !$phone) && $virtual_type == 0) {
  134. throw new ValidateException('请填写姓名和电话');
  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 ValidateException('营销商品不能使用线下支付!');
  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(),
  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' => $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 ValidateException('暂无门店无法选择门店自提');
  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 ValidateException('订单生成失败!');
  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'], $cartInfo);
  251. return $order;
  252. });
  253. //订单创建成功后置事件
  254. event('order.orderCreateAfter', [$order, compact('cartInfo', 'priceData', 'addressId', 'cartIds', 'news'), $uid, $key, $combinationId, $seckillId, $bargainId]);
  255. return $order;
  256. }
  257. /**
  258. * 抵扣积分
  259. * @param array $userInfo
  260. * @param bool $useIntegral
  261. * @param array $priceData
  262. * @param int $uid
  263. * @param string $key
  264. */
  265. public function deductIntegral(array $userInfo, bool $useIntegral, array $priceData, int $uid, $orderId)
  266. {
  267. $res2 = true;
  268. if ($useIntegral && $userInfo['integral'] > 0) {
  269. /** @var UserServices $userServices */
  270. $userServices = app()->make(UserServices::class);
  271. if (!$priceData['SurplusIntegral']) {
  272. $res2 = false !== $userServices->update($uid, ['integral' => 0]);
  273. } else {
  274. $res2 = false !== $userServices->bcDec($userInfo['uid'], 'integral', $priceData['usedIntegral'], 'uid');
  275. }
  276. /** @var UserBillServices $userBillServices */
  277. $userBillServices = app()->make(UserBillServices::class);
  278. $res3 = $userBillServices->income('deduction', $uid, [
  279. 'number' => $priceData['usedIntegral'],
  280. 'deductionPrice' => $priceData['deduction_price']
  281. ], $userInfo['integral'] - $priceData['usedIntegral'], $orderId);
  282. $res2 = $res2 && false != $res3;
  283. }
  284. if (!$res2) {
  285. throw new ValidateException('使用积分抵扣失败!');
  286. }
  287. }
  288. /**
  289. * 扣库存
  290. * @param array $cartInfo
  291. * @param int $combinationId
  292. * @param int $seckillId
  293. * @param int $bargainId
  294. */
  295. public function decGoodsStock(array $cartInfo, int $combinationId, int $seckillId, int $bargainId, int $advanceId)
  296. {
  297. $res5 = true;
  298. /** @var StoreProductServices $services */
  299. $services = app()->make(StoreProductServices::class);
  300. /** @var StoreSeckillServices $seckillServices */
  301. $seckillServices = app()->make(StoreSeckillServices::class);
  302. /** @var StoreCombinationServices $pinkServices */
  303. $pinkServices = app()->make(StoreCombinationServices::class);
  304. /** @var StoreBargainServices $bargainServices */
  305. $bargainServices = app()->make(StoreBargainServices::class);
  306. /** @var StoreAdvanceServices $advanceServices */
  307. $advanceServices = app()->make(StoreAdvanceServices::class);
  308. try {
  309. foreach ($cartInfo as $cart) {
  310. //减库存加销量
  311. if ($combinationId) $res5 = $res5 && $pinkServices->decCombinationStock((int)$cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  312. else if ($seckillId) $res5 = $res5 && $seckillServices->decSeckillStock((int)$cart['cart_num'], $seckillId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  313. else if ($bargainId) $res5 = $res5 && $bargainServices->decBargainStock((int)$cart['cart_num'], $bargainId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  314. else if ($advanceId) $res5 = $res5 && $advanceServices->decAdvanceStock((int)$cart['cart_num'], $advanceId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  315. else $res5 = $res5 && $services->decProductStock((int)$cart['cart_num'], (int)$cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  316. }
  317. if (!$res5) {
  318. throw new ValidateException('库存不足!');
  319. }
  320. } catch (\Throwable $e) {
  321. throw new ValidateException('库存不足!');
  322. }
  323. }
  324. /**
  325. * 订单创建后的后置事件
  326. * @param UserAddressServices $addressServices
  327. * @param $order
  328. * @param array $group
  329. */
  330. public function orderCreateAfter($order, array $group)
  331. {
  332. /** @var UserAddressServices $addressServices */
  333. $addressServices = app()->make(UserAddressServices::class);
  334. //设置用户默认地址
  335. if (!$addressServices->be(['is_default' => 1, 'uid' => $order['uid']])) {
  336. $addressServices->setDefaultAddress($group['addressId'], $order['uid']);
  337. }
  338. //删除购物车
  339. if ($group['news']) {
  340. array_map(function ($key) {
  341. CacheService::redisHandler()->delete($key);
  342. }, $group['cartIds']);
  343. } else {
  344. /** @var StoreCartServices $cartServices */
  345. $cartServices = app()->make(StoreCartServices::class);
  346. $cartServices->deleteCartStatus($group['cartIds']);
  347. }
  348. }
  349. /**
  350. * 计算订单每个商品真实付款价格
  351. * @param array $cartInfo
  352. * @param array $priceData
  353. * @param $addressId
  354. * @param int $uid
  355. * @return array
  356. */
  357. public function computeOrderProductTruePrice(array $cartInfo, array $priceData, $addressId, int $uid, $orderInfo)
  358. {
  359. //统一放入默认数据
  360. foreach ($cartInfo as &$cart) {
  361. $cart['use_integral'] = 0;
  362. $cart['integral_price'] = 0.00;
  363. $cart['coupon_price'] = 0.00;
  364. }
  365. try {
  366. [$cartInfo, $spread_ids] = $this->computeOrderProductBrokerage($uid, $cartInfo, $orderInfo);
  367. $cartInfo = $this->computeOrderProductCoupon($cartInfo, $priceData);
  368. $cartInfo = $this->computeOrderProductIntegral($cartInfo, $priceData);
  369. // $cartInfo = $this->computeOrderProductPostage($cartInfo, $priceData, $addressId);
  370. } catch (\Throwable $e) {
  371. Log::error('订单商品结算失败,File:' . $e->getFile() . ',Line:' . $e->getLine() . ',Message:' . $e->getMessage());
  372. throw new ValidateException('订单商品结算失败');
  373. }
  374. //truePice实际支付单价(存在)
  375. //几件商品总体优惠 以及积分抵扣金额
  376. foreach ($cartInfo as &$cart) {
  377. $coupon_price = $cart['coupon_price'] ?? 0;
  378. $integral_price = $cart['integral_price'] ?? 0;
  379. $cart['sum_true_price'] = bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 2);
  380. if ($coupon_price) {
  381. $cart['sum_true_price'] = bcsub((string)$cart['sum_true_price'], (string)$coupon_price, 2);
  382. $uni_coupon_price = (string)bcdiv((string)$coupon_price, (string)$cart['cart_num'], 4);
  383. $cart['truePrice'] = $cart['truePrice'] > $uni_coupon_price ? bcsub((string)$cart['truePrice'], $uni_coupon_price, 2) : 0;
  384. }
  385. if ($integral_price) {
  386. $cart['sum_true_price'] = bcsub((string)$cart['sum_true_price'], (string)$integral_price, 2);
  387. $uni_integral_price = (string)bcdiv((string)$integral_price, (string)$cart['cart_num'], 4);
  388. $cart['truePrice'] = $cart['truePrice'] > $uni_integral_price ? bcsub((string)$cart['truePrice'], $uni_integral_price, 2) : 0;
  389. }
  390. }
  391. return [$cartInfo, $spread_ids];
  392. }
  393. /**
  394. * 计算每个商品实际支付运费
  395. * @param array $cartInfo
  396. * @param array $priceData
  397. * @return array
  398. */
  399. public function computeOrderProductPostage(array $cartInfo, array $priceData, $addressId)
  400. {
  401. $storePostage = $priceData['pay_postage'] ?? 0;
  402. if ($storePostage) {
  403. /** @var UserAddressServices $addressServices */
  404. $addressServices = app()->make(UserAddressServices::class);
  405. $addr = $addressServices->getAddress($addressId);
  406. if ($addr) {
  407. $addr = $addr->toArray();
  408. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  409. $cityId = $addr['city_id'] ?? 0;
  410. $tempIds[] = 1;
  411. foreach ($cartInfo as $key_c => $item_c) {
  412. $tempIds[] = $item_c['productInfo']['temp_id'];
  413. }
  414. $tempIds = array_unique($tempIds);
  415. /** @var ShippingTemplatesServices $shippServices */
  416. $shippServices = app()->make(ShippingTemplatesServices::class);
  417. $temp = $shippServices->getShippingColumn(['id' => $tempIds], 'type,appoint', 'id');
  418. /** @var ShippingTemplatesRegionServices $regionServices */
  419. $regionServices = app()->make(ShippingTemplatesRegionServices::class);
  420. $regions = $regionServices->getTempRegionList($tempIds, [$cityId, 0], 'temp_id,first,first_price,continue,continue_price', 'temp_id');
  421. $temp_num = [];
  422. foreach ($cartInfo as $cart) {
  423. $tempId = $cart['productInfo']['temp_id'] ?? 1;
  424. $type = $temp[$tempId]['type'] ?? $temp[1]['type'];
  425. if ($type == 1) {
  426. $num = $cart['cart_num'];
  427. } elseif ($type == 2) {
  428. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  429. } else {
  430. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  431. }
  432. $region = $regions[$tempId] ?? $regions[1];
  433. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  434. $temp_num[$cart['productInfo']['temp_id']]['cart_id'][] = $cart['id'];
  435. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  436. $temp_num[$cart['productInfo']['temp_id']]['type'] = $type;
  437. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  438. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  439. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  440. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  441. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  442. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  443. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
  444. } else {
  445. $temp_num[$cart['productInfo']['temp_id']]['cart_id'][] = $cart['id'];
  446. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  447. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  448. }
  449. }
  450. $cartInfo = array_combine(array_column($cartInfo, 'id'), $cartInfo);
  451. /** @var ShippingTemplatesFreeServices $freeServices */
  452. $freeServices = app()->make(ShippingTemplatesFreeServices::class);
  453. foreach ($temp_num as $k => $v) {
  454. if (isset($temp[$v['temp_id']]['appoint']) && $temp[$v['temp_id']]['appoint']) {
  455. if ($freeServices->isFree($v['temp_id'], $v['city_id'], $v['number'], $v['price'], $v['type'])) {
  456. //免运费
  457. foreach ($v['cart_id'] as $c_id) {
  458. if (isset($cartInfo[$c_id])) $cartInfo[$c_id]['postage_price'] = 0.00;
  459. }
  460. }
  461. }
  462. }
  463. $count = 0;
  464. $compute_price = 0.00;
  465. $total_price = 0;
  466. $postage_price = 0.00;
  467. foreach ($cartInfo as &$cart) {
  468. if (isset($cart['postage_price'])) {//免运费
  469. continue;
  470. }
  471. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  472. $count++;
  473. }
  474. foreach ($cartInfo as &$cart) {
  475. if (isset($cart['postage_price'])) {//免运费
  476. continue;
  477. }
  478. if ($count > 1) {
  479. $postage_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$storePostage, 2);
  480. $compute_price = bcadd((string)$compute_price, (string)$postage_price, 2);
  481. } else {
  482. $postage_price = bcsub((string)$storePostage, $compute_price, 2);
  483. }
  484. $cart['postage_price'] = $postage_price;
  485. $count--;
  486. }
  487. $cartInfo = array_merge($cartInfo);
  488. }
  489. }
  490. //保证不进运费模版计算的购物车商品postage_price字段有值
  491. foreach ($cartInfo as &$item) {
  492. if (!isset($item['postage_price'])) $item['postage_price'] = 0.00;
  493. }
  494. return $cartInfo;
  495. }
  496. /**
  497. * 计算订单商品积分实际抵扣金额
  498. * @param array $cartInfo
  499. * @param array $priceData
  500. * @return array
  501. */
  502. public function computeOrderProductIntegral(array $cartInfo, array $priceData)
  503. {
  504. $usedIntegral = $priceData['usedIntegral'] ?? 0;
  505. $deduction_price = $priceData['deduction_price'] ?? 0;
  506. if ($deduction_price) {
  507. $count = 0;
  508. $total_price = 0.00;
  509. $compute_price = 0.00;
  510. $integral_price = 0.00;
  511. $use_integral = 0;
  512. $compute_integral = 0;
  513. foreach ($cartInfo as $cart) {
  514. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  515. $count++;
  516. }
  517. foreach ($cartInfo as &$cart) {
  518. if ($count > 1) {
  519. $integral_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$deduction_price, 2);
  520. $compute_price = bcadd((string)$compute_price, (string)$integral_price, 2);
  521. $use_integral = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$usedIntegral, 0);
  522. $compute_integral = bcadd((string)$compute_integral, $use_integral, 0);
  523. } else {
  524. $integral_price = bcsub((string)$deduction_price, $compute_price, 2);
  525. $use_integral = bcsub((string)$usedIntegral, $compute_integral, 0);
  526. }
  527. $count--;
  528. $cart['integral_price'] = $integral_price;
  529. $cart['use_integral'] = $use_integral;
  530. }
  531. }
  532. return $cartInfo;
  533. }
  534. /**
  535. * 计算订单商品优惠券实际抵扣金额
  536. * @param array $cartInfo
  537. * @param array $priceData
  538. * @return array
  539. */
  540. public function computeOrderProductCoupon(array $cartInfo, array $priceData)
  541. {
  542. if ($priceData['coupon_id'] && $priceData['coupon_price'] ?? 0) {
  543. $count = 0;
  544. $total_price = 0.00;
  545. $compute_price = 0.00;
  546. $coupon_price = 0.00;
  547. /** @var StoreCouponUserServices $couponServices */
  548. $couponServices = app()->make(StoreCouponUserServices::class);
  549. $couponInfo = $couponServices->getOne(['id' => $priceData['coupon_id']], '*', ['issue']);
  550. if ($couponInfo) {
  551. $type = $couponInfo['applicable_type'] ?? 0;
  552. $counpon_id = $couponInfo['id'];
  553. switch ($type) {
  554. case 0:
  555. case 3:
  556. foreach ($cartInfo as $cart) {
  557. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  558. $count++;
  559. }
  560. foreach ($cartInfo as &$cart) {
  561. if ($count > 1) {
  562. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  563. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  564. } else {
  565. $coupon_price = bcsub((string)$couponInfo['coupon_price'], $compute_price, 2);
  566. }
  567. $cart['coupon_price'] = $coupon_price;
  568. $cart['coupon_id'] = $counpon_id;
  569. $count--;
  570. }
  571. break;
  572. case 1://品类券
  573. /** @var StoreCategoryServices $storeCategoryServices */
  574. $storeCategoryServices = app()->make(StoreCategoryServices::class);
  575. $cateGorys = $storeCategoryServices->getAllById((int)$couponInfo['category_id']);
  576. if ($cateGorys) {
  577. $cateIds = array_column($cateGorys, 'id');
  578. foreach ($cartInfo as $cart) {
  579. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  580. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  581. $count++;
  582. }
  583. }
  584. foreach ($cartInfo as &$cart) {
  585. $cart['coupon_id'] = 0;
  586. $cart['coupon_price'] = 0;
  587. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  588. if ($count > 1) {
  589. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  590. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  591. } else {
  592. $coupon_price = bcsub((string)$couponInfo['coupon_price'], $compute_price, 2);
  593. }
  594. $cart['coupon_id'] = $counpon_id;
  595. $cart['coupon_price'] = $coupon_price;
  596. $count--;
  597. }
  598. }
  599. }
  600. break;
  601. case 2://商品劵
  602. foreach ($cartInfo as $cart) {
  603. if (isset($cart['product_id']) && in_array($cart['product_id'], explode(',', $couponInfo['product_id']))) {
  604. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  605. $count++;
  606. }
  607. }
  608. foreach ($cartInfo as &$cart) {
  609. $cart['coupon_id'] = 0;
  610. $cart['coupon_price'] = 0;
  611. if (isset($cart['product_id']) && in_array($cart['product_id'], explode(',', $couponInfo['product_id']))) {
  612. if ($count > 1) {
  613. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  614. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  615. } else {
  616. $coupon_price = bcsub((string)$couponInfo['coupon_price'], $compute_price, 2);
  617. }
  618. $cart['coupon_id'] = $counpon_id;
  619. $cart['coupon_price'] = $coupon_price;
  620. $count--;
  621. }
  622. }
  623. break;
  624. }
  625. }
  626. }
  627. return $cartInfo;
  628. }
  629. /**
  630. * 计算实际佣金
  631. * @param int $uid
  632. * @param array $cartInfo
  633. * @return array
  634. * @throws \think\db\exception\DataNotFoundException
  635. * @throws \think\db\exception\DbException
  636. * @throws \think\db\exception\ModelNotFoundException
  637. */
  638. public function computeOrderProductBrokerage(int $uid, array $cartInfo, $orderInfo)
  639. {
  640. /** @var AgentLevelServices $agentLevelServices */
  641. $agentLevelServices = app()->make(AgentLevelServices::class);
  642. [$one_brokerage_up, $two_brokerage_up, $spread_one_uid, $spread_two_uid] = $agentLevelServices->getAgentLevelBrokerage($uid);
  643. $BrokerageOne = sys_config('store_brokerage_ratio') != '' ? sys_config('store_brokerage_ratio') : 0;
  644. $BrokerageTwo = sys_config('store_brokerage_two') != '' ? sys_config('store_brokerage_two') : 0;
  645. $storeBrokerageRatio = $BrokerageOne + (($BrokerageOne * $one_brokerage_up) / 100);
  646. $storeBrokerageTwo = $BrokerageTwo + (($BrokerageTwo * $two_brokerage_up) / 100);
  647. /** @var DivisionServices $divisionService */
  648. $divisionService = app()->make(DivisionServices::class);
  649. [$storeBrokerageRatio, $storeBrokerageTwo, $staffPercent, $agentPercent, $divisionPercent] = $divisionService->getDivisionPercent($uid, $storeBrokerageRatio, $storeBrokerageTwo, sys_config('is_self_brokerage', 0));
  650. foreach ($cartInfo as &$cart) {
  651. $oneBrokerage = '0';//一级返佣金额
  652. $twoBrokerage = '0';//二级返佣金额
  653. $staffBrokerage = '0';//店员返佣金额
  654. $agentBrokerage = '0';//代理商返佣金额
  655. $divisionBrokerage = '0';//事业部返佣金额
  656. $cartNum = (string)$cart['cart_num'] ?? '0';
  657. if (isset($cart['productInfo'])) {
  658. $productInfo = $cart['productInfo'];
  659. //计算商品金额
  660. if (isset($productInfo['attrInfo'])) {
  661. $price = bcmul((string)($productInfo['attrInfo']['price'] ?? '0'), $cartNum, 4);
  662. } else {
  663. $price = bcmul((string)($productInfo['price'] ?? '0'), $cartNum, 4);
  664. }
  665. $staffBrokerage = bcmul((string)$price, (string)bcdiv($staffPercent, 100, 4), 2);
  666. $agentBrokerage = bcmul((string)$price, (string)bcdiv($agentPercent, 100, 4), 2);
  667. $divisionBrokerage = bcmul((string)$price, (string)bcdiv($divisionPercent, 100, 4), 2);
  668. //指定返佣金额
  669. if (isset($productInfo['is_sub']) && $productInfo['is_sub'] == 1) {
  670. $oneBrokerage = $storeBrokerageRatio > 0 ? bcmul((string)($productInfo['attrInfo']['brokerage'] ?? '0'), $cartNum, 2) : 0;
  671. $twoBrokerage = $storeBrokerageTwo > 0 ? bcmul((string)($productInfo['attrInfo']['brokerage_two'] ?? '0'), $cartNum, 2) : 0;
  672. } else {
  673. if ($price) {
  674. //一级返佣比例 小于等于零时直接返回 不返佣
  675. if ($storeBrokerageRatio > 0) {
  676. //计算获取一级返佣比例
  677. $brokerageRatio = bcdiv($storeBrokerageRatio, 100, 4);
  678. $oneBrokerage = bcmul((string)$price, (string)$brokerageRatio, 2);
  679. }
  680. //二级返佣比例小于等于0 直接返回
  681. if ($storeBrokerageTwo > 0) {
  682. //计算获取二级返佣比例
  683. $brokerageTwo = bcdiv($storeBrokerageTwo, 100, 4);
  684. $twoBrokerage = bcmul((string)$price, (string)$brokerageTwo, 2);
  685. }
  686. }
  687. }
  688. }
  689. $cart['one_brokerage'] = $oneBrokerage;
  690. $cart['two_brokerage'] = $twoBrokerage;
  691. $cart['staff_brokerage'] = $staffBrokerage;
  692. $cart['agent_brokerage'] = $agentBrokerage;
  693. $cart['division_brokerage'] = $divisionBrokerage;
  694. }
  695. return [$cartInfo, [$spread_one_uid, $spread_two_uid]];
  696. }
  697. }