StoreOrderCreateServices.php 43 KB

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