StoreOrderCreateServices.php 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  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. }
  253. $orderPre = $this->dao->search(['uid' => $uid, 'is_del' => 0, 'is_system_del' => 0])->order('add_time', 'desc')->find();
  254. if ($orderPre && $orderPre['add_time'] > (time() - (sys_config('order_time', 0) * 60))) {
  255. throw new ValidateException('请等待' . ((sys_config('order_time', 0) * 60) - (time() - $orderPre['add_time'])) . '秒后再下单');
  256. }
  257. if ($userInfo['user_type'] == 'wechat' || $userInfo['user_type'] == 'routine') {
  258. /** @var WechatUserServices $wechatServices */
  259. $wechatServices = app()->make(WechatUserServices::class);
  260. $orderInfo['province'] = $wechatServices->value(['uid' => $uid, 'user_type' => $userInfo['user_type']], 'province') ?: '';
  261. }
  262. if ($shippingType == 2) {
  263. $orderInfo['verify_code'] = $this->getStoreCode();
  264. /** @var SystemStoreServices $storeServices */
  265. $storeServices = app()->make(SystemStoreServices::class);
  266. $orderInfo['store_id'] = $storeServices->getStoreDisposeCache($storeId, 'id');
  267. if (!$orderInfo['store_id']) {
  268. throw new ValidateException('暂无门店无法选择门店自提');
  269. }
  270. }
  271. $priceData['coupon_id'] = $couponId;
  272. $order = $this->transaction(function () use ($cartIds, $couponId, $orderInfo, $cartInfo, $key, $userInfo, $useIntegral, $priceData, $type, $activity_id, $uid, $addressId, $promotions_give, $storeId) {
  273. //创建订单
  274. $order = $this->dao->save($orderInfo);
  275. if ($couponId) {
  276. /** @var StoreCouponUserServices $couponServices */
  277. $couponServices = app()->make(StoreCouponUserServices::class);
  278. $couponServices->useCoupon($couponId, (int)$userInfo['uid'], $cartInfo, [], $storeId);
  279. }
  280. //抵扣积分
  281. $this->deductIntegral($userInfo, $useIntegral, $priceData, (int)$userInfo['uid'], $key);
  282. //扣库存
  283. $this->decGoodsStock($cartInfo, $type, $activity_id, $orderInfo['store_id'] ?? 0);
  284. //保存购物车商品信息
  285. /** @var StoreOrderCartInfoServices $cartServices */
  286. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  287. $cartServices->setCartInfo($order['id'], $cartInfo, (int)$uid, $promotions_give['promotions'] ?? []);
  288. return $order;
  289. });
  290. if (in_array($type, [9, 10]) && $collate_code_id > 0 && $order) {
  291. //关联订单和拼单、桌码
  292. $collageServices->update($collate_code_id, ['oid' => $order['id'], 'status' => 2]);
  293. /** @var UserCollagePartakeServices $partakeService */
  294. $partakeService = app()->make(UserCollagePartakeServices::class);
  295. $partakeService->update(['collate_code_id' => $collate_code_id, 'is_settle' => 0], ['status' => 0]);
  296. }
  297. //保存购物车商品信息
  298. // StoreCartJob::dispatch([$order['id'], $cartInfo, $uid, $promotions_give['promotions'] ?? []]);
  299. //扣除优惠活动赠品限量
  300. StorePromotionsJob::dispatchDo('changeGiveLimit', [$promotions_give]);
  301. //订单创建事件
  302. event('order.create', [$order, $userInfo, compact('cartInfo', 'priceData', 'addressId', 'cartIds', 'news'), compact('type', 'activity_id'), $invoice_id]);
  303. return $order;
  304. }
  305. /**
  306. * 抵扣积分
  307. * @param array $userInfo
  308. * @param bool $useIntegral
  309. * @param array $priceData
  310. * @param int $uid
  311. * @param string $key
  312. */
  313. public function deductIntegral(array $userInfo, bool $useIntegral, array $priceData, int $uid, string $key)
  314. {
  315. $res2 = true;
  316. if (sys_config('integral_ratio_status', 1) && $userInfo && $useIntegral && $userInfo['integral'] > 0) {
  317. /** @var UserServices $userServices */
  318. $userServices = app()->make(UserServices::class);
  319. if (!$priceData['SurplusIntegral']) {
  320. $integral = 0;
  321. } else {
  322. $integral = bcsub((string)$userInfo['integral'], (string)$priceData['usedIntegral']);
  323. }
  324. $res2 = false !== $userServices->update($uid, ['integral' => $integral]);
  325. /** @var UserBillServices $userBillServices */
  326. $userBillServices = app()->make(UserBillServices::class);
  327. $res3 = $userBillServices->income('deduction', $uid, [
  328. 'number' => (int)$priceData['usedIntegral'],
  329. 'deductionPrice' => $priceData['deduction_price']
  330. ], $integral, $key);
  331. $res2 = $res2 && false != $res3;
  332. }
  333. if (!$res2) {
  334. throw new ValidateException('使用积分抵扣失败!');
  335. }
  336. }
  337. /**
  338. * 扣库存
  339. * @param array $cartInfo
  340. * @param int $type
  341. * @param int $activity_id
  342. * @param int $store_id
  343. */
  344. public function decGoodsStock(array $cartInfo, int $type, int $activity_id, int $store_id = 0)
  345. {
  346. $res5 = true;
  347. /** @var StoreProductServices $services */
  348. $services = app()->make(StoreProductServices::class);
  349. /** @var StoreSeckillServices $seckillServices */
  350. $seckillServices = app()->make(StoreSeckillServices::class);
  351. /** @var StoreCombinationServices $pinkServices */
  352. $pinkServices = app()->make(StoreCombinationServices::class);
  353. /** @var StoreBargainServices $bargainServices */
  354. $bargainServices = app()->make(StoreBargainServices::class);
  355. /** @var StoreDiscountsServices $discountServices */
  356. $discountServices = app()->make(StoreDiscountsServices::class);
  357. /** @var StoreNewcomerServices $storeNewcomerServices */
  358. $storeNewcomerServices = app()->make(StoreNewcomerServices::class);
  359. try {
  360. foreach ($cartInfo as $cart) {
  361. $unique = isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '';
  362. $cart_num = (int)$cart['cart_num'];
  363. //减库存加销量
  364. switch ($type) {
  365. case 0://普通
  366. case 6://预售
  367. case 8://抽奖
  368. case 9://拼单
  369. case 10://桌码
  370. $res5 = $res5 && $services->decProductStock($cart_num, (int)$cart['productInfo']['id'], $unique, $store_id);
  371. break;
  372. case 1://秒杀
  373. $res5 = $res5 && $seckillServices->decSeckillStock($cart_num, $activity_id, $unique, $store_id);
  374. break;
  375. case 2://砍价
  376. $res5 = $res5 && $bargainServices->decBargainStock($cart_num, $activity_id, $unique, $store_id);
  377. break;
  378. case 3://拼团
  379. $res5 = $res5 && $pinkServices->decCombinationStock($cart_num, $activity_id, $unique, $store_id);
  380. break;
  381. case 5://套餐
  382. $res5 = $res5 && $discountServices->decDiscountStock($cart_num, $activity_id, (int)($cart['discount_product_id'] ?? 0), (int)($cart['product_id'] ?? 0), $unique, $store_id);
  383. break;
  384. case 7://新人专享
  385. $res5 = $res5 && $storeNewcomerServices->decNewcomerStock($cart_num, $activity_id, $unique, $store_id);
  386. break;
  387. default:
  388. $res5 = $res5 && $services->decProductStock($cart_num, (int)$cart['productInfo']['id'], $unique, $store_id);
  389. break;
  390. }
  391. }
  392. if ($type == 5 && $activity_id) {
  393. //改变套餐限量
  394. $res5 = $res5 && $discountServices->changeDiscountLimit($activity_id);
  395. }
  396. if (!$res5) {
  397. throw new ValidateException('库存不足!');
  398. }
  399. } catch (\Throwable $e) {
  400. throw new ValidateException('库存不足!');
  401. }
  402. }
  403. /**
  404. * 订单创建后的后置事件
  405. * @param UserAddressServices $addressServices
  406. * @param $order
  407. * @param array $group
  408. */
  409. public function orderCreateAfter($order, array $group)
  410. {
  411. /** @var UserAddressServices $addressServices */
  412. $addressServices = app()->make(UserAddressServices::class);
  413. //设置用户默认地址
  414. if ($order['uid'] && isset($group['addressId']) && $group['addressId'] && !$addressServices->be(['is_default' => 1, 'uid' => $order['uid']])) {
  415. $addressServices->setDefaultAddress($group['addressId'], $order['uid']);
  416. }
  417. //删除购物车
  418. if (isset($group['news']) && $group['news']) {
  419. array_map(function ($key) {
  420. CacheService::redisHandler()->delete($key);
  421. }, $group['cartIds']);
  422. } else {
  423. if (!isset($group['delCart']) || (isset($group['delCart']) && $group['delCart'] !== false)) {
  424. /** @var StoreCartServices $cartServices */
  425. $cartServices = app()->make(StoreCartServices::class);
  426. $cartServices->deleteCartStatus($group['cartIds'] ?? []);
  427. }
  428. }
  429. }
  430. /**
  431. * 计算订单每个商品真实付款价格
  432. * @param array $orderInfo
  433. * @param array $cartInfo
  434. * @param array $priceData
  435. * @param $addressId
  436. * @param int $uid
  437. * @param $userInfo
  438. * @return array
  439. */
  440. public function computeOrderProductTruePrice($orderInfo, array $cartInfo, array $priceData, $addressId, int $uid, $userInfo)
  441. {
  442. //统一放入默认数据
  443. foreach ($cartInfo as &$cart) {
  444. $cart['use_integral'] = 0;
  445. $cart['integral_price'] = 0.00;
  446. if (!isset($cart['coupon_price'])) {
  447. $cart['coupon_price'] = 0.00;
  448. }
  449. $cart['first_order_price'] = 0.00;
  450. $cart['one_brokerage'] = 0.00;
  451. $cart['two_brokerage'] = 0.00;
  452. }
  453. try {
  454. $promotionsGice = isset($orderInfo['promotions_give']) ? (is_string($orderInfo['promotions_give']) ? json_decode($orderInfo['promotions_give'], true) : $orderInfo['promotions_give']) : [];
  455. $promotions = [];
  456. if (isset($promotionsGice['promotions']) && $promotionsGice['promotions']) {
  457. $promotions = $promotionsGice['promotions'];
  458. }
  459. //$cartInfo = $this->computeOrderProductCoupon($cartInfo, $priceData, $promotions);
  460. $cartInfo = $this->computeOrderProductIntegral($cartInfo, $priceData);
  461. // $cartInfo = $this->computeOrderProductPostage($cartInfo, $priceData);
  462. $cartInfo = $this->computeOrderProductFirstDiscount($cartInfo, $priceData);
  463. } catch (\Throwable $e) {
  464. Log::error('订单商品结算失败,File:' . $e->getFile() . ',Line:' . $e->getLine() . ',Message:' . $e->getMessage());
  465. throw new ValidateException('订单商品结算失败');
  466. }
  467. //truePice实际支付单价(存在)
  468. //几件商品总体优惠 以及积分抵扣金额
  469. foreach ($cartInfo as &$cart) {
  470. $coupon_price = $cart['coupon_price'] ?? 0;
  471. $integral_price = $cart['integral_price'] ?? 0;
  472. $first_order_price = $cart['first_order_price'] ?? 0;
  473. $cart['sum_true_price'] = bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 2);
  474. if ($coupon_price) {
  475. $cart['sum_true_price'] = bcsub((string)$cart['sum_true_price'], (string)$coupon_price, 2);
  476. $uni_coupon_price = (string)bcdiv((string)$coupon_price, (string)$cart['cart_num'], 4);
  477. $cart['truePrice'] = $cart['truePrice'] > $uni_coupon_price ? bcsub((string)$cart['truePrice'], $uni_coupon_price, 2) : 0;
  478. }
  479. if ($integral_price) {
  480. $cart['sum_true_price'] = bcsub((string)$cart['sum_true_price'], (string)$integral_price, 2);
  481. $uni_integral_price = (string)bcdiv((string)$integral_price, (string)$cart['cart_num'], 4);
  482. $cart['truePrice'] = $cart['truePrice'] > $uni_integral_price ? bcsub((string)$cart['truePrice'], $uni_integral_price, 2) : 0;
  483. }
  484. if ($first_order_price) {
  485. $cart['sum_true_price'] = bcsub((string)$cart['sum_true_price'], (string)$first_order_price, 2);
  486. $uni_first_order_price = (string)bcdiv((string)$first_order_price, (string)$cart['cart_num'], 4);
  487. $cart['truePrice'] = $cart['truePrice'] > $uni_first_order_price ? bcsub((string)$cart['truePrice'], $uni_first_order_price, 2) : 0;
  488. }
  489. }
  490. //计算佣金:1售价2实际支付金额
  491. [$cartInfo, $spread_ids] = $this->computeOrderProductBrokerage($uid, $cartInfo, $userInfo);
  492. return [$cartInfo, $spread_ids];
  493. }
  494. /**
  495. * 计算每个商品实际支付运费
  496. * @param array $cartInfo
  497. * @param array $priceData
  498. * @return array
  499. */
  500. public function computeOrderProductPostage(array $cartInfo, array $priceData, $addressId)
  501. {
  502. $storePostage = $priceData['pay_postage'] ?? 0;
  503. if ($storePostage) {
  504. /** @var UserAddressServices $addressServices */
  505. $addressServices = app()->make(UserAddressServices::class);
  506. $addr = $addressServices->getAdderssCache($addressId);
  507. if ($addr) {
  508. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  509. $cityId = $addr['city_id'] ?? 0;
  510. $ids = [];
  511. if ($cityId) {
  512. /** @var CityAreaServices $cityAreaServices */
  513. $cityAreaServices = app()->make(CityAreaServices::class);
  514. $ids = $cityAreaServices->getRelationCityIds($cityId);
  515. }
  516. $cityIds = array_merge([0], $ids);
  517. $tempIds[] = 1;
  518. foreach ($cartInfo as $key_c => $item_c) {
  519. $tempIds[] = $item_c['productInfo']['temp_id'];
  520. }
  521. $tempIds = array_unique($tempIds);
  522. /** @var ShippingTemplatesServices $shippServices */
  523. $shippServices = app()->make(ShippingTemplatesServices::class);
  524. $temp = $shippServices->getShippingColumn(['id' => $tempIds], 'type,appoint', 'id');
  525. /** @var ShippingTemplatesRegionServices $regionServices */
  526. $regionServices = app()->make(ShippingTemplatesRegionServices::class);
  527. $regions = $regionServices->getTempRegionList($tempIds, $cityIds, 'temp_id,first,first_price,continue,continue_price', 'temp_id');
  528. $temp_num = [];
  529. foreach ($cartInfo as $cart) {
  530. $tempId = $cart['productInfo']['temp_id'] ?? 1;
  531. $type = isset($temp[$tempId]['type']) ? $temp[$tempId]['type'] : $temp[1]['type'];
  532. if ($type == 1) {
  533. $num = $cart['cart_num'];
  534. } elseif ($type == 2) {
  535. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  536. } else {
  537. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  538. }
  539. $region = isset($regions[$tempId]) ? $regions[$tempId] : $regions[1];
  540. if (!isset($temp_num[$tempId])) {
  541. $temp_num[$tempId] = [
  542. 'cart_id' => [$cart['id']],
  543. 'number' => $num,
  544. 'type' => $type,
  545. 'price' => bcmul($cart['cart_num'], $cart['truePrice'], 2),
  546. 'first' => $region['first'],
  547. 'first_price' => $region['first_price'],
  548. 'continue' => $region['continue'],
  549. 'continue_price' => $region['continue_price'],
  550. 'temp_id' => $tempId
  551. ];
  552. } else {
  553. $temp_num[$tempId]['cart_id'][] = $cart['id'];
  554. $temp_num[$tempId]['number'] += $num;
  555. $temp_num[$tempId]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  556. }
  557. }
  558. $cartInfo = array_combine(array_column($cartInfo, 'id'), $cartInfo);
  559. /** @var ShippingTemplatesFreeServices $freeServices */
  560. $freeServices = app()->make(ShippingTemplatesFreeServices::class);
  561. $freeList = $freeServices->isFreeList($tempIds, $cityIds, 0, 'temp_id,number,price', 'temp_id');
  562. if ($freeList) {
  563. foreach ($temp_num as $k => $v) {
  564. if (isset($temp[$v['temp_id']]['appoint']) && $temp[$v['temp_id']]['appoint'] && isset($freeList[$v['temp_id']])) {
  565. $free = $freeList[$v['temp_id']];
  566. $condition = $free['number'] <= $v['number'];
  567. if ($free['price'] <= $v['price'] && $condition) {
  568. //免运费
  569. foreach ($v['cart_id'] as $c_id) {
  570. if (isset($cartInfo[$c_id])) $cartInfo[$c_id]['postage_price'] = 0.00;
  571. }
  572. }
  573. }
  574. }
  575. }
  576. $count = 0;
  577. $compute_price = 0.00;
  578. $total_price = 0;
  579. $postage_price = 0.00;
  580. foreach ($cartInfo as $cart) {
  581. if (isset($cart['postage_price'])) {//免运费
  582. continue;
  583. }
  584. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  585. continue;
  586. }
  587. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  588. $count++;
  589. }
  590. foreach ($cartInfo as &$cart) {
  591. if (isset($cart['postage_price'])) {//免运费
  592. continue;
  593. }
  594. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  595. continue;
  596. }
  597. if ($count > 1) {
  598. $postage_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$storePostage, 2);
  599. $compute_price = bcadd((string)$compute_price, (string)$postage_price, 2);
  600. } else {
  601. $postage_price = bcsub((string)$storePostage, $compute_price, 2);
  602. }
  603. $cart['postage_price'] = $postage_price;
  604. $count--;
  605. }
  606. $cartInfo = array_merge($cartInfo);
  607. }
  608. }
  609. return $cartInfo;
  610. }
  611. /**
  612. * 计算订单商品积分实际抵扣金额
  613. * @param array $cartInfo
  614. * @param array $priceData
  615. * @return array
  616. */
  617. public function computeOrderProductIntegral(array $cartInfo, array $priceData)
  618. {
  619. $usedIntegral = $priceData['usedIntegral'] ?? 0;
  620. $deduction_price = $priceData['deduction_price'] ?? 0;
  621. if ($deduction_price) {
  622. $count = 0;
  623. $total_price = 0.00;
  624. $compute_price = 0.00;
  625. $integral_price = 0.00;
  626. $use_integral = 0;
  627. $compute_integral = 0;
  628. foreach ($cartInfo as $cart) {
  629. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  630. continue;
  631. }
  632. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  633. $count++;
  634. }
  635. if ($total_price == $deduction_price) {
  636. $ratio = 1;
  637. } else {
  638. $ratio = bcdiv((string)$deduction_price, (string)$total_price, 4);
  639. }
  640. foreach ($cartInfo as &$cart) {
  641. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  642. continue;
  643. }
  644. if ($count > 1) {
  645. $integral_price = bcmul((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$ratio, 2);
  646. $compute_price = bcadd((string)$compute_price, (string)$integral_price, 2);
  647. $use_integral = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$usedIntegral, 0);
  648. $compute_integral = bcadd((string)$compute_integral, $use_integral, 0);
  649. } else {
  650. $integral_price = bcsub((string)$deduction_price, $compute_price, 2);
  651. $use_integral = bcsub((string)$usedIntegral, $compute_integral, 0);
  652. }
  653. $count--;
  654. $cart['integral_price'] = $integral_price;
  655. $cart['use_integral'] = $use_integral;
  656. }
  657. }
  658. return $cartInfo;
  659. }
  660. /**
  661. * 计算订单商品优惠券实际抵扣金额
  662. * @param array $cartInfo
  663. * @param array $priceData
  664. * @return array
  665. */
  666. public function computeOrderProductCoupon(array $cartInfo, array $priceData, array $promotions = [], int $store_id = 0)
  667. {
  668. if ($priceData['coupon_id'] && $priceData['coupon_price'] ?? 0) {
  669. $count = 0;
  670. $total_price = 0.00;
  671. $compute_price = 0.00;
  672. $coupon_price = 0.00;
  673. /** @var StoreCouponUserServices $couponServices */
  674. $couponServices = app()->make(StoreCouponUserServices::class);
  675. $couponInfo = $couponServices->getOne(['id' => $priceData['coupon_id']], '*', ['issue']);
  676. if ($couponInfo) {
  677. //验证是否适用门店
  678. if ($store_id && isset($couponInfo['applicable_type']) && isset($couponInfo['applicable_store_id'])) {
  679. $applicable_store_id = is_array($couponInfo['applicable_store_id']) ? $couponInfo['applicable_store_id'] : explode(',', $couponInfo['applicable_store_id']);
  680. //活动不适用该门店
  681. if ($couponInfo['applicable_type'] == 0 || ($couponInfo['applicable_type'] == 2 && !in_array($store_id, $applicable_store_id))) {
  682. return [[], 0];
  683. }
  684. }
  685. $promotionsList = [];
  686. if ($promotions) {
  687. $promotionsList = array_combine(array_column($promotions, 'id'), $promotions);
  688. }
  689. $isOverlay = function ($cart) use ($promotionsList) {
  690. $productInfo = $cart['productInfo'] ?? [];
  691. if (!$productInfo) {
  692. return false;
  693. }
  694. //门店独立商品 不使用优惠券
  695. $isBranchProduct = isset($productInfo['type']) && isset($productInfo['pid']) && $productInfo['type'] == 1 && !$productInfo['pid'];
  696. if ($isBranchProduct) {
  697. return false;
  698. }
  699. if (isset($cart['promotions_id']) && $cart['promotions_id']) {
  700. foreach ($cart['promotions_id'] as $key => $promotions_id) {
  701. $promotions = $promotionsList[$promotions_id] ?? [];
  702. if ($promotions && $promotions['promotions_type'] != 4) {
  703. $overlay = is_string($promotions['overlay']) ? explode(',', $promotions['overlay']) : $promotions['overlay'];
  704. if (!in_array(5, $overlay)) {
  705. return false;
  706. }
  707. }
  708. }
  709. }
  710. return true;
  711. };
  712. $type = $couponInfo['applicable_type'] ?? 0;
  713. $counpon_id = $couponInfo['id'];
  714. switch ($type) {
  715. case 0:
  716. foreach ($cartInfo as $cart) {
  717. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  718. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  719. $count++;
  720. }
  721. foreach ($cartInfo as &$cart) {
  722. $cart['coupon_id'] = 0;
  723. $cart['coupon_price'] = 0;
  724. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  725. if ($count > 1) {
  726. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$priceData['coupon_price'], 2);
  727. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  728. } else {
  729. $coupon_price = bcsub((string)$priceData['coupon_price'], $compute_price, 2);
  730. }
  731. $cart['coupon_price'] = $coupon_price;
  732. $cart['coupon_id'] = $counpon_id;
  733. $count--;
  734. }
  735. break;
  736. case 1://品类券
  737. /** @var StoreProductCategoryServices $storeCategoryServices */
  738. $storeCategoryServices = app()->make(StoreProductCategoryServices::class);
  739. $cateGorys = $storeCategoryServices->getAllById((int)$couponInfo['category_id']);
  740. if ($cateGorys) {
  741. $cateIds = array_column($cateGorys, 'id');
  742. foreach ($cartInfo as $cart) {
  743. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  744. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  745. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  746. $count++;
  747. }
  748. }
  749. foreach ($cartInfo as &$cart) {
  750. $cart['coupon_id'] = 0;
  751. $cart['coupon_price'] = 0;
  752. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  753. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  754. if ($count > 1) {
  755. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$priceData['coupon_price'], 2);
  756. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  757. } else {
  758. $coupon_price = bcsub((string)$priceData['coupon_price'], $compute_price, 2);
  759. }
  760. $cart['coupon_id'] = $counpon_id;
  761. $cart['coupon_price'] = $coupon_price;
  762. $count--;
  763. }
  764. }
  765. }
  766. break;
  767. case 2://商品劵
  768. foreach ($cartInfo as $cart) {
  769. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  770. $product_id = isset($cart['productInfo']['pid']) && $cart['productInfo']['pid'] ? $cart['productInfo']['pid'] : ($cart['product_id'] ?? 0);
  771. if ($product_id && in_array($product_id, explode(',', $couponInfo['product_id']))) {
  772. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  773. $count++;
  774. }
  775. }
  776. foreach ($cartInfo as &$cart) {
  777. $cart['coupon_id'] = 0;
  778. $cart['coupon_price'] = 0;
  779. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  780. $product_id = isset($cart['productInfo']['pid']) && $cart['productInfo']['pid'] ? $cart['productInfo']['pid'] : ($cart['product_id'] ?? 0);
  781. if ($product_id && in_array($product_id, explode(',', $couponInfo['product_id']))) {
  782. if ($count > 1) {
  783. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$priceData['coupon_price'], 2);
  784. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  785. } else {
  786. $coupon_price = bcsub((string)$priceData['coupon_price'], $compute_price, 2);
  787. }
  788. $cart['coupon_id'] = $counpon_id;
  789. $cart['coupon_price'] = $coupon_price;
  790. $count--;
  791. }
  792. }
  793. break;
  794. case 3://品牌券
  795. /** @var StoreBrandServices $storeBrandServices */
  796. $storeBrandServices = app()->make(StoreBrandServices::class);
  797. $brands = $storeBrandServices->getAllById((int)$couponInfo['brand_id']);
  798. if ($brands) {
  799. $brandIds = array_column($brands, 'id');
  800. foreach ($cartInfo as $cart) {
  801. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  802. if (isset($cart['productInfo']['brand_id']) && in_array($cart['productInfo']['brand_id'], $brandIds)) {
  803. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  804. $count++;
  805. }
  806. }
  807. foreach ($cartInfo as &$cart) {
  808. $cart['coupon_id'] = 0;
  809. $cart['coupon_price'] = 0;
  810. if (!$isOverlay($cart) || (isset($cart['is_gift']) && $cart['is_gift'] == 1)) continue;
  811. if (isset($cart['productInfo']['brand_id']) && in_array($cart['productInfo']['brand_id'], $brandIds)) {
  812. if ($count > 1) {
  813. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$priceData['coupon_price'], 2);
  814. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  815. } else {
  816. $coupon_price = bcsub((string)$priceData['coupon_price'], $compute_price, 2);
  817. }
  818. $cart['coupon_id'] = $counpon_id;
  819. $cart['coupon_price'] = $coupon_price;
  820. $count--;
  821. }
  822. }
  823. }
  824. break;
  825. }
  826. }
  827. }
  828. return $cartInfo;
  829. }
  830. /**
  831. * 计算实际佣金
  832. * @param int $uid
  833. * @param array $cartInfo
  834. * @param $userInfo
  835. * @return array
  836. * @throws \think\db\exception\DataNotFoundException
  837. * @throws \think\db\exception\DbException
  838. * @throws \think\db\exception\ModelNotFoundException
  839. */
  840. public function computeOrderProductBrokerage(int $uid, array $cartInfo, $userInfo)
  841. {
  842. //获取后台一级返佣比例
  843. $storeBrokerageRatio = sys_config('store_brokerage_ratio');
  844. //获取二级返佣比例
  845. $storeBrokerageTwo = sys_config('store_brokerage_two');
  846. //佣金计算方式
  847. $brokerageComputeType = sys_config('brokerage_compute_type', 1);
  848. /** @var AgentLevelServices $agentLevelServices */
  849. $agentLevelServices = app()->make(AgentLevelServices::class);
  850. [$one_brokerage_up, $two_brokerage_up, $spread_uid, $spread_two_uid] = $agentLevelServices->getAgentLevelBrokerage($uid, $userInfo);
  851. // 二级分销开关
  852. if (sys_config('brokerage_level', 2) == 1) {
  853. $storeBrokerageTwo = $spread_two_uid = 0;
  854. }
  855. foreach ($cartInfo as &$cart) {
  856. $oneBrokerage = '0';//一级返佣金额
  857. $twoBrokerage = '0';//二级返佣金额
  858. $cartNum = (string)$cart['cart_num'] ?? '0';
  859. if (isset($cart['productInfo']) && isset($cart['is_gift']) && $cart['is_gift'] == 0) {
  860. $productInfo = $cart['productInfo'];
  861. //指定返佣金额
  862. if (isset($productInfo['is_sub']) && $productInfo['is_sub'] == 1) {
  863. $oneBrokerage = bcmul((string)($productInfo['attrInfo']['brokerage'] ?? '0'), $cartNum, 2);
  864. $twoBrokerage = bcmul((string)($productInfo['attrInfo']['brokerage_two'] ?? '0'), $cartNum, 2);
  865. } else {//比例返佣
  866. $price = 0;
  867. switch ($brokerageComputeType) {
  868. case 1://售价
  869. if (isset($productInfo['attrInfo'])) {
  870. $price = bcmul((string)($productInfo['attrInfo']['price'] ?? '0'), $cartNum, 4);
  871. } else {
  872. $price = bcmul((string)($productInfo['price'] ?? '0'), $cartNum, 4);
  873. }
  874. break;
  875. case 2://实付金额
  876. $price = bcmul((string)($cart['truePrice'] ?? 0), $cartNum, 4);
  877. break;
  878. case 3://商品利润
  879. $price = bcmul(bcsub((string)($cart['truePrice'] ?? 0), (string)($cart['costPrice'] ?? 0), 2), $cartNum, 4);
  880. break;
  881. }
  882. if ($price > 0) {
  883. //一级返佣比例 小于等于零时直接返回 不返佣
  884. if ($storeBrokerageRatio > 0) {
  885. //计算获取一级返佣比例
  886. $brokerageRatio = bcdiv($storeBrokerageRatio, 100, 4);
  887. $oneBrokerage = bcmul((string)$price, (string)$brokerageRatio, 2);
  888. }
  889. //二级返佣比例小于等于0 直接返回
  890. if ($storeBrokerageTwo > 0) {
  891. //计算获取二级返佣比例
  892. $brokerageTwo = bcdiv($storeBrokerageTwo, 100, 4);
  893. $twoBrokerage = bcmul((string)$price, (string)$brokerageTwo, 2);
  894. }
  895. }
  896. }
  897. }
  898. //分销等级上浮佣金
  899. if ($one_brokerage_up) $oneBrokerage = bcadd((string)$oneBrokerage, (string)bcmul((string)$oneBrokerage, (string)bcdiv((string)$one_brokerage_up, '100', 2), 4), 2);
  900. if ($two_brokerage_up) $twoBrokerage = bcadd((string)$twoBrokerage, (string)bcmul((string)$twoBrokerage, (string)bcdiv((string)$two_brokerage_up, '100', 2), 4), 2);
  901. $cart['one_brokerage'] = $oneBrokerage;
  902. $cart['two_brokerage'] = $twoBrokerage;
  903. }
  904. return [$cartInfo, [$spread_uid, $spread_two_uid]];
  905. }
  906. /**
  907. * 计算订单商品信任首单优惠实际抵扣金额
  908. * @param array $cartInfo
  909. * @param array $priceData
  910. * @return array
  911. */
  912. public function computeOrderProductFirstDiscount(array $cartInfo, array $priceData)
  913. {
  914. $first_order_price = $priceData['first_order_price'] ?? 0;
  915. if ($first_order_price) {
  916. $count = 0;
  917. $total_price = 0.00;
  918. $compute_price = 0.00;
  919. $discount_price = 0.00;
  920. foreach ($cartInfo as $cart) {
  921. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  922. continue;
  923. }
  924. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  925. $count++;
  926. }
  927. if ($total_price == $first_order_price) {
  928. $ratio = 1;
  929. } else {
  930. $ratio = bcdiv((string)$first_order_price, (string)$total_price, 4);
  931. }
  932. foreach ($cartInfo as &$cart) {
  933. if (isset($cart['is_gift']) && $cart['is_gift'] == 1) {
  934. continue;
  935. }
  936. if ($count > 1) {
  937. $discount_price = bcmul((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$ratio, 2);
  938. $compute_price = bcadd((string)$compute_price, (string)$discount_price, 2);
  939. } else {
  940. $discount_price = bcsub((string)$first_order_price, $compute_price, 2);
  941. }
  942. $count--;
  943. $cart['first_order_price'] = $discount_price;
  944. }
  945. }
  946. return $cartInfo;
  947. }
  948. }