HomePageModuleClass.php 37 KB

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