diff --git a/TODO.md b/TODO.md index c17e46c..6d7b91d 100644 --- a/TODO.md +++ b/TODO.md @@ -7,7 +7,7 @@ | [ ] | 가중치 재검토 | 10/6 회의 | `backend/seed/index_definition.json` | | [x] | 댓글·좋아요·로그인 API 테스트 (화면 확인은 아직) | 시연 때 미검증 | `backend/services/reaction_service.py`, `backend/services/auth_service.py` | | [x] | 주말 날씨 평일 상시 노출 + 다음 주 주말까지 (예보 닿는 +10일부터) | 10/6 회의 | `backend/services/week_service.py` | -| [ ] | 행사 독립 카드, 피드 무작위 노출 | 10/6 회의 | `backend/services/feed_service.py` | +| [x] | 행사 독립 카드 최대 3장, 피드 무작위 노출 (하루 같은 자리) | 10/6 회의 | `backend/services/feed_service.py` | | [ ] | 계절 소식 제철 정보 확충 | 10/6 회의 | `backend/seed/article.json` | | [x] | 새 각 추가 (야구·공부·넷플릭스·군밤) | 10/6 회의 | `backend/seed/index_definition.json` | | [x] | 지역 단위 조정 (서울 구, 그 외 시·군, 광역시 자치구 유지) | 10/6 회의 | `backend/seed/region.csv`, `backend/seed/ranking_spot.csv` | @@ -17,3 +17,4 @@ | [ ] | 습도 최적값을 30%대로 둘지 결정 (지금은 편한 범위 가운데) | 10/6 회의 예시 "습도 30%" | `backend/seed/index_definition.json` | | [ ] | 예전 일반구 코드를 저장한 브라우저는 지역을 못 찾음 → 시 코드로 넘겨줄지 | 일반구 → 시 합침 | `frontend/src/b/region.tsx` | | [ ] | 지역 격자(nx/ny)가 좌표와 안 맞는 1곳 확인 (4775000000) | 지역 합치며 발견 | `backend/seed/region.csv` | +| [ ] | 처음 보는 지역의 첫 피드에 각 카드가 빠진 채 캐시됨 (최대 1시간) | 행사 카드 확인 중 발견 (부산 해운대구) | `backend/services/feed_service.py` | diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index 6262c95..0ced372 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -1,4 +1,5 @@ import asyncio +import random from dataclasses import dataclass from datetime import date, datetime, time, timedelta from typing import Optional @@ -41,17 +42,19 @@ LINEUP = [ (6, PostType.SUNSET, RefType.NONE, None), (7, PostType.TOMORROW, RefType.NONE, None), (8, PostType.WEEK, RefType.NONE, None), - (9, PostType.EVENT, RefType.NONE, None), + (9, PostType.EVENT, RefType.NONE, 1), (10, PostType.SEASON, RefType.ARTICLE, None), (11, PostType.TIP, RefType.ARTICLE, None), (12, PostType.QUOTE, RefType.NONE, None), + (13, PostType.EVENT, RefType.NONE, 2), + (14, PostType.EVENT, RefType.NONE, 3), ] -# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. +# 시간대별 순서. 목록에 없는 종류는 그 시간대에 꺼진다. '오늘 하루 날씨'는 히어로 바로 아래 고정이라 따로 둔다. 행사는 사이사이 무작위. ORDER = { - "morning": [PostType.ALERT, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.EVENT, PostType.QUOTE], - "day": [PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.EVENT, PostType.WEEK, PostType.SEASON, PostType.TIP, PostType.QUOTE], - "evening": [PostType.SUNSET, PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.TOMORROW, PostType.WEEK, PostType.EVENT, PostType.SEASON, PostType.TIP, PostType.QUOTE], - "night": [PostType.TOMORROW, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.EVENT, PostType.TIP, PostType.QUOTE], + "morning": [PostType.ALERT, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.SUNSET, PostType.TIP, PostType.WEEK, PostType.QUOTE], + "day": [PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.SEASON, PostType.TIP, PostType.QUOTE], + "evening": [PostType.SUNSET, PostType.GAK, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.TOMORROW, PostType.WEEK, PostType.SEASON, PostType.TIP, PostType.QUOTE], + "night": [PostType.TOMORROW, PostType.ALERT, PostType.SUNSET, PostType.WEEK, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SEASON, PostType.TIP, PostType.QUOTE], } _SKY_MODE = {"morning": "morning", "day": "day", "evening": "sunset", "night": "night"} _CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory.TIP.value: "날씨 상식", ArticleCategory.GAK.value: "각 원리", ArticleCategory.QUOTE.value: "한 문장"} @@ -134,8 +137,8 @@ def _spread(cards: list[PostData]) -> list[PostData]: return out -def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime, has_warning: bool) -> list[PostData]: - """켜진 카드만 그 시간대 순서로 놓는다.""" +def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime, has_warning: bool, seed: str = "") -> list[PostData]: + """켜진 카드만 그 시간대 순서로 놓고, 행사 카드는 seed 로 정한 자리에 끼운다.""" order = list(ORDER[slot]) if slot == "evening" and now.weekday() == 4: order.remove(PostType.WEEK) @@ -152,6 +155,10 @@ def arrange(cards: list[PostData], slot: str, now: datetime, sunset_at: datetime rest = _spread([pool[t].pop(0) for t in order if t not in head_types and pool.get(t)]) if slot == "night": rest = [c for c in rest if c.post_type is not PostType.QUOTE] + [c for c in rest if c.post_type is PostType.QUOTE] + events = pool.get(PostType.EVENT, []) + gaps = sorted(random.Random(seed).sample(range(1, len(rest)), min(len(events), max(0, len(rest) - 1))), reverse=True) + for gap, e in zip(gaps, reversed(events[:len(gaps)])): + rest.insert(gap, e) return head + rest @@ -276,7 +283,7 @@ class FeedService: return Res_Feed( region_code=region.code, region_name=region.name, slot=slot, hero=self._hero(now, slot, hourly[0] if hourly else None, now_w, board), - stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning), + stories=[_top(i) for i in items], posts=arrange(cards, slot, now, sunset_at, has_warning, f"{day}:{region.code}"), bands=Bands( events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon) for e in events[:4]], top5=[_top(i) for i in items[:5]], @@ -339,9 +346,10 @@ class FeedService: slides=[RowsSlide(kind="rows", eyebrow=_CATEGORY_META[a.category], line=a.body[0], icon=a.icon)], share_messages=[a.title]) if t is PostType.EVENT: soon = [e for e in c.events if e.event.start_date <= c.now.date() + timedelta(days=7) and e.event.end_date >= c.now.date()] - if not soon: + rank = p.index_rank or 1 + if len(soon) < rank: return None - e = soon[0] + e = soon[rank - 1] rows = [Row(label="장소", value=e.event.place_name), Row(label="기간", value=f"{e.event.start_date:%m.%d}~{e.event.end_date:%m.%d}")] if e.fit: rows.append(Row(label="그날 날씨", value=e.fit)) diff --git a/backend/tests/test_feed.py b/backend/tests/test_feed.py index 6251d94..030af72 100644 --- a/backend/tests/test_feed.py +++ b/backend/tests/test_feed.py @@ -109,6 +109,24 @@ def test_arrange_orders_by_slot_and_keeps_same_types_apart(): assert night[:3] == [PostType.ALERT, PostType.WEATHER, PostType.TOMORROW] and night[-1] is PostType.QUOTE +def test_arrange_scatters_up_to_three_events_same_spot_all_day(): + from datetime import datetime + + from common.utils.kma_time import KST + from services.feed_service import arrange + + sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST) + cards = [_card(t, n) for n, t in enumerate([ + PostType.WEATHER, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.SEASON, + PostType.TIP, PostType.QUOTE, PostType.EVENT, PostType.EVENT, PostType.EVENT, + ])] + run = lambda h, seed: [c.post_type for c in arrange(cards, "day", datetime(2026, 10, 2, h, tzinfo=KST), sunset, False, seed)] # noqa: E731 + out = run(11, "2026-10-02:1144000000") + assert out.count(PostType.EVENT) == 3 and out[0] is PostType.WEATHER + assert all(not (a is PostType.EVENT and b is PostType.EVENT) for a, b in zip(out, out[1:])) + assert run(14, "2026-10-02:1144000000") == out + + @pytest.mark.anyio async def test_build_day_makes_every_card_at_three(): thursday = date(2026, 10, 15)