StoreCartServices.php 35 KB

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