GoodsService.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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\GoodsCategoryModel;
  13. use App\Models\GoodsCollectModel;
  14. use App\Models\GoodsModel;
  15. use App\Models\GoodsSkuModel;
  16. use App\Services\BaseService;
  17. use App\Services\RedisService;
  18. /**
  19. * 商品管理-服务类
  20. * @author laravel开发员
  21. * @since 2020/11/11
  22. * @package App\Services\Api
  23. */
  24. class GoodsService extends BaseService
  25. {
  26. // 静态对象
  27. protected static $instance = null;
  28. /**
  29. * 构造函数
  30. * @author laravel开发员
  31. * @since 2020/11/11
  32. */
  33. public function __construct()
  34. {
  35. $this->model = new GoodsModel();
  36. }
  37. /**
  38. * 静态入口
  39. */
  40. public static function make()
  41. {
  42. if (!self::$instance) {
  43. self::$instance = new static();
  44. }
  45. return self::$instance;
  46. }
  47. /**
  48. * 列表数据
  49. * @param $params
  50. * @param int $pageSize
  51. * @return array
  52. */
  53. public function getDataList($params, $pageSize = 15)
  54. {
  55. $cacheKey = "caches:goods:list_{$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.*"];
  62. $list = $query->select($field)
  63. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  64. $list = $list ? $list->toArray() : [];
  65. if ($list) {
  66. $datas = [
  67. 'pageSize' => $pageSize,
  68. 'total' => isset($list['total']) ? $list['total'] : 0,
  69. 'list' => isset($list['data']) ? $list['data'] : []
  70. ];
  71. RedisService::set($cacheKey, $datas, rand(3, 5));
  72. }
  73. }
  74. return $datas;
  75. }
  76. /**
  77. * 查询条件
  78. * @param $params
  79. * @return mixed
  80. */
  81. public function getQuery($params)
  82. {
  83. $where = ['a.is_recommend'=>1,'a.status' => 1, 'a.mark' => 1];
  84. $status = isset($params['status']) ? $params['status'] : 1;
  85. $isRecommend = isset($params['is_recommend']) ? $params['is_recommend'] : 0;
  86. if ($status > 0) {
  87. $where['a.status'] = $status;
  88. } else {
  89. unset($where['a.status']);
  90. }
  91. if ($isRecommend == 1) {
  92. $where['a.is_recommend'] = $isRecommend;
  93. } else {
  94. unset($where['a.is_recommend']);
  95. }
  96. $model = $this->model->with(['store','category'])
  97. ->from('goods as a')
  98. ->where($where)
  99. ->where(function ($query) use ($params) {
  100. // 分类
  101. $categoryId = isset($params['category_id'])? intval($params['category_id']) : 0;
  102. if($categoryId>0){
  103. $query->where('a.category_id', $categoryId);
  104. }
  105. // 企业
  106. $storeId = isset($params['store_id'])? intval($params['store_id']) : 0;
  107. if($storeId>0){
  108. $query->where('a.store_id', $storeId);
  109. }
  110. $keyword = isset($params['keyword']) ? trim($params['keyword']) : '';
  111. if ($keyword) {
  112. $query->where(function ($query) use ($keyword) {
  113. $query->where('a.goods_name', 'like', "%{$keyword}%")
  114. ->orWhere('a.tags','like',"%{$keyword}%");
  115. });
  116. }
  117. });
  118. return $model;
  119. }
  120. /**
  121. * 分类
  122. * @return array|mixed
  123. */
  124. public function getCategoryList()
  125. {
  126. $cacheKey = "caches:goods:categoryList";
  127. $datas = RedisService::get($cacheKey);
  128. if($datas){
  129. return $datas;
  130. }
  131. $datas = GoodsCategoryModel::where(['pid'=>0,'status'=>1,'mark'=>1])
  132. ->select(['id','name','icon','pid','sort'])
  133. ->orderBy('sort','desc')
  134. ->orderBy('id','asc')
  135. ->get();
  136. $datas = $datas? $datas->toArray() : [];
  137. if($datas){
  138. RedisService::set($cacheKey, $datas, rand(300,600));
  139. }
  140. return $datas;
  141. }
  142. /**
  143. * 详情信息
  144. * @param $id
  145. * @return mixed
  146. */
  147. public function getInfo($id,$userId=0)
  148. {
  149. $cacheKey = "caches:goods:info_{$id}_{$userId}";
  150. $info = RedisService::get($cacheKey);
  151. if ($info) {
  152. return $info;
  153. }
  154. $info = $this->model->with(['store','category','skus'])->where(['id' => $id])->first();
  155. $info = $info ? $info->toArray() : [];
  156. if ($info) {
  157. RedisService::set($cacheKey, $info, rand(10, 20));
  158. }
  159. return $info;
  160. }
  161. /**
  162. * 收藏
  163. * @param $userId
  164. * @param $goodsId
  165. * @return array|false
  166. */
  167. public function collect($userId, $goodsId)
  168. {
  169. $info = $this->model->where(['id' => $goodsId,'status'=>1,'mark'=>1])->first();
  170. $info = $info ? $info->toArray() : [];
  171. if(empty($info)){
  172. $this->error = '商品已下架';
  173. return false;
  174. }
  175. if($id = GoodsCollectModel::where(['user_id'=>$userId,'goods_id'=>$goodsId,'mark'=>1])->value('id')){
  176. GoodsCollectModel::where(['id'=>$id])->update(['mark'=>0,'update_time'=>time()]);
  177. $this->error = '取消收藏';
  178. RedisService::clear("caches:goods:info_{$id}_{$userId}");
  179. return ['id'=>$id,'is_collect'=>0];
  180. }else{
  181. if(!$id = GoodsCollectModel::insertGetId(['user_id'=>$userId,'goods_id'=>$goodsId,'status'=>1,'mark'=>1,'create_time'=>time(),'update_time'=>time()])){
  182. $this->error = '收藏失败';
  183. return false;
  184. }
  185. $this->error = '收藏成功';
  186. RedisService::clear("caches:goods:info_{$id}_{$userId}");
  187. return ['id'=>$id,'is_collect'=>1];
  188. }
  189. }
  190. /**
  191. * @param $ids
  192. * @param $goods
  193. * @param $orderNo
  194. * @return array|false
  195. */
  196. public function getOrderGoods($ids, $goods, $orderNo, $userId=0)
  197. {
  198. $list = $this->model->whereIn('id', $ids)
  199. ->where(['status'=>1,'mark'=>1])
  200. ->select(['id as goods_id','goods_name','category_id','store_id','delivery_fee','sku_type','price','stock','unit','weight','thumb','sku_type'])
  201. ->get();
  202. $list = $list? $list->toArray() : [];
  203. if($list){
  204. $skus = GoodsSkuModel::whereIn('goods_id', $ids)->select(['id','sku_name','price','stock'])->get()->keyBy('id');
  205. $skus = $skus?$skus->toArray() :[];
  206. $result = ['store_id'=>0,'delivery_fee'=>0,'total'=>0,'count'=>0,'goods'=>[]];
  207. foreach ($list as $item){
  208. $item['order_no'] = $orderNo;
  209. $id = isset($item['goods_id'])?$item['goods_id']:0;
  210. $goodsName = isset($item['goods_name'])?$item['goods_name']:'';
  211. $params = isset($goods['id_'.$id])? $goods['id_'.$id]:[];
  212. $goodsId = isset($params['id'])?$params['id']:0;
  213. $storeId = isset($item['store_id'])?$item['store_id']:0;
  214. $deliveryFee = isset($item['delivery_fee'])?$item['delivery_fee']:0;
  215. $stock = isset($item['stock'])?$item['stock']:0;
  216. $num = isset($params['num'])?$params['num']:0;
  217. $skuId = isset($params['sku_id'])?$params['sku_id']:0;
  218. $skuType = isset($item['sku_type'])?$item['sku_type']: 1;
  219. $skuData = isset($skus[$skuId])? $skus[$skuId]:[];
  220. $skuPrice = isset($skuData['price'])?$skuData['price']:0;
  221. $skuStock = isset($skuData['stock'])?$skuData['stock']:0;
  222. $skuName = isset($skuData['sku_name'])?$skuData['sku_name']:'';
  223. $price = $skuType==2 ? $skuPrice : $item['price'];
  224. unset($item['skus']);
  225. if($result['store_id'] && $storeId != $result['store_id']){
  226. $this->error = '一次只能购买同一个商家的商品,请核对后重试~';
  227. return false;
  228. }
  229. if($stock<=0 || $num>$stock){
  230. $this->error = $skuId? "商品[{$goodsName}]规格[{$skuName}]库存不足~" : "商品[{$goodsName}]库存不足~";
  231. return false;
  232. }
  233. if($skuType==2 && ($skuStock<=0 || $num>$skuStock)){
  234. $this->error = "商品[{$goodsName}]规格[{$skuName}]库存不足~";
  235. return false;
  236. }
  237. if($num>0 && $goodsId == $id && $price>0){
  238. $result['store_id'] = $storeId;
  239. $result['delivery_fee'] = max($deliveryFee,$result['delivery_fee']);
  240. $item['user_id'] = $userId;
  241. $item['sku_id'] = $skuId;
  242. $item['price'] = $price;
  243. $item['total'] = $price;
  244. $item['num'] = $num;
  245. $total = round($price * $num,2);
  246. $item['total'] = $total;
  247. $item['thumb'] = get_image_path($item['thumb']);
  248. $result['goods'][] = $item;
  249. $result['total'] += $total;
  250. $result['count']++;
  251. }
  252. }
  253. return $result;
  254. }
  255. return false;
  256. }
  257. }