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