GoodsService.php 15 KB

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