StoreOrderCreateServices.php 46 KB

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