CartService.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | LARAVEL8.0 框架 [ LARAVEL ][ RXThinkCMF ]
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2017~2021 LARAVEL研发中心
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://www.laravel.cn
  8. // +----------------------------------------------------------------------
  9. // | Author: laravel开发员 <laravel.qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace App\Services\Api;
  12. use App\Models\CartModel;
  13. use App\Models\GoodsModel;
  14. use App\Services\BaseService;
  15. use App\Services\RedisService;
  16. use Illuminate\Support\Facades\DB;
  17. /**
  18. * 购物车管理-服务类
  19. * @author laravel开发员
  20. * @since 2020/11/11
  21. * @package App\Services\Api
  22. */
  23. class CartService extends BaseService
  24. {
  25. // 静态对象
  26. protected static $instance = null;
  27. /**
  28. * 构造函数
  29. * @author laravel开发员
  30. * @since 2020/11/11
  31. */
  32. public function __construct()
  33. {
  34. $this->model = new CartModel();
  35. }
  36. /**
  37. * 静态入口
  38. */
  39. public static function make()
  40. {
  41. if (!self::$instance) {
  42. self::$instance = new static();
  43. }
  44. return self::$instance;
  45. }
  46. /**
  47. * 列表数据
  48. * @param $params
  49. * @param int $pageSize
  50. * @return array
  51. */
  52. public function getDataList($params, $pageSize = 15)
  53. {
  54. $userId = isset($params['user_id']) ? intval($params['user_id']) : 0;
  55. $cacheKey = "caches:goods:cartList_{$userId}_{$pageSize}_" . ($params ? md5(json_encode($params)) : 0);
  56. $datas = RedisService::get($cacheKey);
  57. if (empty($datas)) {
  58. $query = $this->getQuery($params)
  59. ->orderBy('a.create_time', 'desc')
  60. ->orderBy('a.id', 'desc');
  61. $field = ["a.id",'a.goods_id','a.user_id','a.store_id','a.num','a.sk_key','a.sku_id'];
  62. $list = $query->select($field)
  63. ->groupBy('a.store_id')
  64. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  65. $list = $list ? $list->toArray() : [];
  66. if ($list) {
  67. $datas = [
  68. 'pageSize' => $pageSize,
  69. 'total' => isset($list['total']) ? $list['total'] : 0,
  70. 'count' => $this->getCount($userId),
  71. 'list' => isset($list['data']) ? $list['data'] : []
  72. ];
  73. RedisService::set($cacheKey, $datas, rand(3, 5));
  74. }
  75. }
  76. return $datas;
  77. }
  78. /**
  79. * 查询条件
  80. * @param $params
  81. * @return mixed
  82. */
  83. public function getQuery($params)
  84. {
  85. $where = ['a.status' => 1, 'a.mark' => 1];
  86. $status = isset($params['status']) ? $params['status'] : 1;
  87. if ($status > 0) {
  88. $where['a.status'] = $status;
  89. } else {
  90. unset($where['a.status']);
  91. }
  92. $model = $this->model->with(['store','cartGoods'])
  93. ->from('carts as a')
  94. ->leftJoin('goods as b', 'b.id', '=', 'a.goods_id')
  95. ->where($where)
  96. ->where(function ($query) use ($params) {
  97. // 商品
  98. $goodsId = isset($params['goods_id']) ? intval($params['goods_id']) : 0;
  99. if ($goodsId > 0) {
  100. $query->where('a.goods_id', $goodsId);
  101. }
  102. $userId = isset($params['user_id']) ? intval($params['user_id']) : 0;
  103. if ($userId > 0) {
  104. $query->where('a.user_id', $userId);
  105. }
  106. // 店铺
  107. $storeId = isset($params['store_id']) ? intval($params['store_id']) : 0;
  108. if ($storeId > 0) {
  109. $query->where('a.store_id', $storeId);
  110. }
  111. $keyword = isset($params['keyword']) ? trim($params['keyword']) : '';
  112. if ($keyword) {
  113. $query->where(function ($query) use ($keyword) {
  114. $query->where('b.goods_name', 'like', "%{$keyword}%")
  115. ->orWhere('b.tags', 'like', "%{$keyword}%");
  116. });
  117. }
  118. });
  119. return $model;
  120. }
  121. /**
  122. * 添加购物车
  123. * @param $userId
  124. * @param $goodsId
  125. * @param int $skuId
  126. * @return array|false
  127. */
  128. public function add($userId, $goodsId, $skuId=0, $num=1)
  129. {
  130. $cacheKey = "caches:goods:addCart:{$userId}_{$goodsId}_{$skuId}";
  131. if(RedisService::get($cacheKey.'_lock')){
  132. $this->error = '处理中~';
  133. return false;
  134. }
  135. RedisService::set($cacheKey.'_lock', ['goods_id'=>$goodsId,'sku_id'=>$skuId], rand(3,5));
  136. $goodsInfo = GoodsModel::with(['skus'])
  137. ->where(['id' => $goodsId, 'status' => 1, 'mark' => 1])
  138. ->select(['id', 'sku_type', 'store_id'])
  139. ->first();
  140. $storeId = isset($goodsInfo['store_id']) ? $goodsInfo['store_id'] : 0;
  141. $skuType = isset($goodsInfo['sku_type']) ? $goodsInfo['sku_type'] : 0;
  142. $skus = isset($goodsInfo['skus']) ? $goodsInfo['skus'] : [];
  143. $skuId = $skuId? $skuId : (isset($skus[0]) ? $skus[0]['id'] : 0);
  144. if (empty($goodsInfo)) {
  145. RedisService::clear($cacheKey.'_lock');
  146. $this->error = '商品已下架';
  147. return false;
  148. }
  149. // 去除其他店铺购物车
  150. $this->model->where(['user_id' => $userId, 'mark' => 1])->whereNotIn('store_id', [$storeId])->update(['mark' => 0, 'update_time' => time()]);
  151. // 添加购物型
  152. if ($id = $this->model->where(['user_id' => $userId,'sku_id'=>$skuId, 'goods_id' => $goodsId])->value('id')) {
  153. $this->model->where(['id' => $id])->update(['store_id' => $storeId,'num'=> DB::raw("num+{$num}"),'sk_key'=>"{$userId}-{$storeId}", 'sku_id' => $skuType == 1 ? 0 : $skuId, 'status' => 1, 'mark' => 1, 'create_time' => time()]);
  154. } else {
  155. $data = [
  156. 'user_id' => $userId,
  157. 'goods_id' => $goodsId,
  158. 'store_id' => $storeId,
  159. 'num'=> $num,
  160. 'sk_key'=>"{$userId}-{$storeId}",
  161. 'sku_id' => $skuType == 1 ? 0 : $skuId,
  162. 'create_time' => time(),
  163. 'status' => 1,
  164. 'mark' => 1,
  165. ];
  166. $id = $this->model->insertGetId($data);
  167. }
  168. $this->error = '添加成功';
  169. RedisService::clear($cacheKey.'_lock');
  170. RedisService::clear("caches:goods:cartCount:{$userId}");
  171. RedisService::keyDel("caches:goods:cartList_{$userId}*");
  172. return ['id' => $id,'sku_id'=>$skuId, 'count' => $this->getCount($userId)];
  173. }
  174. /**
  175. * 更新购物车
  176. * @param $userId
  177. * @param $cartId
  178. * @return array|false
  179. */
  180. public function update($userId, $cartId, $num=1)
  181. {
  182. $cacheKey = "caches:goods:updateCart:{$userId}_{$cartId}";
  183. if(RedisService::get($cacheKey.'_lock')){
  184. $this->error = '处理中~';
  185. return false;
  186. }
  187. RedisService::set($cacheKey.'_lock', ['cart_id'=>$cartId], rand(3,5));
  188. // 去除其他店铺购物车
  189. $info = $this->model->where(['id'=>$cartId, 'user_id' => $userId, 'mark' => 1])->first();
  190. if(empty($info)){
  191. RedisService::clear($cacheKey.'_lock');
  192. $this->error = '数据不存在';
  193. return false;
  194. }
  195. if($num<=0){
  196. $this->model->where(['id' => $cartId])->update(['mark'=>0,'num'=>0,'update_time'=>time()]);
  197. }else{
  198. $this->model->where(['id' => $cartId])->update(['num' => $num,'update_time' => time()]);
  199. }
  200. RedisService::clear($cacheKey.'_lock');
  201. RedisService::clear("caches:goods:cartCount:{$userId}");
  202. return ['id' => $cartId, 'count' => $this->getCount($userId)];
  203. }
  204. /**
  205. * 删除购物车
  206. * @param $userId
  207. * @param $cartId
  208. * @return array|false
  209. */
  210. public function deleteCart($userId, $ids=[])
  211. {
  212. if($ids){
  213. $this->model->where(['user_id'=>$userId,'mark'=>1])->whereIn('id', $ids)->update(['mark'=>0,'num'=>0,'update_time'=>time()]);
  214. }else{
  215. $this->model->where(['user_id'=>$userId,'mark'=>1])->update(['mark' => 0,'num'=>0,'update_time' => time()]);
  216. }
  217. $this->error = '删除成功';
  218. RedisService::clear("caches:goods:cartCount:{$userId}");
  219. return ['ids' => $ids, 'count' => $this->getCount($userId)];
  220. }
  221. /**
  222. * 购物车数量
  223. * @param $userId
  224. * @return array|mixed
  225. */
  226. public function getCount($userId)
  227. {
  228. $cacheKey ="caches:goods:cartCount:{$userId}";
  229. $data = RedisService::get($cacheKey);
  230. if($data){
  231. return $data;
  232. }
  233. $count = $this->model->where(['user_id' => $userId, 'status' => 1, 'mark' => 1])->count('id');
  234. if($count){
  235. RedisService::set($cacheKey, $count, 300);
  236. }
  237. return $count;
  238. }
  239. }