StoreOrderCreateServices.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\order;
  12. use app\services\activity\StoreAdvanceServices;
  13. use app\services\agent\AgentLevelServices;
  14. use app\services\coupon\StoreCouponUserServices;
  15. use app\services\pay\PayServices;
  16. use app\services\product\product\StoreCategoryServices;
  17. use app\services\shipping\ShippingTemplatesFreeServices;
  18. use app\services\shipping\ShippingTemplatesRegionServices;
  19. use app\services\shipping\ShippingTemplatesServices;
  20. use app\services\wechat\WechatUserServices;
  21. use app\services\BaseServices;
  22. use crmeb\services\CacheService;
  23. use app\dao\order\StoreOrderDao;
  24. use app\services\user\UserServices;
  25. use think\exception\ValidateException;
  26. use app\services\user\UserBillServices;
  27. use app\services\user\UserAddressServices;
  28. use app\services\activity\StoreBargainServices;
  29. use app\services\activity\StoreSeckillServices;
  30. use app\services\system\store\SystemStoreServices;
  31. use app\services\activity\StoreCombinationServices;
  32. use app\services\product\product\StoreProductServices;
  33. use think\facade\Log;
  34. /**
  35. * 订单创建
  36. * Class StoreOrderCreateServices
  37. * @package app\services\order
  38. */
  39. class StoreOrderCreateServices extends BaseServices
  40. {
  41. /**
  42. * StoreOrderCreateServices constructor.
  43. * @param StoreOrderDao $dao
  44. */
  45. public function __construct(StoreOrderDao $dao)
  46. {
  47. $this->dao = $dao;
  48. }
  49. /**
  50. * 使用雪花算法生成订单ID
  51. * @return string
  52. * @throws \Exception
  53. */
  54. public function getNewOrderId(string $prefix = 'wx')
  55. {
  56. $snowflake = new \Godruoyi\Snowflake\Snowflake();
  57. //32位
  58. if (PHP_INT_SIZE == 4) {
  59. $id = abs($snowflake->id());
  60. } else {
  61. $id = $snowflake->setStartTimeStamp(strtotime('2020-06-05') * 1000)->id();
  62. }
  63. return $prefix . $id;
  64. }
  65. /**
  66. * 核销订单生成核销码
  67. * @return false|string
  68. */
  69. public function getStoreCode()
  70. {
  71. list($msec, $sec) = explode(' ', microtime());
  72. $num = time() + mt_rand(10, 999999) . '' . substr($msec, 2, 3);//生成随机数
  73. if (strlen($num) < 12)
  74. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  75. else
  76. $num = substr($num, 0, 12);
  77. if ($this->dao->count(['verify_code' => $num])) {
  78. return $this->getStoreCode();
  79. }
  80. return $num;
  81. }
  82. /**
  83. * 创建订单
  84. * @param $uid
  85. * @param $key
  86. * @param $cartGroup
  87. * @param $userInfo
  88. * @param $addressId
  89. * @param $payType
  90. * @param bool $useIntegral
  91. * @param int $couponId
  92. * @param string $mark
  93. * @param int $combinationId
  94. * @param int $pinkId
  95. * @param int $seckillId
  96. * @param int $bargainId
  97. * @param int $isChannel
  98. * @param int $shippingType
  99. * @param string $real_name
  100. * @param string $phone
  101. * @param int $storeId
  102. * @param bool $news
  103. * @return mixed
  104. * @throws \Psr\SimpleCache\InvalidArgumentException
  105. * @throws \think\db\exception\DataNotFoundException
  106. * @throws \think\db\exception\DbException
  107. * @throws \think\db\exception\ModelNotFoundException
  108. */
  109. public function createOrder($uid, $key, $cartGroup, $userInfo, $addressId, $payType, $useIntegral = false, $couponId = 0, $mark = '', $combinationId = 0, $pinkId = 0, $seckillId = 0, $bargainId = 0, $isChannel = 0, $shippingType = 1, $real_name = '', $phone = '', $storeId = 0, $news = false, $advanceId = 0, $virtual_type = 0)
  110. {
  111. /** @var StoreOrderComputedServices $computedServices */
  112. $computedServices = app()->make(StoreOrderComputedServices::class);
  113. $priceData = $computedServices->computedOrder($uid, $userInfo, $cartGroup, $addressId, $payType, $useIntegral, $couponId, true, $shippingType);
  114. /** @var WechatUserServices $wechatServices */
  115. $wechatServices = app()->make(WechatUserServices::class);
  116. /** @var UserAddressServices $addressServices */
  117. $addressServices = app()->make(UserAddressServices::class);
  118. if ($shippingType === 1 && $virtual_type == 0) {
  119. if (!$addressId) {
  120. throw new ValidateException('请选择收货地址!');
  121. }
  122. if (!$addressInfo = $addressServices->getOne(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]))
  123. throw new ValidateException('地址选择有误!');
  124. $addressInfo = $addressInfo->toArray();
  125. } else {
  126. if ((!$real_name || !$phone) && $virtual_type == 0) {
  127. throw new ValidateException('请填写姓名和电话');
  128. }
  129. $addressInfo['real_name'] = $real_name;
  130. $addressInfo['phone'] = $phone;
  131. $addressInfo['province'] = '';
  132. $addressInfo['city'] = '';
  133. $addressInfo['district'] = '';
  134. $addressInfo['detail'] = '';
  135. }
  136. $cartInfo = $cartGroup['cartInfo'];
  137. $priceGroup = $cartGroup['priceGroup'];
  138. $cartIds = [];
  139. $totalNum = 0;
  140. $gainIntegral = 0;
  141. foreach ($cartInfo as $cart) {
  142. $cartIds[] = $cart['id'];
  143. $totalNum += $cart['cart_num'];
  144. if (!$seckillId) $seckillId = $cart['seckill_id'];
  145. if (!$bargainId) $bargainId = $cart['bargain_id'];
  146. if (!$combinationId) $combinationId = $cart['combination_id'];
  147. if (!$advanceId) $advanceId = $cart['advance_id'];
  148. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul((string)$cart['cart_num'], (string)$cart['productInfo']['give_integral'], 0) : 0;
  149. $gainIntegral = bcadd((string)$gainIntegral, (string)$cartInfoGainIntegral, 0);
  150. }
  151. $deduction = $seckillId || $bargainId || $combinationId || $advanceId;
  152. if ($deduction) {
  153. $couponId = 0;
  154. $useIntegral = false;
  155. $systemPayType = PayServices::PAY_TYPE;
  156. unset($systemPayType['offline']);
  157. if ($payType != 'pc' && !array_key_exists($payType, $systemPayType)) {
  158. throw new ValidateException('营销商品不能使用线下支付!');
  159. }
  160. }
  161. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  162. $storeSelfMention = sys_config('store_self_mention') ?? 0;
  163. if (!$storeSelfMention) $shippingType = 1;
  164. $orderInfo = [
  165. 'uid' => $uid,
  166. 'order_id' => $this->getNewOrderId(),
  167. 'real_name' => $addressInfo['real_name'],
  168. 'user_phone' => $addressInfo['phone'],
  169. 'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
  170. 'cart_id' => $cartIds,
  171. 'total_num' => $totalNum,
  172. 'total_price' => $priceGroup['totalPrice'],
  173. 'total_postage' => $priceGroup['storePostage'],
  174. 'coupon_id' => $couponId,
  175. 'coupon_price' => $priceData['coupon_price'],
  176. 'pay_price' => $priceData['pay_price'],
  177. 'pay_postage' => $priceData['pay_postage'],
  178. 'deduction_price' => $priceData['deduction_price'],
  179. 'paid' => 0,
  180. 'pay_type' => $payType,
  181. 'use_integral' => $priceData['usedIntegral'],
  182. 'gain_integral' => $gainIntegral,
  183. 'mark' => htmlspecialchars($mark),
  184. 'combination_id' => $combinationId,
  185. 'pink_id' => $pinkId,
  186. 'seckill_id' => $seckillId,
  187. 'bargain_id' => $bargainId,
  188. 'advance_id' => $advanceId,
  189. 'cost' => $priceGroup['costPrice'],
  190. 'is_channel' => $isChannel,
  191. 'add_time' => time(),
  192. 'unique' => $key,
  193. 'shipping_type' => $shippingType,
  194. 'channel_type' => $userInfo['user_type'],
  195. 'province' => $userInfo['user_type'] == 'wechat' || $userInfo['user_type'] == 'routine' ? $wechatServices->value(['uid' => $uid, 'user_type' => $userInfo['user_type']], 'province') : '',
  196. 'spread_uid' => 0,
  197. 'spread_two_uid' => 0,
  198. 'virtual_type' => $virtual_type
  199. ];
  200. if ($shippingType === 2) {
  201. $orderInfo['verify_code'] = $this->getStoreCode();
  202. /** @var SystemStoreServices $storeServices */
  203. $storeServices = app()->make(SystemStoreServices::class);
  204. $orderInfo['store_id'] = $storeServices->getStoreDispose($storeId, 'id');
  205. if (!$orderInfo['store_id']) {
  206. throw new ValidateException('暂无门店无法选择门店自提');
  207. }
  208. }
  209. /** @var StoreOrderCartInfoServices $cartServices */
  210. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  211. /** @var StoreSeckillServices $seckillServices */
  212. $seckillServices = app()->make(StoreSeckillServices::class);
  213. $priceData['coupon_id'] = $couponId;
  214. $order = $this->transaction(function () use ($cartIds, $orderInfo, $cartInfo, $key, $userInfo, $useIntegral, $priceData, $combinationId, $seckillId, $bargainId, $cartServices, $seckillServices, $uid, $addressId, $advanceId) {
  215. //创建订单
  216. $order = $this->dao->save($orderInfo);
  217. if (!$order) {
  218. throw new ValidateException('订单生成失败!');
  219. }
  220. //记录自提人电话和姓名
  221. /** @var UserServices $userService */
  222. $userService = app()->make(UserServices::class);
  223. $userService->update(['uid' => $uid], ['real_name' => $orderInfo['real_name'], 'record_phone' => $orderInfo['user_phone']]);
  224. //占用库存
  225. $seckillServices->occupySeckillStock($cartInfo, $key);
  226. //积分抵扣
  227. if ($priceData['usedIntegral'] > 0) {
  228. $this->deductIntegral($userInfo, $useIntegral, $priceData, (int)$userInfo['uid'], $order['id']);
  229. }
  230. //扣库存
  231. $this->decGoodsStock($cartInfo, $combinationId, $seckillId, $bargainId, $advanceId);
  232. //保存购物车商品信息
  233. $cartServices->setCartInfo($order['id'], $cartInfo);
  234. return $order;
  235. });
  236. //订单创建成功后置事件
  237. event('order.orderCreateAfter', [$order, compact('cartInfo', 'priceData', 'addressId', 'cartIds', 'news'), $uid, $key, $combinationId, $seckillId, $bargainId]);
  238. return $order;
  239. }
  240. /**
  241. * 抵扣积分
  242. * @param array $userInfo
  243. * @param bool $useIntegral
  244. * @param array $priceData
  245. * @param int $uid
  246. * @param string $key
  247. */
  248. public function deductIntegral(array $userInfo, bool $useIntegral, array $priceData, int $uid, $orderId)
  249. {
  250. $res2 = true;
  251. if ($useIntegral && $userInfo['integral'] > 0) {
  252. /** @var UserServices $userServices */
  253. $userServices = app()->make(UserServices::class);
  254. if (!$priceData['SurplusIntegral']) {
  255. $res2 = false !== $userServices->update($uid, ['integral' => 0]);
  256. } else {
  257. $res2 = false !== $userServices->bcDec($userInfo['uid'], 'integral', $priceData['usedIntegral'], 'uid');
  258. }
  259. /** @var UserBillServices $userBillServices */
  260. $userBillServices = app()->make(UserBillServices::class);
  261. $res3 = $userBillServices->income('deduction', $uid, [
  262. 'number' => $priceData['usedIntegral'],
  263. 'deductionPrice' => $priceData['deduction_price']
  264. ], $userInfo['integral'], $orderId);
  265. $res2 = $res2 && false != $res3;
  266. }
  267. if (!$res2) {
  268. throw new ValidateException('使用积分抵扣失败!');
  269. }
  270. }
  271. /**
  272. * 扣库存
  273. * @param array $cartInfo
  274. * @param int $combinationId
  275. * @param int $seckillId
  276. * @param int $bargainId
  277. */
  278. public function decGoodsStock(array $cartInfo, int $combinationId, int $seckillId, int $bargainId, int $advanceId)
  279. {
  280. $res5 = true;
  281. /** @var StoreProductServices $services */
  282. $services = app()->make(StoreProductServices::class);
  283. /** @var StoreSeckillServices $seckillServices */
  284. $seckillServices = app()->make(StoreSeckillServices::class);
  285. /** @var StoreCombinationServices $pinkServices */
  286. $pinkServices = app()->make(StoreCombinationServices::class);
  287. /** @var StoreBargainServices $bargainServices */
  288. $bargainServices = app()->make(StoreBargainServices::class);
  289. /** @var StoreAdvanceServices $advanceServices */
  290. $advanceServices = app()->make(StoreAdvanceServices::class);
  291. try {
  292. foreach ($cartInfo as $cart) {
  293. //减库存加销量
  294. if ($combinationId) $res5 = $res5 && $pinkServices->decCombinationStock((int)$cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  295. else if ($seckillId) $res5 = $res5 && $seckillServices->decSeckillStock((int)$cart['cart_num'], $seckillId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  296. else if ($bargainId) $res5 = $res5 && $bargainServices->decBargainStock((int)$cart['cart_num'], $bargainId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  297. else if ($advanceId) $res5 = $res5 && $advanceServices->decAdvanceStock((int)$cart['cart_num'], $advanceId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  298. else $res5 = $res5 && $services->decProductStock((int)$cart['cart_num'], (int)$cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  299. }
  300. if (!$res5) {
  301. throw new ValidateException('库存不足!');
  302. }
  303. } catch (\Throwable $e) {
  304. throw new ValidateException('库存不足!');
  305. }
  306. }
  307. /**
  308. * 订单创建后的后置事件
  309. * @param UserAddressServices $addressServices
  310. * @param $order
  311. * @param array $group
  312. */
  313. public function orderCreateAfter($order, array $group)
  314. {
  315. /** @var UserAddressServices $addressServices */
  316. $addressServices = app()->make(UserAddressServices::class);
  317. //设置用户默认地址
  318. if (!$addressServices->be(['is_default' => 1, 'uid' => $order['uid']])) {
  319. $addressServices->setDefaultAddress($group['addressId'], $order['uid']);
  320. }
  321. //删除购物车
  322. if ($group['news']) {
  323. array_map(function ($key) {
  324. CacheService::redisHandler()->delete($key);
  325. }, $group['cartIds']);
  326. } else {
  327. /** @var StoreCartServices $cartServices */
  328. $cartServices = app()->make(StoreCartServices::class);
  329. $cartServices->deleteCartStatus($group['cartIds']);
  330. }
  331. }
  332. /**
  333. * 计算订单每个商品真实付款价格
  334. * @param array $cartInfo
  335. * @param array $priceData
  336. * @param $addressId
  337. * @param int $uid
  338. * @return array
  339. */
  340. public function computeOrderProductTruePrice(array $cartInfo, array $priceData, $addressId, int $uid)
  341. {
  342. //统一放入默认数据
  343. foreach ($cartInfo as &$cart) {
  344. $cart['use_integral'] = 0;
  345. $cart['integral_price'] = 0.00;
  346. $cart['coupon_price'] = 0.00;
  347. }
  348. try {
  349. [$cartInfo, $spread_ids] = $this->computeOrderProductBrokerage($uid, $cartInfo);
  350. $cartInfo = $this->computeOrderProductCoupon($cartInfo, $priceData);
  351. $cartInfo = $this->computeOrderProductIntegral($cartInfo, $priceData);
  352. $cartInfo = $this->computeOrderProductPostage($cartInfo, $priceData, $addressId);
  353. } catch (\Throwable $e) {
  354. Log::error('订单商品结算失败,File:' . $e->getFile() . ',Line:' . $e->getLine() . ',Message:' . $e->getMessage());
  355. throw new ValidateException('订单商品结算失败');
  356. }
  357. //truePice实际支付单价(存在)
  358. //几件商品总体优惠 以及积分抵扣金额
  359. foreach ($cartInfo as &$cart) {
  360. $coupon_price = $cart['coupon_price'] ?? 0;
  361. $integral_price = $cart['integral_price'] ?? 0;
  362. if ($coupon_price) {
  363. $cart['sum_true_price'] = bcsub((string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), (string)$coupon_price, 2);
  364. $uni_coupon_price = (string)bcdiv((string)$coupon_price, (string)$cart['cart_num'], 4);
  365. $cart['truePrice'] = $cart['truePrice'] > $uni_coupon_price ? bcsub((string)$cart['truePrice'], $uni_coupon_price, 2) : 0;
  366. }
  367. if ($integral_price) {
  368. $sum = $coupon_price && isset($cart['sum_true_price']) ? (string)$cart['sum_true_price'] : (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4);
  369. $cart['sum_true_price'] = bcsub($sum, (string)$integral_price, 2);
  370. $uni_integral_price = (string)bcdiv((string)$integral_price, (string)$cart['cart_num'], 4);
  371. $cart['truePrice'] = $cart['truePrice'] > $uni_integral_price ? bcsub((string)$cart['truePrice'], $uni_integral_price, 2) : 0;
  372. }
  373. }
  374. return [$cartInfo, $spread_ids];
  375. }
  376. /**
  377. * 计算每个商品实际支付运费
  378. * @param array $cartInfo
  379. * @param array $priceData
  380. * @return array
  381. */
  382. public function computeOrderProductPostage(array $cartInfo, array $priceData, $addressId)
  383. {
  384. $storePostage = $priceData['pay_postage'] ?? 0;
  385. if ($storePostage) {
  386. /** @var UserAddressServices $addressServices */
  387. $addressServices = app()->make(UserAddressServices::class);
  388. $addr = $addressServices->getAddress($addressId);
  389. if ($addr) {
  390. $addr = $addr->toArray();
  391. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  392. $cityId = $addr['city_id'] ?? 0;
  393. $tempIds[] = 1;
  394. foreach ($cartInfo as $key_c => $item_c) {
  395. $tempIds[] = $item_c['productInfo']['temp_id'];
  396. }
  397. $tempIds = array_unique($tempIds);
  398. /** @var ShippingTemplatesServices $shippServices */
  399. $shippServices = app()->make(ShippingTemplatesServices::class);
  400. $temp = $shippServices->getShippingColumn(['id' => $tempIds], 'type,appoint', 'id');
  401. /** @var ShippingTemplatesRegionServices $regionServices */
  402. $regionServices = app()->make(ShippingTemplatesRegionServices::class);
  403. $regions = $regionServices->getTempRegionList($tempIds, [$cityId, 0], 'temp_id,first,first_price,continue,continue_price', 'temp_id');
  404. $temp_num = [];
  405. foreach ($cartInfo as $cart) {
  406. $tempId = $cart['productInfo']['temp_id'] ?? 1;
  407. $type = isset($temp[$tempId]['type']) ? $temp[$tempId]['type'] : $temp[1]['type'];
  408. if ($type == 1) {
  409. $num = $cart['cart_num'];
  410. } elseif ($type == 2) {
  411. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  412. } else {
  413. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  414. }
  415. $region = isset($regions[$tempId]) ? $regions[$tempId] : $regions[1];
  416. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  417. $temp_num[$cart['productInfo']['temp_id']]['cart_id'][] = $cart['id'];
  418. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  419. $temp_num[$cart['productInfo']['temp_id']]['type'] = $type;
  420. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  421. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  422. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  423. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  424. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  425. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  426. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
  427. } else {
  428. $temp_num[$cart['productInfo']['temp_id']]['cart_id'][] = $cart['id'];
  429. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  430. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  431. }
  432. }
  433. $cartInfo = array_combine(array_column($cartInfo, 'id'), $cartInfo);
  434. /** @var ShippingTemplatesFreeServices $freeServices */
  435. $freeServices = app()->make(ShippingTemplatesFreeServices::class);
  436. foreach ($temp_num as $k => $v) {
  437. if (isset($temp[$v['temp_id']]['appoint']) && $temp[$v['temp_id']]['appoint']) {
  438. if ($freeServices->isFree($v['temp_id'], $v['city_id'], $v['number'], $v['price'], $v['type'])) {
  439. //免运费
  440. foreach ($v['cart_id'] as $c_id) {
  441. if (isset($cartInfo[$c_id])) $cartInfo[$c_id]['postage_price'] = 0.00;
  442. }
  443. }
  444. }
  445. }
  446. $count = 0;
  447. $compute_price = 0.00;
  448. $total_price = 0;
  449. $postage_price = 0.00;
  450. foreach ($cartInfo as &$cart) {
  451. if (isset($cart['postage_price'])) {//免运费
  452. continue;
  453. }
  454. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  455. $count++;
  456. }
  457. foreach ($cartInfo as &$cart) {
  458. if (isset($cart['postage_price'])) {//免运费
  459. continue;
  460. }
  461. if ($count > 1) {
  462. $postage_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$storePostage, 2);
  463. $compute_price = bcadd((string)$compute_price, (string)$postage_price, 2);
  464. } else {
  465. $postage_price = bcsub((string)$storePostage, $compute_price, 2);
  466. }
  467. $cart['postage_price'] = $postage_price;
  468. $count--;
  469. }
  470. $cartInfo = array_merge($cartInfo);
  471. }
  472. }
  473. //保证不进运费模版计算的购物车商品postage_price字段有值
  474. foreach ($cartInfo as &$item) {
  475. if (!isset($item['postage_price'])) $item['postage_price'] = 0.00;
  476. }
  477. return $cartInfo;
  478. }
  479. /**
  480. * 计算订单商品积分实际抵扣金额
  481. * @param array $cartInfo
  482. * @param array $priceData
  483. * @return array
  484. */
  485. public function computeOrderProductIntegral(array $cartInfo, array $priceData)
  486. {
  487. $usedIntegral = $priceData['usedIntegral'] ?? 0;
  488. $deduction_price = $priceData['deduction_price'] ?? 0;
  489. if ($deduction_price) {
  490. $count = 0;
  491. $total_price = 0.00;
  492. $compute_price = 0.00;
  493. $integral_price = 0.00;
  494. $use_integral = 0;
  495. $compute_integral = 0;
  496. foreach ($cartInfo as $cart) {
  497. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  498. $count++;
  499. }
  500. foreach ($cartInfo as &$cart) {
  501. if ($count > 1) {
  502. $integral_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$deduction_price, 2);
  503. $compute_price = bcadd((string)$compute_price, (string)$integral_price, 2);
  504. $use_integral = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$usedIntegral, 0);
  505. $compute_integral = bcadd((string)$compute_integral, $use_integral, 0);
  506. } else {
  507. $integral_price = bcsub((string)$deduction_price, $compute_price, 2);
  508. $use_integral = bcsub((string)$usedIntegral, $compute_integral, 0);
  509. }
  510. $count--;
  511. $cart['integral_price'] = $integral_price;
  512. $cart['use_integral'] = $use_integral;
  513. }
  514. }
  515. return $cartInfo;
  516. }
  517. /**
  518. * 计算订单商品优惠券实际抵扣金额
  519. * @param array $cartInfo
  520. * @param array $priceData
  521. * @return array
  522. */
  523. public function computeOrderProductCoupon(array $cartInfo, array $priceData)
  524. {
  525. if ($priceData['coupon_id'] && $priceData['coupon_price'] ?? 0) {
  526. $count = 0;
  527. $total_price = 0.00;
  528. $compute_price = 0.00;
  529. $coupon_price = 0.00;
  530. /** @var StoreCouponUserServices $couponServices */
  531. $couponServices = app()->make(StoreCouponUserServices::class);
  532. $couponInfo = $couponServices->getOne(['id' => $priceData['coupon_id']], '*', ['issue']);
  533. if ($couponInfo) {
  534. $type = $couponInfo['applicable_type'] ?? 0;
  535. $counpon_id = $couponInfo['id'];
  536. switch ($type) {
  537. case 0:
  538. case 3:
  539. foreach ($cartInfo as $cart) {
  540. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  541. $count++;
  542. }
  543. foreach ($cartInfo as &$cart) {
  544. if ($count > 1) {
  545. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  546. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  547. } else {
  548. $coupon_price = bcsub((string)$couponInfo['coupon_price'], $compute_price, 2);
  549. }
  550. $cart['coupon_price'] = $coupon_price;
  551. $cart['coupon_id'] = $counpon_id;
  552. $count--;
  553. }
  554. break;
  555. case 1://品类券
  556. /** @var StoreCategoryServices $storeCategoryServices */
  557. $storeCategoryServices = app()->make(StoreCategoryServices::class);
  558. $cateGorys = $storeCategoryServices->getAllById((int)$couponInfo['category_id']);
  559. if ($cateGorys) {
  560. $cateIds = array_column($cateGorys, 'id');
  561. foreach ($cartInfo as $cart) {
  562. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  563. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  564. $count++;
  565. }
  566. }
  567. foreach ($cartInfo as &$cart) {
  568. $cart['coupon_id'] = 0;
  569. $cart['coupon_price'] = 0;
  570. if (isset($cart['productInfo']['cate_id']) && array_intersect(explode(',', $cart['productInfo']['cate_id']), $cateIds)) {
  571. if ($count > 1) {
  572. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  573. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  574. } else {
  575. $coupon_price = bcsub((string)$couponInfo['coupon_price'], $compute_price, 2);
  576. }
  577. $cart['coupon_id'] = $counpon_id;
  578. $cart['coupon_price'] = $coupon_price;
  579. $count--;
  580. }
  581. }
  582. }
  583. break;
  584. case 2://商品劵
  585. foreach ($cartInfo as $cart) {
  586. if (isset($cart['product_id']) && in_array($cart['product_id'], explode(',', $couponInfo['product_id']))) {
  587. $total_price = bcadd((string)$total_price, (string)bcmul((string)$cart['truePrice'], (string)$cart['cart_num'], 4), 2);
  588. $count++;
  589. }
  590. }
  591. foreach ($cartInfo as &$cart) {
  592. $cart['coupon_id'] = 0;
  593. $cart['coupon_price'] = 0;
  594. if (isset($cart['product_id']) && in_array($cart['product_id'], explode(',', $couponInfo['product_id']))) {
  595. if ($count > 1) {
  596. $coupon_price = bcmul((string)bcdiv((string)bcmul((string)$cart['cart_num'], (string)$cart['truePrice'], 4), (string)$total_price, 4), (string)$couponInfo['coupon_price'], 2);
  597. $compute_price = bcadd((string)$compute_price, (string)$coupon_price, 2);
  598. } else {
  599. $coupon_price = bcsub((string)$couponInfo['coupon_price'], $compute_price, 2);
  600. }
  601. $cart['coupon_id'] = $counpon_id;
  602. $cart['coupon_price'] = $coupon_price;
  603. $count--;
  604. }
  605. }
  606. break;
  607. }
  608. }
  609. }
  610. return $cartInfo;
  611. }
  612. /**
  613. * 计算实际佣金
  614. * @param int $uid
  615. * @param array $cartInfo
  616. * @return array
  617. * @throws \think\db\exception\DataNotFoundException
  618. * @throws \think\db\exception\DbException
  619. * @throws \think\db\exception\ModelNotFoundException
  620. */
  621. public function computeOrderProductBrokerage(int $uid, array $cartInfo)
  622. {
  623. //获取后台一级返佣比例
  624. $storeBrokerageRatio = sys_config('store_brokerage_ratio');
  625. //获取二级返佣比例
  626. $storeBrokerageTwo = sys_config('store_brokerage_two');
  627. /** @var AgentLevelServices $agentLevelServices */
  628. $agentLevelServices = app()->make(AgentLevelServices::class);
  629. [$one_brokerage_up, $two_brokerage_up, $spread_one_uid, $spread_two_uid] = $agentLevelServices->getAgentLevelBrokerage($uid);
  630. foreach ($cartInfo as &$cart) {
  631. $oneBrokerage = '0';//一级返佣金额
  632. $twoBrokerage = '0';//二级返佣金额
  633. $cartNum = (string)$cart['cart_num'] ?? '0';
  634. if (isset($cart['productInfo'])) {
  635. $productInfo = $cart['productInfo'];
  636. //指定返佣金额
  637. if (isset($productInfo['is_sub']) && $productInfo['is_sub'] == 1) {
  638. $oneBrokerage = bcmul((string)($productInfo['attrInfo']['brokerage'] ?? '0'), $cartNum, 2);
  639. $twoBrokerage = bcmul((string)($productInfo['attrInfo']['brokerage_two'] ?? '0'), $cartNum, 2);
  640. } else {
  641. //比例返佣
  642. if (isset($productInfo['attrInfo'])) {
  643. $price = bcmul((string)($productInfo['attrInfo']['price'] ?? '0'), $cartNum, 4);
  644. } else {
  645. $price = bcmul((string)($productInfo['price'] ?? '0'), $cartNum, 4);
  646. }
  647. if ($price) {
  648. //一级返佣比例 小于等于零时直接返回 不返佣
  649. if ($storeBrokerageRatio > 0) {
  650. //计算获取一级返佣比例
  651. $brokerageRatio = bcdiv($storeBrokerageRatio, 100, 4);
  652. $oneBrokerage = bcmul((string)$price, (string)$brokerageRatio, 2);
  653. }
  654. //二级返佣比例小于等于0 直接返回
  655. if ($storeBrokerageTwo > 0) {
  656. //计算获取二级返佣比例
  657. $brokerageTwo = bcdiv($storeBrokerageTwo, 100, 4);
  658. $twoBrokerage = bcmul((string)$price, (string)$brokerageTwo, 2);
  659. }
  660. }
  661. }
  662. }
  663. if ($one_brokerage_up) $oneBrokerage = bcadd((string)$oneBrokerage, (string)bcmul((string)$oneBrokerage, (string)bcdiv((string)$one_brokerage_up, '100', 2), 4), 2);
  664. if ($two_brokerage_up) $twoBrokerage = bcadd((string)$twoBrokerage, (string)bcmul((string)$twoBrokerage, (string)bcdiv((string)$two_brokerage_up, '100', 2), 4), 2);
  665. $cart['one_brokerage'] = $oneBrokerage;
  666. $cart['two_brokerage'] = $twoBrokerage;
  667. }
  668. return [$cartInfo, [$spread_one_uid, $spread_two_uid]];
  669. }
  670. }