StoreOrderCreateServices.php 50 KB

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