GoodsService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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\Models\MemberModel;
  17. use App\Services\BaseService;
  18. use App\Services\ConfigService;
  19. use App\Services\RedisService;
  20. /**
  21. * 商品管理-服务类
  22. * @author laravel开发员
  23. * @since 2020/11/11
  24. * @package App\Services\Api
  25. */
  26. class GoodsService extends BaseService
  27. {
  28. // 静态对象
  29. protected static $instance = null;
  30. /**
  31. * 构造函数
  32. * @author laravel开发员
  33. * @since 2020/11/11
  34. */
  35. public function __construct()
  36. {
  37. $this->model = new GoodsModel();
  38. }
  39. /**
  40. * 静态入口
  41. */
  42. public static function make()
  43. {
  44. if (!self::$instance) {
  45. self::$instance = new static();
  46. }
  47. return self::$instance;
  48. }
  49. /**
  50. * 列表数据
  51. * @param $params
  52. * @param int $pageSize
  53. * @return array
  54. */
  55. public function getDataList($params, $pageSize = 15)
  56. {
  57. $cacheKey = "caches:goods:list_{$pageSize}_" . ($params ? md5(json_encode($params)) : 0);
  58. $datas = RedisService::get($cacheKey);
  59. if (empty($datas)) {
  60. $query = $this->getQuery($params)
  61. ->orderBy('a.create_time', 'desc')
  62. ->orderBy('a.id', 'desc');
  63. $field = ["a.*"];
  64. $list = $query->select($field)
  65. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  66. $list = $list ? $list->toArray() : [];
  67. if ($list) {
  68. $datas = [
  69. 'pageSize' => $pageSize,
  70. 'total' => isset($list['total']) ? $list['total'] : 0,
  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(['category','sku'])
  93. ->from('goods as a')
  94. ->where(function ($query) use ($params) {
  95. // 分类
  96. $categoryId = isset($params['category_id'])? intval($params['category_id']) : 0;
  97. if($categoryId>0){
  98. $query->where('a.category_id', $categoryId);
  99. }
  100. // 店铺
  101. $storeId = isset($params['store_id'])? intval($params['store_id']) : 0;
  102. if($storeId>0){
  103. $query->where('a.store_id', $storeId);
  104. }
  105. $keyword = isset($params['keyword']) ? trim($params['keyword']) : '';
  106. if ($keyword) {
  107. $query->where(function ($query) use ($keyword) {
  108. $query->where('a.goods_name', 'like', "%{$keyword}%")
  109. ->orWhere('a.tags','like',"%{$keyword}%");
  110. });
  111. }
  112. $type = isset($params['type']) ? $params['type'] : 0;
  113. if($type){
  114. $query->where('a.type', $type);
  115. }
  116. $isRecommend = isset($params['is_recommend']) ? $params['is_recommend'] : 0;
  117. if($isRecommend){
  118. $query->where('a.is_recommend', $isRecommend);
  119. }
  120. $isNew = isset($params['is_new']) ? $params['is_new'] : 0;
  121. if($isNew){
  122. $query->where('a.is_new', $isNew);
  123. }
  124. })->where($where);
  125. return $model;
  126. }
  127. /**
  128. * 分类
  129. * @return array|mixed
  130. */
  131. public function getCategoryList()
  132. {
  133. $cacheKey = "caches:goods:categoryList";
  134. $datas = RedisService::get($cacheKey);
  135. if($datas){
  136. return $datas;
  137. }
  138. $datas = GoodsCategoryModel::where(['pid'=>0,'status'=>1,'mark'=>1])
  139. ->select(['id','name','icon','pid','sort'])
  140. ->orderBy('sort','desc')
  141. ->orderBy('id','asc')
  142. ->get();
  143. $datas = $datas? $datas->toArray() : [];
  144. if($datas){
  145. RedisService::set($cacheKey, $datas, rand(300,600));
  146. }
  147. return $datas;
  148. }
  149. /**
  150. * 详情信息
  151. * @param $id
  152. * @return mixed
  153. */
  154. public function getInfo($id,$userId=0)
  155. {
  156. $cacheKey = "caches:goods:info_{$id}_{$userId}";
  157. $info = RedisService::get($cacheKey);
  158. if ($info) {
  159. return $info;
  160. }
  161. $info = $this->model->with(['store','category','skus'])->where(['id' => $id])->first();
  162. $info = $info ? $info->toArray() : [];
  163. if ($info) {
  164. RedisService::set($cacheKey, $info, rand(10, 20));
  165. }
  166. return $info;
  167. }
  168. /**
  169. * 收藏
  170. * @param $userId
  171. * @param $goodsId
  172. * @return array|false
  173. */
  174. public function collect($userId, $goodsId)
  175. {
  176. $info = $this->model->where(['id' => $goodsId,'status'=>1,'mark'=>1])->first();
  177. $info = $info ? $info->toArray() : [];
  178. if(empty($info)){
  179. $this->error = '商品已下架';
  180. return false;
  181. }
  182. if($id = GoodsCollectModel::where(['user_id'=>$userId,'goods_id'=>$goodsId,'mark'=>1])->value('id')){
  183. GoodsCollectModel::where(['id'=>$id])->update(['mark'=>0,'update_time'=>time()]);
  184. $this->error = '取消收藏';
  185. RedisService::clear("caches:goods:info_{$id}_{$userId}");
  186. return ['id'=>$id,'is_collect'=>0];
  187. }else{
  188. if(!$id = GoodsCollectModel::insertGetId(['user_id'=>$userId,'goods_id'=>$goodsId,'status'=>1,'mark'=>1,'create_time'=>time(),'update_time'=>time()])){
  189. $this->error = '收藏失败';
  190. return false;
  191. }
  192. $this->error = '收藏成功';
  193. RedisService::clear("caches:goods:info_{$id}_{$userId}");
  194. return ['id'=>$id,'is_collect'=>1];
  195. }
  196. }
  197. /**
  198. * @param $ids
  199. * @param $goods
  200. * @param $userId
  201. * @param $orderNo 订单号
  202. * @return array|false
  203. */
  204. public function getOrderGoods($ids, $goods, $userId, $orderNo='', $discountPoint=0)
  205. {
  206. if(empty($ids) || empty($goods)){
  207. $this->error = '请选择商品';
  208. return false;
  209. }
  210. // 用户信息
  211. if(empty($orderNo)){
  212. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  213. ->select(['id','openid', 'status'])
  214. ->first();
  215. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  216. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : 0;
  217. $discountPoint = isset($userInfo['discount_point']) ? $userInfo['discount_point'] : 0; // 折扣
  218. if (empty($userInfo) || $status != 1) {
  219. $this->error = 1045;
  220. return false;
  221. }
  222. if (empty($openid)) {
  223. $this->error = 1042;
  224. return false;
  225. }
  226. }
  227. $list = $this->model->whereIn('id', $ids)
  228. ->where(['status'=>1,'mark'=>1])
  229. ->select(['id as goods_id','goods_name','type','category_id','store_id','delivery_fee','sku_type','price','stock','unit','weight','thumb'])
  230. ->get();
  231. $list = $list? $list->toArray() : [];
  232. if($list){
  233. $skus = GoodsSkuModel::whereIn('goods_id', $ids)->select(['id','sku_name','price','stock'])->get()->keyBy('id');
  234. $skus = $skus?$skus->toArray() :[];
  235. $result = ['discount_point'=>$discountPoint,'store_id'=>0,'discount_total'=>0.00,'delivery_fee'=>0.00,'goods_total'=>0,'order_total'=>0,'count'=>0,'goods'=>[]];
  236. foreach ($list as $item){
  237. $item['order_no'] = $orderNo;
  238. $id = isset($item['goods_id'])?$item['goods_id']:0;
  239. $goodsName = isset($item['goods_name'])?$item['goods_name']:'';
  240. $params = isset($goods['id_'.$id])? $goods['id_'.$id]:[];
  241. $goodsId = isset($params['id'])?$params['id']:0;
  242. $storeId = isset($item['store_id'])?$item['store_id']:0;
  243. $deliveryFee = isset($item['delivery_fee'])?$item['delivery_fee']:0;
  244. $stock = isset($item['stock'])?$item['stock']:0;
  245. $num = isset($params['num'])?$params['num']:0;
  246. $skuId = isset($params['sku_id'])?$params['sku_id']:0;
  247. $skuType = isset($item['sku_type'])?$item['sku_type']: 1;
  248. $skuData = isset($skus[$skuId])? $skus[$skuId]:[];
  249. $skuPrice = isset($skuData['price'])?$skuData['price']:0;
  250. $skuStock = isset($skuData['stock'])?$skuData['stock']:0;
  251. $skuName = isset($skuData['sku_name'])?$skuData['sku_name']:'';
  252. $price = $skuType==2 ? $skuPrice : $item['price'];
  253. unset($item['skus']);
  254. if($result['store_id'] && $storeId != $result['store_id']){
  255. $this->error = '一次只能购买同一个商家的商品,请核对后重试~';
  256. return false;
  257. }
  258. if($stock<=0 || $num>$stock){
  259. $this->error = $skuId? "商品[{$goodsName}]规格[{$skuName}]库存不足~" : "商品[{$goodsName}]库存不足~";
  260. return false;
  261. }
  262. if($skuType==2 && ($skuStock<=0 || $num>$skuStock)){
  263. $this->error = "商品[{$goodsName}]规格[{$skuName}]库存不足~";
  264. return false;
  265. }
  266. if($num>0 && $goodsId == $id && $price>0){
  267. $result['store_id'] = $storeId;
  268. $result['delivery_fee'] = max($deliveryFee,$result['delivery_fee']);
  269. $item['user_id'] = $userId;
  270. $item['sku_id'] = $skuId;
  271. if(empty($orderNo)){
  272. $item['sku'] = $skuData;
  273. }
  274. $item['price'] = $price;
  275. $item['total'] = $price;
  276. $item['num'] = $num;
  277. $total = round($price * $num,2);
  278. $item['total'] = $total;
  279. $item['thumb'] = $orderNo?get_image_path($item['thumb']):$item['thumb'];
  280. $result['goods'][] = $item;
  281. $result['goods_total'] += $total;
  282. $result['order_total'] += $total;
  283. $result['count']++;
  284. }
  285. }
  286. // 会员折扣
  287. $orderTotal = $result['order_total'];
  288. if($discountPoint>0 && $discountPoint<1){
  289. $result['order_total'] = moneyFormat((1-$discountPoint) * $result['order_total'],2);
  290. $result['discount_total'] = moneyFormat($orderTotal - $result['order_total'],2);
  291. }
  292. $result['pay_total'] = moneyFormat($result['order_total'] + $result['delivery_fee'],2);
  293. return $result;
  294. }
  295. return false;
  296. }
  297. /**
  298. * 专区商品
  299. * @param $type 专区类型:2-午夜限定,3-蜜友优选
  300. * @return array|mixed
  301. */
  302. public function getListByZoneType($type, $limit=0)
  303. {
  304. $limit = $limit?$limit : ConfigService::make()->getConfigByCode("zone_type{$type}_num", 6);
  305. $cacheKey = "caches:goods:zoneList_{$type}_{$limit}";
  306. $data = RedisService::get($cacheKey);
  307. if($data){
  308. return $data;
  309. }
  310. $data = $this->model->with(['sku'])->where(['zone_type'=>$type,'status'=>1,'mark'=>1])
  311. ->select(['id','thumb','price','market_price','sku_type','goods_name','sales','stock','category_id','type','zone_type','is_new','status'])
  312. ->orderBy('sort','desc')
  313. ->orderBy('id','asc')
  314. ->get();
  315. $data = $data? $data->toArray() :[];
  316. if($data){
  317. RedisService::set($cacheKey, $data, rand(10, 20));
  318. }
  319. return $data;
  320. }
  321. }