HomePageModuleClass.php 37 KB

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