GoodsService.php 12 KB

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