StoreOrderCreateServices.php 42 KB

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