StoreOrderCreateServices.php 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  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\jobs\activity\StorePromotionsJob;
  13. use app\services\activity\discounts\StoreDiscountsServices;
  14. use app\services\activity\newcomer\StoreNewcomerServices;
  15. use app\services\agent\AgentLevelServices;
  16. use app\services\activity\coupon\StoreCouponUserServices;
  17. use app\services\other\CityAreaServices;
  18. use app\services\pay\PayServices;
  19. use app\services\product\branch\StoreBranchProductServices;
  20. use app\services\product\brand\StoreBrandServices;
  21. use app\services\product\category\StoreProductCategoryServices;
  22. use app\services\product\shipping\ShippingTemplatesFreeServices;
  23. use app\services\product\shipping\ShippingTemplatesRegionServices;
  24. use app\services\product\shipping\ShippingTemplatesServices;
  25. use app\services\wechat\WechatUserServices;
  26. use app\services\BaseServices;
  27. use crmeb\services\CacheService;
  28. use app\dao\order\StoreOrderDao;
  29. use app\services\user\UserServices;
  30. use crmeb\traits\ServicesTrait;
  31. use think\exception\ValidateException;
  32. use app\services\user\UserBillServices;
  33. use app\services\user\UserAddressServices;
  34. use app\services\activity\bargain\StoreBargainServices;
  35. use app\services\activity\seckill\StoreSeckillServices;
  36. use app\services\store\SystemStoreServices;
  37. use app\services\activity\combination\StoreCombinationServices;
  38. use app\services\product\product\StoreProductServices;
  39. use app\services\activity\collage\UserCollageServices;
  40. use app\services\activity\collage\UserCollagePartakeServices;
  41. use think\facade\Cache;
  42. use think\facade\Log;
  43. /**
  44. * 订单创建
  45. * Class StoreOrderCreateServices
  46. * @package app\services\order
  47. * @mixin StoreOrderDao
  48. */
  49. class StoreOrderCreateServices extends BaseServices
  50. {
  51. use ServicesTrait;
  52. /**
  53. * StoreOrderCreateServices constructor.
  54. * @param StoreOrderDao $dao
  55. */
  56. public function __construct(StoreOrderDao $dao)
  57. {
  58. $this->dao = $dao;
  59. }
  60. /**
  61. * 使用雪花算法生成订单ID
  62. * @return string
  63. * @throws \Exception
  64. */
  65. public function getNewOrderId(string $prefix = 'wx')
  66. {
  67. $snowflake = new \Godruoyi\Snowflake\Snowflake();
  68. $is_callable = function ($currentTime) {
  69. // if (is_win()) {
  70. $redis = Cache::store('redis');
  71. $swooleSequenceResolver = new \Godruoyi\Snowflake\RedisSequenceResolver($redis->handler());
  72. return $swooleSequenceResolver->sequence($currentTime);
  73. // } else {
  74. // $swooleSequenceResolver = new \Godruoyi\Snowflake\SwooleSequenceResolver();
  75. // return $swooleSequenceResolver->sequence($currentTime);
  76. // }
  77. };
  78. //32位
  79. if (PHP_INT_SIZE == 4) {
  80. $id = abs($snowflake->setSequenceResolver($is_callable)->id());
  81. } else {
  82. $id = $snowflake->setStartTimeStamp(strtotime('2020-06-05') * 1000)->setSequenceResolver($is_callable)->id();
  83. }
  84. return $prefix . $id;
  85. }
  86. /**
  87. * 核销订单生成核销码
  88. * @return false|string
  89. */
  90. public function getStoreCode()
  91. {
  92. mt_srand();
  93. [$msec, $sec] = explode(' ', microtime());
  94. $num = time() + mt_rand(10, 999999) . '' . substr($msec, 2, 3);//生成随机数
  95. if (strlen($num) < 12)
  96. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  97. else
  98. $num = substr($num, 0, 12);
  99. if ($this->dao->count(['verify_code' => $num])) {
  100. return $this->getStoreCode();
  101. }
  102. return $num;
  103. }
  104. /**
  105. * 创建订单
  106. * @param int $uid
  107. * @param string $key
  108. * @param array $cartGroup
  109. * @param int $addressId
  110. * @param string $payType
  111. * @param array $addressInfo
  112. * @param array $userInfo
  113. * @param bool $useIntegral
  114. * @param int $couponId
  115. * @param string $mark
  116. * @param int $pinkId
  117. * @param int $isChannel
  118. * @param int $shippingType
  119. * @param int $storeId
  120. * @param false $news
  121. * @param array $customForm
  122. * @param int $invoice_id
  123. * @param string $from
  124. * @return mixed
  125. * @throws \think\db\exception\DataNotFoundException
  126. * @throws \think\db\exception\DbException
  127. * @throws \think\db\exception\ModelNotFoundException
  128. */
  129. public function createOrder(int $uid, string $key, array $cartGroup, int $addressId, string $payType, array $addressInfo, array $userInfo = [], bool $useIntegral = false, $couponId = 0, $mark = '', $pinkId = 0, $isChannel = 0, $shippingType = 1, $storeId = 0, $news = false, $customForm = [], int $invoice_id = 0, string $from = '', int $collate_code_id = 0)
  130. {
  131. /** @var StoreOrderComputedServices $computedServices */
  132. $computedServices = app()->make(StoreOrderComputedServices::class);
  133. $priceData = $computedServices->computedOrder($uid, $userInfo, $cartGroup, $addressId, $payType, $useIntegral, $couponId, $shippingType);
  134. $cartInfo = $cartGroup['cartInfo'];
  135. $priceGroup = $cartGroup['priceGroup'];
  136. $cartIds = [];
  137. $totalNum = 0;
  138. $gainIntegral = 0;
  139. foreach ($cartInfo as $cart) {
  140. $cartIds[] = $cart['id'];
  141. $totalNum += $cart['cart_num'];
  142. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul((string)$cart['cart_num'], (string)$cart['productInfo']['give_integral'], 0) : 0;
  143. $gainIntegral = bcadd((string)$gainIntegral, (string)$cartInfoGainIntegral, 0);
  144. }
  145. $deduction = $cartGroup['deduction'];
  146. $other = $cartGroup['other'];
  147. $promotions_give = [
  148. 'give_integral' => $other['give_integral'] ?? 0,
  149. 'give_coupon' => $other['give_coupon'] ?? [],
  150. 'give_product' => $other['give_product'] ?? [],
  151. 'promotions' => $other['promotions'] ?? []
  152. ];
  153. $type = (int)$deduction['type'] ?? 0;
  154. $activity_id = (int)$deduction['activity_id'] ?? 0;
  155. $collateCodeId = (int)$deduction['collate_code_id'] ?? 0;
  156. $product_type = (int)$deduction['product_type'] ?? 0;
  157. /** @var UserCollageServices $collageServices */
  158. $collageServices = app()->make(UserCollageServices::class);
  159. if (in_array($type, [1, 2, 3, 5])) {
  160. $couponId = 0;
  161. if ($type != 5) $useIntegral = false;
  162. $systemPayType = PayServices::PAY_TYPE;
  163. unset($systemPayType['offline']);
  164. if ($from != 'pc' && !array_key_exists($payType, $systemPayType)) {
  165. throw new ValidateException('营销商品不能使用线下支付!');
  166. }
  167. } else if ($type == 8) {
  168. $gainIntegral = 0;
  169. } else if ($type == 9 || $type == 10) {
  170. if ($collateCodeId != $collate_code_id) throw new ValidateException('拼单/桌码ID有误!');
  171. $status = $collageServices->value(['id' => $collate_code_id], 'status');
  172. if ($status >= 2) throw new ValidateException($type == 10 ? '桌码' : '拼单' . '已生成订单!');
  173. $activity_id = $collate_code_id;
  174. }
  175. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  176. if (!sys_config('store_func_status', 1) || !sys_config('store_self_mention', 1)) $shippingType = 1;
  177. $userAddress = $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['street'] . ' ' . $addressInfo['detail'];
  178. $userLocation = $addressInfo['longitude'] . ' ' . $addressInfo['latitude'];
  179. $orderInfo = [
  180. 'uid' => $uid,
  181. 'type' => $type,
  182. 'order_id' => $this->getNewOrderId(),
  183. 'real_name' => $addressInfo['real_name'],
  184. 'user_phone' => $addressInfo['phone'],
  185. 'user_address' => $userAddress,
  186. 'order_province' => $addressInfo['province'],
  187. 'order_city' => $addressInfo['city'],
  188. 'order_district' => $addressInfo['district'],
  189. 'send_area_award' => 0,
  190. 'user_location' => $userLocation,
  191. 'cart_id' => $cartIds,
  192. 'total_num' => $totalNum,
  193. 'total_price' => $priceGroup['sumPrice'] ?? $priceGroup['totalPrice'],
  194. 'total_postage' => $priceData['total_postage'] ?? $priceGroup['storePostage'],
  195. 'coupon_id' => $couponId,
  196. 'coupon_price' => $priceData['coupon_price'],
  197. 'first_order_price' => $priceData['first_order_price'],
  198. 'promotions_price' => $priceData['promotions_price'],
  199. 'pay_price' => $priceData['pay_price'],
  200. 'pay_postage' => $priceData['pay_postage'],
  201. 'deduction_price' => $priceData['deduction_price'],
  202. 'paid' => 0,
  203. 'pay_type' => $payType,
  204. 'use_integral' => $priceData['usedIntegral'],
  205. 'gain_integral' => $gainIntegral,
  206. 'mark' => htmlspecialchars($mark),
  207. 'product_type' => $product_type,
  208. 'activity_id' => $activity_id,
  209. 'pink_id' => $pinkId,
  210. 'cost' => $priceGroup['costPrice'],
  211. 'is_channel' => $isChannel,
  212. 'add_time' => time(),
  213. 'unique' => $key,
  214. 'shipping_type' => $shippingType,
  215. 'channel_type' => $userInfo['user_type'],
  216. 'province' => '',
  217. 'spread_uid' => 0,
  218. 'spread_two_uid' => 0,
  219. 'custom_form' => json_encode($customForm),
  220. 'promotions_give' => json_encode($promotions_give),
  221. 'give_integral' => $promotions_give['give_integral'] ?? 0,
  222. 'give_coupon' => implode(',', $promotions_give['give_coupon'] ?? []),
  223. 'store_id' => $storeId
  224. ];
  225. if ($orderInfo['total_price'] > sys_config('max_price', 0) && sys_config('max_price', 0) > 0) {
  226. throw new ValidateException('下单金额不超过' . sys_config('max_price'));
  227. }
  228. if ($orderInfo['total_price'] < sys_config('min_price', 0) && sys_config('min_price', 0) > 0) {
  229. throw new ValidateException('下单金额不低于' . sys_config('max_price'));
  230. }
  231. $orderPre = $this->dao->search(['uid' => $uid, 'is_del' => 0, 'is_system_del' => 0])->order('add_time', 'desc')->find();
  232. if ($orderPre && $orderPre['add_time'] > (time() - (sys_config('order_time', 0) * 60))) {
  233. throw new ValidateException('请等待' . ((sys_config('order_time', 0) * 60) - (time() - $orderPre['add_time'])) . '秒后再下单');
  234. }
  235. if ($userInfo['user_type'] == 'wechat' || $userInfo['user_type'] == 'routine') {
  236. /** @var WechatUserServices $wechatServices */
  237. $wechatServices = app()->make(WechatUserServices::class);
  238. $orderInfo['province'] = $wechatServices->value(['uid' => $uid, 'user_type' => $userInfo['user_type']], 'province') ?: '';
  239. }
  240. if ($shippingType == 2) {
  241. $orderInfo['verify_code'] = $this->getStoreCode();
  242. /** @var SystemStoreServices $storeServices */
  243. $storeServices = app()->make(SystemStoreServices::class);
  244. $orderInfo['store_id'] = $storeServices->getStoreDisposeCache($storeId, 'id');
  245. if (!$orderInfo['store_id']) {
  246. throw new ValidateException('暂无门店无法选择门店自提');
  247. }
  248. }
  249. $priceData['coupon_id'] = $couponId;
  250. $order = $this->transaction(function () use ($cartIds, $couponId, $orderInfo, $cartInfo, $key, $userInfo, $useIntegral, $priceData, $type, $activity_id, $uid, $addressId, $promotions_give, $storeId) {
  251. //创建订单
  252. $order = $this->dao->save($orderInfo);
  253. if ($couponId) {
  254. /** @var StoreCouponUserServices $couponServices */
  255. $couponServices = app()->make(StoreCouponUserServices::class);
  256. $couponServices->useCoupon($couponId, (int)$userInfo['uid'], $cartInfo, [], $storeId);
  257. }
  258. //抵扣积分
  259. $this->deductIntegral($userInfo, $useIntegral, $priceData, (int)$userInfo['uid'], $key);
  260. //扣库存
  261. $this->decGoodsStock($cartInfo, $type, $activity_id, $orderInfo['store_id'] ?? 0);
  262. //保存购物车商品信息
  263. /** @var StoreOrderCartInfoServices $cartServices */
  264. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  265. $cartServices->setCartInfo($order['id'], $cartInfo, (int)$uid, $promotions_give['promotions'] ?? []);
  266. return $order;
  267. });
  268. if (in_array($type, [9, 10]) && $collate_code_id > 0 && $order) {
  269. //关联订单和拼单、桌码
  270. $collageServices->update($collate_code_id, ['oid' => $order['id'], 'status' => 2]);
  271. /** @var UserCollagePartakeServices $partakeService */
  272. $partakeService = app()->make(UserCollagePartakeServices::class);
  273. $partakeService->update(['collate_code_id' => $collate_code_id, 'is_settle' => 0], ['status' => 0]);
  274. }
  275. //保存购物车商品信息
  276. // StoreCartJob::dispatch([$order['id'], $cartInfo, $uid, $promotions_give['promotions'] ?? []]);
  277. //扣除优惠活动赠品限量
  278. StorePromotionsJob::dispatchDo('changeGiveLimit', [$promotions_give]);
  279. //订单创建事件
  280. event('order.create', [$order, $userInfo, compact('cartInfo', 'priceData', 'addressId', 'cartIds', 'news'), compact('type', 'activity_id'), $invoice_id]);
  281. return $order;
  282. }
  283. /**
  284. * 抵扣积分
  285. * @param array $userInfo
  286. * @param bool $useIntegral
  287. * @param array $priceData
  288. * @param int $uid
  289. * @param string $key
  290. */
  291. public function deductIntegral(array $userInfo, bool $useIntegral, array $priceData, int $uid, string $key)
  292. {
  293. $res2 = true;
  294. if (sys_config('integral_ratio_status', 1) && $userInfo && $useIntegral && $userInfo['integral'] > 0) {
  295. /** @var UserServices $userServices */
  296. $userServices = app()->make(UserServices::class);
  297. if (!$priceData['SurplusIntegral']) {
  298. $integral = 0;
  299. } else {
  300. $integral = bcsub((string)$userInfo['integral'], (string)$priceData['usedIntegral']);
  301. }
  302. $res2 = false !== $userServices->update($uid, ['integral' => $integral]);
  303. /** @var UserBillServices $userBillServices */
  304. $userBillServices = app()->make(UserBillServices::class);
  305. $res3 = $userBillServices->income('deduction', $uid, [
  306. 'number' => (int)$priceData['usedIntegral'],
  307. 'deductionPrice' => $priceData['deduction_price']
  308. ], $integral, $key);
  309. $res2 = $res2 && false != $res3;
  310. }
  311. if (!$res2) {
  312. throw new ValidateException('使用积分抵扣失败!');
  313. }
  314. }
  315. /**
  316. * 扣库存
  317. * @param array $cartInfo
  318. * @param int $type
  319. * @param int $activity_id
  320. * @param int $store_id
  321. */
  322. public function decGoodsStock(array $cartInfo, int $type, int $activity_id, int $store_id = 0)
  323. {
  324. $res5 = true;
  325. /** @var StoreProductServices $services */
  326. $services = app()->make(StoreProductServices::class);
  327. /** @var StoreSeckillServices $seckillServices */
  328. $seckillServices = app()->make(StoreSeckillServices::class);
  329. /** @var StoreCombinationServices $pinkServices */
  330. $pinkServices = app()->make(StoreCombinationServices::class);
  331. /** @var StoreBargainServices $bargainServices */
  332. $bargainServices = app()->make(StoreBargainServices::class);
  333. /** @var StoreDiscountsServices $discountServices */
  334. $discountServices = app()->make(StoreDiscountsServices::class);
  335. /** @var StoreNewcomerServices $storeNewcomerServices */
  336. $storeNewcomerServices = app()->make(StoreNewcomerServices::class);
  337. try {
  338. foreach ($cartInfo as $cart) {
  339. $unique = isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '';
  340. $cart_num = (int)$cart['cart_num'];
  341. //减库存加销量
  342. switch ($type) {
  343. case 0://普通
  344. case 6://预售
  345. case 8://抽奖
  346. case 9://拼单
  347. case 10://桌码
  348. $res5 = $res5 && $services->decProductStock($cart_num, (int)$cart['productInfo']['id'], $unique, $store_id);
  349. break;
  350. case 1://秒杀
  351. $res5 = $res5 && $seckillServices->decSeckillStock($cart_num, $activity_id, $unique, $store_id);
  352. break;
  353. case 2://砍价
  354. $res5 = $res5 && $bargainServices->decBargainStock($cart_num, $activity_id, $unique, $store_id);
  355. break;
  356. case 3://拼团
  357. $res5 = $res5 && $pinkServices->decCombinationStock($cart_num, $activity_id, $unique, $store_id);
  358. break;
  359. case 5://套餐
  360. $res5 = $res5 && $discountServices->decDiscountStock($cart_num, $activity_id, (int)($cart['discount_product_id'] ?? 0), (int)($cart['product_id'] ?? 0), $unique, $store_id);
  361. break;
  362. case 7://新人专享
  363. $res5 = $res5 && $storeNewcomerServices->decNewcomerStock($cart_num, $activity_id, $unique, $store_id);
  364. break;
  365. default:
  366. $res5 = $res5 && $services->decProductStock($cart_num, (int)$cart['productInfo']['id'], $unique, $store_id);
  367. break;
  368. }
  369. }
  370. if ($type == 5 && $activity_id) {
  371. //改变套餐限量
  372. $res5 = $res5 && $discountServices->changeDiscountLimit($activity_id);
  373. }
  374. if (!$res5) {
  375. throw new ValidateException('库存不足!');
  376. }
  377. } catch (\Throwable $e) {
  378. throw new ValidateException('库存不足!');
  379. }
  380. }
  381. /**
  382. * 订单创建后的后置事件
  383. * @param UserAddressServices $addressServices
  384. * @param $order
  385. * @param array $group
  386. */
  387. public function orderCreateAfter($order, array $group)
  388. {
  389. /** @var UserAddressServices $addressServices */
  390. $addressServices = app()->make(UserAddressServices::class);
  391. //设置用户默认地址
  392. if ($order['uid'] && isset($group['addressId']) && $group['addressId'] && !$addressServices->be(['is_default' => 1, 'uid' => $order['uid']])) {
  393. $addressServices->setDefaultAddress($group['addressId'], $order['uid']);
  394. }
  395. //删除购物车
  396. if (isset($group['news']) && $group['news']) {
  397. array_map(function ($key) {
  398. CacheService::redisHandler()->delete($key);
  399. }, $group['cartIds']);
  400. } else {
  401. if (!isset($group['delCart']) || (isset($group['delCart']) && $group['delCart'] !== false)) {
  402. /** @var StoreCartServices $cartServices */
  403. $cartServices = app()->make(StoreCartServices::class);
  404. $cartServices->deleteCartStatus($group['cartIds'] ?? []);
  405. }
  406. }
  407. }
  408. /**
  409. * 计算订单每个商品真实付款价格
  410. * @param array $orderInfo
  411. * @param array $cartInfo
  412. * @param array $priceData
  413. * @param $addressId
  414. * @param int $uid
  415. * @param $userInfo
  416. * @return array
  417. */
  418. public function computeOrderProductTruePrice($orderInfo, array $cartInfo, array $priceData, $addressId, int $uid, $userInfo)
  419. {
  420. //统一放入默认数据
  421. foreach ($cartInfo as &$cart) {
  422. $cart['use_integral'] = 0;
  423. $cart['integral_price'] = 0.00;
  424. if (!isset($cart['coupon_price'])) {
  425. $cart['coupon_price'] = 0.00;
  426. }
  427. $cart['first_order_price'] = 0.00;
  428. $cart['one_brokerage'] = 0.00;
  429. $cart['two_brokerage'] = 0.00;
  430. }
  431. try {
  432. $promotionsGice = isset($orderInfo['promotions_give']) ? (is_string($orderInfo['promotions_give']) ? json_decode($orderInfo['promotions_give'], true) : $orderInfo['promotions_give']) : [];
  433. $promotions = [];
  434. if (isset($promotionsGice['promotions']) && $promotionsGice['promotions']) {
  435. $promotions = $promotionsGice['promotions'];
  436. }
  437. //$cartInfo = $this->computeOrderProductCoupon($cartInfo, $priceData, $promotions);
  438. $cartInfo = $this->computeOrderProductIntegral($cartInfo, $priceData);
  439. // $cartInfo = $this->computeOrderProductPostage($cartInfo, $priceData);
  440. $cartInfo = $this->computeOrderProductFirstDiscount($cartInfo, $priceData);
  441. } catch (\Throwable $e) {
  442. Log::error('订单商品结算失败,File:' . $e->getFile() . ',Line:' . $e->getLine() . ',Message:' . $e->getMessage());
  443. throw new ValidateException('订单商品结算失败');
  444. }
  445. //truePice实际支付单价(存在)
  446. //几件商品总体优惠 以及积分抵扣金额
  447. foreach ($cartInfo as &$cart) {
  448. $coupon_price = $cart['coupon_price'] ?? 0;
  449. $integral_price = $cart['integral_price'] ?? 0;
  450. $first_order_price = $cart['first_order_price'] ?? 0;
  451. $cart['sum_true_price'] = bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 2);
  452. if ($coupon_price) {
  453. $cart['sum_true_price'] = bcsub((string)$cart['sum_true_price'], (string)$coupon_price, 2);
  454. $uni_coupon_price = (string)bcdiv((string)$coupon_price, (string)$cart['cart_num'], 4);
  455. $cart['truePrice'] = $cart['truePrice'] > $uni_coupon_price ? bcsub((string)$cart['truePrice'], $uni_coupon_price, 2) : 0;
  456. }
  457. if ($integral_price) {
  458. $cart['sum_true_price'] = bcsub((string)$cart['sum_true_price'], (string)$integral_price, 2);
  459. $uni_integral_price = (string)bcdiv((string)$integral_price, (string)$cart['cart_num'], 4);
  460. $cart['truePrice'] = $cart['truePrice'] > $uni_integral_price ? bcsub((string)$cart['truePrice'], $uni_integral_price, 2) : 0;
  461. }
  462. if ($first_order_price) {
  463. $cart['sum_true_price'] = bcsub((string)$cart['sum_true_price'], (string)$first_order_price, 2);
  464. $uni_first_order_price = (string)bcdiv((string)$first_order_price, (string)$cart['cart_num'], 4);
  465. $cart['truePrice'] = $cart['truePrice'] > $uni_first_order_price ? bcsub((string)$cart['truePrice'], $uni_first_order_price, 2) : 0;
  466. }
  467. }
  468. //计算佣金:1售价2实际支付金额
  469. [$cartInfo, $spread_ids] = $this->computeOrderProductBrokerage($uid, $cartInfo, $userInfo);
  470. return [$cartInfo, $spread_ids];
  471. }
  472. /**
  473. * 计算每个商品实际支付运费
  474. * @param array $cartInfo
  475. * @param array $priceData
  476. * @return array
  477. */
  478. public function computeOrderProductPostage(array $cartInfo, array $priceData, $addressId)
  479. {
  480. $storePostage = $priceData['pay_postage'] ?? 0;
  481. if ($storePostage) {
  482. /** @var UserAddressServices $addressServices */
  483. $addressServices = app()->make(UserAddressServices::class);
  484. $addr = $addressServices->getAdderssCache($addressId);
  485. if ($addr) {
  486. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  487. $cityId = $addr['city_id'] ?? 0;
  488. $ids = [];
  489. if ($cityId) {
  490. /** @var CityAreaServices $cityAreaServices */
  491. $cityAreaServices = app()->make(CityAreaServices::class);
  492. $ids = $cityAreaServices->getRelationCityIds($cityId);
  493. }
  494. $cityIds = array_merge([0], $ids);
  495. $tempIds[] = 1;
  496. foreach ($cartInfo as $key_c => $item_c) {
  497. $tempIds[] = $item_c['productInfo']['temp_id'];
  498. }
  499. $tempIds = array_unique($tempIds);
  500. /** @var ShippingTemplatesServices $shippServices */
  501. $shippServices = app()->make(ShippingTemplatesServices::class);
  502. $temp = $shippServices->getShippingColumn(['id' => $tempIds], 'type,appoint', 'id');
  503. /** @var ShippingTemplatesRegionServices $regionServices */
  504. $regionServices = app()->make(ShippingTemplatesRegionServices::class);
  505. $regions = $regionServices->getTempRegionList($tempIds, $cityIds, 'temp_id,first,first_price,continue,continue_price', 'temp_id');
  506. $temp_num = [];
  507. foreach ($cartInfo as $cart) {
  508. $tempId = $cart['productInfo']['temp_id'] ?? 1;
  509. $type = isset($temp[$tempId]['type']) ? $temp[$tempId]['type'] : $temp[1]['type'];
  510. if ($type == 1) {
  511. $num = $cart['cart_num'];
  512. } elseif ($type == 2) {
  513. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  514. } else {
  515. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  516. }
  517. $region = isset($regions[$tempId]) ? $regions[$tempId] : $regions[1];
  518. if (!isset($temp_num[$tempId])) {
  519. $temp_num[$tempId] = [
  520. 'cart_id' => [$cart['id']],
  521. 'number' => $num,
  522. 'type' => $type,
  523. 'price' => bcmul($cart['cart_num'], $cart['truePrice'], 2),
  524. 'first' => $region['first'],
  525. 'first_price' => $region['first_price'],
  526. 'continue' => $region['continue'],
  527. 'continue_price' => $region['continue_price'],
  528. 'temp_id' => $tempId
  529. ];
  530. } else {
  531. $temp_num[$tempId]['cart_id'][] = $cart['id'];
  532. $temp_num[$tempId]['number'] += $num;
  533. $temp_num[$tempId]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  534. }
  535. }
  536. $cartInfo = array_combine(array_column($cartInfo, 'id'), $cartInfo);
  537. /** @var ShippingTemplatesFreeServices $freeServices */
  538. $freeServices = app()->make(ShippingTemplatesFreeServices::class);
  539. $freeList = $freeServices->isFreeList($tempIds, $cityIds, 0, 'temp_id,number,price', 'temp_id');
  540. if ($freeList) {
  541. foreach ($temp_num as $k => $v) {
  542. if (isset($temp[$v['temp_id']]['appoint']) && $temp[$v['temp_id']]['appoint'] && isset($freeList[$v['temp_id']])) {
  543. $free = $freeList[$v['temp_id']];
  544. $condition = $free['number'] <= $v['number'];
  545. if ($free['price'] <= $v['price'] && $condition) {
  546. //免运费
  547. foreach ($v['cart_id'] as $c_id) {
  548. if (isset($cartInfo[$c_id])) $cartInfo[$c_id]['postage_price'] = 0.00;
  549. }
  550. }
  551. }
  552. }
  553. }
  554. $count = 0;
  555. $compute_price = 0.00;
  556. $total_price = 0;
  557. $postage_price = 0.00;
  558. foreach ($cartInfo as $cart) {
  559. if (isset($cart['postage_price'])) {//免运费
  560. continue;
  561. }
  562. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  563. continue;
  564. }
  565. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  566. $count++;
  567. }
  568. foreach ($cartInfo as &$cart) {
  569. if (isset($cart['postage_price'])) {//免运费
  570. continue;
  571. }
  572. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  573. continue;
  574. }
  575. if ($count > 1) {
  576. $postage_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$storePostage, 2);
  577. $compute_price = bcadd((string)$compute_price, (string)$postage_price, 2);
  578. } else {
  579. $postage_price = bcsub((string)$storePostage, $compute_price, 2);
  580. }
  581. $cart['postage_price'] = $postage_price;
  582. $count--;
  583. }
  584. $cartInfo = array_merge($cartInfo);
  585. }
  586. }
  587. return $cartInfo;
  588. }
  589. /**
  590. * 计算订单商品积分实际抵扣金额
  591. * @param array $cartInfo
  592. * @param array $priceData
  593. * @return array
  594. */
  595. public function computeOrderProductIntegral(array $cartInfo, array $priceData)
  596. {
  597. $usedIntegral = $priceData['usedIntegral'] ?? 0;
  598. $deduction_price = $priceData['deduction_price'] ?? 0;
  599. if ($deduction_price) {
  600. $count = 0;
  601. $total_price = 0.00;
  602. $compute_price = 0.00;
  603. $integral_price = 0.00;
  604. $use_integral = 0;
  605. $compute_integral = 0;
  606. foreach ($cartInfo as $cart) {
  607. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  608. continue;
  609. }
  610. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  611. $count++;
  612. }
  613. if ($total_price == $deduction_price) {
  614. $ratio = 1;
  615. } else {
  616. $ratio = bcdiv((string)$deduction_price, (string)$total_price, 4);
  617. }
  618. foreach ($cartInfo as &$cart) {
  619. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  620. continue;
  621. }
  622. if ($count > 1) {
  623. $integral_price = bcmul((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$ratio, 2);
  624. $compute_price = bcadd((string)$compute_price, (string)$integral_price, 2);
  625. $use_integral = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$usedIntegral, 0);
  626. $compute_integral = bcadd((string)$compute_integral, $use_integral, 0);
  627. } else {
  628. $integral_price = bcsub((string)$deduction_price, $compute_price, 2);
  629. $use_integral = bcsub((string)$usedIntegral, $compute_integral, 0);
  630. }
  631. $count--;
  632. $cart['integral_price'] = $integral_price;
  633. $cart['use_integral'] = $use_integral;
  634. }
  635. }
  636. return $cartInfo;
  637. }
  638. /**
  639. * 计算订单商品优惠券实际抵扣金额
  640. * @param array $cartInfo
  641. * @param array $priceData
  642. * @return array
  643. */
  644. public function computeOrderProductCoupon(array $cartInfo, array $priceData, array $promotions = [], int $store_id = 0)
  645. {
  646. if ($priceData['coupon_id'] && $priceData['coupon_price'] ?? 0) {
  647. $count = 0;
  648. $total_price = 0.00;
  649. $compute_price = 0.00;
  650. $coupon_price = 0.00;
  651. /** @var StoreCouponUserServices $couponServices */
  652. $couponServices = app()->make(StoreCouponUserServices::class);
  653. $couponInfo = $couponServices->getOne(['id' => $priceData['coupon_id']], '*', ['issue']);
  654. if ($couponInfo) {
  655. //验证是否适用门店
  656. if ($store_id && isset($couponInfo['applicable_type']) && isset($couponInfo['applicable_store_id'])) {
  657. $applicable_store_id = is_array($couponInfo['applicable_store_id']) ? $couponInfo['applicable_store_id'] : explode(',', $couponInfo['applicable_store_id']);
  658. //活动不适用该门店
  659. if ($couponInfo['applicable_type'] == 0 || ($couponInfo['applicable_type'] == 2 && !in_array($store_id, $applicable_store_id))) {
  660. return [[], 0];
  661. }
  662. }
  663. $promotionsList = [];
  664. if ($promotions) {
  665. $promotionsList = array_combine(array_column($promotions, 'id'), $promotions);
  666. }
  667. $isOverlay = function ($cart) use ($promotionsList) {
  668. $productInfo = $cart['productInfo'] ?? [];
  669. if (!$productInfo) {
  670. return false;
  671. }
  672. //门店独立商品 不使用优惠券
  673. $isBranchProduct = isset($productInfo['type']) && isset($productInfo['pid']) && $productInfo['type'] == 1 && !$productInfo['pid'];
  674. if ($isBranchProduct) {
  675. return false;
  676. }
  677. if (isset($cart['promotions_id']) && $cart['promotions_id']) {
  678. foreach ($cart['promotions_id'] as $key => $promotions_id) {
  679. $promotions = $promotionsList[$promotions_id] ?? [];
  680. if ($promotions && $promotions['promotions_type'] != 4) {
  681. $overlay = is_string($promotions['overlay']) ? explode(',', $promotions['overlay']) : $promotions['overlay'];
  682. if (!in_array(5, $overlay)) {
  683. return false;
  684. }
  685. }
  686. }
  687. }
  688. return true;
  689. };
  690. $type = $couponInfo['applicable_type'] ?? 0;
  691. $counpon_id = $couponInfo['id'];
  692. switch ($type) {
  693. case 0:
  694. foreach ($cartInfo as $cart) {
  695. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  696. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  697. $count++;
  698. }
  699. foreach ($cartInfo as &$cart) {
  700. $cart['coupon_id'] = 0;
  701. $cart['coupon_price'] = 0;
  702. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  703. if ($count > 1) {
  704. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$priceData['coupon_price'], 2);
  705. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  706. } else {
  707. $coupon_price = bcsub((string)$priceData['coupon_price'], $compute_price, 2);
  708. }
  709. $cart['coupon_price'] = $coupon_price;
  710. $cart['coupon_id'] = $counpon_id;
  711. $count--;
  712. }
  713. break;
  714. case 1://品类券
  715. /** @var StoreProductCategoryServices $storeCategoryServices */
  716. $storeCategoryServices = app()->make(StoreProductCategoryServices::class);
  717. $cateGorys = $storeCategoryServices->getAllById((int)$couponInfo['category_id']);
  718. if ($cateGorys) {
  719. $cateIds = array_column($cateGorys, 'id');
  720. foreach ($cartInfo as $cart) {
  721. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  722. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  723. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  724. $count++;
  725. }
  726. }
  727. foreach ($cartInfo as &$cart) {
  728. $cart['coupon_id'] = 0;
  729. $cart['coupon_price'] = 0;
  730. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  731. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  732. if ($count > 1) {
  733. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$priceData['coupon_price'], 2);
  734. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  735. } else {
  736. $coupon_price = bcsub((string)$priceData['coupon_price'], $compute_price, 2);
  737. }
  738. $cart['coupon_id'] = $counpon_id;
  739. $cart['coupon_price'] = $coupon_price;
  740. $count--;
  741. }
  742. }
  743. }
  744. break;
  745. case 2://商品劵
  746. foreach ($cartInfo as $cart) {
  747. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  748. $product_id = isset($cart['productInfo']['pid']) && $cart['productInfo']['pid'] ? $cart['productInfo']['pid'] : ($cart['product_id'] ?? 0);
  749. if ($product_id && in_array($product_id, explode(',', $couponInfo['product_id']))) {
  750. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  751. $count++;
  752. }
  753. }
  754. foreach ($cartInfo as &$cart) {
  755. $cart['coupon_id'] = 0;
  756. $cart['coupon_price'] = 0;
  757. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  758. $product_id = isset($cart['productInfo']['pid']) && $cart['productInfo']['pid'] ? $cart['productInfo']['pid'] : ($cart['product_id'] ?? 0);
  759. if ($product_id && in_array($product_id, explode(',', $couponInfo['product_id']))) {
  760. if ($count > 1) {
  761. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$priceData['coupon_price'], 2);
  762. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  763. } else {
  764. $coupon_price = bcsub((string)$priceData['coupon_price'], $compute_price, 2);
  765. }
  766. $cart['coupon_id'] = $counpon_id;
  767. $cart['coupon_price'] = $coupon_price;
  768. $count--;
  769. }
  770. }
  771. break;
  772. case 3://品牌券
  773. /** @var StoreBrandServices $storeBrandServices */
  774. $storeBrandServices = app()->make(StoreBrandServices::class);
  775. $brands = $storeBrandServices->getAllById((int)$couponInfo['brand_id']);
  776. if ($brands) {
  777. $brandIds = array_column($brands, 'id');
  778. foreach ($cartInfo as $cart) {
  779. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  780. if (isset($cart['productInfo']['brand_id']) && in_array($cart['productInfo']['brand_id'], $brandIds)) {
  781. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  782. $count++;
  783. }
  784. }
  785. foreach ($cartInfo as &$cart) {
  786. $cart['coupon_id'] = 0;
  787. $cart['coupon_price'] = 0;
  788. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  789. if (isset($cart['productInfo']['brand_id']) && in_array($cart['productInfo']['brand_id'], $brandIds)) {
  790. if ($count > 1) {
  791. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$priceData['coupon_price'], 2);
  792. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  793. } else {
  794. $coupon_price = bcsub((string)$priceData['coupon_price'], $compute_price, 2);
  795. }
  796. $cart['coupon_id'] = $counpon_id;
  797. $cart['coupon_price'] = $coupon_price;
  798. $count--;
  799. }
  800. }
  801. }
  802. break;
  803. }
  804. }
  805. }
  806. return $cartInfo;
  807. }
  808. /**
  809. * 计算实际佣金
  810. * @param int $uid
  811. * @param array $cartInfo
  812. * @param $userInfo
  813. * @return array
  814. * @throws \think\db\exception\DataNotFoundException
  815. * @throws \think\db\exception\DbException
  816. * @throws \think\db\exception\ModelNotFoundException
  817. */
  818. public function computeOrderProductBrokerage(int $uid, array $cartInfo, $userInfo)
  819. {
  820. //获取后台一级返佣比例
  821. $storeBrokerageRatio = sys_config('store_brokerage_ratio');
  822. //获取二级返佣比例
  823. $storeBrokerageTwo = sys_config('store_brokerage_two');
  824. //佣金计算方式
  825. $brokerageComputeType = sys_config('brokerage_compute_type', 1);
  826. /** @var AgentLevelServices $agentLevelServices */
  827. $agentLevelServices = app()->make(AgentLevelServices::class);
  828. [$one_brokerage_up, $two_brokerage_up, $spread_uid, $spread_two_uid] = $agentLevelServices->getAgentLevelBrokerage($uid, $userInfo);
  829. // 二级分销开关
  830. if (sys_config('brokerage_level', 2) == 1) {
  831. $storeBrokerageTwo = $spread_two_uid = 0;
  832. }
  833. foreach ($cartInfo as &$cart) {
  834. $oneBrokerage = '0';//一级返佣金额
  835. $twoBrokerage = '0';//二级返佣金额
  836. $cartNum = (string)$cart['cart_num'] ?? '0';
  837. if (isset($cart['productInfo']) && isset($cart['is_gift']) && $cart['is_gift'] == 0) {
  838. $productInfo = $cart['productInfo'];
  839. //指定返佣金额
  840. if (isset($productInfo['is_sub']) && $productInfo['is_sub'] == 1) {
  841. $oneBrokerage = bcmul((string)($productInfo['attrInfo']['brokerage'] ?? '0'), $cartNum, 2);
  842. $twoBrokerage = bcmul((string)($productInfo['attrInfo']['brokerage_two'] ?? '0'), $cartNum, 2);
  843. } else {//比例返佣
  844. $price = 0;
  845. switch ($brokerageComputeType) {
  846. case 1://售价
  847. if (isset($productInfo['attrInfo'])) {
  848. $price = bcmul((string)($productInfo['attrInfo']['price'] ?? '0'), $cartNum, 4);
  849. } else {
  850. $price = bcmul((string)($productInfo['price'] ?? '0'), $cartNum, 4);
  851. }
  852. break;
  853. case 2://实付金额
  854. $price = bcmul((string)($cart['truePrice'] ?? 0), $cartNum, 4);
  855. break;
  856. case 3://商品利润
  857. $price = bcmul(bcsub((string)($cart['truePrice'] ?? 0), (string)($cart['costPrice'] ?? 0), 2), $cartNum, 4);
  858. break;
  859. }
  860. if ($price > 0) {
  861. //一级返佣比例 小于等于零时直接返回 不返佣
  862. if ($storeBrokerageRatio > 0) {
  863. //计算获取一级返佣比例
  864. $brokerageRatio = bcdiv($storeBrokerageRatio, 100, 4);
  865. $oneBrokerage = bcmul((string)$price, (string)$brokerageRatio, 2);
  866. }
  867. //二级返佣比例小于等于0 直接返回
  868. if ($storeBrokerageTwo > 0) {
  869. //计算获取二级返佣比例
  870. $brokerageTwo = bcdiv($storeBrokerageTwo, 100, 4);
  871. $twoBrokerage = bcmul((string)$price, (string)$brokerageTwo, 2);
  872. }
  873. }
  874. }
  875. }
  876. //分销等级上浮佣金
  877. if ($one_brokerage_up) $oneBrokerage = bcadd((string)$oneBrokerage, (string)bcmul((string)$oneBrokerage, (string)bcdiv((string)$one_brokerage_up, '100', 2), 4), 2);
  878. if ($two_brokerage_up) $twoBrokerage = bcadd((string)$twoBrokerage, (string)bcmul((string)$twoBrokerage, (string)bcdiv((string)$two_brokerage_up, '100', 2), 4), 2);
  879. $cart['one_brokerage'] = $oneBrokerage;
  880. $cart['two_brokerage'] = $twoBrokerage;
  881. }
  882. return [$cartInfo, [$spread_uid, $spread_two_uid]];
  883. }
  884. /**
  885. * 计算订单商品信任首单优惠实际抵扣金额
  886. * @param array $cartInfo
  887. * @param array $priceData
  888. * @return array
  889. */
  890. public function computeOrderProductFirstDiscount(array $cartInfo, array $priceData)
  891. {
  892. $first_order_price = $priceData['first_order_price'] ?? 0;
  893. if ($first_order_price) {
  894. $count = 0;
  895. $total_price = 0.00;
  896. $compute_price = 0.00;
  897. $discount_price = 0.00;
  898. foreach ($cartInfo as $cart) {
  899. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  900. continue;
  901. }
  902. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  903. $count++;
  904. }
  905. if ($total_price == $first_order_price) {
  906. $ratio = 1;
  907. } else {
  908. $ratio = bcdiv((string)$first_order_price, (string)$total_price, 4);
  909. }
  910. foreach ($cartInfo as &$cart) {
  911. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  912. continue;
  913. }
  914. if ($count > 1) {
  915. $discount_price = bcmul((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$ratio, 2);
  916. $compute_price = bcadd((string)$compute_price, (string)$discount_price, 2);
  917. } else {
  918. $discount_price = bcsub((string)$first_order_price, $compute_price, 2);
  919. }
  920. $count--;
  921. $cart['first_order_price'] = $discount_price;
  922. }
  923. }
  924. return $cartInfo;
  925. }
  926. }