feat: 지역 카드 좋아요·댓글을 시도 단위로 나눔 (계절·상식·한 문장·달은 전국)

This commit is contained in:
minaChoi committed 2026-10-08 09:33:04 +09:00
1 parent dddd52475e
commit 90c4a36c25
9 files changed
+175 -25

No files matched your search

+37 -7
View File
@@ -63,6 +63,19 @@ LINEUP = [
(19, PostType.MOON, RefType.NONE, None),
(20, PostType.UV, RefType.NONE, None),
]
# 좋아요·댓글 단위. 이 종류들은 전국이 같은 카드 하나, 나머지는 그 구 데이터로 채우는 카드라 시도마다 따로 만든다.
NATIONAL_SCOPE = "00"
NATIONAL_TYPES = frozenset({PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.MOON})
def sido_of(region_code: str) -> str:
"""구 행정코드의 시도 부분(앞 2자리)."""
return region_code[:2]
def post_scope(post_type: PostType, region_code: str) -> str:
return NATIONAL_SCOPE if post_type in NATIONAL_TYPES else sido_of(region_code)
# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위.
ORDER = {
"morning": [PostType.ALERT, PostType.AIR, PostType.UV, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.WEEKEND_PLAN, PostType.WEEKEND_PLAN, PostType.DAY_TRIP, PostType.MOON, PostType.QUOTE],
@@ -224,17 +237,33 @@ def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime
return head + rest
def _by_position(posts: list[Post]) -> list[Post]:
"""번호마다 하나. 전국 행과 시도 행이 같이 있으면 전국 행을 쓴다 (지역 카드라도 그날 전국 행이 있으면 전국이 그 행을 같이 쓴다)."""
out: dict[int, Post] = {}
for p in sorted(posts, key=lambda p: (p.position, p.scope != NATIONAL_SCOPE)):
out.setdefault(p.position, p)
return list(out.values())
def _top(i: IndexItem) -> TopIndex:
d = i.definition
return TopIndex(index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, score=i.score.score, rank=i.rank, summary=i.score.summary)
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) -> ErrorType:
"""그날 피드 카드를 넣는다. 이미 있는 번호는 그대로 두고, 새로 생긴 종류만 더한다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, regions: RegionCRUD) -> ErrorType:
"""그날 피드 카드를 전국 1벌·시도마다 1벌 넣는다. 이미 있는 (scope, 번호)는 그대로 두고, 빠진 것만 더한다.
전국 행이 있는 번호는 모든 시도가 그 행을 쓰므로 시도 행을 만들지 않는다. 모든 카드는 03:00 부터 다음 날 03:00 까지 유효하다."""
err, made = await DB_SESSION_MNG.execute_lambda(lambda s: crud.positions(s, day))
if err is not ErrorType.SUCCESS:
return err
lineup = [x for x in LINEUP if x[0] not in made]
err, all_regions = await DB_SESSION_MNG.execute_lambda(lambda s: regions.search(s))
if err is not ErrorType.SUCCESS:
return err
sidos = sorted({sido_of(r.code) for r in all_regions})
lineup = [
(scope, *x) for x in LINEUP for scope in ([NATIONAL_SCOPE] if x[1] in NATIONAL_TYPES else sidos)
if (scope, x[0]) not in made and (NATIONAL_SCOPE, x[0]) not in made
]
if not lineup:
return err
_, season = await DB_SESSION_MNG.execute_lambda(lambda s: season_crud.articles(s, day, ArticleCategory.SEASON.value))
@@ -243,12 +272,12 @@ async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD) ->
start = kst_midnight(day) + timedelta(hours=_FEED_DAY_START)
end = start + timedelta(days=1)
rows = []
for position, post_type, ref_type, rank in lineup:
for scope, position, post_type, ref_type, rank in lineup:
ref = refs.get(post_type)
if ref_type is RefType.ARTICLE and ref is None:
continue
rows.append({
"feed_date": day, "position": position, "post_type": post_type.value, "ref_type": ref_type.value,
"feed_date": day, "position": position, "scope": scope, "post_type": post_type.value, "ref_type": ref_type.value,
"ref_id": ref.article_id if ref is not None else None, "index_rank": rank,
"published_at": start, "end_at": end,
})
@@ -302,7 +331,7 @@ class FeedService:
day = feed_day(now)
async with redis_lock("lock:feed:build", ttl_sec=20):
await build_feed_day(day, self.crud, self.season_crud)
await build_feed_day(day, self.crud, self.season_crud, self.regions)
res, partial = await self._assemble(region, now, day, slot, sunset_at)
try:
await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at))
@@ -333,7 +362,8 @@ class FeedService:
_, hourly = await DB_SESSION_MNG.execute_lambda(
lambda s: self.weather_crud.hourly_between(s, region.code, hour, kst_midnight(now.date() + timedelta(days=2)))
)
_, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.day(s, day))
_, posts = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.day(s, day, [NATIONAL_SCOPE, sido_of(region.code)]))
posts = _by_position(posts or [])
_, articles = await DB_SESSION_MNG.execute_lambda(lambda s: self.season_crud.articles(s, now.date(), None))
by_article = {a.article_id: a for a in articles or []}
quotes = [a for a in articles or [] if a.category == ArticleCategory.QUOTE.value]