GoodsService.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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\MemberCouponModel;
  17. use App\Models\MemberModel;
  18. use App\Services\BaseService;
  19. use App\Services\ConfigService;
  20. use App\Services\RedisService;
  21. /**
  22. * 商品管理-服务类
  23. * @author laravel开发员
  24. * @since 2020/11/11
  25. * @package App\Services\Api
  26. */
  27. class GoodsService extends BaseService
  28. {
  29. // 静态对象
  30. protected static $instance = null;
  31. /**
  32. * 构造函数
  33. * @author laravel开发员
  34. * @since 2020/11/11
  35. */
  36. public function __construct()
  37. {
  38. $this->model = new GoodsModel();
  39. }
  40. /**
  41. * 静态入口
  42. */
  43. public static function make()
  44. {
  45. if (!self::$instance) {
  46. self::$instance = new static();
  47. }
  48. return self::$instance;
  49. }
  50. /**
  51. * 列表数据
  52. * @param $params
  53. * @param int $pageSize
  54. * @return array
  55. */
  56. public function getDataList($params, $pageSize = 15)
  57. {
  58. $cacheKey = "caches:goods:list_{$pageSize}_" . ($params ? md5(json_encode($params)) : 0);
  59. $datas = RedisService::get($cacheKey);
  60. if (empty($datas)) {
  61. $query = $this->getQuery($params)
  62. ->orderBy('a.create_time', 'desc')
  63. ->orderBy('a.id', 'desc');
  64. $field = ["a.*"];
  65. $list = $query->select($field)
  66. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  67. $list = $list ? $list->toArray() : [];
  68. if ($list) {
  69. $datas = [
  70. 'pageSize' => $pageSize,
  71. 'total' => isset($list['total']) ? $list['total'] : 0,
  72. 'list' => isset($list['data']) ? $list['data'] : []
  73. ];
  74. RedisService::set($cacheKey, $datas, rand(3, 5));
  75. }
  76. }
  77. return $datas;
  78. }
  79. /**
  80. * 查询条件
  81. * @param $params
  82. * @return mixed
  83. */
  84. public function getQuery($params)
  85. {
  86. $where = ['a.status' => 1, 'a.mark' => 1];
  87. $status = isset($params['status']) ? $params['status'] : 1;
  88. if ($status > 0) {
  89. $where['a.status'] = $status;
  90. } else {
  91. unset($where['a.status']);
  92. }
  93. $model = $this->model->with(['category','sku'])
  94. ->from('goods as a')
  95. ->where(function ($query) use ($params) {
  96. // 分类
  97. $categoryId = isset($params['category_id'])? intval($params['category_id']) : 0;
  98. if($categoryId>0){
  99. $query->where('a.category_id', $categoryId);
  100. }
  101. // 店铺
  102. $storeId = isset($params['store_id'])? intval($params['store_id']) : 0;
  103. if($storeId>0){
  104. $query->where('a.store_id', $storeId);
  105. }
  106. $keyword = isset($params['keyword']) ? trim($params['keyword']) : '';
  107. if ($keyword) {
  108. $query->where(function ($query) use ($keyword) {
  109. $query->where('a.goods_name', 'like', "%{$keyword}%")
  110. ->orWhere('a.tags','like',"%{$keyword}%");
  111. });
  112. }
  113. $type = isset($params['type']) ? $params['type'] : 0;
  114. if($type){
  115. $query->where('a.type', $type);
  116. }
  117. $isRecommend = isset($params['is_recommend']) ? $params['is_recommend'] : 0;
  118. if($isRecommend){
  119. $query->where('a.is_recommend', $isRecommend);
  120. }
  121. $isNew = isset($params['is_new']) ? $params['is_new'] : 0;
  122. if($isNew){
  123. $query->where('a.is_new', $isNew);
  124. }
  125. })->where($where);
  126. return $model;
  127. }
  128. /**
  129. * 分类
  130. * @return array|mixed
  131. */
  132. public function getCategoryList()
  133. {
  134. $cacheKey = "caches:goods:categoryList";
  135. $datas = RedisService::get($cacheKey);
  136. if($datas){
  137. return $datas;
  138. }
  139. $datas = GoodsCategoryModel::where(['pid'=>0,'status'=>1,'mark'=>1])
  140. ->select(['id','name','icon','pid','sort'])
  141. ->orderBy('sort','desc')
  142. ->orderBy('id','asc')
  143. ->get();
  144. $datas = $datas? $datas->toArray() : [];
  145. if($datas){
  146. RedisService::set($cacheKey, $datas, rand(300,600));
  147. }
  148. return $datas;
  149. }
  150. /**
  151. * 详情信息
  152. * @param $id
  153. * @return mixed
  154. */
  155. public function getInfo($id,$userId=0)
  156. {
  157. $cacheKey = "caches:goods:info_{$id}_{$userId}";
  158. $info = RedisService::get($cacheKey);
  159. if ($info) {
  160. return $info;
  161. }
  162. $info = $this->model->with(['store','category','skus'])->where(['id' => $id])->first();
  163. $info = $info ? $info->toArray() : [];
  164. if ($info) {
  165. RedisService::set($cacheKey, $info, rand(10, 20));
  166. }
  167. return $info;
  168. }
  169. /**
  170. * 收藏
  171. * @param $userId
  172. * @param $goodsId
  173. * @return array|false
  174. */
  175. public function collect($userId, $goodsId)
  176. {
  177. $info = $this->model->where(['id' => $goodsId,'status'=>1,'mark'=>1])->first();
  178. $info = $info ? $info->toArray() : [];
  179. if(empty($info)){
  180. $this->error = '商品已下架';
  181. return false;
  182. }
  183. if($id = GoodsCollectModel::where(['user_id'=>$userId,'goods_id'=>$goodsId,'mark'=>1])->value('id')){
  184. GoodsCollectModel::where(['id'=>$id])->update(['mark'=>0,'update_time'=>time()]);
  185. $this->error = '取消收藏';
  186. RedisService::clear("caches:goods:info_{$id}_{$userId}");
  187. return ['id'=>$id,'is_collect'=>0];
  188. }else{
  189. if(!$id = GoodsCollectModel::insertGetId(['user_id'=>$userId,'goods_id'=>$goodsId,'status'=>1,'mark'=>1,'create_time'=>time(),'update_time'=>time()])){
  190. $this->error = '收藏失败';
  191. return false;
  192. }
  193. $this->error = '收藏成功';
  194. RedisService::clear("caches:goods:info_{$id}_{$userId}");
  195. return ['id'=>$id,'is_collect'=>1];
  196. }
  197. }
  198. /**
  199. * @param $ids
  200. * @param $goods
  201. * @param $userId
  202. * @param $orderNo 订单号
  203. * @return array|false
  204. */
  205. public function getOrderGoods($ids, $goods, $userId, $orderNo='', $discountPoint=0, $couponId=0)
  206. {
  207. if(empty($ids) || empty($goods)){
  208. $this->error = '请选择商品';
  209. return false;
  210. }
  211. // 用户信息
  212. if(empty($orderNo)){
  213. $userInfo = MemberModel::with(['levelData'])->where(['id' => $userId, 'mark' => 1])
  214. ->select(['id','openid','vip_expired','member_level', 'status'])
  215. ->first();
  216. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  217. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : 0;
  218. $vipExpired = isset($userInfo['vip_expired']) ? $userInfo['vip_expired'] : 0;
  219. $levelData = isset($userInfo['level_data']) ? $userInfo['level_data'] : [];
  220. if (empty($userInfo) || $status != 1) {
  221. $this->error = 1045;
  222. return false;
  223. }
  224. if (empty($openid)) {
  225. $this->error = 1042;
  226. return false;
  227. }
  228. // 有效会员
  229. if($vipExpired != 0){
  230. $discountPoint = isset($levelData['discount']) ? $levelData['discount'] : 0; // 会员折扣
  231. }
  232. }
  233. $couponGoodsIds = [];
  234. $couponInfo = [];
  235. if($couponId){
  236. $couponInfo = MemberCouponModel::where(['coupon_id'=>$couponId,'user_id'=>$userId,'mark'=>1])->first();
  237. $couponType = isset($couponInfo['coupon_type'])?$couponInfo['coupon_type'] : 0;
  238. $couponGoodsIds = isset($couponInfo['goods_ids'])&& $couponInfo['goods_ids']?explode(',', $couponInfo['goods_ids']) : [];
  239. if(empty($couponInfo) || $couponType<=0){
  240. $this->error = '优惠券无效';
  241. return false;
  242. }
  243. }
  244. $list = $this->model->whereIn('id', $ids)
  245. ->where(['status'=>1,'mark'=>1])
  246. ->select(['id as goods_id','goods_name','type','category_id','store_id','delivery_fee','sku_type','price','stock','unit','weight','thumb'])
  247. ->get()
  248. ->keyBy('goods_id');
  249. $list = $list? $list->toArray() : [];
  250. if($list){
  251. $isGoodsCoupon = false;
  252. $skus = GoodsSkuModel::whereIn('goods_id', $ids)->select(['id','sku_name','price','stock'])->get()->keyBy('id');
  253. $skus = $skus?$skus->toArray() :[];
  254. $result = ['discount_point'=>$discountPoint,'store_id'=>0,'coupon_id'=>$couponId,'coupon_total'=>0,'discount_total'=>0.00,'delivery_fee'=>0.00,'goods_total'=>0,'order_total'=>0,'count'=>0,'goods'=>[]];
  255. foreach ($goods as $params){
  256. $goodsId = isset($params['id'])?$params['id']:0;
  257. $skuId = isset($params['sku_id'])?$params['sku_id']:0;
  258. $num = isset($params['num'])?$params['num']:0;
  259. $item = isset($list[$goodsId])?$list[$goodsId] : [];
  260. if(empty($item)){
  261. continue;
  262. }
  263. $item['order_no'] = $orderNo;
  264. $id = isset($item['goods_id'])?$item['goods_id']:0;
  265. $goodsName = isset($item['goods_name'])?$item['goods_name']:'';
  266. $storeId = isset($item['store_id'])?$item['store_id']:0;
  267. $deliveryFee = isset($item['delivery_fee'])?$item['delivery_fee']:0;
  268. $stock = isset($item['stock'])?$item['stock']:0;
  269. $skuType = isset($item['sku_type'])?$item['sku_type']: 1;
  270. $skuData = isset($skus[$skuId])? $skus[$skuId]:[];
  271. $skuPrice = isset($skuData['price'])?$skuData['price']:0;
  272. $skuStock = isset($skuData['stock'])?$skuData['stock']:0;
  273. $skuName = isset($skuData['sku_name'])?$skuData['sku_name']:'';
  274. $price = $skuType==2 ? $skuPrice : $item['price'];
  275. unset($item['skus']);
  276. if($result['store_id'] && $storeId != $result['store_id']){
  277. $this->error = '一次只能购买同一个商家的商品,请核对后重试~';
  278. return false;
  279. }
  280. if($stock<=0 || $num>$stock){
  281. $this->error = $skuId? "商品[{$goodsName}]规格[{$skuName}]库存不足~" : "商品[{$goodsName}]库存不足~";
  282. return false;
  283. }
  284. if($skuType==2 && ($skuStock<=0 || $num>$skuStock)){
  285. $this->error = "商品[{$goodsName}]规格[{$skuName}]库存不足~";
  286. return false;
  287. }
  288. if($num>0 && $goodsId == $id && $price>0){
  289. $result['store_id'] = $storeId;
  290. $result['delivery_fee'] = max($deliveryFee,$result['delivery_fee']);
  291. $item['user_id'] = $userId;
  292. $item['sku_id'] = $skuId;
  293. if(empty($orderNo)){
  294. $item['sku'] = $skuData;
  295. }
  296. $item['price'] = $price;
  297. $item['total'] = $price;
  298. $item['num'] = $num;
  299. $total = round($price * $num,2);
  300. // 计算优惠
  301. $couponData = $this->countCouponTotal($goodsId, $total, $couponInfo);
  302. if(!$couponData){
  303. return false;
  304. }
  305. // 是否商品使用的优惠券
  306. $couponTotal = isset($couponData['coupon_total'])?$couponData['coupon_total'] : 0;
  307. $payTotal = isset($couponData['total'])?$couponData['total'] : 0;
  308. if($payTotal){
  309. $total = $payTotal;
  310. $item['coupon_id'] = $couponId;
  311. $item['coupon_total'] = $couponTotal;
  312. $result['coupon_id'] = $couponId;
  313. $result['coupon_total'] = $couponTotal;
  314. $isGoodsCoupon = true;
  315. }
  316. $item['total'] = $total;
  317. $item['thumb'] = $orderNo?get_image_path($item['thumb']):$item['thumb'];
  318. $result['goods'][] = $item;
  319. $result['goods_total'] += $total;
  320. $result['order_total'] += $total;
  321. $result['count']++;
  322. }
  323. }
  324. // 会员折扣
  325. $orderTotal = $result['order_total'];
  326. if($discountPoint>0 && $discountPoint<1){
  327. $result['order_total'] = moneyFormat((1-$discountPoint) * $result['order_total'],2);
  328. $result['discount_total'] = moneyFormat($orderTotal - $result['order_total'],2);
  329. }
  330. // 非商品优惠券,整个订单的优惠券
  331. if($couponId && !$isGoodsCoupon){
  332. $couponData = $this->countCouponTotal(0, $orderTotal, $couponInfo);
  333. if(!$couponData){
  334. return false;
  335. }
  336. $couponTotal = isset($couponData['coupon_total'])?$couponData['coupon_total'] : 0;
  337. $result['order_total'] = isset($couponData['total'])?$couponData['total'] : 0;
  338. $result['coupon_total'] = $couponTotal;
  339. }
  340. $result['pay_total'] = moneyFormat($result['order_total'] + $result['delivery_fee'],2);
  341. return $result;
  342. }
  343. return false;
  344. }
  345. /**
  346. * 优惠券计算
  347. * @param $goodsId
  348. * @param $total
  349. * @param $couponInfo
  350. * @return array|bool|int
  351. */
  352. public function countCouponTotal($goodsId, $total, $couponInfo)
  353. {
  354. $couponStatus = isset($couponInfo['status'])?$couponInfo['status'] : 0;
  355. $couponType = isset($couponInfo['coupon_type'])?$couponInfo['coupon_type'] : 0;
  356. $couponGoodsIds = isset($couponInfo['goods_ids'])&& $couponInfo['goods_ids']?explode(',', $couponInfo['goods_ids']) : [];
  357. // 按商品或全平台(非购买券)
  358. if($goodsId && $couponType != 20 && ($couponGoodsIds && !in_array($goodsId, $couponGoodsIds))){
  359. $this->error = "优惠券非该商品使用";
  360. return false;
  361. }
  362. if($total <= 0 ){
  363. $this->error = "消费金额错误";
  364. return false;
  365. }
  366. if($couponStatus != 1){
  367. $this->error = "该优惠券已被使用";
  368. return false;
  369. }
  370. $endTime = isset($couponInfo['end_time'])?$couponInfo['end_time']:0;
  371. $startTime = isset($couponInfo['start_time'])?$couponInfo['start_time']:0;
  372. if($startTime && time() < $startTime){
  373. $this->error = '优惠券使用时间未到';
  374. return false;
  375. }
  376. if($endTime>0 && time() > $endTime){
  377. $this->error = '优惠券已过期';
  378. return false;
  379. }
  380. // 满减券
  381. if($couponType == 10){
  382. $minPrice = isset($couponInfo['min_price'])?$couponInfo['min_price']:0;
  383. $reducePrice = isset($couponInfo['reduce_price'])?$couponInfo['reduce_price']:0;
  384. if($total<= $reducePrice){
  385. $this->error = '金额不足优惠券使用条件';
  386. return false;
  387. }
  388. // 满足最低消费
  389. if($reducePrice && $minPrice && $total >= $minPrice){
  390. return ['total'=>moneyFormat($total-$reducePrice,2),'coupon_total'=>$reducePrice];
  391. }
  392. }
  393. // 购买券
  394. else if($couponType == 20){
  395. $reducePrice = isset($couponInfo['reduce_price'])?$couponInfo['reduce_price']:0;
  396. if($total<= $reducePrice){
  397. $this->error = '金额不足优惠券使用条件';
  398. return -1;
  399. }
  400. return ['total'=>moneyFormat($total-$reducePrice,2),'coupon_total'=>$reducePrice];
  401. }
  402. // 折扣券
  403. else if($couponType == 30){
  404. $reducePrice = isset($couponInfo['reduce_price'])?$couponInfo['reduce_price']:0;
  405. $discount = isset($couponInfo['discount'])?$couponInfo['discount']:0;
  406. $payTotal = moneyFormat($total * $discount/10, 2);
  407. return ['total'=>$payTotal,'coupon_total'=> moneyFormat($total-$payTotal,2)];
  408. }
  409. return true;
  410. }
  411. /**
  412. * 专区商品
  413. * @param $type 专区类型:2-午夜限定,3-蜜友优选
  414. * @return array|mixed
  415. */
  416. public function getListByZoneType($type, $limit=0)
  417. {
  418. $limit = $limit?$limit : ConfigService::make()->getConfigByCode("zone_type{$type}_num", 6);
  419. $cacheKey = "caches:goods:zoneList_{$type}_{$limit}";
  420. $data = RedisService::get($cacheKey);
  421. if($data){
  422. return $data;
  423. }
  424. $data = $this->model->with(['sku'])->where(['zone_type'=>$type,'status'=>1,'mark'=>1])
  425. ->select(['id','thumb','price','market_price','sku_type','goods_name','sales','stock','category_id','type','zone_type','is_new','status'])
  426. ->orderBy('sort','desc')
  427. ->orderBy('id','asc')
  428. ->get();
  429. $data = $data? $data->toArray() :[];
  430. if($data){
  431. RedisService::set($cacheKey, $data, rand(10, 20));
  432. }
  433. return $data;
  434. }
  435. }