From d6525f592cc7c2b71f277d2c9e7fcb9437fc9edd Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Thu, 8 Oct 2026 17:07:26 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EA=B0=81=20=EC=A0=90=EC=88=98=EB=A5=BC?= =?UTF-8?q?=20=EC=95=84=EC=B9=A8=C2=B7=EB=82=AE=C2=B7=EC=A0=80=EB=85=81?= =?UTF-8?q?=C2=B7=EB=B0=A4=20=EA=B5=AC=EA=B0=84=EB=B3=84=EB=A1=9C=20?= =?UTF-8?q?=E2=80=94=20=EC=A7=80=EA=B8=88=20=EA=B5=AC=EA=B0=84=20=EC=A0=90?= =?UTF-8?q?=EC=88=98=EB=A1=9C=20=EC=88=9C=EC=9C=84,=20=EA=B5=AC=EA=B0=84?= =?UTF-8?q?=EC=9D=B4=20=EC=95=88=20=EA=B2=B9=EC=B9=98=EB=8A=94=20=EA=B0=81?= =?UTF-8?q?=EC=9D=80=20=EC=88=9C=EC=9C=84=C2=B7=ED=94=BC=EB=93=9C=EC=97=90?= =?UTF-8?q?=EC=84=9C=20=EB=B9=BC=EA=B3=A0=20=EB=AA=A9=EB=A1=9D=20=EB=81=9D?= =?UTF-8?q?=EC=97=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/common/database/model/models.py | 1 + backend/crud/index_crud.py | 9 +- backend/postgres-init/init.sql | 2 + backend/router/v1/feed/protocol.py | 1 + backend/router/v1/index/index.py | 9 +- backend/router/v1/index/protocol.py | 11 ++- backend/router/v1/watch/watch.py | 2 +- backend/services/calc/day_slot.py | 27 ++++++ backend/services/feed_service.py | 22 ++--- backend/services/index_service.py | 109 ++++++++++++++++++++---- backend/tests/test_day_slot.py | 63 ++++++++++++++ backend/tests/test_index_api.py | 10 ++- 12 files changed, 226 insertions(+), 40 deletions(-) create mode 100644 backend/services/calc/day_slot.py create mode 100644 backend/tests/test_day_slot.py diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py index d28d756..5a7be6f 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.py @@ -206,6 +206,7 @@ class IndexScore(Base): zero_reason: Mapped[Optional[str]] = mapped_column(String(100), nullable=True) notes: Mapped[dict] = mapped_column(JSONB) estimated: Mapped[bool] = mapped_column(Boolean, default=False) + slots: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}") computed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True)) diff --git a/backend/crud/index_crud.py b/backend/crud/index_crud.py index d408aab..ce43105 100644 --- a/backend/crud/index_crud.py +++ b/backend/crud/index_crud.py @@ -1,6 +1,6 @@ from datetime import date -from sqlalchemy import func, select +from sqlalchemy import func, select, text from sqlalchemy.dialects.postgresql import insert from sqlalchemy.ext.asyncio import AsyncSession @@ -34,6 +34,13 @@ class IndexCRUD: stmt = select(func.min(IndexScore.computed_at)).where(IndexScore.region_code == region_code, IndexScore.score_date == day) return await s.scalar(stmt) + async def has_unslotted(self, s: AsyncSession, region_code: str, day: date) -> bool: + """그날 행 중 구간 점수가 비어 있는 행(구간 계산 전 행)이 있는지.""" + stmt = select(IndexScore.index_id).where( + IndexScore.region_code == region_code, IndexScore.score_date == day, text("index_score.slots = '{}'::jsonb") + ).limit(1) + return (await s.scalar(stmt)) is not None + async def upsert_scores(self, s: AsyncSession, rows: list[dict]) -> None: if not rows: return diff --git a/backend/postgres-init/init.sql b/backend/postgres-init/init.sql index ce5c456..9ebce24 100644 --- a/backend/postgres-init/init.sql +++ b/backend/postgres-init/init.sql @@ -153,12 +153,14 @@ CREATE TABLE IF NOT EXISTS public.index_score ( zero_reason VARCHAR(100) NULL, -- 0점이 된 이유 (걸리지 않았으면 NULL) notes JSONB NOT NULL, -- 요소별 근거 문장 {"temp": "체감 21°, 편한 범위 18~24° 안", ...} estimated BOOLEAN NOT NULL DEFAULT false, -- 시간별 예보가 없어 중기예보로 낸 예상 점수 + slots JSONB NOT NULL DEFAULT '{}', -- 오늘만: 구간별 점수 {"morning"|"day"|"evening"|"night"|"early": {score, summary, factors, zero_reason, notes}}. 각 시간대와 안 겹치는 구간은 없음 computed_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (region_code, score_date, index_id) ); ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS uv_score SMALLINT NOT NULL DEFAULT 0; ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS sun_score SMALLINT NOT NULL DEFAULT 0; ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS view_score SMALLINT NOT NULL DEFAULT 0; +ALTER TABLE public.index_score ADD COLUMN IF NOT EXISTS slots JSONB NOT NULL DEFAULT '{}'; -- 피드 카드. 매일 03:00 스케줄러가 그날 카드를 전부 만들고, 볼 때 시간대에 따라 켜고 끄고 순서를 정해 그 구 데이터로 채운다. CREATE TABLE IF NOT EXISTS public.post ( diff --git a/backend/router/v1/feed/protocol.py b/backend/router/v1/feed/protocol.py index 032d6e8..b495804 100644 --- a/backend/router/v1/feed/protocol.py +++ b/backend/router/v1/feed/protocol.py @@ -131,6 +131,7 @@ class TopIndex(WebPacketProtocol): score: int rank: int summary: Optional[str] = None + active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수") class HeroStat(WebPacketProtocol): diff --git a/backend/router/v1/index/index.py b/backend/router/v1/index/index.py index 543bc03..efcbc6f 100644 --- a/backend/router/v1/index/index.py +++ b/backend/router/v1/index/index.py @@ -5,7 +5,8 @@ from fastapi import APIRouter, Depends, Path, Query from common.enums import ErrorType, IndexCategory from common.models.errors import error_info -from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, ScoreBand, TrendPoint +from router.v1.index.protocol import Factor, IndexSummary, Res_IndexDetail, Res_IndexList, ScoreBand, SlotPoint, TrendPoint +from services.calc.day_slot import SLOT_LABEL from services.calc.index_calc import AXES, axis_label, zero_rules_text from services.index_service import IndexItem, IndexService, slot_label @@ -18,10 +19,11 @@ def _summary(i: IndexItem, today: date) -> IndexSummary: index_id=d.index_id, code=d.code, name=d.name, icon=d.icon, category=IndexCategory(d.category), is_fun=d.is_fun, is_core=d.is_core, score=i.score.score, rank=i.rank, summary=i.score.summary, trend=[TrendPoint(day=t.score_date, label=slot_label(t.score_date, today), score=t.score, estimated=t.estimated) for t in i.trend], + active=i.active, slot=i.slot, slots=[SlotPoint(slot=k, label=SLOT_LABEL[k], score=v) for k, v in i.slots.items()], ) -@router.get("/list", response_model=Res_IndexList, response_model_exclude_none=True, summary="지수 목록 (점수순, 1~3위, 오늘 날씨 점수)") +@router.get("/list", response_model=Res_IndexList, response_model_exclude_none=True, summary="지수 목록 (지금 구간 점수순, 1~3위, 지금 날씨 점수)") async def list_indices( region: str = Query(..., description="구 행정코드"), category: Optional[IndexCategory] = Query(None), @@ -32,8 +34,9 @@ async def list_indices( if err is not ErrorType.SUCCESS: return Res_IndexList(result=error_info(err)) items = [_summary(i, board.day) for i in board.items] + top3 = [_summary(i, board.day) for i in board.ranked[:3]] filtered = [x for x in items if (category is None or x.category is category) and (not core or x.is_core)] - return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=items[:3], items=filtered) + return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=top3, items=filtered) @router.get("/{index_id}", response_model=Res_IndexDetail, response_model_exclude_none=True, summary="지수 계산 근거") diff --git a/backend/router/v1/index/protocol.py b/backend/router/v1/index/protocol.py index ae5cdba..29f3296 100644 --- a/backend/router/v1/index/protocol.py +++ b/backend/router/v1/index/protocol.py @@ -14,6 +14,12 @@ class TrendPoint(WebPacketProtocol): estimated: bool = Field(description="시간별 예보가 없어 중기예보로 낸 예상 점수") +class SlotPoint(WebPacketProtocol): + slot: str = Field(description="morning / day / evening / night") + label: str = Field(description="아침 / 낮 / 저녁 / 밤") + score: int + + class IndexSummary(WebPacketProtocol): index_id: int code: str @@ -26,12 +32,15 @@ class IndexSummary(WebPacketProtocol): rank: int summary: str trend: list[TrendPoint] = [] + active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수") + slot: Optional[str] = Field(default=None, description="score 가 어느 구간 점수인지 (지금 구간)") + slots: list[SlotPoint] = Field(default=[], description="오늘 구간별 점수. 각 시간대와 안 겹치는 구간은 없음") class Res_IndexList(Res_WebPacketProtocol): region_code: Optional[str] = None day: Optional[date] = None - weather_score: Optional[int] = None + weather_score: Optional[int] = Field(default=None, description="지금 날씨 점수 (지금 구간 기준)") top3: list[IndexSummary] = [] items: list[IndexSummary] = [] diff --git a/backend/router/v1/watch/watch.py b/backend/router/v1/watch/watch.py index ff82612..b2dc72e 100644 --- a/backend/router/v1/watch/watch.py +++ b/backend/router/v1/watch/watch.py @@ -97,7 +97,7 @@ async def get_watch_summary( res.warning = now_w.warnings[0].text if now_w.warnings else None if board is not None: - res.top = [_top(i) for i in board.items[:TOP_N]] + res.top = [_top(i) for i in board.ranked[:TOP_N]] codes = [c.strip() for c in (pick or "").split(",") if c.strip()][:MAX_PICKS] by_code = {i.definition.code: i for i in board.items} res.picks = [_top(by_code[c]) for c in codes if c in by_code] diff --git a/backend/services/calc/day_slot.py b/backend/services/calc/day_slot.py new file mode 100644 index 0000000..b15cf4e --- /dev/null +++ b/backend/services/calc/day_slot.py @@ -0,0 +1,27 @@ +from datetime import date, datetime, time, timedelta + +from common.utils.kma_time import KST + +SLOTS = ("morning", "day", "evening", "night") +SLOT_LABEL = {"morning": "아침", "day": "낮", "evening": "저녁", "night": "밤"} +NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤 +NIGHT_END_HOUR = 5 + + +def slot_of(now: datetime, sunset_at: datetime) -> str: + """아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다.""" + h = now.hour + if NIGHT_END_HOUR <= h < 11: + return "morning" + if h >= 11 and now < sunset_at + NIGHT_AFTER_SUNSET: + return "day" if now < sunset_at - timedelta(hours=2) else "evening" + return "night" + + +def slot_hours(day: date, sunset_at: datetime) -> dict[str, set[int]]: + """그날 5시~다음 날 5시를 구간별 시각으로 나눈다. 24 이상은 다음 날 시각. 한 시간은 그 30분 시점의 구간에 넣는다.""" + out: dict[str, set[int]] = {s: set() for s in SLOTS} + start = datetime.combine(day, time(0), tzinfo=KST) + for h in range(NIGHT_END_HOUR, 24 + NIGHT_END_HOUR): + out[slot_of(start + timedelta(hours=h, minutes=30), sunset_at)].add(h) + return out diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index 2e5b9d8..18cb55c 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -25,6 +25,7 @@ from router.v1.feed.protocol import ( ) from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL from services.air_service import pm10_grade, pm25_grade +from services.calc.day_slot import NIGHT_AFTER_SUNSET, slot_of from services.calc.index_calc import rank_score from services.calc.moon import illumination, nearest, phase_name from services.calc.sky_score import GRADE_LABEL, SITUATION_LINE @@ -88,7 +89,6 @@ _CATEGORY_META = {ArticleCategory.SEASON.value: "계절 소식", ArticleCategory _FEED_TTL_MAX = 3600 _PARTIAL_TTL = 60 _SUNSET_HOUR = 18 # 노을 시간대 각의 대략적인 순서용 -_NIGHT_AFTER_SUNSET = timedelta(hours=1) # 해 지고 이만큼 지나면 밤 _RAIN_PROB = 40 _UV_SHOW = 3 # 자외선 포스트: 오늘 가장 셀 때 '보통' 이상이면 띄운다 _HERO_RAIN_PROB = 60 # 히어로 '오늘 비': 오늘 남은 칸 중 비 형태가 있거나 확률이 이만큼 넘는 첫 칸 @@ -154,22 +154,12 @@ def feed_day(now: datetime) -> date: return (now - timedelta(hours=_FEED_DAY_START)).date() -def slot_of(now: datetime, sunset_at: datetime) -> str: - """아침 05–11 · 낮 11–일몰 2시간 전 · 저녁 일몰 2시간 전–일몰 1시간 뒤 · 밤 일몰 1시간 뒤–05. 밤은 계절 따라 18시대~21시대에 온다.""" - h = now.hour - if 5 <= h < 11: - return "morning" - if h >= 11 and now < sunset_at + _NIGHT_AFTER_SUNSET: - return "day" if now < sunset_at - timedelta(hours=2) else "evening" - return "night" - - def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int: """다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·미세먼지 갱신 중 가장 빠른 쪽.""" day = now.date() at = lambda d, h: datetime.combine(d, time(h), tzinfo=KST) # noqa: E731 sunset = sunset_at.astimezone(KST) - changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + _NIGHT_AFTER_SUNSET, + changes = [at(day, _FEED_DAY_START), at(day, 5), at(day, 11), sunset - timedelta(hours=2), sunset, sunset + NIGHT_AFTER_SUNSET, at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now)] air = now.replace(minute=20, second=0, microsecond=0) changes.append(air if air > now else air + timedelta(hours=1)) @@ -247,7 +237,7 @@ def _by_position(posts: list[Post]) -> list[Post]: 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) + 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, active=i.active) async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, regions: RegionCRUD) -> ErrorType: @@ -371,7 +361,7 @@ class FeedService: days=days, events=events, sunsets=sunsets, hourly=hourly or [], articles=by_article, quotes=quotes, trip=trip, uv=await self._uv_today(region.code, now)) - gak = sorted(board.items[:3], key=lambda i: _gak_key(i, now.hour)) if board else [] + gak = sorted(board.ranked[:3], key=lambda i: _gak_key(i, now.hour)) if board else [] cards = [] for p in posts or []: if PostType(p.post_type) is PostType.GAK: @@ -391,7 +381,7 @@ class FeedService: bands=Bands( events=[BandEvent(event_id=e.event.event_id, name=e.event.name, status_label=e.status_label, icon=e.event.icon, image=e.event.image_url, image_credit=image_credit(e.event)) for e in mix_kinds(events)[:4]], - top5=[_top(i) for i in items[:5]], + top5=[_top(i) for i in board.ranked[:5]] if board else [], season=[ BandArticle(article_id=a.article_id, title=a.title, meta=f"{_CATEGORY_META[a.category]} · {a.read_minutes}분", icon=a.icon, image=a.image_url, image_credit=a.image_credit) @@ -434,7 +424,7 @@ class FeedService: def _hero(self, now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], board: Optional[IndexBoard], today: Optional[TodayWeather] = None, uv: Optional[float] = None) -> Hero: - top = board.items[0] if board and board.items else None + top = board.ranked[0] if board and board.ranked else None bubble = None if top is not None: bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요" diff --git a/backend/services/index_service.py b/backend/services/index_service.py index cddde85..3246232 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -1,5 +1,5 @@ import asyncio -from dataclasses import dataclass, replace +from dataclasses import dataclass, field, replace from datetime import date, datetime, time, timedelta from types import SimpleNamespace from typing import Optional @@ -16,6 +16,7 @@ from crud.sky_crud import SkyCRUD from crud.weather_crud import WeatherCRUD from crud.week_crud import WeekCRUD from services.air_service import GRADE_LABEL, AirService +from services.calc.day_slot import NIGHT_END_HOUR, SLOTS, slot_hours, slot_of from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, rank_score from services.calc.moon import illumination from services.calc.sun import sun_times @@ -28,7 +29,7 @@ DAYS = 3 _LOOKAHEAD_HOURS = (9, 18) _WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일") -# 메인 하늘 영역의 '오늘 날씨 점수': 낮 9~21시 밖에 나가기 좋은 정도. +# 메인 하늘 영역의 '지금 날씨 점수': 지금 구간(아침·낮·저녁·밤) 밖에 나가기 좋은 정도. WEATHER_SCORE_DEF = SimpleNamespace( weight_temp=30, weight_rain=25, weight_wind=10, weight_humidity=10, weight_air=10, weight_sun=15, weight_time=0, factor_rules={ @@ -36,7 +37,7 @@ WEATHER_SCORE_DEF = SimpleNamespace( "wind": {"type": "calm", "ok": 2, "limit": 10}, "humidity": {"type": "range", "lo": 40, "hi": 60, "best": 50}, "air": {"zero": 75, "full": 10}, "sun": {"zero": 0.2, "full": 0.9}, "time": {"type": "fixed", "value": 100}, }, - zero_rules=[], windows=[{"from": 9, "to": 21}], + zero_rules=[], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}], ) @@ -46,6 +47,9 @@ class IndexItem: score: IndexScore rank: int trend: list[IndexScore] + slot: Optional[str] = None + slots: dict[str, int] = field(default_factory=dict) + active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다 @dataclass @@ -55,6 +59,11 @@ class IndexBoard: weather_score: Optional[int] items: list[IndexItem] + @property + def ranked(self) -> list[IndexItem]: + """지금 구간에 해당하는 각만 (순위·피드용).""" + return [i for i in self.items if i.active] + def _hour(r: WeatherHourly) -> Hour: return Hour( @@ -119,13 +128,17 @@ def _om_fields(instant: Optional[OpenMeteoHourly], covering: Optional[OpenMeteoH def windows_for( - defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None + defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: Optional[dict[datetime, OpenMeteoHourly]] = None, + only: Optional[set[int]] = None, ) -> list[list[Hour]]: - """시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간).""" + """시간대 정의를 그날의 시간별 날씨 목록으로 바꾼다. 24시 이후는 다음 날로 넘어간다. 시간마다 Open-Meteo 3시간 구간 값을 붙인다 (순간값은 가장 가까운 구간, 일조는 덮는 구간). + only 가 있으면 그 시각만 남긴다.""" by_om = by_om or {} start = kst_midnight(day) out = [] for hours in window_hours(defn, day, region): + if only is not None: + hours = [h for h in hours if h in only] rows = [by_at.get(start + timedelta(hours=h)) for h in hours] out.append([ replace(_hour(r), hour=h, **_om_fields( @@ -136,6 +149,44 @@ def windows_for( return out +EARLY = "early" # 0~5시: 전날 밤 구간 + + +def current_slot(now: datetime, sunset_at: datetime) -> str: + return EARLY if now.hour < NIGHT_END_HOUR else slot_of(now, sunset_at) + + +def shown_slot(key: str) -> str: + return "night" if key == EARLY else key + + +def slot_results( + defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime, +) -> dict[str, Result]: + """그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다.""" + parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in slot_hours(day, sunset_at).items()} + parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR))) + out = {} + for key, windows in parts.items(): + result = evaluate(defn, windows, ctx) + if result is not None: + out[key] = result + return out + + +def _slot_json(r: Result) -> dict: + return {"score": r.score, "summary": r.summary, "factors": r.factors, "zero_reason": r.zero_reason, "notes": r.notes} + + +def _with_slot(row: IndexScore, data: dict) -> IndexScore: + """저장된 하루 점수 행을 구간 점수로 바꾼 사본 (DB에 붙지 않음).""" + out = IndexScore(**{c.key: getattr(row, c.key) for c in IndexScore.__table__.columns}) + out.score, out.summary, out.zero_reason, out.notes = data["score"], data["summary"], data["zero_reason"], data["notes"] + for a in AXES: + setattr(out, f"{a}_score", data["factors"].get(a, 0)) + return out + + def day_forecast(d: WeatherDaily) -> DayForecast: return DayForecast( temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None, @@ -205,20 +256,44 @@ class IndexService: if err is not ErrorType.SUCCESS: return err, None today = now.date() + cur = current_slot(now, sun_times(today, float(region.lat), float(region.lon)).sunset_at) slots = slot_days(today) err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s)) err2, scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.scores(s, region.code, today, slots[-1])) if ErrorType.DB_ERROR in (err, err2): return ErrorType.DB_ERROR, None by_key = {(x.index_id, x.score_date): x for x in scores} - ranked = sorted((d for d in defs if (d.index_id, today) in by_key), key=lambda d: rank_score(by_key[(d.index_id, today)].score, d.priority), reverse=True) - items = [ - IndexItem( - definition=d, score=by_key[(d.index_id, today)], rank=i + 1, - trend=[by_key[k] for k in ((d.index_id, day) for day in slots) if k in by_key], - ) - for i, d in enumerate(ranked) - ] + # 오늘 점수는 지금 구간 점수. 구간 점수가 없는 행(예전 계산분)은 하루 점수 그대로, 지금 구간과 안 겹치는 각은 뺀다 + now_score: dict[int, IndexScore] = {} + for d in defs: + row = by_key.get((d.index_id, today)) + if row is None: + continue + if not row.slots: + now_score[d.index_id] = row + elif cur in row.slots: + now_score[d.index_id] = _with_slot(row, row.slots[cur]) + ranked = sorted((d for d in defs if d.index_id in now_score), key=lambda d: rank_score(now_score[d.index_id].score, d.priority), reverse=True) + items = [] + for i, d in enumerate(ranked): + row = by_key[(d.index_id, today)] + parts = {shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)} + items.append(IndexItem( + definition=d, score=now_score[d.index_id], rank=i + 1, + trend=[now_score[d.index_id] if day == today else by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key], + slot=shown_slot(cur), slots={k: parts[k] for k in SLOTS if k in parts}, + )) + off = sorted( + (d for d in defs if d.index_id not in now_score and (d.index_id, today) in by_key), + key=lambda d: rank_score(by_key[(d.index_id, today)].score, d.priority), reverse=True, + ) + for d in off: + row = by_key[(d.index_id, today)] + items.append(IndexItem( + definition=d, score=row, rank=len(items) + 1, + trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key], + slots={shown_slot(k): v["score"] for k, v in row.slots.items() if k != ("night" if cur == EARLY else EARLY)}, active=False, + )) return ErrorType.SUCCESS, IndexBoard(region=region, day=today, weather_score=weather_score, items=items) async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[int]]: @@ -251,7 +326,8 @@ class IndexService: wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []), ) today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx) - weather_result = evaluate(WEATHER_SCORE_DEF, windows_for(WEATHER_SCORE_DEF, today, region, by_at, by_om), today_ctx) + sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at + weather_result = slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).get(current_slot(now, sunset_at)) issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []]) inputs_at = max(issued, air.measured_at) if air else issued @@ -259,8 +335,9 @@ class IndexService: inputs_at = max(inputs_at, max(r.fetched_at for r in by_om.values())) err, computed = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.last_computed(s, region.code, today)) _, scored = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.score_dates(s, region.code, today, days[-1])) + _, unslotted = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.has_unslotted(s, region.code, today)) wanted = {d for d in days if d >= today + timedelta(days=DAYS) and d in daily and None not in (daily[d].temp_min_c, daily[d].temp_max_c)} - if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()): + if err is ErrorType.SUCCESS and computed is not None and computed >= inputs_at and wanted <= (scored or set()) and unslotted is False: return ErrorType.SUCCESS, weather_result.score if weather_result else None err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s)) @@ -279,10 +356,12 @@ class IndexService: result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om) if result is None: continue + parts = slot_results(d, day, region, by_at, by_om, ctx, sunset_at) if day == today else {} out.append({ "region_code": region.code, "score_date": day, "index_id": d.index_id, "score": result.score, "summary": result.summary, **{f"{a}_score": result.factors[a] for a in AXES}, "zero_reason": result.zero_reason, "notes": result.notes, "estimated": result.estimated, "computed_at": now, + "slots": {k: _slot_json(r) for k, r in parts.items()}, }) err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.upsert_scores(s, out)]) return err, weather_result.score if weather_result else None diff --git a/backend/tests/test_day_slot.py b/backend/tests/test_day_slot.py new file mode 100644 index 0000000..ffd6b4f --- /dev/null +++ b/backend/tests/test_day_slot.py @@ -0,0 +1,63 @@ +from datetime import date, datetime, timedelta +from types import SimpleNamespace + +from common.enums import RainType, Sky +from common.utils.kma_time import KST, kst_midnight +from services.calc.day_slot import slot_hours +from services.calc.index_calc import Context +from services.index_service import EARLY, WEATHER_SCORE_DEF, current_slot, slot_results + +DAY = date(2026, 10, 8) +SUNSET = datetime(2026, 10, 8, 18, 0, tzinfo=KST) +REGION = SimpleNamespace(lat=37.5, lon=127.0) +CTX = Context(day=DAY, is_holiday=False, pm25=10, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0) + + +def _rows(rain_from: int = 99): + start = kst_midnight(DAY) + return { + start + timedelta(hours=h): SimpleNamespace( + forecast_at=start + timedelta(hours=h), feels_c=21.0, rain_type=RainType.RAIN.value if h >= rain_from else RainType.NONE.value, + rain_prob=90 if h >= rain_from else 0, wind_ms=1.0, humidity=50, sky=Sky.CLEAR.value, + ) + for h in range(0, 30) + } + + +def _defn(windows): + return SimpleNamespace( + weight_temp=50, weight_rain=50, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=0, + factor_rules={"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "ignore"}, + "humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100}}, + zero_rules=[], windows=windows, + ) + + +def test_slot_hours_split_by_sunset(): + hours = slot_hours(DAY, SUNSET) + assert hours["morning"] == set(range(5, 11)) + assert hours["day"] == set(range(11, 16)) + assert hours["evening"] == {16, 17, 18} + assert hours["night"] == set(range(19, 29)) + + +def test_current_slot_before_5_is_previous_night(): + assert current_slot(datetime(2026, 10, 8, 2, 0, tzinfo=KST), SUNSET) == EARLY + assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening" + + +def test_gak_hidden_in_slots_outside_its_window(): + parts = slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET) + assert set(parts) == {"evening", "night"} + + +def test_rain_in_evening_lowers_only_later_slots(): + parts = slot_results(_defn([{"from": 7, "to": 23}]), DAY, REGION, _rows(rain_from=16), {}, CTX, SUNSET) + assert parts["morning"].score > 80 + assert parts["evening"].score < parts["morning"].score + assert parts["night"].score < parts["morning"].score + + +def test_weather_score_covers_every_slot(): + parts = slot_results(WEATHER_SCORE_DEF, DAY, REGION, _rows(), {}, CTX, SUNSET) + assert set(parts) == {"morning", "day", "evening", "night", EARLY} diff --git a/backend/tests/test_index_api.py b/backend/tests/test_index_api.py index 5dbbdc0..73b4c86 100644 --- a/backend/tests/test_index_api.py +++ b/backend/tests/test_index_api.py @@ -60,8 +60,12 @@ async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes): assert body["result"]["success"] is True assert len(body["items"]) == 34 and len(body["top3"]) == 3 priority = {d["code"]: d["priority"] for d in _seed()} - weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"]] - assert weighted == sorted(weighted, reverse=True) + # 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤. 각 묶음 안에서는 점수 × 중요도 순 + actives = [i["active"] for i in body["items"]] + assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"]) + for group in (True, False): + weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group] + assert weighted == sorted(weighted, reverse=True) today = now_kst().date() for i in body["items"]: assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)] @@ -123,7 +127,7 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch): SimpleNamespace(index_id=2, code="mid", priority=2), SimpleNamespace(index_id=3, code="high", priority=1), ] - scores = [SimpleNamespace(index_id=x, score_date=today, score=v) for x, v in ((1, 90), (2, 80), (3, 70))] + scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))] crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores)) service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None) monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, 50)))