StoreCartServices.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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. declare (strict_types=1);
  12. namespace app\services\order;
  13. use app\model\agent\AgentLevel;
  14. use app\services\activity\advance\StoreAdvanceServices;
  15. use app\services\agent\AgentLevelServices;
  16. use app\services\BaseServices;
  17. use app\dao\order\StoreCartDao;
  18. use app\services\activity\coupon\StoreCouponIssueServices;
  19. use app\services\product\shipping\ShippingTemplatesServices;
  20. use app\services\shipping\ShippingTemplatesNoDeliveryServices;
  21. use app\services\system\SystemUserLevelServices;
  22. use app\services\user\member\MemberCardServices;
  23. use app\services\user\UserServices;
  24. use app\jobs\ProductLogJob;
  25. use crmeb\exceptions\ApiException;
  26. use crmeb\services\CacheService;
  27. use app\services\activity\seckill\StoreSeckillServices;
  28. use app\services\activity\bargain\StoreBargainServices;
  29. use app\services\activity\combination\StoreCombinationServices;
  30. use app\services\product\product\StoreProductServices;
  31. use app\services\product\sku\StoreProductAttrValueServices;
  32. /**
  33. *
  34. * Class StoreCartServices
  35. * @package app\services\order
  36. * @method updateCartStatus($cartIds) 修改购物车状态
  37. * @method getUserCartNum(int $uid, string $type, int $numType) 购物车数量
  38. * @method deleteCartStatus(array $cartIds) 修改购物车状态
  39. * @method array productIdByCartNum(array $ids, int $uid) 根据商品id获取购物车数量
  40. * @method getCartList(array $where, ?int $page = 0, ?int $limit = 0, ?array $with = []) 获取用户购物车
  41. * @method getSum($where, $field) 求和
  42. * @method getProductTrend($time, $timeType, $str) 购物车趋势
  43. */
  44. class StoreCartServices extends BaseServices
  45. {
  46. /**
  47. * StoreCartServices constructor.
  48. * @param StoreCartDao $dao
  49. */
  50. public function __construct(StoreCartDao $dao)
  51. {
  52. $this->dao = $dao;
  53. }
  54. /**
  55. * 获取某个用户下的购物车数量
  56. * @param array $unique
  57. * @param int $productId
  58. * @param int $uid
  59. * @return array
  60. */
  61. public function getUserCartNums(array $unique, int $productId, int $uid)
  62. {
  63. $where['is_pay'] = 0;
  64. $where['is_del'] = 0;
  65. $where['is_new'] = 0;
  66. $where['product_id'] = $productId;
  67. $where['uid'] = $uid;
  68. return $this->dao->getUserCartNums($where, $unique);
  69. }
  70. /**
  71. * 获取用户下的购物车列表
  72. * @param $uid
  73. * @param string $cartIds
  74. * @param bool $new
  75. * @param array $addr
  76. * @return array
  77. * @throws \Psr\SimpleCache\InvalidArgumentException
  78. * @throws \think\db\exception\DataNotFoundException
  79. * @throws \think\db\exception\DbException
  80. * @throws \think\db\exception\ModelNotFoundException
  81. */
  82. public function getUserProductCartListV1($uid, $cartIds = '', bool $new, $addr = [], int $shipping_type = 1)
  83. {
  84. if ($new) {
  85. $cartIds = explode(',', $cartIds);
  86. $cartInfo = [];
  87. foreach ($cartIds as $key) {
  88. $info = CacheService::get($key);
  89. if ($info) {
  90. $cartInfo[] = $info;
  91. }
  92. }
  93. } else {
  94. $cartInfo = $this->dao->getCartList(['uid' => $uid, 'status' => 1, 'id' => $cartIds], 0, 0, ['productInfo', 'attrInfo']);
  95. }
  96. if (!$cartInfo) {
  97. throw new ApiException(410233);
  98. }
  99. [$cartInfo, $valid, $invalid] = $this->handleCartList($uid, $cartInfo, $addr, $shipping_type);
  100. $seckillIds = array_unique(array_column($cartInfo, 'seckill_id'));
  101. $bargainIds = array_unique(array_column($cartInfo, 'bargain_id'));
  102. $combinationId = array_unique(array_column($cartInfo, 'combination_id'));
  103. $advanceId = array_unique(array_column($cartInfo, 'advance_id'));
  104. $deduction = ['seckill_id' => $seckillIds[0] ?? 0, 'bargain_id' => $bargainIds[0] ?? 0, 'combination_id' => $combinationId[0] ?? 0, 'advance_id' => $advanceId[0] ?? 0];
  105. return ['cartInfo' => $cartInfo, 'valid' => $valid, 'invalid' => $invalid, 'deduction' => $deduction];
  106. }
  107. /**
  108. * 使用雪花算法生成订单ID
  109. * @return string
  110. * @throws \Exception
  111. */
  112. public function getCartId($prefix)
  113. {
  114. $snowflake = new \Godruoyi\Snowflake\Snowflake();
  115. //32位
  116. if (PHP_INT_SIZE == 4) {
  117. $id = abs((int)$snowflake->id());
  118. } else {
  119. $id = $snowflake->setStartTimeStamp(strtotime('2020-06-05') * 1000)->id();
  120. }
  121. return $prefix . $id;
  122. }
  123. /**
  124. * 验证库存
  125. * @param int $uid
  126. * @param int $cartNum
  127. * @param string $unique
  128. * @param int $type
  129. * @param $productId
  130. * @param int $seckillId
  131. * @param int $bargainId
  132. * @param int $combinationId
  133. * @return array
  134. * @throws \Psr\SimpleCache\InvalidArgumentException
  135. * @throws \think\db\exception\DataNotFoundException
  136. * @throws \think\db\exception\DbException
  137. * @throws \think\db\exception\ModelNotFoundException
  138. */
  139. public function checkProductStock(int $uid, int $cartNum, string $unique, int $type = 0, $productId, int $seckillId, int $bargainId, int $combinationId, int $advanceId)
  140. {
  141. /** @var StoreProductAttrValueServices $attrValueServices */
  142. $attrValueServices = app()->make(StoreProductAttrValueServices::class);
  143. switch ($type) {
  144. case 0://普通
  145. if ($unique == '') {
  146. $unique = $attrValueServices->value(['product_id' => $productId, 'type' => 0], 'unique');
  147. }
  148. /** @var StoreProductServices $productServices */
  149. $productServices = app()->make(StoreProductServices::class);
  150. $productInfo = $productServices->isValidProduct($productId);
  151. if (!$productInfo) {
  152. throw new ApiException(410295);
  153. }
  154. $attrInfo = $attrValueServices->getOne(['unique' => $unique, 'type' => 0]);
  155. if (!$unique || !$attrInfo || $attrInfo['product_id'] != $productId) {
  156. throw new ApiException(410305);
  157. }
  158. $nowStock = $attrInfo['stock'];//现有库存
  159. if ($cartNum > $nowStock) {
  160. throw new ApiException(410297, ['num' => $cartNum]);
  161. }
  162. if ($productInfo['is_virtual'] == 1 && $productInfo['virtual_type'] == 2 && $attrInfo['coupon_id']) {
  163. /** @var StoreCouponIssueServices $issueCoupon */
  164. $issueCoupon = app()->make(StoreCouponIssueServices::class);
  165. if (!$issueCoupon->getCount(['id' => $attrInfo['coupon_id'], 'status' => 1, 'is_del' => 0])) {
  166. throw new ApiException(410234);
  167. }
  168. }
  169. $stockNum = $this->dao->value(['product_id' => $productId, 'product_attr_unique' => $unique, 'uid' => $uid, 'status' => 1], 'cart_num') ?: 0;
  170. if ($nowStock < ($cartNum + $stockNum)) {
  171. $surplusStock = $nowStock - $cartNum;//剩余库存
  172. if ($surplusStock < $stockNum) {
  173. $this->dao->update(['product_id' => $productId, 'product_attr_unique' => $unique, 'uid' => $uid, 'status' => 1], ['cart_num' => $surplusStock]);
  174. }
  175. }
  176. break;
  177. case 1://秒杀
  178. /** @var StoreSeckillServices $seckillService */
  179. $seckillService = app()->make(StoreSeckillServices::class);
  180. [$attrInfo, $unique, $productInfo] = $seckillService->checkSeckillStock($uid, $seckillId, $cartNum, $unique);
  181. break;
  182. case 2://砍价
  183. /** @var StoreBargainServices $bargainService */
  184. $bargainService = app()->make(StoreBargainServices::class);
  185. [$attrInfo, $unique, $productInfo, $bargainUserInfo] = $bargainService->checkBargainStock($uid, $bargainId, $cartNum, $unique);
  186. break;
  187. case 3://拼团
  188. /** @var StoreCombinationServices $combinationService */
  189. $combinationService = app()->make(StoreCombinationServices::class);
  190. [$attrInfo, $unique, $productInfo] = $combinationService->checkCombinationStock($uid, $combinationId, $cartNum, $unique);
  191. break;
  192. case 6://预售
  193. /** @var StoreAdvanceServices $advanceService */
  194. $advanceService = app()->make(StoreAdvanceServices::class);
  195. [$attrInfo, $unique, $productInfo] = $advanceService->checkAdvanceStock($uid, $advanceId, $cartNum, $unique);
  196. break;
  197. default:
  198. throw new ApiException(410236);
  199. }
  200. if ($type && $type != 6) {
  201. //根商品规格库存
  202. $product_stock = $attrValueServices->value(['product_id' => $productInfo['product_id'], 'suk' => $attrInfo['suk'], 'type' => 0], 'stock');
  203. if ($product_stock < $cartNum) {
  204. throw new ApiException(410297, ['num' => $cartNum]);
  205. }
  206. }
  207. return [$attrInfo, $unique, $bargainUserInfo['bargain_price_min'] ?? 0, $cartNum, $productInfo];
  208. }
  209. /**
  210. * 添加购物车
  211. * @param int $uid 用户UID
  212. * @param int $product_id 商品ID
  213. * @param int $cart_num 商品数量
  214. * @param string $product_attr_unique 商品SKU
  215. * @param string $type 添加购物车类型
  216. * @param bool $new true = 立即购买,false = 加入购物车
  217. * @param int $combination_id 拼团商品ID
  218. * @param int $seckill_id 秒杀商品ID
  219. * @param int $bargain_id 砍价商品ID
  220. * @return mixed|string
  221. * @throws \Psr\SimpleCache\InvalidArgumentException
  222. * @throws \think\db\exception\DataNotFoundException
  223. * @throws \think\db\exception\DbException
  224. * @throws \think\db\exception\ModelNotFoundException
  225. */
  226. public function setCart(int $uid, int $product_id, int $cart_num = 1, string $product_attr_unique = '', int $type = 0, bool $new = true, int $combination_id = 0, int $seckill_id = 0, int $bargain_id = 0, int $advance_id = 0)
  227. {
  228. if ($cart_num < 1) $cart_num = 1;
  229. if ($type == 0) {
  230. //检查限购
  231. $this->checkLimit($uid, $product_id, $cart_num, $new);
  232. }
  233. //检测库存限量
  234. [$attrInfo, $product_attr_unique, $bargainPriceMin, $cart_num, $productInfo] = $this->checkProductStock($uid, $cart_num, $product_attr_unique, $type, $product_id, $seckill_id, $bargain_id, $combination_id, $advance_id);
  235. if ($new) {
  236. /** @var StoreOrderCreateServices $storeOrderCreateService */
  237. $storeOrderCreateService = app()->make(StoreOrderCreateServices::class);
  238. $key = $storeOrderCreateService->getNewOrderId((string)$uid);
  239. $info['id'] = $key;
  240. $info['type'] = $type;
  241. $info['seckill_id'] = $seckill_id;
  242. $info['bargain_id'] = $bargain_id;
  243. $info['combination_id'] = $combination_id;
  244. $info['advance_id'] = $advance_id;
  245. $info['product_id'] = $product_id;
  246. $info['product_attr_unique'] = $product_attr_unique;
  247. $info['cart_num'] = $cart_num;
  248. $info['productInfo'] = $productInfo ? $productInfo->toArray() : [];
  249. $info['productInfo']['attrInfo'] = $attrInfo->toArray();
  250. $info['attrInfo'] = $attrInfo->toArray();
  251. $info['sum_price'] = $info['productInfo']['attrInfo']['price'];
  252. //砍价
  253. if ($bargain_id) {
  254. $info['truePrice'] = $bargainPriceMin;
  255. $info['productInfo']['attrInfo']['price'] = $bargainPriceMin;
  256. } else {
  257. $info['truePrice'] = $info['productInfo']['attrInfo']['price'] ?? $info['productInfo']['price'] ?? 0;
  258. }
  259. //拼团砍价秒杀不参与会员价
  260. if ($bargain_id || $combination_id || $seckill_id || $advance_id) {
  261. $info['truePrice'] = $info['productInfo']['attrInfo']['price'] ?? 0;
  262. $info['vip_truePrice'] = 0;
  263. }
  264. $info['trueStock'] = $info['productInfo']['attrInfo']['stock'];
  265. $info['costPrice'] = $info['productInfo']['attrInfo']['cost'];
  266. try {
  267. CacheService::set($key, $info, 3600);
  268. } catch (\Throwable $e) {
  269. throw new ApiException($e->getMessage());
  270. }
  271. return $key;
  272. } else {//加入购物车记录
  273. ProductLogJob::dispatch(['cart', ['uid' => $uid, 'product_id' => $product_id, 'cart_num' => $cart_num]]);
  274. $cart = $this->dao->getOne(['type' => $type, 'uid' => $uid, 'product_id' => $product_id, 'product_attr_unique' => $product_attr_unique, 'is_del' => 0, 'is_new' => 0, 'is_pay' => 0, 'status' => 1]);
  275. if ($cart) {
  276. $cart->cart_num = $cart_num + $cart->cart_num;
  277. $cart->add_time = time();
  278. $cart->save();
  279. return $cart->id;
  280. } else {
  281. $add_time = time();
  282. return $this->dao->save(compact('uid', 'product_id', 'cart_num', 'product_attr_unique', 'type', 'add_time'))->id;
  283. }
  284. }
  285. }
  286. /**移除购物车商品
  287. * @param int $uid
  288. * @param array $ids
  289. * @return StoreCartDao|bool
  290. */
  291. public function removeUserCart(int $uid, array $ids)
  292. {
  293. if (!$uid || !$ids) return false;
  294. return $this->dao->removeUserCart($uid, $ids);
  295. }
  296. /**购物车 修改商品数量
  297. * @param $id
  298. * @param $number
  299. * @param $uid
  300. * @return bool|\crmeb\basic\BaseModel
  301. * @throws \think\db\exception\DataNotFoundException
  302. * @throws \think\db\exception\DbException
  303. * @throws \think\db\exception\ModelNotFoundException
  304. */
  305. public function changeUserCartNum($id, $number, $uid)
  306. {
  307. if (!$id || !$number || !$uid) return false;
  308. $where = ['uid' => $uid, 'id' => $id];
  309. $carInfo = $this->dao->getOne($where, 'product_id,combination_id,seckill_id,bargain_id,product_attr_unique,cart_num');
  310. //购物车修改数量检查限购
  311. /** @var StoreProductServices $productServices */
  312. $productServices = app()->make(StoreProductServices::class);
  313. $limitInfo = $productServices->get($carInfo->product_id, ['is_limit', 'limit_type', 'limit_num', 'min_qty']);
  314. if ($number < $limitInfo['min_qty']) {
  315. throw new ApiException('不能小于起购数量');
  316. }
  317. if ($limitInfo['is_limit']) {
  318. if ($limitInfo['limit_type'] == 1 && $number > $limitInfo['limit_num']) {
  319. throw new ApiException(410239, ['limit' => $limitInfo['limit_num']]);
  320. } else if ($limitInfo['limit_type'] == 2) {
  321. /** @var StoreOrderCartInfoServices $orderCartServices */
  322. $orderCartServices = app()->make(StoreOrderCartInfoServices::class);
  323. $orderPayNum = $orderCartServices->sum(['uid' => $uid, 'product_id' => $carInfo->product_id], 'cart_num');
  324. $orderRefundNum = $orderCartServices->sum(['uid' => $uid, 'product_id' => $carInfo->product_id], 'refund_num');
  325. $orderNum = $orderPayNum - $orderRefundNum;
  326. if (($number + $orderNum) > $limitInfo['limit_num']) {
  327. throw new ApiException(410240, ['limit' => $limitInfo['limit_num'], 'pay_num' => $orderNum]);
  328. }
  329. }
  330. }
  331. $stock = $productServices->getProductStock($carInfo->product_id, $carInfo->product_attr_unique);
  332. if (!$stock) throw new ApiException(410237);
  333. if ($stock < $number) throw new ApiException(410297, ['num' => $number]);
  334. if ($carInfo->cart_num == $number) return true;
  335. return $this->dao->changeUserCartNum(['uid' => $uid, 'id' => $id], (int)$number);
  336. }
  337. /**
  338. * 修改购物车状态
  339. * @param int $productId
  340. * @param int $status 0 商品下架
  341. */
  342. public function changeStatus(int $productId, $status = 0)
  343. {
  344. $this->dao->update($productId, ['status' => $status], 'product_id');
  345. }
  346. /**
  347. * 获取购物车列表
  348. * @param int $uid
  349. * @param int $status
  350. * @return array
  351. * @throws \think\db\exception\DataNotFoundException
  352. * @throws \think\db\exception\DbException
  353. * @throws \think\db\exception\ModelNotFoundException
  354. */
  355. public function getUserCartList(int $uid, int $status, string $cartIds = '')
  356. {
  357. [$page, $limit] = $this->getPageValue();
  358. $list = $this->dao->getCartList(['uid' => $uid, 'status' => $status, 'id' => $cartIds], $page, $limit, ['productInfo', 'attrInfo']);
  359. [$list, $valid, $invalid] = $this->handleCartList($uid, $list);
  360. $seckillIds = array_unique(array_column($list, 'seckill_id'));
  361. $bargainIds = array_unique(array_column($list, 'bargain_id'));
  362. $combinationId = array_unique(array_column($list, 'combination_id'));
  363. $discountId = array_unique(array_column($list, 'discount_id'));
  364. $deduction = ['seckill_id' => $seckillIds[0] ?? 0, 'bargain_id' => $bargainIds[0] ?? 0, 'combination_id' => $combinationId[0] ?? 0, 'discount_id' => $discountId[0] ?? 0];
  365. if ($status == 1) {
  366. return ['valid' => $list, 'invalid' => [], 'deduction' => $deduction];
  367. } else {
  368. return ['valid' => [], 'invalid' => $list, 'deduction' => $deduction];
  369. }
  370. }
  371. /**
  372. * 购物车重选
  373. * @param int $cart_id
  374. * @param int $product_id
  375. * @param string $unique
  376. */
  377. public function modifyCart(int $cart_id, int $product_id, string $unique)
  378. {
  379. /** @var StoreProductAttrValueServices $attrService */
  380. $attrService = app()->make(StoreProductAttrValueServices::class);
  381. $stock = $attrService->value(['product_id' => $product_id, 'unique' => $unique, 'type' => 0], 'stock');
  382. if ($stock > 0) {
  383. $this->dao->update($cart_id, ['product_attr_unique' => $unique, 'cart_num' => 1]);
  384. } else {
  385. throw new ApiException(410238);
  386. }
  387. }
  388. /**
  389. * 重选购物车
  390. * @param $id
  391. * @param $uid
  392. * @param $productId
  393. * @param $unique
  394. * @param $num
  395. * @throws \think\db\exception\DataNotFoundException
  396. * @throws \think\db\exception\DbException
  397. * @throws \think\db\exception\ModelNotFoundException
  398. */
  399. public function resetCart($id, $uid, $productId, $unique, $num)
  400. {
  401. $res = $this->dao->getOne(['uid' => $uid, 'product_id' => $productId, 'product_attr_unique' => $unique]);
  402. if ($res) {
  403. $res->cart_num = $res->cart_num + $num;
  404. $res->save();
  405. $this->dao->delete($id);
  406. } else {
  407. $this->dao->update($id, ['product_attr_unique' => $unique, 'cart_num' => $num]);
  408. }
  409. }
  410. /**
  411. * 首页加入购物车
  412. * @param $uid
  413. * @param $productId
  414. * @param $num
  415. * @param $unique
  416. * @param $type
  417. * @return mixed
  418. * @throws \think\db\exception\DataNotFoundException
  419. * @throws \think\db\exception\DbException
  420. * @throws \think\db\exception\ModelNotFoundException
  421. */
  422. public function setCartNum($uid, $productId, $num, $unique, $type)
  423. {
  424. if ($type == 1) {
  425. //检查限购
  426. $this->checkLimit($uid, $productId, $num, 0);
  427. }
  428. /** @var StoreProductAttrValueServices $attrValueServices */
  429. $attrValueServices = app()->make(StoreProductAttrValueServices::class);
  430. if ($unique == '') {
  431. $unique = $attrValueServices->value(['product_id' => $productId, 'type' => 0], 'unique');
  432. }
  433. /** @var StoreProductServices $productServices */
  434. $productServices = app()->make(StoreProductServices::class);
  435. if (!$productServices->isValidProduct((int)$productId, 'id')) {
  436. throw new ApiException(410295);
  437. }
  438. if (!($unique && $attrValueServices->getAttrvalueCount($productId, $unique, 0))) {
  439. throw new ApiException(410305);
  440. }
  441. if ($productServices->getProductStock((int)$productId, $unique) < $num) {
  442. throw new ApiException(410297, ['num' => $num]);
  443. }
  444. $cart = $this->dao->getOne(['uid' => $uid, 'product_id' => $productId, 'product_attr_unique' => $unique]);
  445. if ($cart) {
  446. if ($type == -1) {
  447. $cart->cart_num = $num;
  448. } elseif ($type == 0) {
  449. $cart->cart_num = $cart->cart_num - $num;
  450. if ($cart->cart_num < $productServices->value(['id' => $productId], 'min_qty')) {
  451. throw new ApiException('不能小于起购数量');
  452. }
  453. } elseif ($type == 1) {
  454. $cart->cart_num = $cart->cart_num + $num;
  455. }
  456. if ($cart->cart_num === 0) {
  457. return $this->dao->delete($cart->id);
  458. } else {
  459. $cart->add_time = time();
  460. $cart->save();
  461. return $cart->id;
  462. }
  463. } else {
  464. $data = [
  465. 'uid' => $uid,
  466. 'product_id' => $productId,
  467. 'cart_num' => $num,
  468. 'product_attr_unique' => $unique,
  469. 'type' => 0,
  470. 'add_time' => time()
  471. ];
  472. return $this->dao->save($data)->id;
  473. }
  474. }
  475. /**
  476. * 获取用户购物车数量 ids 统计金额
  477. * @param int $uid
  478. * @param string $numType
  479. * @throws \think\db\exception\DataNotFoundException
  480. * @throws \think\db\exception\DbException
  481. * @throws \think\db\exception\ModelNotFoundException
  482. */
  483. public function getUserCartCount(int $uid, string $numType)
  484. {
  485. $count = 0;
  486. $ids = [];
  487. $sum_price = 0;
  488. $cartList = $this->dao->getUserCartList($uid, '*', ['productInfo', 'attrInfo']);
  489. if ($cartList) {
  490. // 检查是否有礼包商品(is_gift为1)
  491. $hasGift = false;
  492. foreach ($cartList as $item) {
  493. if (($item['productInfo']['is_gift'] ?? 0) == 1) {
  494. $hasGift = true;
  495. break;
  496. }
  497. }
  498. /** @var StoreProductServices $productServices */
  499. $productServices = app()->make(StoreProductServices::class);
  500. /** @var MemberCardServices $memberCardService */
  501. $memberCardService = app()->make(MemberCardServices::class);
  502. $vipStatus = $memberCardService->isOpenMemberCard('vip_price', false);
  503. /** @var UserServices $user */
  504. $user = app()->make(UserServices::class);
  505. $userInfo = $user->getUserInfo($uid);
  506. $discount = 100;
  507. if (!$hasGift && sys_config('member_func_status', 1)) {
  508. /** @var SystemUserLevelServices $systemLevel */
  509. $systemLevel = app()->make(SystemUserLevelServices::class);
  510. $discount = $systemLevel->value(['id' => $userInfo['level'], 'is_del' => 0, 'is_show' => 1], 'discount') ?: 100;
  511. }else{
  512. /** @var AgentLevelServices $agentLevel */
  513. $agentLevel = app()->make(AgentLevelServices::class);
  514. $discount = $agentLevel->value(['id' => $userInfo['agent_level'], 'is_del' => 0], 'discount') ?: 100;
  515. }
  516. foreach ($cartList as &$item) {
  517. $productInfo = $item['productInfo'];
  518. if ($item['productInfo']['is_gift']==1||$item['productInfo']['is_free']==1){
  519. $discount_copy = 100;
  520. }else{
  521. $discount_copy = $discount;
  522. }
  523. if (isset($productInfo['attrInfo']['product_id']) && $item['product_attr_unique']) {
  524. [$truePrice, $vip_truePrice, $type] = $productServices->setLevelPrice($productInfo['attrInfo']['price'] ?? 0, $uid, $userInfo, $vipStatus, $discount_copy, $productInfo['attrInfo']['vip_price'] ?? 0, $productInfo['is_vip'] ?? 0, true);
  525. $item['truePrice'] = $truePrice;
  526. $item['price_type'] = $type;
  527. } else {
  528. [$truePrice, $vip_truePrice, $type] = $productServices->setLevelPrice($item['productInfo']['price'] ?? 0, $uid, $userInfo, $vipStatus, $discount_copy, $item['productInfo']['vip_price'] ?? 0, $item['productInfo']['is_vip'] ?? 0, true);
  529. $item['truePrice'] = $truePrice;
  530. $item['price_type'] = $type;
  531. }
  532. $sum_price = bcadd((string)$sum_price, (string)bcmul((string)$item['cart_num'], (string)$item['truePrice'], 4), 2);
  533. }
  534. $ids = array_column($cartList, 'id');
  535. if ($numType) {
  536. $count = count($cartList);
  537. } else {
  538. $count = array_sum(array_column($cartList, 'cart_num'));
  539. }
  540. }
  541. return compact('count', 'ids', 'sum_price');
  542. }
  543. /**
  544. * 处理购物车数据
  545. * @param int $uid
  546. * @param array $cartList
  547. * @param array $addr
  548. * @param int $shipping_type
  549. * @return array
  550. * @throws \think\db\exception\DataNotFoundException
  551. * @throws \think\db\exception\DbException
  552. * @throws \think\db\exception\ModelNotFoundException
  553. * @author 吴汐
  554. * @email 442384644@qq.com
  555. * @date 2023/02/16
  556. */
  557. public function handleCartList(int $uid, array $cartList, array $addr = [], int $shipping_type = 1)
  558. {
  559. if (!$cartList) return [$cartList, [], []];
  560. $tempIds = [];
  561. $userInfo = [];
  562. $discount = 100;
  563. if ($uid) {
  564. /** @var UserServices $user */
  565. $user = app()->make(UserServices::class);
  566. $userInfo = $user->getUserInfo($uid);
  567. //用户等级是否开启
  568. if (sys_config('member_func_status', 1)) {
  569. /** @var SystemUserLevelServices $systemLevel */
  570. $systemLevel = app()->make(SystemUserLevelServices::class);
  571. $discount = $systemLevel->value(['id' => $userInfo['level'], 'is_del' => 0, 'is_show' => 1], 'discount') ?: 100;
  572. }else{
  573. /** @var AgentLevelServices $agentLevel */
  574. $agentLevel = app()->make(AgentLevelServices::class);
  575. $discount = $agentLevel->value(['id' => $userInfo['agent_level'], 'is_del' => 0], 'discount') ?: 100;
  576. }
  577. }
  578. //付费会员是否开启,用户是否是付费会员,两个都满足,订单计算金额才会按照付费会员计算。
  579. /** @var MemberCardServices $memberCardService */
  580. $memberCardService = app()->make(MemberCardServices::class);
  581. $vipStatus = $memberCardService->isOpenMemberCard('vip_price', false) && $userInfo['is_money_level'] > 0;
  582. //不送达运费模板
  583. if ($shipping_type == 1 && $addr) {
  584. $cityId = (int)($addr['city_id'] ?? 0);
  585. if ($cityId) {
  586. foreach ($cartList as $item) {
  587. $tempIds[] = $item['productInfo']['temp_id'];
  588. }
  589. $tempIds = array_unique($tempIds);
  590. $shippingService = app()->make(\app\services\shipping\ShippingTemplatesServices::class);
  591. $tempIds = $shippingService->getColumn([['id', 'in', $tempIds], ['no_delivery', '=', 1]], 'id');
  592. if ($tempIds) {
  593. /** @var ShippingTemplatesNoDeliveryServices $noDeliveryServices */
  594. $noDeliveryServices = app()->make(ShippingTemplatesNoDeliveryServices::class);
  595. $tempIds = $noDeliveryServices->isNoDelivery(array_unique($tempIds), $cityId);
  596. }
  597. }
  598. }
  599. /** @var StoreProductServices $productServices */
  600. $productServices = app()->make(StoreProductServices::class);
  601. $valid = $invalid = [];
  602. foreach ($cartList as &$item) {
  603. @file_put_contents("quanju.txt", $item['productInfo']['id']."-购物车商品id\r\n", 8);
  604. @file_put_contents("quanju.txt", $item['productInfo']['is_gift']."-是否礼包\r\n", 8);
  605. if ($item['productInfo']['is_gift']==1||$item['productInfo']['is_free']==1){
  606. $discount_copy = 100;
  607. }else{
  608. $discount_copy = $discount;
  609. }
  610. $item['productInfo']['express_delivery'] = false;
  611. $item['productInfo']['store_mention'] = false;
  612. if (isset($item['productInfo']['logistics'])) {
  613. if (in_array(1, explode(',', $item['productInfo']['logistics']))) {
  614. $item['productInfo']['express_delivery'] = true;
  615. }
  616. if (in_array(2, explode(',', $item['productInfo']['logistics']))) {
  617. $item['productInfo']['store_mention'] = true;
  618. }
  619. }
  620. if (isset($item['attrInfo']) && $item['attrInfo'] && (!isset($item['productInfo']['attrInfo']) || !$item['productInfo']['attrInfo'])) {
  621. $item['productInfo']['attrInfo'] = $item['attrInfo'] ?? [];
  622. }
  623. $item['attrStatus'] = isset($item['productInfo']['attrInfo']['stock']) && $item['productInfo']['attrInfo']['stock'];
  624. $item['productInfo']['attrInfo']['image'] = $item['productInfo']['attrInfo']['image'] ?? $item['productInfo']['image'] ?? '';
  625. $item['productInfo']['attrInfo']['suk'] = $item['productInfo']['attrInfo']['suk'] ?? '已失效';
  626. if (isset($item['productInfo']['attrInfo'])) {
  627. $item['productInfo']['attrInfo'] = get_thumb_water($item['productInfo']['attrInfo']);
  628. }
  629. $item['productInfo'] = get_thumb_water($item['productInfo']);
  630. $productInfo = $item['productInfo'];
  631. $item['vip_truePrice'] = 0;
  632. $is_activity = $item['seckill_id'] || $item['bargain_id'] || $item['combination_id'] || $item['advance_id'];
  633. if (isset($productInfo['attrInfo']['product_id']) && $item['product_attr_unique']) {
  634. $item['costPrice'] = $productInfo['attrInfo']['cost'] ?? 0;
  635. $item['trueStock'] = $productInfo['attrInfo']['stock'] ?? 0;
  636. $item['truePrice'] = $productInfo['attrInfo']['price'] ?? 0;
  637. $item['sum_price'] = $productInfo['attrInfo']['price'] ?? 0;
  638. if (!$is_activity) {
  639. [$truePrice, $vip_truePrice, $type] = $productServices->setLevelPrice($productInfo['attrInfo']['price'] ?? 0, $uid, $userInfo, $vipStatus, $discount_copy, $productInfo['attrInfo']['vip_price'] ?? 0, $productInfo['is_vip'] ?? 0, true);
  640. $item['truePrice'] = $truePrice;
  641. $item['vip_truePrice'] = $vip_truePrice;
  642. $item['price_type'] = $type;
  643. } else {
  644. $item['price_type'] = 'activity';
  645. }
  646. } else {
  647. $item['costPrice'] = $item['productInfo']['cost'] ?? 0;
  648. $item['trueStock'] = $item['productInfo']['stock'] ?? 0;
  649. $item['truePrice'] = $item['productInfo']['price'] ?? 0;
  650. $item['sum_price'] = $item['productInfo']['price'] ?? 0;
  651. if (!$is_activity) {
  652. [$truePrice, $vip_truePrice, $type] = $productServices->setLevelPrice($item['productInfo']['price'] ?? 0, $uid, $userInfo, $vipStatus, $discount_copy, $item['productInfo']['vip_price'] ?? 0, $item['productInfo']['is_vip'] ?? 0, true);
  653. $item['truePrice'] = $truePrice;
  654. $item['vip_truePrice'] = $vip_truePrice;
  655. $item['price_type'] = $type;
  656. } else {
  657. $item['price_type'] = 'activity';
  658. }
  659. }
  660. if (isset($item['status']) && $item['status'] == 0) {
  661. $item['is_valid'] = 0;
  662. $invalid[] = $item;
  663. } else {
  664. switch ($shipping_type) {
  665. case 1:
  666. //不送达
  667. if (in_array($item['productInfo']['temp_id'], $tempIds) || (isset($item['productInfo']['logistics']) && !in_array(1, explode(',', $item['productInfo']['logistics'])) && $item['productInfo']['logistics'] != 0)) {
  668. $item['is_valid'] = 0;
  669. $invalid[] = $item;
  670. } else {
  671. $item['is_valid'] = 1;
  672. $valid[] = $item;
  673. }
  674. break;
  675. case 2:
  676. //不支持到店自提
  677. if (isset($item['productInfo']['logistics']) && $item['productInfo']['logistics'] && !in_array(2, explode(',', $item['productInfo']['logistics'])) && $item['productInfo']['logistics'] != 0) {
  678. $item['is_valid'] = 0;
  679. $invalid[] = $item;
  680. } else {
  681. $item['is_valid'] = 1;
  682. $valid[] = $item;
  683. }
  684. break;
  685. }
  686. }
  687. unset($item['attrInfo']);
  688. if ($item['productInfo']['is_gift']==1){
  689. $item['product_type'] = 1;
  690. }elseif ($item['productInfo']['is_repeat']==1){
  691. $item['product_type'] = 2;
  692. }elseif ($item['productInfo']['is_free']==1){
  693. $item['product_type'] = 3;
  694. }else{
  695. $item['product_type'] = 0;
  696. }
  697. }
  698. return [$cartList, $valid, $invalid];
  699. }
  700. /**
  701. * 检查限购
  702. * @param $uid
  703. * @param $product_id
  704. * @param $num
  705. * @param $new
  706. * @return bool
  707. * @throws \ReflectionException
  708. */
  709. public function checkLimit($uid, $product_id, $num, $new)
  710. {
  711. /** @var StoreProductServices $productServices */
  712. $productServices = app()->make(StoreProductServices::class);
  713. /** @var StoreOrderCartInfoServices $orderCartServices */
  714. $orderCartServices = app()->make(StoreOrderCartInfoServices::class);
  715. $limitInfo = $productServices->get($product_id, ['is_limit', 'limit_type', 'limit_num']);
  716. if (!$limitInfo) throw new ApiException(410294);
  717. $limitInfo = $limitInfo->toArray();
  718. if (!$limitInfo['is_limit']) return true;
  719. if ($limitInfo['limit_type'] == 1) {
  720. $cartNum = 0;
  721. if (!$new) {
  722. $cartNum = $this->dao->sum(['uid' => $uid, 'product_id' => $product_id], 'cart_num');
  723. }
  724. if (($num + $cartNum) > $limitInfo['limit_num']) {
  725. throw new ApiException(410239, ['limit' => $limitInfo['limit_num']]);
  726. }
  727. } else if ($limitInfo['limit_type'] == 2) {
  728. $cartNum = $this->dao->sum(['uid' => $uid, 'product_id' => $product_id], 'cart_num');
  729. $orderPayNum = $orderCartServices->sum(['uid' => $uid, 'product_id' => $product_id, 'split_status' => 0], 'cart_num');
  730. $orderRefundNum = $orderCartServices->sum(['uid' => $uid, 'product_id' => $product_id, 'split_status' => 0], 'refund_num');
  731. $orderNum = $orderPayNum - $orderRefundNum;
  732. if (($num + $orderNum + $cartNum) > $limitInfo['limit_num']) {
  733. throw new ApiException(410240, ['limit' => $limitInfo['limit_num'], 'pay_num' => $orderNum]);
  734. }
  735. }
  736. return true;
  737. }
  738. }