StoreOrderCreateServices.php 40 KB

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