StoreCartServices.php 35 KB

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