StoreOrderCreateServices.php 45 KB

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