GoodsService.php 41 KB

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