HomePageModuleClass.php 35 KB

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