HomePageModuleClass.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  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. // 按已添加商品数量 + 展开开关动态推导列数与展示数量(不依赖商家手动配置)
  159. $layout = self::resolveActivityLayout(count($data['goods']), $data['expand']);
  160. $data['layoutCols'] = $layout['layoutCols'];
  161. $data['displayCount'] = $layout['displayCount'];
  162. $data['status'] = self::calcActivityStatus($data['startTime'], $data['endTime'], $data['enabled']);
  163. return $data;
  164. }
  165. public static function saveSeckill($mainId, $data)
  166. {
  167. $mainId = intval($mainId);
  168. if ($mainId <= 0) {
  169. util::fail('无效门店');
  170. }
  171. $base = self::validateActivityBase($data);
  172. $goods = self::validateSeckillGoods($mainId, self::decodeList($data['goods'] ?? []));
  173. self::setJson($mainId, self::REDIS_SECKILL, array_merge($base, ['goods' => $goods]));
  174. HomePageConfigClass::updateModuleEnabled($mainId, 'seckill', !empty($data['enabled']) ? 1 : 0);
  175. return true;
  176. }
  177. /**
  178. * 校验并规范化秒杀商品;秒杀库存不得超过实际商品库存
  179. */
  180. public static function validateSeckillGoods($mainId, $rawList)
  181. {
  182. $list = [];
  183. foreach ($rawList as $index => $item) {
  184. if (!is_array($item)) {
  185. continue;
  186. }
  187. $no = $index + 1;
  188. $goodsId = intval($item['goodsId'] ?? 0);
  189. $price = floatval($item['price'] ?? 0);
  190. $stock = intval($item['stock'] ?? 0);
  191. $limit = intval($item['limit'] ?? 0);
  192. if ($goodsId <= 0) {
  193. util::fail("请选择第{$no}个秒杀商品");
  194. }
  195. if ($price <= 0) {
  196. util::fail("请填写第{$no}个秒杀价格");
  197. }
  198. if ($stock <= 0) {
  199. util::fail("请填写第{$no}个秒杀库存");
  200. }
  201. if ($limit <= 0) {
  202. util::fail("请填写第{$no}个单人限购");
  203. }
  204. $goods = GoodsClass::getById($goodsId, true);
  205. if (empty($goods) || intval($goods->mainId ?? 0) !== intval($mainId)) {
  206. util::fail("第{$no}个秒杀商品无效");
  207. }
  208. $realStock = intval($goods->stock ?? 0);
  209. // 秒杀库存不得超过实际库存
  210. if ($stock > $realStock) {
  211. util::fail("第{$no}个秒杀库存不能超过商品实际库存({$realStock})");
  212. }
  213. $status = !empty($item['status']) ? 1 : 0;
  214. // 实际库存已低于秒杀库存:自动下架该秒杀商品
  215. if ($realStock < $stock) {
  216. $status = 0;
  217. }
  218. $list[] = [
  219. 'goodsId' => $goodsId,
  220. 'price' => round($price, 2),
  221. 'stock' => $stock,
  222. 'limit' => $limit,
  223. 'status' => $status,
  224. 'name' => strval($goods->name ?? ($item['name'] ?? '')),
  225. 'cover' => strval($goods->shortCover ?? ($goods->cover ?? ($item['cover'] ?? ''))),
  226. 'originPrice' => floatval($goods->price ?? ($item['originPrice'] ?? 0)),
  227. ];
  228. }
  229. return $list;
  230. }
  231. /**
  232. * 读取时刷新秒杀商品状态:实际库存低于秒杀库存则下架,并回写 Redis
  233. */
  234. public static function normalizeSeckillGoods($rawList, $mainId, $refreshStock = true)
  235. {
  236. $list = [];
  237. $changed = false;
  238. foreach (self::decodeList($rawList) as $item) {
  239. if (!is_array($item) || empty($item['goodsId'])) {
  240. continue;
  241. }
  242. $row = [
  243. 'goodsId' => intval($item['goodsId']),
  244. 'price' => floatval($item['price'] ?? 0),
  245. 'stock' => intval($item['stock'] ?? 0),
  246. 'limit' => intval($item['limit'] ?? 0),
  247. 'status' => !empty($item['status']) ? 1 : 0,
  248. 'name' => strval($item['name'] ?? ''),
  249. 'cover' => strval($item['cover'] ?? ''),
  250. 'originPrice' => floatval($item['originPrice'] ?? 0),
  251. 'realStock' => intval($item['stock'] ?? 0),
  252. ];
  253. if ($refreshStock) {
  254. $goods = GoodsClass::getById($row['goodsId'], true);
  255. if (!empty($goods) && intval($goods->mainId ?? 0) === intval($mainId)) {
  256. $realStock = intval($goods->stock ?? 0);
  257. $row['realStock'] = $realStock;
  258. $row['name'] = strval($goods->name ?? $row['name']);
  259. $row['cover'] = strval($goods->shortCover ?? ($goods->cover ?? $row['cover']));
  260. $row['originPrice'] = floatval($goods->price ?? $row['originPrice']);
  261. if ($realStock < $row['stock'] && $row['status'] == 1) {
  262. $row['status'] = 0;
  263. $changed = true;
  264. }
  265. }
  266. }
  267. $list[] = $row;
  268. }
  269. if ($changed && $refreshStock) {
  270. $saved = self::getJson($mainId, self::REDIS_SECKILL);
  271. $persist = [];
  272. foreach ($list as $g) {
  273. $persist[] = [
  274. 'goodsId' => $g['goodsId'],
  275. 'price' => $g['price'],
  276. 'stock' => $g['stock'],
  277. 'limit' => $g['limit'],
  278. 'status' => $g['status'],
  279. 'name' => $g['name'],
  280. 'cover' => $g['cover'],
  281. 'originPrice' => $g['originPrice'],
  282. ];
  283. }
  284. $saved['goods'] = $persist;
  285. self::setJson($mainId, self::REDIS_SECKILL, $saved);
  286. }
  287. return $list;
  288. }
  289. // -------------------- 团购 --------------------
  290. public static function getGroupBuy($mainId, $refreshStock = true)
  291. {
  292. $mainId = intval($mainId);
  293. if ($mainId <= 0) {
  294. util::fail('无效门店');
  295. }
  296. $saved = self::getJson($mainId, self::REDIS_GROUP_BUY);
  297. $data = self::normalizeActivityBase($saved);
  298. $data['enabled'] = HomePageConfigClass::getModuleEnabled($mainId, 'groupBuy');
  299. $data['goods'] = self::normalizeGroupBuyGoods($saved['goods'] ?? [], $mainId, $refreshStock);
  300. // 按已添加商品数量 + 展开开关动态推导列数与展示数量(不依赖商家手动配置)
  301. $layout = self::resolveActivityLayout(count($data['goods']), $data['expand']);
  302. $data['layoutCols'] = $layout['layoutCols'];
  303. $data['displayCount'] = $layout['displayCount'];
  304. $data['status'] = self::calcActivityStatus($data['startTime'], $data['endTime'], $data['enabled']);
  305. return $data;
  306. }
  307. public static function saveGroupBuy($mainId, $data)
  308. {
  309. $mainId = intval($mainId);
  310. if ($mainId <= 0) {
  311. util::fail('无效门店');
  312. }
  313. $base = self::validateActivityBase($data);
  314. $goods = self::validateGroupBuyGoods($mainId, self::decodeList($data['goods'] ?? []));
  315. self::setJson($mainId, self::REDIS_GROUP_BUY, array_merge($base, ['goods' => $goods]));
  316. HomePageConfigClass::updateModuleEnabled($mainId, 'groupBuy', !empty($data['enabled']) ? 1 : 0);
  317. return true;
  318. }
  319. public static function validateGroupBuyGoods($mainId, $rawList)
  320. {
  321. $list = [];
  322. foreach ($rawList as $index => $item) {
  323. if (!is_array($item)) {
  324. continue;
  325. }
  326. $no = $index + 1;
  327. $goodsId = intval($item['goodsId'] ?? 0);
  328. $price = floatval($item['price'] ?? 0);
  329. $stock = intval($item['stock'] ?? 0);
  330. $limit = intval($item['limit'] ?? 0);
  331. $groupSize = intval($item['groupSize'] ?? 3);
  332. if (!in_array($groupSize, [2, 3, 5], true)) {
  333. util::fail("第{$no}个成团人数无效");
  334. }
  335. if ($goodsId <= 0 || $price <= 0 || $stock <= 0 || $limit <= 0) {
  336. util::fail("请完善第{$no}个团购商品");
  337. }
  338. $goods = GoodsClass::getById($goodsId, true);
  339. if (empty($goods) || intval($goods->mainId ?? 0) !== intval($mainId)) {
  340. util::fail("第{$no}个团购商品无效");
  341. }
  342. $realStock = intval($goods->stock ?? 0);
  343. if ($stock > $realStock) {
  344. util::fail("第{$no}个团购库存不能超过商品实际库存({$realStock})");
  345. }
  346. $virtualGroup = !empty($item['virtualGroup']) ? 1 : 0;
  347. $virtualMinutes = intval($item['virtualMinutes'] ?? 0);
  348. if ($virtualGroup && $virtualMinutes <= 0) {
  349. util::fail("请填写第{$no}个虚拟成团时间");
  350. }
  351. $list[] = [
  352. 'goodsId' => $goodsId,
  353. 'price' => round($price, 2),
  354. 'stock' => $stock,
  355. 'limit' => $limit,
  356. 'groupSize' => $groupSize,
  357. 'virtualGroup' => $virtualGroup,
  358. 'virtualMinutes' => $virtualMinutes,
  359. 'autoRefund' => !empty($item['autoRefund']) ? 1 : 0,
  360. 'status' => ($realStock < $stock) ? 0 : (!empty($item['status']) ? 1 : 0),
  361. 'name' => strval($goods->name ?? ($item['name'] ?? '')),
  362. 'cover' => strval($goods->shortCover ?? ($goods->cover ?? ($item['cover'] ?? ''))),
  363. 'originPrice' => floatval($goods->price ?? ($item['originPrice'] ?? 0)),
  364. ];
  365. }
  366. return $list;
  367. }
  368. public static function normalizeGroupBuyGoods($rawList, $mainId, $refreshStock = true)
  369. {
  370. $list = [];
  371. $changed = false;
  372. foreach (self::decodeList($rawList) as $item) {
  373. if (!is_array($item) || empty($item['goodsId'])) {
  374. continue;
  375. }
  376. $row = [
  377. 'goodsId' => intval($item['goodsId']),
  378. 'price' => floatval($item['price'] ?? 0),
  379. 'stock' => intval($item['stock'] ?? 0),
  380. 'limit' => intval($item['limit'] ?? 0),
  381. 'groupSize' => intval($item['groupSize'] ?? 3),
  382. 'virtualGroup' => !empty($item['virtualGroup']) ? 1 : 0,
  383. 'virtualMinutes' => intval($item['virtualMinutes'] ?? 0),
  384. 'autoRefund' => !empty($item['autoRefund']) ? 1 : 0,
  385. 'status' => !empty($item['status']) ? 1 : 0,
  386. 'name' => strval($item['name'] ?? ''),
  387. 'cover' => strval($item['cover'] ?? ''),
  388. 'originPrice' => floatval($item['originPrice'] ?? 0),
  389. 'realStock' => intval($item['stock'] ?? 0),
  390. ];
  391. if ($refreshStock) {
  392. $goods = GoodsClass::getById($row['goodsId'], true);
  393. if (!empty($goods) && intval($goods->mainId ?? 0) === intval($mainId)) {
  394. $realStock = intval($goods->stock ?? 0);
  395. $row['realStock'] = $realStock;
  396. $row['name'] = strval($goods->name ?? $row['name']);
  397. $row['cover'] = strval($goods->shortCover ?? ($goods->cover ?? $row['cover']));
  398. $row['originPrice'] = floatval($goods->price ?? $row['originPrice']);
  399. if ($realStock < $row['stock'] && $row['status'] == 1) {
  400. $row['status'] = 0;
  401. $changed = true;
  402. }
  403. }
  404. }
  405. $list[] = $row;
  406. }
  407. if ($changed && $refreshStock) {
  408. $saved = self::getJson($mainId, self::REDIS_GROUP_BUY);
  409. $persist = [];
  410. foreach ($list as $g) {
  411. unset($g['realStock']);
  412. $persist[] = $g;
  413. }
  414. $saved['goods'] = $persist;
  415. self::setJson($mainId, self::REDIS_GROUP_BUY, $saved);
  416. }
  417. return $list;
  418. }
  419. // -------------------- 热门/上新/下拉 --------------------
  420. public static function getGoodsSection($mainId, $moduleKey)
  421. {
  422. $mainId = intval($mainId);
  423. $suffix = self::sectionSuffix($moduleKey);
  424. $saved = self::getJson($mainId, $suffix);
  425. $defaults = [
  426. 'hot' => '热门推荐',
  427. 'new' => '今日上新',
  428. 'pullGoods' => '更多商品',
  429. ];
  430. return [
  431. 'enabled' => HomePageConfigClass::getModuleEnabled($mainId, $moduleKey),
  432. 'name' => strval($saved['name'] ?? ($defaults[$moduleKey] ?? '')),
  433. 'type' => intval($saved['type'] ?? self::LINK_GOODS),
  434. 'value' => strval($saved['value'] ?? ''),
  435. 'sort' => intval($saved['sort'] ?? self::SORT_PRODUCT),
  436. ];
  437. }
  438. public static function saveGoodsSection($mainId, $moduleKey, $data)
  439. {
  440. $mainId = intval($mainId);
  441. $suffix = self::sectionSuffix($moduleKey);
  442. $name = trim(strval($data['name'] ?? ''));
  443. $type = intval($data['type'] ?? 0);
  444. $value = trim(strval($data['value'] ?? ''));
  445. $sort = intval($data['sort'] ?? self::SORT_PRODUCT);
  446. // layoutCols/displayCount 由读取时按真实商品数量自动推导,保存时不再接收商家手动配置
  447. if ($name === '') {
  448. util::fail('请输入首页展示名称');
  449. }
  450. if (mb_strlen($name) > 20) {
  451. util::fail('展示名称不能超过20字');
  452. }
  453. if (!in_array($type, [self::LINK_GOODS, self::LINK_CATEGORY, self::LINK_USE_CASE], true)) {
  454. util::fail('关联类型无效');
  455. }
  456. if ($value === '') {
  457. util::fail('请选择关联内容');
  458. }
  459. if (!in_array($sort, [self::SORT_PRODUCT, self::SORT_SALES, self::SORT_NEW], true)) {
  460. util::fail('排序规则无效');
  461. }
  462. self::setJson($mainId, $suffix, [
  463. 'name' => $name,
  464. 'type' => $type,
  465. 'value' => $value,
  466. 'sort' => $sort,
  467. ]);
  468. HomePageConfigClass::updateModuleEnabled($mainId, $moduleKey, !empty($data['enabled']) ? 1 : 0);
  469. return true;
  470. }
  471. /**
  472. * 按真实商品总数与模块类型自动推导首页列数与展示数量
  473. * - 1个商品:1排1列,展示全部
  474. * - 2个商品:1排2列,展示全部
  475. * - ≥3个:hot/new 按1排3列且只展示3个;pullGoods 按1排2列且展示全部
  476. *
  477. * @param int $goodsTotal 关联配置解析出的真实商品总数
  478. * @param string $moduleKey hot|new|pullGoods
  479. * @return array{layoutCols:int,displayCount:int}
  480. */
  481. public static function resolveGoodsSectionLayout($goodsTotal, $moduleKey)
  482. {
  483. $goodsTotal = intval($goodsTotal);
  484. if ($goodsTotal <= 1) {
  485. return ['layoutCols' => 1, 'displayCount' => 0];
  486. }
  487. if ($goodsTotal === 2) {
  488. return ['layoutCols' => 2, 'displayCount' => 0];
  489. }
  490. if ($moduleKey === 'pullGoods') {
  491. return ['layoutCols' => 2, 'displayCount' => 0];
  492. }
  493. return ['layoutCols' => 3, 'displayCount' => 3];
  494. }
  495. /**
  496. * 规范化排列规则取值,非法/缺省时回退默认值
  497. */
  498. public static function normalizeLayoutCols($cols)
  499. {
  500. $cols = intval($cols);
  501. return in_array($cols, self::LAYOUT_COLS_OPTIONS, true) ? $cols : self::DEFAULT_LAYOUT_COLS;
  502. }
  503. /**
  504. * 将热门推荐/今日上新/下拉商品的关联配置(type+value)解析为真实商品列表,用于首页展示
  505. * type=2 商品:value 为商品ID逗号拼接,按选择顺序展示
  506. * type=3 分类:value 为分类ID逗号拼接,取分类下全部商品
  507. * type=4 场景:value 为场景ID逗号拼接,取场景下全部商品
  508. * sort=1 按上面解析出的原始顺序;sort=2 按销量(虚拟+实际)降序;sort=3 按上架时间降序
  509. *
  510. * @param int $mainId
  511. * @param int $type
  512. * @param string $value
  513. * @param int $sort
  514. * @param int $limit
  515. * @return array [{id,name,price,stock,cover,coverUrl,sold}]
  516. */
  517. public static function resolveDisplayGoods($mainId, $type, $value, $sort, $limit = self::DISPLAY_GOODS_LIMIT)
  518. {
  519. $paged = self::resolveDisplayGoodsPaged($mainId, $type, $value, $sort, 1, $limit);
  520. return $paged['list'];
  521. }
  522. /**
  523. * 匹配关联配置下的全部商品行(未截断、未格式化封面URL),供分页与总数统计复用
  524. *
  525. * @param int $mainId
  526. * @param int $type
  527. * @param string $value
  528. * @param int $sort
  529. * @return array
  530. */
  531. public static function matchGoodsRows($mainId, $type, $value, $sort)
  532. {
  533. $mainId = intval($mainId);
  534. $type = intval($type);
  535. $value = trim(strval($value));
  536. if ($mainId <= 0 || $value === '') {
  537. return [];
  538. }
  539. $ids = array_values(array_unique(array_filter(array_map('intval', explode(',', $value)))));
  540. if (empty($ids)) {
  541. return [];
  542. }
  543. $goodsIds = [];
  544. if ($type === self::LINK_GOODS) {
  545. // 商品类型:保留用户选择顺序
  546. $goodsIds = $ids;
  547. } elseif ($type === self::LINK_CATEGORY) {
  548. $rows = GoodsCategoryClass::getAllByCondition(
  549. ['cId' => ['in', $ids], 'delStatus' => 0],
  550. null,
  551. 'gId'
  552. );
  553. $goodsIds = array_values(array_unique(array_map('intval', array_column($rows, 'gId'))));
  554. } elseif ($type === self::LINK_USE_CASE) {
  555. $rows = GoodsUseCaseClass::getAllByCondition(
  556. ['useCaseId' => ['in', $ids]],
  557. null,
  558. 'goodsId'
  559. );
  560. $goodsIds = array_values(array_unique(array_map('intval', array_column($rows, 'goodsId'))));
  561. }
  562. if (empty($goodsIds)) {
  563. return [];
  564. }
  565. // 注意:Base::getByIds 传入 $order 会走到未定义的 order() 方法而报错,这里统一取回后在 PHP 侧排序
  566. $rows = GoodsClass::getByIds($goodsIds, null, null, 'id,name,price,stock,cover,sold,actualSold,status,delStatus,masterId,mainId,createTime');
  567. // 仅取当前门店、未删除、上架中的主规格商品
  568. $rows = array_values(array_filter($rows, function ($row) use ($mainId) {
  569. return intval($row['mainId'] ?? 0) === $mainId
  570. && intval($row['delStatus'] ?? 0) === 0
  571. && intval($row['status'] ?? 0) === 1
  572. && intval($row['masterId'] ?? 0) === 0;
  573. }));
  574. if ($sort == self::SORT_SALES) {
  575. usort($rows, function ($a, $b) {
  576. $soldA = floatval($a['actualSold'] ?? 0) + floatval($a['sold'] ?? 0);
  577. $soldB = floatval($b['actualSold'] ?? 0) + floatval($b['sold'] ?? 0);
  578. return $soldB <=> $soldA;
  579. });
  580. } elseif ($sort == self::SORT_NEW) {
  581. usort($rows, function ($a, $b) {
  582. return strtotime($b['createTime'] ?? '') <=> strtotime($a['createTime'] ?? '');
  583. });
  584. } elseif ($type === self::LINK_GOODS) {
  585. // 商品类型按用户选择顺序重新排列;分类/场景按商品排序时无自定义顺序可依,保持数据库默认返回顺序
  586. $indexBy = [];
  587. foreach ($rows as $row) {
  588. $indexBy[intval($row['id'])] = $row;
  589. }
  590. $ordered = [];
  591. foreach ($goodsIds as $gid) {
  592. if (isset($indexBy[$gid])) {
  593. $ordered[] = $indexBy[$gid];
  594. }
  595. }
  596. $rows = $ordered;
  597. }
  598. return $rows;
  599. }
  600. /**
  601. * 将原始商品行格式化为首页/列表展示结构(含 coverUrl)
  602. *
  603. * @param array $rows
  604. * @return array
  605. */
  606. public static function formatGoodsRows($rows)
  607. {
  608. $list = [];
  609. $goodsIds = [];
  610. foreach ($rows as $row) {
  611. $goodsIds[] = intval($row['id'] ?? 0);
  612. }
  613. $specEnabledMap = GoodsClass::getSpecEnabledMap($goodsIds);
  614. foreach ($rows as $row) {
  615. $id = intval($row['id']);
  616. $cover = strval($row['cover'] ?? '');
  617. $coverUrl = $cover !== '' ? imgUtil::groupImg($cover) . '?x-oss-process=image/resize,m_fill,h_700,w_700' : '';
  618. $list[] = [
  619. 'id' => $id,
  620. 'name' => strval($row['name'] ?? ''),
  621. 'price' => floatval($row['price'] ?? 0),
  622. 'stock' => intval($row['stock'] ?? 0),
  623. 'cover' => $cover,
  624. 'coverUrl' => $coverUrl,
  625. 'sold' => intval(bcadd($row['actualSold'] ?? 0, $row['sold'] ?? 0)),
  626. 'specEnabled' => intval($specEnabledMap[$id] ?? 0),
  627. ];
  628. }
  629. return $list;
  630. }
  631. /**
  632. * 分页解析关联配置下的商品列表,返回 list + total(真实总数,不受首页展示上限限制)
  633. *
  634. * @param int $mainId
  635. * @param int $type
  636. * @param string $value
  637. * @param int $sort
  638. * @param int $page
  639. * @param int $pageSize 传 0 表示不分页返回全部
  640. * @return array {list, total}
  641. */
  642. public static function resolveDisplayGoodsPaged($mainId, $type, $value, $sort, $page = 1, $pageSize = self::DISPLAY_GOODS_LIMIT)
  643. {
  644. $rows = self::matchGoodsRows($mainId, $type, $value, $sort);
  645. $total = count($rows);
  646. $page = max(1, intval($page));
  647. $pageSize = intval($pageSize);
  648. if ($pageSize > 0) {
  649. $rows = array_slice($rows, ($page - 1) * $pageSize, $pageSize);
  650. }
  651. return [
  652. 'list' => self::formatGoodsRows($rows),
  653. 'total' => $total,
  654. ];
  655. }
  656. /**
  657. * 根据 displayCount 计算首页实际截断条数:1-10 用配置值,0(全部)回退默认上限
  658. * 供秒杀/团购等活动模块使用
  659. *
  660. * @param mixed $displayCount
  661. * @return int
  662. */
  663. public static function resolveHomeDisplayLimit($displayCount)
  664. {
  665. $count = intval($displayCount);
  666. if ($count >= 1 && $count <= 10) {
  667. return $count;
  668. }
  669. return self::DISPLAY_GOODS_LIMIT;
  670. }
  671. public static function sectionSuffix($moduleKey)
  672. {
  673. $map = [
  674. 'hot' => self::REDIS_HOT,
  675. 'new' => self::REDIS_NEW,
  676. 'pullGoods' => self::REDIS_PULL_GOODS,
  677. ];
  678. if (!isset($map[$moduleKey])) {
  679. util::fail('无效模块');
  680. }
  681. return $map[$moduleKey];
  682. }
  683. // -------------------- 活动公共 --------------------
  684. public static function normalizeActivityBase($saved)
  685. {
  686. return [
  687. 'title' => strval($saved['title'] ?? ''),
  688. 'subtitle' => strval($saved['subtitle'] ?? ''),
  689. 'showCountdown' => !empty($saved['showCountdown']) ? 1 : 0,
  690. // 商品展开:开启后首页按1排1列展示全部商品,默认关闭
  691. 'expand' => !empty($saved['expand']) ? 1 : 0,
  692. 'startTime' => intval($saved['startTime'] ?? 0),
  693. 'endTime' => intval($saved['endTime'] ?? 0),
  694. 'desc' => strval($saved['desc'] ?? ''),
  695. ];
  696. }
  697. /**
  698. * 按已添加商品数量与「商品展开」开关自动推导首页列数与展示数量
  699. * - expand 开启:1排1列,展示全部
  700. * - 1个商品:1排1列;2个:1排2列;≥3个:1排3列且只展示3个
  701. *
  702. * @param int $goodsCount 已添加商品总数(含未上架)
  703. * @param int $expand 商品展开开关 0/1
  704. * @return array{layoutCols:int,displayCount:int}
  705. */
  706. public static function resolveActivityLayout($goodsCount, $expand)
  707. {
  708. if (!empty($expand)) {
  709. return ['layoutCols' => 1, 'displayCount' => 0];
  710. }
  711. $goodsCount = intval($goodsCount);
  712. if ($goodsCount <= 1) {
  713. return ['layoutCols' => 1, 'displayCount' => 0];
  714. }
  715. if ($goodsCount === 2) {
  716. return ['layoutCols' => 2, 'displayCount' => 0];
  717. }
  718. return ['layoutCols' => 3, 'displayCount' => 3];
  719. }
  720. public static function validateActivityBase($data)
  721. {
  722. $title = trim(strval($data['title'] ?? ''));
  723. $subtitle = trim(strval($data['subtitle'] ?? ''));
  724. $desc = trim(strval($data['desc'] ?? ''));
  725. $startTime = intval($data['startTime'] ?? 0);
  726. $endTime = intval($data['endTime'] ?? 0);
  727. // layoutCols/displayCount 由读取时按商品数量自动推导,保存时不再接收商家手动配置
  728. if ($title === '') {
  729. util::fail('请输入活动标题');
  730. }
  731. if (mb_strlen($title) > 10) {
  732. util::fail('活动标题不能超过10字');
  733. }
  734. if ($subtitle === '') {
  735. util::fail('请输入活动副标题');
  736. }
  737. if (mb_strlen($subtitle) > 20) {
  738. util::fail('活动副标题不能超过20字');
  739. }
  740. if ($startTime <= 0 || $endTime <= 0) {
  741. util::fail('请选择活动时间');
  742. }
  743. if ($endTime <= $startTime) {
  744. util::fail('结束时间必须大于开始时间');
  745. }
  746. if ($desc === '') {
  747. util::fail('请输入活动说明');
  748. }
  749. if (mb_strlen($desc) > 500) {
  750. util::fail('活动说明不能超过500字');
  751. }
  752. return [
  753. 'title' => $title,
  754. 'subtitle' => $subtitle,
  755. 'showCountdown' => !empty($data['showCountdown']) ? 1 : 0,
  756. 'expand' => !empty($data['expand']) ? 1 : 0,
  757. 'startTime' => $startTime,
  758. 'endTime' => $endTime,
  759. 'desc' => $desc,
  760. ];
  761. }
  762. /**
  763. * 活动状态:0未开始 1进行中 2已结束;模块关闭视为已结束展示用
  764. */
  765. public static function calcActivityStatus($startTime, $endTime, $enabled)
  766. {
  767. if (empty($enabled)) {
  768. return 2;
  769. }
  770. $now = time();
  771. $startTime = intval($startTime);
  772. $endTime = intval($endTime);
  773. if ($startTime <= 0 || $endTime <= 0) {
  774. return 0;
  775. }
  776. if ($now < $startTime) {
  777. return 0;
  778. }
  779. if ($now > $endTime) {
  780. return 2;
  781. }
  782. return 1;
  783. }
  784. }