HomePageModuleClass.php 32 KB

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