GoodsService.php 19 KB

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