StoreOrderCreateServices.php 44 KB

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