HomePageModuleClass.php 37 KB

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