StoreOrderCreateServices.php 40 KB

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