HomePageModuleClass.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. <?php
  2. namespace bizHd\homePageConfig\classes;
  3. use bizHd\goods\classes\GoodsClass;
  4. use bizHd\goods\classes\GoodsCategoryClass;
  5. use bizHd\goods\classes\GoodsUseCaseClass;
  6. use common\components\imgUtil;
  7. use common\components\util;
  8. use Yii;
  9. /**
  10. * 门店首页其余模块配置(金刚区/秒杀/团购/热门/上新/下拉商品)
  11. * 数据按 mainId 存 Redis,供 hdApp 配置、mallApp 读取展示。
  12. */
  13. class HomePageModuleClass
  14. {
  15. const REDIS_NAV_GRID = '_home_page_config_nav_grid';
  16. const REDIS_SECKILL = '_home_page_config_seckill';
  17. const REDIS_GROUP_BUY = '_home_page_config_group_buy';
  18. const REDIS_HOT = '_home_page_config_hot';
  19. const REDIS_NEW = '_home_page_config_new';
  20. const REDIS_PULL_GOODS = '_home_page_config_pull_goods';
  21. const NAV_OSS_ROOT = 'uploads_home_nav';
  22. const MAX_NAV_COUNT = 20;
  23. /** 关联:商品 */
  24. const LINK_GOODS = 2;
  25. /** 关联:分类 */
  26. const LINK_CATEGORY = 3;
  27. /** 关联:场景 */
  28. const LINK_USE_CASE = 4;
  29. /** 排序:按商品排序 */
  30. const SORT_PRODUCT = 1;
  31. /** 排序:按销量 */
  32. const SORT_SALES = 2;
  33. /** 排序:按上新时间 */
  34. const SORT_NEW = 3;
  35. /** 排列规则合法取值:1排1列/1排2列/1排3列 */
  36. const LAYOUT_COLS_OPTIONS = [1, 2, 3];
  37. /** 排列规则默认值 */
  38. const DEFAULT_LAYOUT_COLS = 3;
  39. /** 首页展示商品解析默认条数上限 */
  40. const DISPLAY_GOODS_LIMIT = 20;
  41. public static function redisKey($mainId, $suffix)
  42. {
  43. return intval($mainId) . $suffix;
  44. }
  45. public static function getJson($mainId, $suffix)
  46. {
  47. $raw = Yii::$app->redis->executeCommand('GET', [self::redisKey($mainId, $suffix)]);
  48. if (empty($raw)) {
  49. return [];
  50. }
  51. $data = json_decode($raw, true);
  52. return is_array($data) ? $data : [];
  53. }
  54. public static function setJson($mainId, $suffix, $payload)
  55. {
  56. Yii::$app->redis->executeCommand('SET', [
  57. self::redisKey($mainId, $suffix),
  58. json_encode($payload, JSON_UNESCAPED_UNICODE),
  59. ]);
  60. }
  61. public static function decodeList($raw)
  62. {
  63. if (is_string($raw)) {
  64. $decoded = json_decode($raw, true);
  65. return is_array($decoded) ? $decoded : [];
  66. }
  67. return is_array($raw) ? $raw : [];
  68. }
  69. // -------------------- 金刚区 --------------------
  70. public static function getNavGrid($mainId)
  71. {
  72. $mainId = intval($mainId);
  73. if ($mainId <= 0) {
  74. util::fail('无效门店');
  75. }
  76. $saved = self::getJson($mainId, self::REDIS_NAV_GRID);
  77. $cols = isset($saved['cols']) ? intval($saved['cols']) : 5;
  78. if (!in_array($cols, [4, 5], true)) {
  79. $cols = 5;
  80. }
  81. $list = [];
  82. foreach (self::decodeList($saved['list'] ?? []) as $item) {
  83. if (!is_array($item)) {
  84. continue;
  85. }
  86. $list[] = [
  87. 'id' => strval($item['id'] ?? ''),
  88. 'name' => strval($item['name'] ?? ''),
  89. 'icon' => strval($item['icon'] ?? ''),
  90. 'iconType' => intval($item['iconType'] ?? 1),
  91. 'enabled' => !empty($item['enabled']) ? 1 : 0,
  92. 'type' => intval($item['type'] ?? self::LINK_CATEGORY),
  93. 'value' => strval($item['value'] ?? ''),
  94. ];
  95. }
  96. return [
  97. 'enabled' => HomePageConfigClass::getModuleEnabled($mainId, 'navGrid'),
  98. 'cols' => $cols,
  99. 'list' => $list,
  100. ];
  101. }
  102. public static function saveNavGrid($mainId, $data)
  103. {
  104. $mainId = intval($mainId);
  105. if ($mainId <= 0) {
  106. util::fail('无效门店');
  107. }
  108. $enabled = !empty($data['enabled']) ? 1 : 0;
  109. $cols = isset($data['cols']) ? intval($data['cols']) : 5;
  110. if (!in_array($cols, [4, 5], true)) {
  111. util::fail('排列规则无效');
  112. }
  113. $rawList = self::decodeList($data['list'] ?? []);
  114. if (count($rawList) > self::MAX_NAV_COUNT) {
  115. util::fail('最多可配置' . self::MAX_NAV_COUNT . '个导航');
  116. }
  117. $list = [];
  118. foreach ($rawList as $index => $item) {
  119. if (!is_array($item)) {
  120. continue;
  121. }
  122. $name = trim(strval($item['name'] ?? ''));
  123. $icon = trim(strval($item['icon'] ?? ''));
  124. $type = intval($item['type'] ?? 0);
  125. $value = trim(strval($item['value'] ?? ''));
  126. $no = $index + 1;
  127. if ($name === '' || $icon === '' || $value === '') {
  128. util::fail("请完善第{$no}个导航项");
  129. }
  130. if (!in_array($type, [self::LINK_CATEGORY, self::LINK_USE_CASE], true)) {
  131. util::fail("第{$no}个导航关联类型无效");
  132. }
  133. $list[] = [
  134. 'id' => strval($item['id'] ?? ('nav_' . ($index + 1))),
  135. 'name' => mb_substr($name, 0, 20),
  136. 'icon' => $icon,
  137. 'iconType' => intval($item['iconType'] ?? 1) === 2 ? 2 : 1,
  138. 'enabled' => !empty($item['enabled']) ? 1 : 0,
  139. 'type' => $type,
  140. 'value' => $value,
  141. ];
  142. }
  143. self::setJson($mainId, self::REDIS_NAV_GRID, ['cols' => $cols, 'list' => $list]);
  144. HomePageConfigClass::updateModuleEnabled($mainId, 'navGrid', $enabled);
  145. return true;
  146. }
  147. // -------------------- 秒杀 --------------------
  148. public static function getSeckill($mainId, $refreshStock = true)
  149. {
  150. $mainId = intval($mainId);
  151. if ($mainId <= 0) {
  152. util::fail('无效门店');
  153. }
  154. $saved = self::getJson($mainId, self::REDIS_SECKILL);
  155. $data = self::normalizeActivityBase($saved);
  156. $data['enabled'] = HomePageConfigClass::getModuleEnabled($mainId, 'seckill');
  157. $data['goods'] = self::normalizeSeckillGoods($saved['goods'] ?? [], $mainId, $refreshStock);
  158. $data['status'] = self::calcActivityStatus($data['startTime'], $data['endTime'], $data['enabled']);
  159. return $data;
  160. }
  161. public static function saveSeckill($mainId, $data)
  162. {
  163. $mainId = intval($mainId);
  164. if ($mainId <= 0) {
  165. util::fail('无效门店');
  166. }
  167. $base = self::validateActivityBase($data);
  168. $goods = self::validateSeckillGoods($mainId, self::decodeList($data['goods'] ?? []));
  169. self::setJson($mainId, self::REDIS_SECKILL, array_merge($base, ['goods' => $goods]));
  170. HomePageConfigClass::updateModuleEnabled($mainId, 'seckill', !empty($data['enabled']) ? 1 : 0);
  171. return true;
  172. }
  173. /**
  174. * 校验并规范化秒杀商品;秒杀库存不得超过实际商品库存
  175. */
  176. public static function validateSeckillGoods($mainId, $rawList)
  177. {
  178. $list = [];
  179. foreach ($rawList as $index => $item) {
  180. if (!is_array($item)) {
  181. continue;
  182. }
  183. $no = $index + 1;
  184. $goodsId = intval($item['goodsId'] ?? 0);
  185. $price = floatval($item['price'] ?? 0);
  186. $stock = intval($item['stock'] ?? 0);
  187. $limit = intval($item['limit'] ?? 0);
  188. if ($goodsId <= 0) {
  189. util::fail("请选择第{$no}个秒杀商品");
  190. }
  191. if ($price <= 0) {
  192. util::fail("请填写第{$no}个秒杀价格");
  193. }
  194. if ($stock <= 0) {
  195. util::fail("请填写第{$no}个秒杀库存");
  196. }
  197. if ($limit <= 0) {
  198. util::fail("请填写第{$no}个单人限购");
  199. }
  200. $goods = GoodsClass::getById($goodsId, true);
  201. if (empty($goods) || intval($goods->mainId ?? 0) !== intval($mainId)) {
  202. util::fail("第{$no}个秒杀商品无效");
  203. }
  204. $realStock = intval($goods->stock ?? 0);
  205. // 秒杀库存不得超过实际库存
  206. if ($stock > $realStock) {
  207. util::fail("第{$no}个秒杀库存不能超过商品实际库存({$realStock})");
  208. }
  209. $status = !empty($item['status']) ? 1 : 0;
  210. // 实际库存已低于秒杀库存:自动下架该秒杀商品
  211. if ($realStock < $stock) {
  212. $status = 0;
  213. }
  214. $list[] = [
  215. 'goodsId' => $goodsId,
  216. 'price' => round($price, 2),
  217. 'stock' => $stock,
  218. 'limit' => $limit,
  219. 'status' => $status,
  220. 'name' => strval($goods->name ?? ($item['name'] ?? '')),
  221. 'cover' => strval($goods->shortCover ?? ($goods->cover ?? ($item['cover'] ?? ''))),
  222. 'originPrice' => floatval($goods->price ?? ($item['originPrice'] ?? 0)),
  223. ];
  224. }
  225. return $list;
  226. }
  227. /**
  228. * 读取时刷新秒杀商品状态:实际库存低于秒杀库存则下架,并回写 Redis
  229. */
  230. public static function normalizeSeckillGoods($rawList, $mainId, $refreshStock = true)
  231. {
  232. $list = [];
  233. $changed = false;
  234. foreach (self::decodeList($rawList) as $item) {
  235. if (!is_array($item) || empty($item['goodsId'])) {
  236. continue;
  237. }
  238. $row = [
  239. 'goodsId' => intval($item['goodsId']),
  240. 'price' => floatval($item['price'] ?? 0),
  241. 'stock' => intval($item['stock'] ?? 0),
  242. 'limit' => intval($item['limit'] ?? 0),
  243. 'status' => !empty($item['status']) ? 1 : 0,
  244. 'name' => strval($item['name'] ?? ''),
  245. 'cover' => strval($item['cover'] ?? ''),
  246. 'originPrice' => floatval($item['originPrice'] ?? 0),
  247. 'realStock' => intval($item['stock'] ?? 0),
  248. ];
  249. if ($refreshStock) {
  250. $goods = GoodsClass::getById($row['goodsId'], true);
  251. if (!empty($goods) && intval($goods->mainId ?? 0) === intval($mainId)) {
  252. $realStock = intval($goods->stock ?? 0);
  253. $row['realStock'] = $realStock;
  254. $row['name'] = strval($goods->name ?? $row['name']);
  255. $row['cover'] = strval($goods->shortCover ?? ($goods->cover ?? $row['cover']));
  256. $row['originPrice'] = floatval($goods->price ?? $row['originPrice']);
  257. if ($realStock < $row['stock'] && $row['status'] == 1) {
  258. $row['status'] = 0;
  259. $changed = true;
  260. }
  261. }
  262. }
  263. $list[] = $row;
  264. }
  265. if ($changed && $refreshStock) {
  266. $saved = self::getJson($mainId, self::REDIS_SECKILL);
  267. $persist = [];
  268. foreach ($list as $g) {
  269. $persist[] = [
  270. 'goodsId' => $g['goodsId'],
  271. 'price' => $g['price'],
  272. 'stock' => $g['stock'],
  273. 'limit' => $g['limit'],
  274. 'status' => $g['status'],
  275. 'name' => $g['name'],
  276. 'cover' => $g['cover'],
  277. 'originPrice' => $g['originPrice'],
  278. ];
  279. }
  280. $saved['goods'] = $persist;
  281. self::setJson($mainId, self::REDIS_SECKILL, $saved);
  282. }
  283. return $list;
  284. }
  285. // -------------------- 团购 --------------------
  286. public static function getGroupBuy($mainId, $refreshStock = true)
  287. {
  288. $mainId = intval($mainId);
  289. if ($mainId <= 0) {
  290. util::fail('无效门店');
  291. }
  292. $saved = self::getJson($mainId, self::REDIS_GROUP_BUY);
  293. $data = self::normalizeActivityBase($saved);
  294. $data['enabled'] = HomePageConfigClass::getModuleEnabled($mainId, 'groupBuy');
  295. $data['goods'] = self::normalizeGroupBuyGoods($saved['goods'] ?? [], $mainId, $refreshStock);
  296. $data['status'] = self::calcActivityStatus($data['startTime'], $data['endTime'], $data['enabled']);
  297. return $data;
  298. }
  299. public static function saveGroupBuy($mainId, $data)
  300. {
  301. $mainId = intval($mainId);
  302. if ($mainId <= 0) {
  303. util::fail('无效门店');
  304. }
  305. $base = self::validateActivityBase($data);
  306. $goods = self::validateGroupBuyGoods($mainId, self::decodeList($data['goods'] ?? []));
  307. self::setJson($mainId, self::REDIS_GROUP_BUY, array_merge($base, ['goods' => $goods]));
  308. HomePageConfigClass::updateModuleEnabled($mainId, 'groupBuy', !empty($data['enabled']) ? 1 : 0);
  309. return true;
  310. }
  311. public static function validateGroupBuyGoods($mainId, $rawList)
  312. {
  313. $list = [];
  314. foreach ($rawList as $index => $item) {
  315. if (!is_array($item)) {
  316. continue;
  317. }
  318. $no = $index + 1;
  319. $goodsId = intval($item['goodsId'] ?? 0);
  320. $price = floatval($item['price'] ?? 0);
  321. $stock = intval($item['stock'] ?? 0);
  322. $limit = intval($item['limit'] ?? 0);
  323. $groupSize = intval($item['groupSize'] ?? 3);
  324. if (!in_array($groupSize, [2, 3, 5], true)) {
  325. util::fail("第{$no}个成团人数无效");
  326. }
  327. if ($goodsId <= 0 || $price <= 0 || $stock <= 0 || $limit <= 0) {
  328. util::fail("请完善第{$no}个团购商品");
  329. }
  330. $goods = GoodsClass::getById($goodsId, true);
  331. if (empty($goods) || intval($goods->mainId ?? 0) !== intval($mainId)) {
  332. util::fail("第{$no}个团购商品无效");
  333. }
  334. $realStock = intval($goods->stock ?? 0);
  335. if ($stock > $realStock) {
  336. util::fail("第{$no}个团购库存不能超过商品实际库存({$realStock})");
  337. }
  338. $virtualGroup = !empty($item['virtualGroup']) ? 1 : 0;
  339. $virtualMinutes = intval($item['virtualMinutes'] ?? 0);
  340. if ($virtualGroup && $virtualMinutes <= 0) {
  341. util::fail("请填写第{$no}个虚拟成团时间");
  342. }
  343. $list[] = [
  344. 'goodsId' => $goodsId,
  345. 'price' => round($price, 2),
  346. 'stock' => $stock,
  347. 'limit' => $limit,
  348. 'groupSize' => $groupSize,
  349. 'virtualGroup' => $virtualGroup,
  350. 'virtualMinutes' => $virtualMinutes,
  351. 'autoRefund' => !empty($item['autoRefund']) ? 1 : 0,
  352. 'status' => ($realStock < $stock) ? 0 : (!empty($item['status']) ? 1 : 0),
  353. 'name' => strval($goods->name ?? ($item['name'] ?? '')),
  354. 'cover' => strval($goods->shortCover ?? ($goods->cover ?? ($item['cover'] ?? ''))),
  355. 'originPrice' => floatval($goods->price ?? ($item['originPrice'] ?? 0)),
  356. ];
  357. }
  358. return $list;
  359. }
  360. public static function normalizeGroupBuyGoods($rawList, $mainId, $refreshStock = true)
  361. {
  362. $list = [];
  363. $changed = false;
  364. foreach (self::decodeList($rawList) as $item) {
  365. if (!is_array($item) || empty($item['goodsId'])) {
  366. continue;
  367. }
  368. $row = [
  369. 'goodsId' => intval($item['goodsId']),
  370. 'price' => floatval($item['price'] ?? 0),
  371. 'stock' => intval($item['stock'] ?? 0),
  372. 'limit' => intval($item['limit'] ?? 0),
  373. 'groupSize' => intval($item['groupSize'] ?? 3),
  374. 'virtualGroup' => !empty($item['virtualGroup']) ? 1 : 0,
  375. 'virtualMinutes' => intval($item['virtualMinutes'] ?? 0),
  376. 'autoRefund' => !empty($item['autoRefund']) ? 1 : 0,
  377. 'status' => !empty($item['status']) ? 1 : 0,
  378. 'name' => strval($item['name'] ?? ''),
  379. 'cover' => strval($item['cover'] ?? ''),
  380. 'originPrice' => floatval($item['originPrice'] ?? 0),
  381. 'realStock' => intval($item['stock'] ?? 0),
  382. ];
  383. if ($refreshStock) {
  384. $goods = GoodsClass::getById($row['goodsId'], true);
  385. if (!empty($goods) && intval($goods->mainId ?? 0) === intval($mainId)) {
  386. $realStock = intval($goods->stock ?? 0);
  387. $row['realStock'] = $realStock;
  388. $row['name'] = strval($goods->name ?? $row['name']);
  389. $row['cover'] = strval($goods->shortCover ?? ($goods->cover ?? $row['cover']));
  390. $row['originPrice'] = floatval($goods->price ?? $row['originPrice']);
  391. if ($realStock < $row['stock'] && $row['status'] == 1) {
  392. $row['status'] = 0;
  393. $changed = true;
  394. }
  395. }
  396. }
  397. $list[] = $row;
  398. }
  399. if ($changed && $refreshStock) {
  400. $saved = self::getJson($mainId, self::REDIS_GROUP_BUY);
  401. $persist = [];
  402. foreach ($list as $g) {
  403. unset($g['realStock']);
  404. $persist[] = $g;
  405. }
  406. $saved['goods'] = $persist;
  407. self::setJson($mainId, self::REDIS_GROUP_BUY, $saved);
  408. }
  409. return $list;
  410. }
  411. // -------------------- 热门/上新/下拉 --------------------
  412. public static function getGoodsSection($mainId, $moduleKey)
  413. {
  414. $mainId = intval($mainId);
  415. $suffix = self::sectionSuffix($moduleKey);
  416. $saved = self::getJson($mainId, $suffix);
  417. $defaults = [
  418. 'hot' => '热门推荐',
  419. 'new' => '今日上新',
  420. 'pullGoods' => '更多商品',
  421. ];
  422. return [
  423. 'enabled' => HomePageConfigClass::getModuleEnabled($mainId, $moduleKey),
  424. 'name' => strval($saved['name'] ?? ($defaults[$moduleKey] ?? '')),
  425. 'type' => intval($saved['type'] ?? self::LINK_GOODS),
  426. 'value' => strval($saved['value'] ?? ''),
  427. 'sort' => intval($saved['sort'] ?? self::SORT_PRODUCT),
  428. 'layoutCols' => self::normalizeLayoutCols($saved['layoutCols'] ?? null),
  429. 'displayCount' => intval($saved['displayCount'] ?? 0),
  430. ];
  431. }
  432. public static function saveGoodsSection($mainId, $moduleKey, $data)
  433. {
  434. $mainId = intval($mainId);
  435. $suffix = self::sectionSuffix($moduleKey);
  436. $name = trim(strval($data['name'] ?? ''));
  437. $type = intval($data['type'] ?? 0);
  438. $value = trim(strval($data['value'] ?? ''));
  439. $sort = intval($data['sort'] ?? self::SORT_PRODUCT);
  440. $layoutCols = intval($data['layoutCols'] ?? self::DEFAULT_LAYOUT_COLS);
  441. $displayCount = self::normalizeDisplayCount($data['displayCount'] ?? 0);
  442. if ($name === '') {
  443. util::fail('请输入首页展示名称');
  444. }
  445. if (mb_strlen($name) > 20) {
  446. util::fail('展示名称不能超过20字');
  447. }
  448. if (!in_array($type, [self::LINK_GOODS, self::LINK_CATEGORY, self::LINK_USE_CASE], true)) {
  449. util::fail('关联类型无效');
  450. }
  451. if ($value === '') {
  452. util::fail('请选择关联内容');
  453. }
  454. if (!in_array($sort, [self::SORT_PRODUCT, self::SORT_SALES, self::SORT_NEW], true)) {
  455. util::fail('排序规则无效');
  456. }
  457. if (!in_array($layoutCols, self::LAYOUT_COLS_OPTIONS, true)) {
  458. util::fail('排列规则无效');
  459. }
  460. self::setJson($mainId, $suffix, [
  461. 'name' => $name,
  462. 'type' => $type,
  463. 'value' => $value,
  464. 'sort' => $sort,
  465. 'layoutCols' => $layoutCols,
  466. 'displayCount' => $displayCount,
  467. ]);
  468. HomePageConfigClass::updateModuleEnabled($mainId, $moduleKey, !empty($data['enabled']) ? 1 : 0);
  469. return true;
  470. }
  471. /**
  472. * 规范化排列规则取值,非法/缺省时回退默认值
  473. */
  474. public static function normalizeLayoutCols($cols)
  475. {
  476. $cols = intval($cols);
  477. return in_array($cols, self::LAYOUT_COLS_OPTIONS, true) ? $cols : self::DEFAULT_LAYOUT_COLS;
  478. }
  479. /**
  480. * 将热门推荐/今日上新/下拉商品的关联配置(type+value)解析为真实商品列表,用于首页展示
  481. * type=2 商品:value 为商品ID逗号拼接,按选择顺序展示
  482. * type=3 分类:value 为分类ID逗号拼接,取分类下全部商品
  483. * type=4 场景:value 为场景ID逗号拼接,取场景下全部商品
  484. * sort=1 按上面解析出的原始顺序;sort=2 按销量(虚拟+实际)降序;sort=3 按上架时间降序
  485. *
  486. * @param int $mainId
  487. * @param int $type
  488. * @param string $value
  489. * @param int $sort
  490. * @param int $limit
  491. * @return array [{id,name,price,stock,cover,coverUrl,sold}]
  492. */
  493. public static function resolveDisplayGoods($mainId, $type, $value, $sort, $limit = self::DISPLAY_GOODS_LIMIT)
  494. {
  495. $paged = self::resolveDisplayGoodsPaged($mainId, $type, $value, $sort, 1, $limit);
  496. return $paged['list'];
  497. }
  498. /**
  499. * 匹配关联配置下的全部商品行(未截断、未格式化封面URL),供分页与总数统计复用
  500. *
  501. * @param int $mainId
  502. * @param int $type
  503. * @param string $value
  504. * @param int $sort
  505. * @return array
  506. */
  507. public static function matchGoodsRows($mainId, $type, $value, $sort)
  508. {
  509. $mainId = intval($mainId);
  510. $type = intval($type);
  511. $value = trim(strval($value));
  512. if ($mainId <= 0 || $value === '') {
  513. return [];
  514. }
  515. $ids = array_values(array_unique(array_filter(array_map('intval', explode(',', $value)))));
  516. if (empty($ids)) {
  517. return [];
  518. }
  519. $goodsIds = [];
  520. if ($type === self::LINK_GOODS) {
  521. // 商品类型:保留用户选择顺序
  522. $goodsIds = $ids;
  523. } elseif ($type === self::LINK_CATEGORY) {
  524. $rows = GoodsCategoryClass::getAllByCondition(
  525. ['cId' => ['in', $ids], 'delStatus' => 0],
  526. null,
  527. 'gId'
  528. );
  529. $goodsIds = array_values(array_unique(array_map('intval', array_column($rows, 'gId'))));
  530. } elseif ($type === self::LINK_USE_CASE) {
  531. $rows = GoodsUseCaseClass::getAllByCondition(
  532. ['useCaseId' => ['in', $ids]],
  533. null,
  534. 'goodsId'
  535. );
  536. $goodsIds = array_values(array_unique(array_map('intval', array_column($rows, 'goodsId'))));
  537. }
  538. if (empty($goodsIds)) {
  539. return [];
  540. }
  541. // 注意:Base::getByIds 传入 $order 会走到未定义的 order() 方法而报错,这里统一取回后在 PHP 侧排序
  542. $rows = GoodsClass::getByIds($goodsIds, null, null, 'id,name,price,stock,cover,sold,actualSold,status,delStatus,masterId,mainId,createTime');
  543. // 仅取当前门店、未删除、上架中的主规格商品
  544. $rows = array_values(array_filter($rows, function ($row) use ($mainId) {
  545. return intval($row['mainId'] ?? 0) === $mainId
  546. && intval($row['delStatus'] ?? 0) === 0
  547. && intval($row['status'] ?? 0) === 1
  548. && intval($row['masterId'] ?? 0) === 0;
  549. }));
  550. if ($sort == self::SORT_SALES) {
  551. usort($rows, function ($a, $b) {
  552. $soldA = floatval($a['actualSold'] ?? 0) + floatval($a['sold'] ?? 0);
  553. $soldB = floatval($b['actualSold'] ?? 0) + floatval($b['sold'] ?? 0);
  554. return $soldB <=> $soldA;
  555. });
  556. } elseif ($sort == self::SORT_NEW) {
  557. usort($rows, function ($a, $b) {
  558. return strtotime($b['createTime'] ?? '') <=> strtotime($a['createTime'] ?? '');
  559. });
  560. } elseif ($type === self::LINK_GOODS) {
  561. // 商品类型按用户选择顺序重新排列;分类/场景按商品排序时无自定义顺序可依,保持数据库默认返回顺序
  562. $indexBy = [];
  563. foreach ($rows as $row) {
  564. $indexBy[intval($row['id'])] = $row;
  565. }
  566. $ordered = [];
  567. foreach ($goodsIds as $gid) {
  568. if (isset($indexBy[$gid])) {
  569. $ordered[] = $indexBy[$gid];
  570. }
  571. }
  572. $rows = $ordered;
  573. }
  574. return $rows;
  575. }
  576. /**
  577. * 将原始商品行格式化为首页/列表展示结构(含 coverUrl)
  578. *
  579. * @param array $rows
  580. * @return array
  581. */
  582. public static function formatGoodsRows($rows)
  583. {
  584. $list = [];
  585. foreach ($rows as $row) {
  586. $cover = strval($row['cover'] ?? '');
  587. $coverUrl = $cover !== '' ? imgUtil::groupImg($cover) . '?x-oss-process=image/resize,m_fill,h_700,w_700' : '';
  588. $list[] = [
  589. 'id' => intval($row['id']),
  590. 'name' => strval($row['name'] ?? ''),
  591. 'price' => floatval($row['price'] ?? 0),
  592. 'stock' => intval($row['stock'] ?? 0),
  593. 'cover' => $cover,
  594. 'coverUrl' => $coverUrl,
  595. 'sold' => intval(bcadd($row['actualSold'] ?? 0, $row['sold'] ?? 0)),
  596. ];
  597. }
  598. return $list;
  599. }
  600. /**
  601. * 分页解析关联配置下的商品列表,返回 list + total(真实总数,不受首页展示上限限制)
  602. *
  603. * @param int $mainId
  604. * @param int $type
  605. * @param string $value
  606. * @param int $sort
  607. * @param int $page
  608. * @param int $pageSize 传 0 表示不分页返回全部
  609. * @return array {list, total}
  610. */
  611. public static function resolveDisplayGoodsPaged($mainId, $type, $value, $sort, $page = 1, $pageSize = self::DISPLAY_GOODS_LIMIT)
  612. {
  613. $rows = self::matchGoodsRows($mainId, $type, $value, $sort);
  614. $total = count($rows);
  615. $page = max(1, intval($page));
  616. $pageSize = intval($pageSize);
  617. if ($pageSize > 0) {
  618. $rows = array_slice($rows, ($page - 1) * $pageSize, $pageSize);
  619. }
  620. return [
  621. 'list' => self::formatGoodsRows($rows),
  622. 'total' => $total,
  623. ];
  624. }
  625. /**
  626. * 规范化首页商品展示数量:0=全部,1-10=具体数量
  627. *
  628. * @param mixed $value
  629. * @return int
  630. */
  631. public static function normalizeDisplayCount($value)
  632. {
  633. if ($value === '' || $value === null || intval($value) === 0) {
  634. return 0;
  635. }
  636. $count = intval($value);
  637. if ($count < 1 || $count > 10) {
  638. util::fail('商品展示数量范围为1-10,留空表示全部');
  639. }
  640. return $count;
  641. }
  642. /**
  643. * 根据 displayCount 计算首页实际截断条数:1-10 用配置值,0(全部)回退默认上限
  644. *
  645. * @param mixed $displayCount
  646. * @return int
  647. */
  648. public static function resolveHomeDisplayLimit($displayCount)
  649. {
  650. $count = intval($displayCount);
  651. if ($count >= 1 && $count <= 10) {
  652. return $count;
  653. }
  654. return self::DISPLAY_GOODS_LIMIT;
  655. }
  656. public static function sectionSuffix($moduleKey)
  657. {
  658. $map = [
  659. 'hot' => self::REDIS_HOT,
  660. 'new' => self::REDIS_NEW,
  661. 'pullGoods' => self::REDIS_PULL_GOODS,
  662. ];
  663. if (!isset($map[$moduleKey])) {
  664. util::fail('无效模块');
  665. }
  666. return $map[$moduleKey];
  667. }
  668. // -------------------- 活动公共 --------------------
  669. public static function normalizeActivityBase($saved)
  670. {
  671. return [
  672. 'title' => strval($saved['title'] ?? ''),
  673. 'subtitle' => strval($saved['subtitle'] ?? ''),
  674. 'showCountdown' => !empty($saved['showCountdown']) ? 1 : 0,
  675. 'displayCount' => intval($saved['displayCount'] ?? 0),
  676. 'startTime' => intval($saved['startTime'] ?? 0),
  677. 'endTime' => intval($saved['endTime'] ?? 0),
  678. 'desc' => strval($saved['desc'] ?? ''),
  679. 'layoutCols' => self::normalizeLayoutCols($saved['layoutCols'] ?? null),
  680. ];
  681. }
  682. public static function validateActivityBase($data)
  683. {
  684. $title = trim(strval($data['title'] ?? ''));
  685. $subtitle = trim(strval($data['subtitle'] ?? ''));
  686. $desc = trim(strval($data['desc'] ?? ''));
  687. $startTime = intval($data['startTime'] ?? 0);
  688. $endTime = intval($data['endTime'] ?? 0);
  689. $layoutCols = intval($data['layoutCols'] ?? self::DEFAULT_LAYOUT_COLS);
  690. $displayCount = self::normalizeDisplayCount($data['displayCount'] ?? 0);
  691. if ($title === '') {
  692. util::fail('请输入活动标题');
  693. }
  694. if (mb_strlen($title) > 10) {
  695. util::fail('活动标题不能超过10字');
  696. }
  697. if ($subtitle === '') {
  698. util::fail('请输入活动副标题');
  699. }
  700. if (mb_strlen($subtitle) > 20) {
  701. util::fail('活动副标题不能超过20字');
  702. }
  703. if ($startTime <= 0 || $endTime <= 0) {
  704. util::fail('请选择活动时间');
  705. }
  706. if ($endTime <= $startTime) {
  707. util::fail('结束时间必须大于开始时间');
  708. }
  709. if ($desc === '') {
  710. util::fail('请输入活动说明');
  711. }
  712. if (mb_strlen($desc) > 500) {
  713. util::fail('活动说明不能超过500字');
  714. }
  715. if (!in_array($layoutCols, self::LAYOUT_COLS_OPTIONS, true)) {
  716. util::fail('排列规则无效');
  717. }
  718. return [
  719. 'title' => $title,
  720. 'subtitle' => $subtitle,
  721. 'showCountdown' => !empty($data['showCountdown']) ? 1 : 0,
  722. 'displayCount' => $displayCount,
  723. 'startTime' => $startTime,
  724. 'endTime' => $endTime,
  725. 'desc' => $desc,
  726. 'layoutCols' => $layoutCols,
  727. ];
  728. }
  729. /**
  730. * 活动状态:0未开始 1进行中 2已结束;模块关闭视为已结束展示用
  731. */
  732. public static function calcActivityStatus($startTime, $endTime, $enabled)
  733. {
  734. if (empty($enabled)) {
  735. return 2;
  736. }
  737. $now = time();
  738. $startTime = intval($startTime);
  739. $endTime = intval($endTime);
  740. if ($startTime <= 0 || $endTime <= 0) {
  741. return 0;
  742. }
  743. if ($now < $startTime) {
  744. return 0;
  745. }
  746. if ($now > $endTime) {
  747. return 2;
  748. }
  749. return 1;
  750. }
  751. }