GoodsService.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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\CartsModel;
  14. use App\Models\GoodsCategoryModel;
  15. use App\Models\GoodsModel;
  16. use App\Models\GoodsSkuModel;
  17. use App\Models\MemberModel;
  18. use App\Models\MerchantModel;
  19. use App\Models\OrderModel;
  20. use App\Models\ShopModel;
  21. use App\Models\TradeModel;
  22. use App\Services\BaseService;
  23. use App\Services\ConfigService;
  24. use App\Services\RedisService;
  25. use App\Services\SupplyService;
  26. use App\Services\WalletService;
  27. use BN\Red;
  28. use Illuminate\Support\Facades\DB;
  29. /**
  30. * 商品管理-服务类
  31. * @author laravel开发员
  32. * @since 2020/11/11
  33. * Class GoodsService
  34. * @package App\Services\Api
  35. */
  36. class GoodsService extends BaseService
  37. {
  38. // 静态对象
  39. protected static $instance = null;
  40. /**
  41. * 构造函数
  42. * @author laravel开发员
  43. * @since 2020/11/11
  44. * GoodsService constructor.
  45. */
  46. public function __construct()
  47. {
  48. $this->model = new GoodsModel();
  49. }
  50. /**
  51. * 静态入口
  52. * @return static|null
  53. */
  54. public static function make()
  55. {
  56. if (!self::$instance) {
  57. self::$instance = (new static());
  58. }
  59. return self::$instance;
  60. }
  61. /**
  62. * 商品列表
  63. * @param $params
  64. * @param int $pageSize
  65. * @param int $userId
  66. * @return array
  67. */
  68. public function getDataList($params, $pageSize = 12, $userId = 0)
  69. {
  70. $model = $this->model->with(['skuList'])->from('goods as a')
  71. ->where(['a.status' => 1, 'a.mark' => 1])
  72. ->where('a.retail_price', '>', 0)
  73. ->where(function ($query) use ($params) {
  74. $supplyType = isset($params['supply_type']) ? intval($params['supply_type']) : 0;
  75. if ($supplyType > 0) {
  76. $query->where('a.supply_type', $supplyType);
  77. }
  78. $cateId = isset($params['cate_id']) ? intval($params['cate_id']) : 0;
  79. if ($cateId > 0) {
  80. $subIds = GoodsCategoryModel::where(['pid'=> $cateId,'mark'=>1,'status'=>1])->pluck('cate_id');
  81. $query->where(function($query) use($cateId,$subIds){
  82. if($subIds){
  83. $query->whereIn('a.cate_id', $subIds)
  84. ->orWhere('a.cate_id', $cateId);
  85. }else{
  86. $query->where('a.cate_id', $cateId);
  87. }
  88. });
  89. }
  90. })
  91. ->where(function ($query) use ($params) {
  92. $keyword = isset($params['kw']) ? $params['kw'] : '';
  93. if ($keyword) {
  94. $query->where('a.goods_name', 'like', "%{$keyword}%")
  95. ->orWhere('a.spu_name', 'like', "%{$keyword}%")
  96. ->orWhere('a.tag', 'like', "%{$keyword}%");
  97. }
  98. })
  99. ->select(['a.*']);
  100. // 排序
  101. $sortType = isset($params['sort_type'])? $params['sort_type'] : 1;
  102. if ($sortType == 2){
  103. $model = $model->orderBy('a.is_recommend','asc')->orderBy('a.sales', 'desc');
  104. }
  105. $list = $model->orderBy('a.create_time', 'desc')
  106. ->paginate($pageSize > 0 ? $pageSize : 9999999);
  107. $list = $list ? $list->toArray() : [];
  108. if ($list) {
  109. $locale = RedisService::get("caches:locale:lang_{$userId}");
  110. $locale = $locale ? $locale : session('locale_lang');
  111. $locale = $locale ? $locale : 'zh-cn';
  112. $supplyList = config('goods.supplyList');
  113. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  114. if($usdtPrice<=0){
  115. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  116. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  117. }
  118. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  119. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  120. foreach ($list['data'] as &$item) {
  121. $item['detail_img'] = isset($item['detail_img']) && $item['detail_img'] ? json_decode($item['detail_img'], true) : [];
  122. $item['supply_name'] = isset($supplyList[$item['supply_type']]) ? $supplyList[$item['supply_type']] : '';
  123. $item['usdt_price'] = $usdtPrice;
  124. $item['xd_price_rate'] = $xdPrice;
  125. $item['retail_price1'] = $item['retail_price'];
  126. $item['retail_price'] = $this->getRealSalePrice($item['cost_price']);
  127. }
  128. unset($item);
  129. } else {
  130. $this->updateGoods();
  131. }
  132. return [
  133. 'total' => isset($list['total']) ? $list['total'] : 9,
  134. 'pageSize' => $pageSize,
  135. 'list' => isset($list['data']) ? $list['data'] : [],
  136. ];
  137. }
  138. /**
  139. * 详情
  140. * @param $id
  141. * @return array
  142. */
  143. public function getInfo($goodsId, $userId=0, $updateView=true)
  144. {
  145. $field = ['a.*'];
  146. $info = $this->model->from('goods as a')->with(['category','skuList'])
  147. ->where(['a.goods_id'=> $goodsId,'a.status'=>1,'a.mark'=>1])
  148. ->select($field)
  149. ->first();
  150. $info = $info? $info->toArray() : [];
  151. if($info){
  152. if(isset($info['main_img'])){
  153. $info['main_img'] = $info['main_img']? get_image_url($info['main_img']) : '';
  154. }
  155. if(isset($info['detail_img'])){
  156. $info['detail_img'] = $info['detail_img']? json_decode($info['detail_img'], true) : [];
  157. }
  158. if(empty($info['detail_img'])){
  159. $info['detail_img'] = [$info['main_img']];
  160. }
  161. $supplyList = config('goods.supplyList');
  162. $info['supply_name'] = isset($supplyList[$info['supply_type']]) ? $supplyList[$info['supply_type']] : '';
  163. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  164. if($usdtPrice<=0){
  165. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  166. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  167. }
  168. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  169. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  170. $info['usdt_price_rate'] = $usdtPrice;
  171. $info['xd_price'] = $xdPrice;
  172. $info['custom_uid'] = ConfigService::make()->getConfigByCode('xl_custom_id',100001);
  173. if(isset($info['retail_price']) && $info['retail_price']){
  174. $info['retail_price1'] =$info['retail_price'];
  175. $info['retail_price'] = $this->getRealSalePrice($info['cost_price']);
  176. }
  177. if(isset($info['sku_list']) && $info['sku_list']){
  178. foreach ($info['sku_list'] as &$v){
  179. $v['detail_img'] = $v['detail_img']? json_decode($v['detail_img'], true) : [];
  180. $v['attr'] = $v['attr']? json_decode($v['attr'], true) : [];
  181. $v['main_img'] = $v['main_img']? get_image_url($v['main_img']) : '';
  182. $v['retail_price_1'] = $v['retail_price'];
  183. $v['retail_price'] = $this->getRealSalePrice($v['plat_price']);
  184. }
  185. unset($v);
  186. }
  187. // 更新访问量
  188. if($updateView){
  189. $this->updateView($userId, $goodsId);
  190. }
  191. }
  192. return $info;
  193. }
  194. /**
  195. * 实际售价
  196. * @param $price 成本价或其他价格
  197. * @param bool $float 是否浮动转换,1-浮动转换,2-不浮动转换,3-浮动不转换
  198. * @return string
  199. */
  200. public function getRealSalePrice($price, $float=1)
  201. {
  202. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  203. if($usdtPrice<=0){
  204. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  205. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  206. }
  207. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  208. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  209. $floatRate = ConfigService::make()->getConfigByCode('goods_price_float_rate', 0);
  210. $floatRate = $floatRate>0 && $floatRate<100? $floatRate : 0;
  211. $price = $float == 2? $price : floatval($price * (1 + ($floatRate/100)));
  212. if($float==3){
  213. return $price;
  214. }
  215. return $usdtPrice > 0 ? moneyFormat($price / $usdtPrice * $xdPrice, 2) : $price;
  216. }
  217. /**
  218. * 获取要购买或结算的商品列表
  219. * @param $userId
  220. * @param array $params
  221. * @return array|false|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
  222. */
  223. public function getBuyList($userId, $params=[])
  224. {
  225. $goodsId = isset($params['goods_id'])? $params['goods_id'] : 0;
  226. $skuId = isset($params['sku_id'])? $params['sku_id'] : 0;
  227. $num = isset($params['num'])? $params['num'] : 0;
  228. $cartIds = isset($params['cart_ids'])? $params['cart_ids'] : '';
  229. $cartIds = $cartIds? explode('|', $cartIds) : [];
  230. if(empty($goodsId) && empty($cartIds)){
  231. $this->error = 2901;
  232. return false;
  233. }
  234. if($goodsId && (empty($skuId) || $num<=0)){
  235. $this->error = 2901;
  236. return false;
  237. }
  238. $cacheKey = "caches:goods:buyList:{$userId}_".md5(json_encode($params,256));
  239. $datas = RedisService::get($cacheKey);
  240. if($datas){
  241. return $datas;
  242. }
  243. $goods = [];
  244. $skuList = [];
  245. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  246. if($usdtPrice<=0){
  247. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  248. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  249. }
  250. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  251. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  252. if($goodsId){
  253. $info = $this->getInfo($goodsId, $userId, false);
  254. if($info){
  255. $info['num'] = $num;
  256. $info['sku_id'] = $skuId;
  257. $skuInfo = GoodsSkuModel::where(['goods_id'=> $goodsId,'sku_id'=> $skuId,'mark'=>1])->first();
  258. $price = isset($skuInfo['plat_price'])? $skuInfo['plat_price'] : 0;
  259. if($price){
  260. $info['retail_price1'] = $info['retail_price'];
  261. $info['retail_price'] = $this->getRealSalePrice($price);
  262. }
  263. if(isset($skuInfo['attr']) && $skuInfo['attr']){
  264. $skuInfo['attr'] = json_decode($skuInfo['attr'], true);
  265. }
  266. $skuList[$goodsId] = [
  267. 'sku_id'=> $skuId,
  268. 'num'=> $num
  269. ];
  270. $info['sku'] = $skuInfo;
  271. $goods[] = $info;
  272. }
  273. }else {
  274. $goods = CartsModel::with(['sku'])->from('carts as a')
  275. ->leftJoin('goods as b','b.goods_id','=','a.goods_id')
  276. ->leftJoin('goods_sku as c','c.sku_id','=','a.sku_id')
  277. ->whereIn('a.id', $cartIds)
  278. ->where(['a.status' => 1, 'a.mark' => 1,'b.status'=>1,'b.mark'=>1])
  279. ->where('b.retail_price', '>', 0)
  280. ->where('a.num', '>', 0)
  281. ->select(['b.goods_id','b.merch_id','b.goods_name','b.supply_type','b.main_img','b.cost_price','b.retail_price','b.limit_num','b.lowest_num','b.brand_name','a.num','a.sku_id'])
  282. ->get();
  283. if($goods){
  284. // 价格等参数格式化
  285. $locale = RedisService::get("caches:locale:lang_{$userId}");
  286. $locale = $locale ? $locale : session('locale_lang');
  287. $locale = $locale ? $locale : 'zh-cn';
  288. $supplyList = config('goods.supplyList');
  289. foreach ($goods as &$item) {
  290. $item['detail_img'] = isset($item['detail_img']) && $item['detail_img'] ? json_decode($item['detail_img'], true) : [];
  291. $item['supply_name'] = isset($supplyList[$item['supply_type']]) ? $supplyList[$item['supply_type']] : '';
  292. $item['usdt_price'] = $usdtPrice;
  293. $item['xd_price_rate'] = $xdPrice;
  294. $item['retail_price1'] = $item['retail_price'];
  295. $skuInfo = isset($item['sku'])? $item['sku'] : [];
  296. if(isset($skuInfo['attr']) && $skuInfo['attr']){
  297. $skuInfo['attr'] = json_decode($skuInfo['attr'], true);
  298. }
  299. $item['sku'] = $skuInfo;
  300. $price = isset($skuInfo['plat_price'])? $skuInfo['plat_price'] : 0;
  301. if($price){
  302. $item['retail_price'] = $this->getRealSalePrice($price);
  303. }else{
  304. $item['retail_price'] = $this->getRealSalePrice($item['cost_price']);
  305. }
  306. $skuList[$item['goods_id']] = [
  307. 'sku_id'=> $item['sku_id'],
  308. 'num'=> $item['num']
  309. ];
  310. }
  311. unset($item);
  312. }
  313. }
  314. if(empty($goods)){
  315. $this->error = 2901;
  316. return false;
  317. }
  318. RedisService::set($cacheKey, ['sku_list'=> array_values($skuList), 'goods'=> $goods], rand(2,3));
  319. return ['sku_list'=> array_values($skuList), 'goods'=> $goods];
  320. }
  321. /**
  322. * 订单商品
  323. * @param $userId
  324. * @param $ids
  325. * @return array
  326. */
  327. public function getOrderGoods($userId, $ids)
  328. {
  329. $cacheKey = "caches:goodsOrder:{$userId}_".md5(json_encode($ids,256));
  330. $datas = RedisService::get($cacheKey);
  331. if($datas){
  332. return $datas;
  333. }
  334. $goods = $this->model->from('goods as a')
  335. ->whereIn('a.goods_id',$ids)
  336. ->where(['a.status' => 1, 'a.mark' => 1])
  337. ->where('a.retail_price', '>', 0)
  338. ->select(['a.goods_id','a.merch_id','a.goods_name','a.cate_id','a.supply_type','a.main_img','a.cost_price','a.retail_price'])
  339. ->get();
  340. $goods = $goods? $goods->toArray() : [];
  341. if($goods){
  342. RedisService::set($cacheKey, $goods, rand(5,10));
  343. }
  344. return $goods;
  345. }
  346. /**
  347. * 添加/更新购物车
  348. * @param $userId
  349. * @param $goodsId
  350. * @param $params
  351. * @return array|false
  352. */
  353. public function updateCart($userId, $goodsId, $params)
  354. {
  355. $skuId = isset($params['sku_id'])? $params['sku_id'] : 0;
  356. $status = isset($params['status'])? $params['status'] : 0;
  357. $merchId = isset($params['merch_id'])? $params['merch_id'] : 0;
  358. $num = isset($params['num'])? $params['num'] : 1;
  359. if($skuId<=0 || $goodsId<=0 || $userId<=0 || $num<=0){
  360. $this->error = 2014;
  361. return false;
  362. }
  363. if(CartsModel::where(['user_id'=> $userId,'status'=>1,'mark'=>1])->count('id') > 20){
  364. $this->error = 1050;
  365. return false;
  366. }
  367. $cartId = CartsModel::where(['user_id'=> $userId,'goods_id'=> $goodsId,'sku_id'=>$skuId])->value('id');
  368. if($cartId){
  369. CartsModel::where(['id'=> $cartId])->update(['num'=> $num,'merch_id'=>$merchId,'status'=> $status,'mark'=>1,'update_time'=>time()]);
  370. RedisService::clear("caches:members:cartList:{$userId}");
  371. $count = $this->getCartCount($userId,true);
  372. return ['id'=> $cartId,'count'=> $count];
  373. }else{
  374. $cartId = CartsModel::insertGetId(['user_id'=> $userId,'goods_id'=>$goodsId,'merch_id'=>$merchId,'sku_id'=>$skuId,'num'=> $num,'status'=> $status,'mark'=>1,'create_time'=>time()]);
  375. RedisService::clear("caches:members:cartList:{$userId}");
  376. $count = $this->getCartCount($userId, true);
  377. return ['id'=> $cartId,'count'=>$count];
  378. }
  379. }
  380. /**
  381. * 删除购物车商品
  382. * @param $userId
  383. * @param $params
  384. * @return bool
  385. */
  386. public function deleteCart($userId, $params)
  387. {
  388. $ids = isset($params['ids'])? $params['ids'] : [];
  389. if(empty($ids)){
  390. $this->error = 2923;
  391. return false;
  392. }
  393. CartsModel::whereIn('id', $ids)->update(['status'=>2,'update_time'=>time()]);
  394. $this->error = 1002;
  395. RedisService::clear("caches:members:cartCount:{$userId}");
  396. RedisService::clear("caches:members:cartList:{$userId}");
  397. return true;
  398. }
  399. /**
  400. * 购物车列表
  401. * @param $userId
  402. * @param int $pageSize
  403. * @return array|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|mixed
  404. */
  405. public function getCartList($userId, $pageSize = 30)
  406. {
  407. $cacheKey = "caches:members:cartList:{$userId}";
  408. $cacheCountKey = "caches:members:cartCount:{$userId}";
  409. $datas = RedisService::get($cacheKey);
  410. if($datas){
  411. return $datas;
  412. }
  413. $datas = CartsModel::with(['sku'])->from('carts as a')
  414. ->leftJoin('goods as b','b.goods_id','=','a.goods_id')
  415. ->leftJoin('goods_sku as c','c.sku_id','=','a.sku_id')
  416. ->where(['a.status' => 1, 'a.mark' => 1,'b.status'=>1,'b.mark'=>1])
  417. ->where('b.cost_price', '>', 0)
  418. ->where('a.num', '>', 0)
  419. ->select(['a.id as cart_id','b.goods_id','b.merch_id','b.goods_name','b.supply_type','b.main_img','b.cost_price','b.retail_price','b.limit_num','b.lowest_num','b.brand_name','a.num','a.sku_id'])
  420. ->orderBy('a.create_time','desc')
  421. ->limit($pageSize)
  422. ->get();
  423. $datas = $datas? $datas->toArray() : [];
  424. if($datas){
  425. // 价格等参数格式化
  426. $locale = RedisService::get("caches:locale:lang_{$userId}");
  427. $locale = $locale ? $locale : session('locale_lang');
  428. $locale = $locale ? $locale : 'zh-cn';
  429. $supplyList = config('goods.supplyList');
  430. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  431. if($usdtPrice<=0){
  432. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  433. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  434. }
  435. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  436. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  437. foreach ($datas as &$item) {
  438. $item['detail_img'] = isset($item['detail_img']) && $item['detail_img'] ? json_decode($item['detail_img'], true) : [];
  439. $item['supply_name'] = isset($supplyList[$item['supply_type']]) ? $supplyList[$item['supply_type']] : '';
  440. $item['usdt_price'] = $usdtPrice;
  441. $item['xd_price_rate'] = $xdPrice;
  442. $item['retail_price1'] = $item['retail_price'];
  443. $skuInfo = isset($item['sku'])? $item['sku'] : [];
  444. $skuInfo['attr'] = isset($skuInfo['attr'])&&$skuInfo['attr']? json_decode($skuInfo['attr'],true) : [];
  445. $item['sku'] = $skuInfo;
  446. $price = isset($skuInfo['plat_price'])? $skuInfo['plat_price'] : 0;
  447. if($price){
  448. $item['retail_price'] = $this->getRealSalePrice($price);
  449. }else{
  450. $item['retail_price'] = $this->getRealSalePrice($item['cost_price']);
  451. }
  452. }
  453. unset($item);
  454. RedisService::set($cacheCountKey, count($datas), rand(300, 600));
  455. RedisService::set($cacheKey, $datas, rand(300, 600));
  456. }
  457. return $datas;
  458. }
  459. /**
  460. * 购物车中数量
  461. * @param $userId
  462. * @return array|mixed
  463. */
  464. public function getCartCount($userId, $refresh = false)
  465. {
  466. $cacheKey = "caches:member:cartCount:{$userId}";
  467. $data = RedisService::get($cacheKey);
  468. if($data>0 && !$refresh){
  469. return $data;
  470. }
  471. $data = CartsModel::from('carts as a')
  472. ->leftJoin('goods as b','b.goods_id','=','a.goods_id')
  473. ->where(['a.status' => 1, 'a.mark' => 1,'b.status'=>1,'b.mark'=>1])
  474. ->where('a.num', '>', 0)
  475. ->where('b.cost_price', '>', 0)
  476. ->count('a.id');
  477. if($data){
  478. RedisService::set($cacheKey, $data, rand(300, 600));
  479. }
  480. return $data;
  481. }
  482. /**
  483. * 运费
  484. */
  485. public function getFreight($userId, $addressId,$skuList)
  486. {
  487. $cacheKey = "caches:goods:freight:{$userId}_{$addressId}_".md5(json_encode($skuList,256));
  488. $data = RedisService::get($cacheKey);
  489. if($data){
  490. return $data;
  491. }
  492. if(empty($addressId)){
  493. $address = MemberAddressService::make()->getBindInfo($userId);
  494. $streetCode = isset($address['street_code'])? $address['street_code'] : '';
  495. $addressId = $streetCode? $streetCode : (isset($address['district_code'])? $address['district_code'] : '');
  496. }
  497. $result = SupplyService::make()->getApiData('getFreight',['address_id'=> intval($addressId),'sku_list'=> $skuList]);
  498. $freight = isset($result['freight'])? floatval($result['freight']) : -1;
  499. if($freight>=0){
  500. // 价格参数
  501. $usdtPrice = RedisService::get("caches:wallets:usdt_rate");
  502. if($usdtPrice<=0){
  503. $usdtCnyPrice = ConfigService::make()->getConfigByCode('usdt_cny_price', 7.2);
  504. $usdtPrice = $usdtCnyPrice>0 && $usdtCnyPrice< 100? $usdtCnyPrice : 0;
  505. }
  506. $xdPrice = ConfigService::make()->getConfigByCode('xd_price', 100);
  507. $xdPrice = $xdPrice > 0 && $xdPrice <= 10000 ? $xdPrice : 100;
  508. $xdFreight = $freight? moneyFormat($freight/$usdtPrice * $xdPrice, 2) : 0;
  509. RedisService::set($cacheKey, ['freight'=>$xdFreight,'fee'=> $freight], rand(5,10));
  510. return ['freight'=>$xdFreight,'fee'=> $freight];
  511. }else{
  512. $errorCode = SupplyService::make()->getError();
  513. $this->error = $errorCode? $errorCode : 1052;
  514. return false;
  515. }
  516. }
  517. public function getSkuInfo($sakuId)
  518. {
  519. $cacheKey = "caches:goodsSku:{$sakuId}";
  520. $data = RedisService::get($cacheKey);
  521. if($data){
  522. return $data;
  523. }
  524. $data = GoodsSkuModel::where(['sku_id'=> $sakuId,'status'=>1,'mark'=>1])
  525. ->select(['id','sku_id','goods_id','retail_price','plat_price','sku_sn','sku_name','main_img','attr'])
  526. ->first();
  527. $data = $data? $data->toArray() : [];
  528. if($data){
  529. RedisService::set($cacheKey, $data, rand(3,5));
  530. }
  531. return $data;
  532. }
  533. /**
  534. * 更新浏览量
  535. * @param $userId
  536. * @param $dynamicId
  537. * @return array|mixed
  538. */
  539. public function updateView($userId, $id)
  540. {
  541. $cacheKey = "caches:goods:views:u{$userId}_d{$id}";
  542. $data = RedisService::get($cacheKey);
  543. if($data){
  544. return false;
  545. }
  546. $data = $this->model->where(['goods_id'=> $id])->update(['views'=>DB::raw('views + 1'),'update_time'=>time()]);
  547. RedisService::set($cacheKey, $id, rand(1,3)*7200);
  548. return $data;
  549. }
  550. /**
  551. * 更新商品SKU数据到本地
  552. * @param int $pageSize
  553. * @param $params 参数
  554. * @return array|false
  555. */
  556. public function updateGoodsSku($pageSize = 100, $params = [])
  557. {
  558. $cacheKey = "caches:supply:goods_sku_update_{$pageSize}";
  559. if (RedisService::get($cacheKey)) {
  560. $this->error = 1047;
  561. return false;
  562. }
  563. $page = RedisService::get($cacheKey . '_page');
  564. $page = $page ? $page + 1 : 1;
  565. $lastDate = GoodsSkuModel::where(['mark' => 1])->orderBy('last_update_at', 'desc')->value('last_update_at');
  566. $params = [
  567. 'limit' => $pageSize > 0 ? $pageSize : 50,
  568. 'page' => $page,
  569. 'date' => $lastDate ? $lastDate : '', // 开始时间
  570. ];
  571. $goods = [];
  572. $updated = 0;
  573. $error = 0;
  574. $datas = SupplyService::make()->getApiData('getSkuUpdate', $params);
  575. if ($datas && $datas['list']) {
  576. foreach ($datas['list'] as &$item) {
  577. $goodsId = isset($item['goods_id']) ? $item['goods_id'] : 0;
  578. $goodsSkuSn = isset($item['sku_sn']) ? $item['sku_sn'] : '';
  579. $changeType = isset($item['change_type']) ? $item['change_type'] : '';
  580. if ($goodsId && $goodsSkuSn && $changeType) {
  581. $skuInfo = SupplyService::make()->getApiData('getSkuDetail', ['sku_sn' => $goodsSkuSn]);
  582. if ($skuInfo) {
  583. $updateData = ['goods_id'=>$goodsId,'sku_sn'=> $goodsSkuSn,'remark'=>'SKU更新','update_time' => time(),'mark'=>1, 'last_update_at' => $item['update_time']];
  584. if (isset($skuInfo['sku_name']) && $skuInfo['sku_name']) {
  585. $updateData['sku_name'] = $skuInfo['sku_name'];
  586. }
  587. if (isset($skuInfo['main_img']) && $skuInfo['main_img']) {
  588. $updateData['main_img'] = $skuInfo['main_img'];
  589. }
  590. if (isset($skuInfo['spu_sn']) && $skuInfo['spu_sn']) {
  591. $updateData['spu_sn'] = $skuInfo['spu_sn'];
  592. }
  593. if (isset($skuInfo['sku_id']) && $skuInfo['sku_id']) {
  594. $updateData['sku_id'] = intval($skuInfo['sku_id']);
  595. }
  596. if (isset($skuInfo['status']) && $skuInfo['status']) {
  597. $updateData['status'] = intval($skuInfo['status']);
  598. }
  599. if (isset($skuInfo['retail_price']) && $skuInfo['retail_price']) {
  600. $updateData['retail_price'] = floatval($skuInfo['retail_price']);
  601. }
  602. if (isset($skuInfo['plat_price']) && $skuInfo['plat_price']) {
  603. $updateData['plat_price'] = floatval($skuInfo['plat_price']);
  604. }
  605. if (isset($skuInfo['detail_img']) && $skuInfo['detail_img']) {
  606. $updateData['detail_img'] = json_encode($skuInfo['detail_img'], 256);
  607. }
  608. if (isset($skuInfo['attr']) && $skuInfo['attr']) {
  609. $updateData['attr'] = json_encode($skuInfo['attr'], 256);
  610. }
  611. if(GoodsSkuModel::where(['goods_id' => $goodsId])->value('id')){
  612. GoodsSkuModel::where(['goods_id' => $goodsId, 'mark' => 1])->update($updateData);
  613. $updated++;
  614. }else{
  615. $error++;
  616. }
  617. } else {
  618. $error++;
  619. }
  620. } else {
  621. $error++;
  622. }
  623. }
  624. unset($item);
  625. RedisService::set($cacheKey . '_page', $page, rand(300, 600));
  626. }else{
  627. RedisService::set($cacheKey . '_page', 0, rand(300, 600));
  628. }
  629. return ['count' => count($goods), 'updated' => $updated, 'errorCount' => $error,'page'=>$page];
  630. }
  631. /**
  632. * 更新商品
  633. * @param int $pageSize
  634. * @param $params 参数
  635. * @return array|false
  636. */
  637. public function updateGoods($pageSize = 100, $params = [])
  638. {
  639. set_time_limit(0);
  640. $cacheKey = "caches:supply:goods_list_update_{$pageSize}";
  641. if (RedisService::get($cacheKey)) {
  642. $this->error = 1047;
  643. return false;
  644. }
  645. $size = ConfigService::make()->getConfigByCode('goods_update_limit', 0);
  646. $pageSize = $size>10 && $size < 500? $size : $pageSize;
  647. $page = RedisService::get($cacheKey . '_page');
  648. $page = $page ? $page + 1 : 1;
  649. $lastTime = $this->model->where(['mark' => 1])->orderBy('create_time', 'desc')->value('create_time');
  650. $params = [
  651. 'limit' => $pageSize > 0 ? $pageSize : 50,
  652. 'page' => $page,
  653. 'status' => isset($params['status']) ? $params['status'] : 1, // 状态:0-全部,1-上架的,2-下架的
  654. 'supply_type' => isset($params['supply_type']) ? $params['supply_type'] : 0, // 渠道商
  655. 'title' => isset($params['title']) ? $params['title'] : '', // 标题关键词
  656. 'cate_id' => isset($params['cate_id']) ? $params['cate_id'] : '', // 分类ID
  657. 'begin_time' => $lastTime ? $lastTime : '', // 开始时间
  658. ];
  659. $goods = [];
  660. $skus = [];
  661. $updated = 0;
  662. $error = 0;
  663. $datas = SupplyService::make()->getApiData('getGoodsList', $params);
  664. if ($datas && $datas['list']) {
  665. foreach ($datas['list'] as &$item) {
  666. $goodsId = isset($item['goods_id']) ? $item['goods_id'] : 0;
  667. if ($goodsId && !$this->checkGoods($goodsId)) {
  668. $info = $this->getApiInfo($goodsId);
  669. if ($info) {
  670. $skuList = isset($info['sku_list']) ? $info['sku_list'] : [];
  671. $goods[] = [
  672. 'goods_id' => $goodsId,
  673. 'supply_type' => isset($item['supply_type']) ? $item['supply_type'] : 0,
  674. 'spu_sn' => isset($item['spu_sn']) ? $item['spu_sn'] : '',
  675. 'spu_name' => isset($info['spu_name']) ? $info['spu_name'] : '',
  676. 'main_img' => isset($info['main_img']) ? $info['main_img'] : '',
  677. 'detail_img' => isset($info['detail_img']) ? json_encode($info['detail_img'], 256) : '',
  678. 'goods_name' => isset($item['goods_name']) ? $item['goods_name'] : '',
  679. 'brand_name' => isset($info['brand_name']) ? $info['brand_name'] : '',
  680. 'limit_num' => isset($info['limit_num']) ? intval($info['limit_num']) : 0,
  681. 'lowest_num' => isset($info['lowest_num']) ? intval($info['lowest_num']) : 1,
  682. 'cost_price' => isset($info['cost_price']) ? floatval($info['cost_price']) : 0,
  683. 'retail_price' => isset($info['retail_price']) ? floatval($info['retail_price']) : 0,
  684. 'profit' => isset($info['profit']) ? floatval($info['profit']) : 0,
  685. 'sku_list' => $skuList? json_encode($skuList,256):'',
  686. 'sku_total' => isset($info['sku_total']) ? intval($info['sku_total']) : 0,
  687. 'tag' => isset($item['tag']) ? json_encode($item['tag'], 256) : '',
  688. 'status' => isset($info['status']) ? intval($info['status']) : 1,
  689. 'cate_id' => isset($item['cate_id']) ? intval($item['cate_id']) : 0,
  690. 'last_update_at' => isset($info['update_time']) ? $info['update_time'] : (isset($item['time']) && $item['time'] ? $item['time'] : date('Y-m-d H:i:s')),
  691. 'create_time' => time(),
  692. ];
  693. foreach($skuList as $v){
  694. $skus[] = [
  695. 'sku_id'=> isset($v['sku_id'])? $v['sku_id'] : 0,
  696. 'goods_id'=> $goodsId,
  697. 'spu_sn'=> isset($v['spu_sn'])? $v['spu_sn'] : '',
  698. 'sku_sn'=> isset($v['sku_sn'])? $v['sku_sn'] : '',
  699. 'sku_name'=> isset($v['sku_name'])? $v['sku_name'] : '',
  700. 'main_img'=> isset($v['main_img'])? $v['main_img'] : '',
  701. 'status'=> isset($v['status'])? $v['status'] : 1,
  702. 'source_type'=> isset($v['source_type'])? $v['source_type'] : 0,
  703. 'retail_price'=> isset($v['retail_price'])? floatval($v['retail_price']) : 0,
  704. 'plat_price'=> isset($v['plat_price'])? floatval($v['plat_price']) : 0,
  705. 'profit'=> isset($v['profit'])? floatval($v['profit']) : 0,
  706. 'last_update_at'=> isset($v['update_time'])? $v['update_time'] : date('Y-m-d H:i:s'),
  707. 'detail_img'=> isset($v['detail_img'])? json_encode($v['detail_img'],256) : '',
  708. 'attr'=> isset($v['attr'])? json_encode($v['attr'],256) : '',
  709. 'remark'=>'SKU同步创建',
  710. ];
  711. }
  712. $updated++;
  713. } else {
  714. $error++;
  715. }
  716. } else {
  717. $error++;
  718. }
  719. }
  720. unset($item);
  721. } else {
  722. RedisService::set($cacheKey . '_page', 0, rand(300, 600));
  723. }
  724. if ($goods) {
  725. RedisService::set($cacheKey . '_page', $page, rand(300, 600));
  726. RedisService::set($cacheKey, $goods, rand(5, 10));
  727. DB::beginTransaction();
  728. try {
  729. $this->model->insertAll($goods);
  730. if($skus){
  731. GoodsSkuModel::insert($skus);
  732. }
  733. DB::commit();
  734. }catch (\Exception $exception){
  735. DB::rollBack();
  736. }
  737. }
  738. return ['count' => count($goods), 'updated' => $updated, 'errorCount' => $error,'page'=>$page];
  739. }
  740. /**
  741. * 更新商品分类
  742. * @param int $pid 上级ID
  743. * @param int $pageSize
  744. * @param $params 参数
  745. * @return array|false
  746. */
  747. public function updateGoodsCategory($pid=0, $pageSize = 200, $params = [])
  748. {
  749. set_time_limit(0);
  750. $cacheKey = "caches:supply:goods_category_update_{$pid}_{$pageSize}";
  751. if (RedisService::get($cacheKey)) {
  752. $this->error = 1047;
  753. return false;
  754. }
  755. $params = [
  756. 'limit' => $pageSize > 0 ? $pageSize : 50,
  757. 'page' => 1,
  758. 'pid' => $pid, // 上级ID
  759. ];
  760. $categorys = [];
  761. $updated = 0;
  762. $error = 0;
  763. $datas = SupplyService::make()->getApiData('getGoodsCategory', $params);
  764. if ($datas && $datas['data']) {
  765. foreach ($datas['data'] as &$item) {
  766. $cateId = isset($item['id']) ? $item['id'] : 0;
  767. if ($cateId && !$this->checkCategory($cateId)) {
  768. $categorys[] = [
  769. 'cate_id' => $cateId,
  770. 'name' => isset($item['name']) ? $item['name'] : '',
  771. 'pid' => isset($item['pid']) ? intval($item['pid']) : 0,
  772. 'create_time' => time(),
  773. ];
  774. $updated++;
  775. } else {
  776. $error++;
  777. }
  778. }
  779. unset($item);
  780. }
  781. if ($categorys) {
  782. RedisService::set($cacheKey, $categorys, rand(5, 10));
  783. GoodsCategoryModel::insert($categorys);
  784. }
  785. return ['count' => count($categorys), 'updated' => $updated,'pid'=>$pid, 'errorCount' => $error];
  786. }
  787. /**
  788. * 验证
  789. * @param $goodsId
  790. * @return bool
  791. */
  792. public function checkGoods($goodsId)
  793. {
  794. $cacheKey = "caches:goods:check_{$goodsId}";
  795. if (RedisService::get($cacheKey) || RedisService::exists($cacheKey)) {
  796. return true;
  797. }
  798. $data = $this->model->where(['goods_id' => $goodsId, 'mark' => 1])->value('id');
  799. RedisService::set($cacheKey, $data, rand(30, 60));
  800. return $data;
  801. }
  802. /**
  803. * 验证分类
  804. * @param $cateId
  805. * @return bool
  806. */
  807. public function checkCategory($cateId)
  808. {
  809. $cacheKey = "caches:goods:category_check_{$cateId}";
  810. if (RedisService::get($cacheKey) || RedisService::exists($cacheKey)) {
  811. return true;
  812. }
  813. $data = GoodsCategoryModel::where(['cate_id' => $cateId, 'mark' => 1])->value('id');
  814. RedisService::set($cacheKey, $data, rand(30, 60));
  815. return $data;
  816. }
  817. /**
  818. * 接口商品详情
  819. * @param $goodsId 商品ID
  820. * @param int $isReal 是否实时数据,0-是,1-否
  821. * @param int $type 数据类型:0-详情,1-仅SKU数据
  822. * @return array|false|mixed|string
  823. */
  824. public function getApiInfo($goodsId, $isReal = 0, $type = 0)
  825. {
  826. $cacheKey = "caches:goods:detail_{$goodsId}_{$isReal}_{$type}";
  827. $info = RedisService::get($cacheKey);
  828. if (empty($info)) {
  829. $params = [
  830. 'goods_id' => $goodsId,
  831. 'is_real' => $isReal,
  832. 'type' => $type
  833. ];
  834. $info = SupplyService::make()->getApiData('getGoodsDetail', $params);
  835. if ($info) {
  836. RedisService::set($cacheKey, $info, rand(5, 10));
  837. }
  838. }
  839. return $info;
  840. }
  841. public function apiCategory($num)
  842. {
  843. }
  844. }