GoodsService.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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\AgentModel;
  13. use App\Models\GoodsCategoryModel;
  14. use App\Models\GoodsModel;
  15. use App\Models\GoodsSkuModel;
  16. use App\Models\MemberModel;
  17. use App\Models\MerchantModel;
  18. use App\Models\OrderModel;
  19. use App\Models\ShopModel;
  20. use App\Models\TradeModel;
  21. use App\Services\BaseService;
  22. use App\Services\ConfigService;
  23. use App\Services\RedisService;
  24. use App\Services\SupplyService;
  25. use App\Services\WalletService;
  26. use BN\Red;
  27. use Illuminate\Support\Facades\DB;
  28. /**
  29. * 商品管理-服务类
  30. * @author laravel开发员
  31. * @since 2020/11/11
  32. * Class GoodsService
  33. * @package App\Services\Api
  34. */
  35. class GoodsService extends BaseService
  36. {
  37. // 静态对象
  38. protected static $instance = null;
  39. /**
  40. * 构造函数
  41. * @author laravel开发员
  42. * @since 2020/11/11
  43. * GoodsService constructor.
  44. */
  45. public function __construct()
  46. {
  47. $this->model = new GoodsModel();
  48. }
  49. /**
  50. * 静态入口
  51. * @return static|null
  52. */
  53. public static function make()
  54. {
  55. if (!self::$instance) {
  56. self::$instance = (new static());
  57. }
  58. return self::$instance;
  59. }
  60. /**
  61. * 商品列表
  62. * @param $params
  63. * @param int $pageSize
  64. * @param int $userId
  65. * @return array
  66. */
  67. public function getDataList($params, $pageSize = 12, $userId = 0)
  68. {
  69. $model = $this->model->with(['skuList'])->from('goods as a')
  70. ->where(['a.status' => 1, 'a.mark' => 1])
  71. ->where('a.cost_price', '>', 0)
  72. ->where(function ($query) use ($params) {
  73. $supplyType = isset($params['supply_type']) ? intval($params['supply_type']) : 0;
  74. if ($supplyType > 0) {
  75. $query->where('a.supply_type', $supplyType);
  76. }
  77. $cateId = isset($params['cate_id']) ? intval($params['cate_id']) : 0;
  78. if ($cateId > 0) {
  79. $subIds = GoodsCategoryModel::where(['pid'=> $cateId,'mark'=>1,'status'=>1])->pluck('cate_id');
  80. $query->where(function($query) use($cateId,$subIds){
  81. if($subIds){
  82. $query->whereIn('a.cate_id', $subIds)
  83. ->orWhere('a.cate_id', $cateId);
  84. }else{
  85. $query->where('a.cate_id', $cateId);
  86. }
  87. });
  88. }
  89. })
  90. ->where(function ($query) use ($params) {
  91. $keyword = isset($params['kw']) ? $params['kw'] : '';
  92. if ($keyword) {
  93. $query->where('a.goods_name', 'like', "%{$keyword}%")
  94. ->orWhere('a.spu_name', 'like', "%{$keyword}%")
  95. ->orWhere('a.tag', 'like', "%{$keyword}%");
  96. }
  97. })
  98. ->select(['a.*']);
  99. // 排序
  100. $sortType = isset($params['sort_type'])? $params['sort_type'] : 1;
  101. if ($sortType == 2){
  102. $model = $model->orderBy('a.is_recommend','asc')->orderBy('a.sales', 'desc');
  103. }
  104. $list = $model->orderBy('a.create_time', 'desc')
  105. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  106. $list = $list ? $list->toArray() : [];
  107. if ($list) {
  108. $locale = RedisService::get("caches:locale:lang_{$userId}");
  109. $locale = $locale ? $locale : session('locale_lang');
  110. $locale = $locale ? $locale : 'zh-cn';
  111. $supplyList = config('goods.supplyList');
  112. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  113. if($usdtPrice<=0){
  114. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  115. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  116. }
  117. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  118. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  119. foreach ($list['data'] as &$item) {
  120. $item['detail_img'] = isset($item['detail_img']) && $item['detail_img'] ? json_decode($item['detail_img'], true) : [];
  121. $item['supply_name'] = isset($supplyList[$item['supply_type']]) ? $supplyList[$item['supply_type']] : '';
  122. $item['usdt_price'] = $usdtPrice;
  123. $item['xd_price_rate'] = $xdPrice;
  124. $item['original_price'] = $item['cost_price'];
  125. $item['cost_price'] = $usdtPrice > 0 ? moneyFormat($item['cost_price'] / $usdtPrice * $xdPrice, 2) : $item['cost_price'];
  126. }
  127. unset($item);
  128. } else {
  129. $this->updateGoods();
  130. }
  131. return [
  132. 'total' => isset($list['total']) ? $list['total'] : 9,
  133. 'pageSize' => $pageSize,
  134. 'list' => isset($list['data']) ? $list['data'] : [],
  135. ];
  136. }
  137. /**
  138. * 详情
  139. * @param $id
  140. * @return array
  141. */
  142. public function getInfo($goodsId, $userId=0)
  143. {
  144. $field = ['a.*'];
  145. $info = $this->model->from('goods as a')->with(['category','skuList'])
  146. ->where(['a.goods_id'=> $goodsId,'a.status'=>1,'a.mark'=>1])
  147. ->select($field)
  148. ->first();
  149. $info = $info? $info->toArray() : [];
  150. if($info){
  151. if(isset($info['main_img'])){
  152. $info['main_img'] = $info['main_img']? get_image_url($info['main_img']) : '';
  153. }
  154. if(isset($info['detail_img'])){
  155. $info['detail_img'] = $info['detail_img']? json_decode($info['detail_img'], true) : [];
  156. }
  157. $supplyList = config('goods.supplyList');
  158. $info['supply_name'] = isset($supplyList[$info['supply_type']]) ? $supplyList[$info['supply_type']] : '';
  159. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  160. if($usdtPrice<=0){
  161. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  162. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  163. }
  164. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  165. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  166. $info['usdt_price_rate'] = $usdtPrice;
  167. $info['xd_price'] = $xdPrice;
  168. if(isset($info['cost_price']) && $info['cost_price']){
  169. $info['cost_price'] = moneyFormat($info['cost_price']/$usdtPrice * $xdPrice,2);
  170. }
  171. if(isset($info['sku_list']) && $info['sku_list']){
  172. foreach ($info['sku_list'] as &$v){
  173. $v['detail_img'] = $v['detail_img']? json_decode($v['detail_img'], true) : [];
  174. $v['attr'] = $v['attr']? json_decode($v['attr'], true) : [];
  175. $v['main_img'] = $v['main_img']? get_image_url($v['main_img']) : '';
  176. $v['cost_prict'] = $v['retail_price']? moneyFormat($v['retail_price']/$usdtPrice * $xdPrice,2) : $info['cost_price'];
  177. }
  178. unset($v);
  179. }
  180. $this->updateView($userId, $goodsId);
  181. }
  182. return $info;
  183. }
  184. public function getFreight($userId, $addressId)
  185. {
  186. $cacheKey = "caches:goods:freight:{$userId}_{$addressId}";
  187. $data = RedisService::get($cacheKey);
  188. if($data){
  189. return $data;
  190. }
  191. $result = SupplyService::make()->getApiData('getFreight',['address_id'=> $addressId]);
  192. }
  193. /**
  194. * 更新浏览量
  195. * @param $userId
  196. * @param $dynamicId
  197. * @return array|mixed
  198. */
  199. public function updateView($userId, $id)
  200. {
  201. $cacheKey = "caches:goods:views:u{$userId}_d{$id}";
  202. $data = RedisService::get($cacheKey);
  203. if($data){
  204. return false;
  205. }
  206. $data = $this->model->where(['goods_id'=> $id])->update(['views'=>DB::raw('views + 1'),'update_time'=>time()]);
  207. RedisService::set($cacheKey, $id, rand(1,3)*7200);
  208. return $data;
  209. }
  210. /**
  211. * 更新商品SKU数据到本地
  212. * @param int $pageSize
  213. * @param $params 参数
  214. * @return array|false
  215. */
  216. public function updateGoodsSku($pageSize = 100, $params = [])
  217. {
  218. $cacheKey = "caches:supply:goods_sku_update_{$pageSize}";
  219. if (RedisService::get($cacheKey)) {
  220. $this->error = 1047;
  221. return false;
  222. }
  223. $page = RedisService::get($cacheKey . '_page');
  224. $page = $page ? $page + 1 : 1;
  225. $lastDate = GoodsSkuModel::where(['mark' => 1])->orderBy('last_update_at', 'desc')->value('last_update_at');
  226. $params = [
  227. 'limit' => $pageSize > 0 ? $pageSize : 50,
  228. 'page' => $page,
  229. 'date' => $lastDate ? $lastDate : '', // 开始时间
  230. ];
  231. $goods = [];
  232. $updated = 0;
  233. $error = 0;
  234. $datas = SupplyService::make()->getApiData('getSkuUpdate', $params);
  235. if ($datas && $datas['list']) {
  236. foreach ($datas['list'] as &$item) {
  237. $goodsId = isset($item['goods_id']) ? $item['goods_id'] : 0;
  238. $goodsSkuSn = isset($item['sku_sn']) ? $item['sku_sn'] : '';
  239. $changeType = isset($item['change_type']) ? $item['change_type'] : '';
  240. if ($goodsId && $goodsSkuSn && $changeType) {
  241. $skuInfo = SupplyService::make()->getApiData('getSkuDetail', ['sku_sn' => $goodsSkuSn]);
  242. if ($skuInfo) {
  243. $updateData = ['goods_id'=>$goodsId,'sku_sn'=> $goodsSkuSn,'remark'=>'SKU更新','update_time' => time(),'mark'=>1, 'last_update_at' => $item['update_time']];
  244. if (isset($skuInfo['sku_name']) && $skuInfo['sku_name']) {
  245. $updateData['sku_name'] = $skuInfo['sku_name'];
  246. }
  247. if (isset($skuInfo['main_img']) && $skuInfo['main_img']) {
  248. $updateData['main_img'] = $skuInfo['main_img'];
  249. }
  250. if (isset($skuInfo['spu_sn']) && $skuInfo['spu_sn']) {
  251. $updateData['spu_sn'] = $skuInfo['spu_sn'];
  252. }
  253. if (isset($skuInfo['sku_id']) && $skuInfo['sku_id']) {
  254. $updateData['sku_id'] = intval($skuInfo['sku_id']);
  255. }
  256. if (isset($skuInfo['status']) && $skuInfo['status']) {
  257. $updateData['status'] = intval($skuInfo['status']);
  258. }
  259. if (isset($skuInfo['retail_price']) && $skuInfo['retail_price']) {
  260. $updateData['retail_price'] = floatval($skuInfo['retail_price']);
  261. }
  262. if (isset($skuInfo['plat_price']) && $skuInfo['plat_price']) {
  263. $updateData['plat_price'] = floatval($skuInfo['plat_price']);
  264. }
  265. if (isset($skuInfo['detail_img']) && $skuInfo['detail_img']) {
  266. $updateData['detail_img'] = json_encode($skuInfo['detail_img'], 256);
  267. }
  268. if (isset($skuInfo['attr']) && $skuInfo['attr']) {
  269. $updateData['attr'] = json_encode($skuInfo['attr'], 256);
  270. }
  271. if(GoodsSkuModel::where(['goods_id' => $goodsId])->value('id')){
  272. GoodsSkuModel::where(['goods_id' => $goodsId, 'mark' => 1])->update($updateData);
  273. $updated++;
  274. }else{
  275. $error++;
  276. }
  277. } else {
  278. $error++;
  279. }
  280. } else {
  281. $error++;
  282. }
  283. }
  284. unset($item);
  285. RedisService::set($cacheKey . '_page', $page, rand(300, 600));
  286. }else{
  287. RedisService::set($cacheKey . '_page', 0, rand(300, 600));
  288. }
  289. return ['count' => count($goods), 'updated' => $updated, 'errorCount' => $error,'page'=>$page];
  290. }
  291. /**
  292. * 更新商品
  293. * @param int $pageSize
  294. * @param $params 参数
  295. * @return array|false
  296. */
  297. public function updateGoods($pageSize = 100, $params = [])
  298. {
  299. set_time_limit(0);
  300. $cacheKey = "caches:supply:goods_list_update_{$pageSize}";
  301. if (RedisService::get($cacheKey)) {
  302. $this->error = 1047;
  303. return false;
  304. }
  305. $page = RedisService::get($cacheKey . '_page');
  306. $page = $page ? $page + 1 : 1;
  307. $lastTime = $this->model->where(['mark' => 1])->orderBy('create_time', 'desc')->value('create_time');
  308. $params = [
  309. 'limit' => $pageSize > 0 ? $pageSize : 50,
  310. 'page' => $page,
  311. 'status' => isset($params['status']) ? $params['status'] : 1, // 状态:0-全部,1-上架的,2-下架的
  312. 'supply_type' => isset($params['supply_type']) ? $params['supply_type'] : 0, // 渠道商
  313. 'title' => isset($params['title']) ? $params['title'] : '', // 标题关键词
  314. 'cate_id' => isset($params['cate_id']) ? $params['cate_id'] : '', // 分类ID
  315. 'begin_time' => $lastTime ? $lastTime : '', // 开始时间
  316. ];
  317. $goods = [];
  318. $skus = [];
  319. $updated = 0;
  320. $error = 0;
  321. $datas = SupplyService::make()->getApiData('getGoodsList', $params);
  322. if ($datas && $datas['list']) {
  323. foreach ($datas['list'] as &$item) {
  324. $goodsId = isset($item['goods_id']) ? $item['goods_id'] : 0;
  325. if ($goodsId && !$this->checkGoods($goodsId)) {
  326. $info = $this->getApiInfo($goodsId);
  327. if ($info) {
  328. $skuList = isset($info['sku_list']) ? $info['sku_list'] : [];
  329. $goods[] = [
  330. 'goods_id' => $goodsId,
  331. 'supply_type' => isset($item['supply_type']) ? $item['supply_type'] : 0,
  332. 'spu_sn' => isset($item['spu_sn']) ? $item['spu_sn'] : '',
  333. 'spu_name' => isset($info['spu_name']) ? $info['spu_name'] : '',
  334. 'main_img' => isset($info['main_img']) ? $info['main_img'] : '',
  335. 'detail_img' => isset($info['detail_img']) ? json_encode($info['detail_img'], 256) : '',
  336. 'goods_name' => isset($item['goods_name']) ? $item['goods_name'] : '',
  337. 'brand_name' => isset($info['brand_name']) ? $info['brand_name'] : '',
  338. 'limit_num' => isset($info['limit_num']) ? intval($info['limit_num']) : 0,
  339. 'lowest_num' => isset($info['lowest_num']) ? intval($info['lowest_num']) : 1,
  340. 'cost_price' => isset($info['cost_price']) ? floatval($info['cost_price']) : 0,
  341. 'retail_price' => isset($info['retail_price']) ? floatval($info['retail_price']) : 0,
  342. 'profit' => isset($info['profit']) ? floatval($info['profit']) : 0,
  343. 'sku_list' => $skuList? json_encode($skuList,256):'',
  344. 'sku_total' => isset($info['sku_total']) ? intval($info['sku_total']) : 0,
  345. 'tag' => isset($item['tag']) ? json_encode($item['tag'], 256) : '',
  346. 'status' => isset($info['status']) ? intval($info['status']) : 1,
  347. 'cate_id' => isset($item['cate_id']) ? intval($item['cate_id']) : 0,
  348. 'last_update_at' => isset($info['update_time']) ? $info['update_time'] : (isset($item['time']) && $item['time'] ? $item['time'] : date('Y-m-d H:i:s')),
  349. 'create_time' => time(),
  350. ];
  351. foreach($skuList as $v){
  352. $skus[] = [
  353. 'sku_id'=> isset($v['sku_id'])? $v['sku_id'] : 0,
  354. 'goods_id'=> $goodsId,
  355. 'spu_sn'=> isset($v['spu_sn'])? $v['spu_sn'] : '',
  356. 'sku_sn'=> isset($v['sku_sn'])? $v['sku_sn'] : '',
  357. 'sku_name'=> isset($v['sku_name'])? $v['sku_name'] : '',
  358. 'main_img'=> isset($v['main_img'])? $v['main_img'] : '',
  359. 'status'=> isset($v['status'])? $v['status'] : 1,
  360. 'source_type'=> isset($v['source_type'])? $v['source_type'] : 0,
  361. 'retail_price'=> isset($v['retail_price'])? floatval($v['retail_price']) : 0,
  362. 'plat_price'=> isset($v['plat_price'])? floatval($v['plat_price']) : 0,
  363. 'profit'=> isset($v['profit'])? floatval($v['profit']) : 0,
  364. 'last_update_at'=> isset($v['update_time'])? $v['update_time'] : date('Y-m-d H:i:s'),
  365. 'detail_img'=> isset($v['detail_img'])? json_encode($v['detail_img'],256) : '',
  366. 'attr'=> isset($v['attr'])? json_encode($v['attr'],256) : '',
  367. 'remark'=>'SKU同步创建',
  368. ];
  369. }
  370. $updated++;
  371. } else {
  372. $error++;
  373. }
  374. } else {
  375. $error++;
  376. }
  377. }
  378. unset($item);
  379. } else {
  380. RedisService::set($cacheKey . '_page', 0, rand(300, 600));
  381. }
  382. if ($goods) {
  383. RedisService::set($cacheKey . '_page', $page, rand(300, 600));
  384. RedisService::set($cacheKey, $goods, rand(5, 10));
  385. DB::beginTransaction();
  386. try {
  387. $this->model->insertAll($goods);
  388. if($skus){
  389. GoodsSkuModel::insert($skus);
  390. }
  391. DB::commit();
  392. }catch (\Exception $exception){
  393. DB::rollBack();
  394. }
  395. }
  396. return ['count' => count($goods), 'updated' => $updated, 'errorCount' => $error,'page'=>$page];
  397. }
  398. /**
  399. * 更新商品分类
  400. * @param int $pid 上级ID
  401. * @param int $pageSize
  402. * @param $params 参数
  403. * @return array|false
  404. */
  405. public function updateGoodsCategory($pid=0, $pageSize = 200, $params = [])
  406. {
  407. set_time_limit(0);
  408. $cacheKey = "caches:supply:goods_category_update_{$pid}_{$pageSize}";
  409. if (RedisService::get($cacheKey)) {
  410. $this->error = 1047;
  411. return false;
  412. }
  413. $params = [
  414. 'limit' => $pageSize > 0 ? $pageSize : 50,
  415. 'page' => 1,
  416. 'pid' => $pid, // 上级ID
  417. ];
  418. $categorys = [];
  419. $updated = 0;
  420. $error = 0;
  421. $datas = SupplyService::make()->getApiData('getGoodsCategory', $params);
  422. if ($datas && $datas['data']) {
  423. foreach ($datas['data'] as &$item) {
  424. $cateId = isset($item['id']) ? $item['id'] : 0;
  425. if ($cateId && !$this->checkCategory($cateId)) {
  426. $categorys[] = [
  427. 'cate_id' => $cateId,
  428. 'name' => isset($item['name']) ? $item['name'] : '',
  429. 'pid' => isset($item['pid']) ? intval($item['pid']) : 0,
  430. 'create_time' => time(),
  431. ];
  432. $updated++;
  433. } else {
  434. $error++;
  435. }
  436. }
  437. unset($item);
  438. }
  439. if ($categorys) {
  440. RedisService::set($cacheKey, $categorys, rand(5, 10));
  441. GoodsCategoryModel::insert($categorys);
  442. }
  443. return ['count' => count($categorys), 'updated' => $updated,'pid'=>$pid, 'errorCount' => $error];
  444. }
  445. /**
  446. * 验证
  447. * @param $goodsId
  448. * @return bool
  449. */
  450. public function checkGoods($goodsId)
  451. {
  452. $cacheKey = "caches:goods:check_{$goodsId}";
  453. if (RedisService::get($cacheKey) || RedisService::exists($cacheKey)) {
  454. return true;
  455. }
  456. $data = $this->model->where(['goods_id' => $goodsId, 'mark' => 1])->value('id');
  457. RedisService::set($cacheKey, $data, rand(30, 60));
  458. return $data;
  459. }
  460. /**
  461. * 验证分类
  462. * @param $cateId
  463. * @return bool
  464. */
  465. public function checkCategory($cateId)
  466. {
  467. $cacheKey = "caches:goods:category_check_{$cateId}";
  468. if (RedisService::get($cacheKey) || RedisService::exists($cacheKey)) {
  469. return true;
  470. }
  471. $data = GoodsCategoryModel::where(['cate_id' => $cateId, 'mark' => 1])->value('id');
  472. RedisService::set($cacheKey, $data, rand(30, 60));
  473. return $data;
  474. }
  475. /**
  476. * 接口商品详情
  477. * @param $goodsId 商品ID
  478. * @param int $isReal 是否实时数据,0-是,1-否
  479. * @param int $type 数据类型:0-详情,1-仅SKU数据
  480. * @return array|false|mixed|string
  481. */
  482. public function getApiInfo($goodsId, $isReal = 0, $type = 0)
  483. {
  484. $cacheKey = "caches:goods:detail_{$goodsId}_{$isReal}_{$type}";
  485. $info = RedisService::get($cacheKey);
  486. if (empty($info)) {
  487. $params = [
  488. 'goods_id' => $goodsId,
  489. 'is_real' => $isReal,
  490. 'type' => $type
  491. ];
  492. $info = SupplyService::make()->getApiData('getGoodsDetail', $params);
  493. if ($info) {
  494. RedisService::set($cacheKey, $info, rand(5, 10));
  495. }
  496. }
  497. return $info;
  498. }
  499. public function apiCategory($num)
  500. {
  501. }
  502. }