GoodsService.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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(['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. $userInfo = $userInfo?$userInfo->toArray() : [];
  217. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  218. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : 0;
  219. $vipExpired = isset($userInfo['vip_expired']) ? $userInfo['vip_expired'] : 0;
  220. $levelData = isset($userInfo['level_data']) ? $userInfo['level_data'] : [];
  221. if (empty($userInfo) || $status != 1) {
  222. $this->error = 1045;
  223. return false;
  224. }
  225. if (empty($openid)) {
  226. $this->error = 1042;
  227. return false;
  228. }
  229. // 有效会员
  230. if($vipExpired != 0){
  231. $discountPoint = isset($levelData['discount']) ? $levelData['discount'] : 0; // 会员折扣
  232. }
  233. }
  234. // 优惠券信息
  235. $couponInfo = [];
  236. if($couponId){
  237. $couponInfo = MemberCouponModel::where(['coupon_id'=>$couponId,'user_id'=>$userId,'mark'=>1])->first();
  238. $couponType = isset($couponInfo['coupon_type'])?$couponInfo['coupon_type'] : 0;
  239. $couponStatus = isset($couponInfo['status'])?$couponInfo['status'] : 0;
  240. $startTime = isset($couponInfo['start_time'])?$couponInfo['start_time'] : 0;
  241. $endTime = isset($couponInfo['end_time'])?$couponInfo['end_time'] : 0;
  242. // 下单需验证
  243. if($orderNo){
  244. if(empty($couponInfo) || $couponType<=0){
  245. $this->error = '优惠券无效';
  246. return false;
  247. }
  248. if($couponStatus != 1){
  249. $this->error = '该优惠券已使用,请刷新后重试~';
  250. return false;
  251. }
  252. if($startTime > time()){
  253. $this->error = '该优惠券使用时间未到~';
  254. return false;
  255. }
  256. if($endTime && $endTime < time()){
  257. $this->error = '该优惠券已过期~';
  258. return false;
  259. }
  260. }
  261. }
  262. $list = $this->model->whereIn('id', $ids)
  263. ->where(['status'=>1,'mark'=>1])
  264. ->select(['id as goods_id','goods_name','type','category_id','store_id','delivery_fee','sku_type','price','stock','unit','weight','thumb'])
  265. ->get()
  266. ->keyBy('goods_id');
  267. $list = $list? $list->toArray() : [];
  268. if($list){
  269. $isGoodsCoupon = false;
  270. $skus = GoodsSkuModel::whereIn('goods_id', $ids)->select(['id','sku_name','price','stock'])->get()->keyBy('id');
  271. $skus = $skus?$skus->toArray() :[];
  272. $result = ['discount_point'=>floatval($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'=>[]];
  273. foreach ($goods as $params){
  274. $goodsId = isset($params['id'])?$params['id']:0;
  275. $skuId = isset($params['sku_id'])?$params['sku_id']:0;
  276. $num = isset($params['num'])?$params['num']:0;
  277. $item = isset($list[$goodsId])?$list[$goodsId] : [];
  278. if(empty($item)){
  279. continue;
  280. }
  281. $item['order_no'] = $orderNo;
  282. $id = isset($item['goods_id'])?$item['goods_id']:0;
  283. $goodsName = isset($item['goods_name'])?$item['goods_name']:'';
  284. $storeId = isset($item['store_id'])?$item['store_id']:0;
  285. $deliveryFee = isset($item['delivery_fee'])?$item['delivery_fee']:0;
  286. $stock = isset($item['stock'])?$item['stock']:0;
  287. $skuType = isset($item['sku_type'])?$item['sku_type']: 1;
  288. $skuData = isset($skus[$skuId])? $skus[$skuId]:[];
  289. $skuPrice = isset($skuData['price'])?$skuData['price']:0;
  290. $skuStock = isset($skuData['stock'])?$skuData['stock']:0;
  291. $skuName = isset($skuData['sku_name'])?$skuData['sku_name']:'';
  292. $price = $skuType==2 ? $skuPrice : $item['price'];
  293. unset($item['skus']);
  294. if($result['store_id'] && $storeId != $result['store_id']){
  295. $this->error = '一次只能购买同一个商家的商品,请核对后重试~';
  296. return false;
  297. }
  298. if($stock<=0 || $num>$stock){
  299. $this->error = $skuId? "商品[{$goodsName}]规格[{$skuName}]库存不足~" : "商品[{$goodsName}]库存不足~";
  300. return false;
  301. }
  302. if($skuType==2 && ($skuStock<=0 || $num>$skuStock)){
  303. $this->error = "商品[{$goodsName}]规格[{$skuName}]库存不足~";
  304. return false;
  305. }
  306. if($num>0 && $goodsId == $id && $price>0){
  307. $result['store_id'] = $storeId;
  308. $result['delivery_fee'] = max($deliveryFee,$result['delivery_fee']);
  309. $item['user_id'] = $userId;
  310. $item['sku_id'] = $skuId;
  311. if(empty($orderNo)){
  312. $item['sku'] = $skuData;
  313. }
  314. $item['price'] = $price;
  315. $item['total'] = $price;
  316. $item['num'] = $num;
  317. $total = round($price * $num,2);
  318. // 计算优惠
  319. $couponData = $this->countCouponTotal($goodsId, $total, $couponInfo);
  320. if(!$couponData){
  321. return false;
  322. }
  323. // 是否商品使用的优惠券
  324. $couponTotal = isset($couponData['coupon_total'])?$couponData['coupon_total'] : 0;
  325. $payTotal = isset($couponData['total'])?$couponData['total'] : 0;
  326. if($payTotal){
  327. $item['total'] = $payTotal;
  328. //$total = $payTotal;
  329. $item['coupon_id'] = $couponId;
  330. $item['coupon_total'] = floatval($couponTotal);
  331. $result['coupon_id'] = $couponId;
  332. $result['coupon_total'] = floatval($couponTotal);
  333. $isGoodsCoupon = true;
  334. }else{
  335. $item['total'] = $total;
  336. }
  337. $item['thumb'] = $orderNo?get_image_path($item['thumb']):$item['thumb'];
  338. $result['goods'][] = $item;
  339. $result['goods_total'] += $total;
  340. $result['order_total'] += $total;
  341. $result['count']++;
  342. }
  343. }
  344. // 非商品优惠券,整个订单的优惠券
  345. $discountTotal = 0;
  346. $couponTotal = $result['coupon_total'];
  347. if($couponId && !$isGoodsCoupon){
  348. $couponData = $this->countCouponTotal(0, $result['order_total'], $couponInfo);
  349. if(!$couponData){
  350. return false;
  351. }
  352. $couponTotal = isset($couponData['coupon_total'])?$couponData['coupon_total'] : 0;
  353. $result['coupon_total'] = floatval($couponTotal);
  354. }
  355. // 会员折扣
  356. if($discountPoint>0 && $discountPoint<10){
  357. $discountTotal = floatval(moneyFormat( $result['order_total']*(1-$discountPoint/10),2));
  358. $result['discount_total'] = $discountTotal;
  359. }
  360. // 折后订单总金额
  361. $result['order_total'] = floatval(moneyFormat($result['order_total']-$couponTotal-$discountTotal,2));
  362. // 实付订单总金额加上运费
  363. $result['pay_total'] = floatval(moneyFormat($result['order_total'] + $result['delivery_fee'],2));
  364. return $result;
  365. }
  366. return false;
  367. }
  368. /**
  369. * 优惠券计算
  370. * @param $goodsId
  371. * @param $total
  372. * @param $couponInfo
  373. * @return array|bool|int
  374. */
  375. public function countCouponTotal($goodsId, $total, $couponInfo)
  376. {
  377. $couponStatus = isset($couponInfo['status'])?$couponInfo['status'] : 0;
  378. $couponType = isset($couponInfo['coupon_type'])?$couponInfo['coupon_type'] : 0;
  379. $couponGoodsIds = isset($couponInfo['goods_ids'])&& $couponInfo['goods_ids']?explode(',', $couponInfo['goods_ids']) : [];
  380. // 按商品或全平台(非购买券)
  381. if($goodsId && $couponType != 20 && ($couponGoodsIds && !in_array($goodsId, $couponGoodsIds))){
  382. $this->error = "优惠券非该商品使用";
  383. return false;
  384. }
  385. if($total <= 0 ){
  386. $this->error = "消费金额错误";
  387. return false;
  388. }
  389. if($couponInfo && $couponStatus != 1){
  390. $this->error = "该优惠券已被使用";
  391. return false;
  392. }
  393. $endTime = isset($couponInfo['end_time'])?$couponInfo['end_time']:0;
  394. $startTime = isset($couponInfo['start_time'])?$couponInfo['start_time']:0;
  395. if($startTime && time() < $startTime){
  396. $this->error = '优惠券使用时间未到';
  397. return false;
  398. }
  399. if($endTime>0 && time() > $endTime){
  400. $this->error = '优惠券已过期';
  401. return false;
  402. }
  403. // 满减券
  404. if($couponType == 10){
  405. $minPrice = isset($couponInfo['min_price'])?$couponInfo['min_price']:0;
  406. $reducePrice = isset($couponInfo['reduce_price'])?$couponInfo['reduce_price']:0;
  407. if($total<= $reducePrice){
  408. $this->error = '金额不足优惠券使用条件';
  409. return false;
  410. }
  411. // 满足最低消费
  412. if($reducePrice && $minPrice && $total >= $minPrice){
  413. return ['total'=>moneyFormat($total-$reducePrice,2),'coupon_total'=>$reducePrice];
  414. }
  415. }
  416. // 购买券
  417. else if($couponType == 20){
  418. $reducePrice = isset($couponInfo['reduce_price'])?$couponInfo['reduce_price']:0;
  419. if($total<= $reducePrice){
  420. $this->error = '金额不足优惠券使用条件';
  421. return -1;
  422. }
  423. return ['total'=>moneyFormat($total-$reducePrice,2),'coupon_total'=>$reducePrice];
  424. }
  425. // 折扣券
  426. else if($couponType == 30){
  427. $reducePrice = isset($couponInfo['reduce_price'])?$couponInfo['reduce_price']:0;
  428. $discount = isset($couponInfo['discount'])?$couponInfo['discount']:0;
  429. $payTotal = moneyFormat($total * $discount/10, 2);
  430. return ['total'=>$payTotal,'coupon_total'=> moneyFormat($total-$payTotal,2)];
  431. }
  432. return true;
  433. }
  434. /**
  435. * 专区商品
  436. * @param $type 专区类型:2-午夜限定,3-蜜友优选
  437. * @return array|mixed
  438. */
  439. public function getListByZoneType($type, $limit=0)
  440. {
  441. $limit = $limit?$limit : ConfigService::make()->getConfigByCode("zone_type{$type}_num", 6);
  442. $cacheKey = "caches:goods:zoneList_{$type}_{$limit}";
  443. $data = RedisService::get($cacheKey);
  444. if($data){
  445. return $data;
  446. }
  447. $data = $this->model->with(['sku'])->where(['zone_type'=>$type,'status'=>1,'mark'=>1])
  448. ->select(['id','thumb','price','market_price','sku_type','goods_name','sales','stock','category_id','type','zone_type','is_new','status'])
  449. ->orderBy('sort','desc')
  450. ->orderBy('id','asc')
  451. ->get();
  452. $data = $data? $data->toArray() :[];
  453. if($data){
  454. RedisService::set($cacheKey, $data, rand(10, 20));
  455. }
  456. return $data;
  457. }
  458. }