GoodsService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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.is_recommend'=>1,'a.status' => 1, 'a.mark' => 1];
  85. $status = isset($params['status']) ? $params['status'] : 1;
  86. $isRecommend = isset($params['is_recommend']) ? $params['is_recommend'] : 0;
  87. if ($status > 0) {
  88. $where['a.status'] = $status;
  89. } else {
  90. unset($where['a.status']);
  91. }
  92. if ($isRecommend == 1) {
  93. $where['a.is_recommend'] = $isRecommend;
  94. } else {
  95. unset($where['a.is_recommend']);
  96. }
  97. $model = $this->model->with(['store','category'])
  98. ->from('goods as a')
  99. ->where($where)
  100. ->where(function ($query) use ($params) {
  101. // 分类
  102. $categoryId = isset($params['category_id'])? intval($params['category_id']) : 0;
  103. if($categoryId>0){
  104. $query->where('a.category_id', $categoryId);
  105. }
  106. // 企业
  107. $storeId = isset($params['store_id'])? intval($params['store_id']) : 0;
  108. if($storeId>0){
  109. $query->where('a.store_id', $storeId);
  110. }
  111. $keyword = isset($params['keyword']) ? trim($params['keyword']) : '';
  112. if ($keyword) {
  113. $query->where(function ($query) use ($keyword) {
  114. $query->where('a.goods_name', 'like', "%{$keyword}%")
  115. ->orWhere('a.tags','like',"%{$keyword}%");
  116. });
  117. }
  118. });
  119. return $model;
  120. }
  121. /**
  122. * 分类
  123. * @return array|mixed
  124. */
  125. public function getCategoryList()
  126. {
  127. $cacheKey = "caches:goods:categoryList";
  128. $datas = RedisService::get($cacheKey);
  129. if($datas){
  130. return $datas;
  131. }
  132. $datas = GoodsCategoryModel::where(['pid'=>0,'status'=>1,'mark'=>1])
  133. ->select(['id','name','icon','pid','sort'])
  134. ->orderBy('sort','desc')
  135. ->orderBy('id','asc')
  136. ->get();
  137. $datas = $datas? $datas->toArray() : [];
  138. if($datas){
  139. RedisService::set($cacheKey, $datas, rand(300,600));
  140. }
  141. return $datas;
  142. }
  143. /**
  144. * 详情信息
  145. * @param $id
  146. * @return mixed
  147. */
  148. public function getInfo($id,$userId=0)
  149. {
  150. $cacheKey = "caches:goods:info_{$id}_{$userId}";
  151. $info = RedisService::get($cacheKey);
  152. if ($info) {
  153. return $info;
  154. }
  155. $info = $this->model->with(['store','category','skus'])->where(['id' => $id])->first();
  156. $info = $info ? $info->toArray() : [];
  157. if ($info) {
  158. RedisService::set($cacheKey, $info, rand(10, 20));
  159. }
  160. return $info;
  161. }
  162. /**
  163. * 收藏
  164. * @param $userId
  165. * @param $goodsId
  166. * @return array|false
  167. */
  168. public function collect($userId, $goodsId)
  169. {
  170. $info = $this->model->where(['id' => $goodsId,'status'=>1,'mark'=>1])->first();
  171. $info = $info ? $info->toArray() : [];
  172. if(empty($info)){
  173. $this->error = '商品已下架';
  174. return false;
  175. }
  176. if($id = GoodsCollectModel::where(['user_id'=>$userId,'goods_id'=>$goodsId,'mark'=>1])->value('id')){
  177. GoodsCollectModel::where(['id'=>$id])->update(['mark'=>0,'update_time'=>time()]);
  178. $this->error = '取消收藏';
  179. RedisService::clear("caches:goods:info_{$id}_{$userId}");
  180. return ['id'=>$id,'is_collect'=>0];
  181. }else{
  182. if(!$id = GoodsCollectModel::insertGetId(['user_id'=>$userId,'goods_id'=>$goodsId,'status'=>1,'mark'=>1,'create_time'=>time(),'update_time'=>time()])){
  183. $this->error = '收藏失败';
  184. return false;
  185. }
  186. $this->error = '收藏成功';
  187. RedisService::clear("caches:goods:info_{$id}_{$userId}");
  188. return ['id'=>$id,'is_collect'=>1];
  189. }
  190. }
  191. /**
  192. * @param $ids
  193. * @param $goods
  194. * @param $userId
  195. * @param $orderNo 订单号
  196. * @return array|false
  197. */
  198. public function getOrderGoods($ids, $goods, $userId, $orderNo='', $discountPoint=0)
  199. {
  200. if(empty($ids) || empty($goods)){
  201. $this->error = '请选择商品';
  202. return false;
  203. }
  204. // 用户信息
  205. if(empty($orderNo)){
  206. $userInfo = MemberModel::where(['id' => $userId, 'mark' => 1])
  207. ->select(['id','openid', 'discount_point', 'status'])
  208. ->first();
  209. $status = isset($userInfo['status']) ? $userInfo['status'] : 0;
  210. $openid = isset($userInfo['openid']) ? $userInfo['openid'] : 0;
  211. $discountPoint = isset($userInfo['discount_point']) ? $userInfo['discount_point'] : 0; // 折扣
  212. if (empty($userInfo) || $status != 1) {
  213. $this->error = 1045;
  214. return false;
  215. }
  216. if (empty($openid)) {
  217. $this->error = 1042;
  218. return false;
  219. }
  220. }
  221. $list = $this->model->whereIn('id', $ids)
  222. ->where(['status'=>1,'mark'=>1])
  223. ->select(['id as goods_id','goods_name','category_id','store_id','delivery_fee','sku_type','price','stock','unit','weight','thumb','sku_type'])
  224. ->get();
  225. $list = $list? $list->toArray() : [];
  226. if($list){
  227. $skus = GoodsSkuModel::whereIn('goods_id', $ids)->select(['id','sku_name','price','stock'])->get()->keyBy('id');
  228. $skus = $skus?$skus->toArray() :[];
  229. $result = ['discount_point'=>$discountPoint,'store_id'=>0,'discount_total'=>0.00,'delivery_fee'=>0.00,'goods_total'=>0,'order_total'=>0,'count'=>0,'goods'=>[]];
  230. foreach ($list as $item){
  231. $item['order_no'] = $orderNo;
  232. $id = isset($item['goods_id'])?$item['goods_id']:0;
  233. $goodsName = isset($item['goods_name'])?$item['goods_name']:'';
  234. $params = isset($goods['id_'.$id])? $goods['id_'.$id]:[];
  235. $goodsId = isset($params['id'])?$params['id']:0;
  236. $storeId = isset($item['store_id'])?$item['store_id']:0;
  237. $deliveryFee = isset($item['delivery_fee'])?$item['delivery_fee']:0;
  238. $stock = isset($item['stock'])?$item['stock']:0;
  239. $num = isset($params['num'])?$params['num']:0;
  240. $skuId = isset($params['sku_id'])?$params['sku_id']:0;
  241. $skuType = isset($item['sku_type'])?$item['sku_type']: 1;
  242. $skuData = isset($skus[$skuId])? $skus[$skuId]:[];
  243. $skuPrice = isset($skuData['price'])?$skuData['price']:0;
  244. $skuStock = isset($skuData['stock'])?$skuData['stock']:0;
  245. $skuName = isset($skuData['sku_name'])?$skuData['sku_name']:'';
  246. $price = $skuType==2 ? $skuPrice : $item['price'];
  247. unset($item['skus']);
  248. if($result['store_id'] && $storeId != $result['store_id']){
  249. $this->error = '一次只能购买同一个商家的商品,请核对后重试~';
  250. return false;
  251. }
  252. if($stock<=0 || $num>$stock){
  253. $this->error = $skuId? "商品[{$goodsName}]规格[{$skuName}]库存不足~" : "商品[{$goodsName}]库存不足~";
  254. return false;
  255. }
  256. if($skuType==2 && ($skuStock<=0 || $num>$skuStock)){
  257. $this->error = "商品[{$goodsName}]规格[{$skuName}]库存不足~";
  258. return false;
  259. }
  260. if($num>0 && $goodsId == $id && $price>0){
  261. $result['store_id'] = $storeId;
  262. $result['delivery_fee'] = max($deliveryFee,$result['delivery_fee']);
  263. $item['user_id'] = $userId;
  264. $item['sku_id'] = $skuId;
  265. if(empty($orderNo)){
  266. $item['sku'] = $skuData;
  267. }
  268. $item['price'] = $price;
  269. $item['total'] = $price;
  270. $item['num'] = $num;
  271. $total = round($price * $num,2);
  272. $item['total'] = $total;
  273. $item['thumb'] = $orderNo?get_image_path($item['thumb']):$item['thumb'];
  274. $result['goods'][] = $item;
  275. $result['goods_total'] += $total;
  276. $result['order_total'] += $total;
  277. $result['count']++;
  278. }
  279. }
  280. // 会员折扣
  281. $orderTotal = $result['order_total'];
  282. if($discountPoint>0 && $discountPoint<1){
  283. $result['order_total'] = moneyFormat((1-$discountPoint) * $result['order_total'],2);
  284. $result['discount_total'] = moneyFormat($orderTotal - $result['order_total'],2);
  285. }
  286. $result['pay_total'] = moneyFormat($result['order_total'] + $result['delivery_fee'],2);
  287. return $result;
  288. }
  289. return false;
  290. }
  291. }