From 4c24d959913f9aca313a1e8d25cb2d449f69ea5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EA=B2=BD?= Date: Mon, 23 Nov 2026 15:43:50 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20=ED=9E=88=EC=96=B4=EB=A1=9C=EC=9D=98=20?= =?UTF-8?q?=EC=A7=80=EA=B8=88=20=EA=B0=92=EC=97=90=20=EC=B4=88=EB=8B=A8?= =?UTF-8?q?=EA=B8=B0=EC=8B=A4=ED=99=A9=20=EB=B0=98=EC=98=81,=20=EA=B5=AC?= =?UTF-8?q?=EA=B0=84=20=EA=B2=BD=EA=B3=84=20=EC=8B=9C=EA=B0=81=EC=9D=98=20?= =?UTF-8?q?=EC=9A=B0=EC=82=B0=EA=B0=81=20'=EC=A7=80=EA=B8=88=20=EB=B9=84'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 히어로가 DB 예보 행을 직접 읽어 실황이 안 들어가던 것 — 지금 시각 행을 관측값으로 덮음. 피드 캐시도 새 시각 실황이 나오는 매시 10분에 끝나게 함 - 낮이 15:20 에 끝나는 날 15:00~15:20 처럼 구간 경계 직전에는 지금 시각 행이 다음 구간 칸에 들어, 화면이 보여 주는 지금 구간의 우산각이 '지금 비'를 놓치던 것 — 우산각의 지금은 화면이 보여 주는 구간 기준으로 정하고 그 줄 문구도 지금 시각 날씨로 --- backend/services/feed_service.py | 12 ++++++++---- backend/services/index_service.py | 15 +++++++++++---- backend/tests/test_day_slot.py | 15 +++++++++++++++ backend/tests/test_feed.py | 27 +++++++++++++++++++++++++++ 4 files changed, 61 insertions(+), 8 deletions(-) diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index 0b295ff..3922c2a 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -13,7 +13,7 @@ from common.database.db_session_manager import DB_SESSION_MNG from common.database.model.models import Article, CardSet, IndexScore, OpenMeteoHourly, Post, Region, WeatherHourly from common.enums import AirGrade, ArticleCategory, ErrorType, EventKind, PostType, RainType, RefType, Sky, SkyGrade, SkySituation, SkyType, WarningType from common.logger import LOG -from common.utils.kma_time import KST, ULTRA_DELAY, kst_midnight, latest_ultra_base, next_vilage_available, now_kst +from common.utils.kma_time import KST, NCST_DELAY, ULTRA_DELAY, kst_midnight, latest_ncst_base, latest_ultra_base, next_vilage_available, now_kst from common.utils.text import compass, day_range, hour_label, short_day from crud.card_crud import CardCRUD from crud.feed_crud import FeedCRUD @@ -38,7 +38,7 @@ from services.index_service import IndexBoard, IndexItem, IndexService, slot_lab from services.now_service import NowService, NowWeather from services.season_service import SeasonService from services.sky_service import SkyService, SkyView, day_verdict -from services.weather_service import TodayWeather, WeatherService +from services.weather_service import TodayWeather, WeatherService, observed_now, with_observed from services.week_service import DayPlan, EventItem, WeekService, event_sidos, image_credit, mix_kinds from services.weekend_plan import day_plan, forecast, pick_events from services.weekend_rank import TripPick, WeekendRank, pick_trip, weekend_days @@ -173,13 +173,13 @@ def feed_day(now: datetime) -> date: def feed_ttl_sec(now: datetime, sunset_at: datetime) -> int: - """다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·03:00·예보·초단기예보·미세먼지 갱신·정각(지금 구간이 줄어듦) 중 가장 빠른 쪽.""" + """다음에 피드가 달라지는 시각까지. 시간대 경계·일몰(노을 카드가 내일 것으로)·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, at(day + timedelta(days=1), _FEED_DAY_START), next_vilage_available(now), latest_ultra_base(now) + timedelta(hours=1) + ULTRA_DELAY, - now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)] + latest_ncst_base(now) + timedelta(hours=1) + NCST_DELAY, now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)] air = now.replace(minute=20, second=0, microsecond=0) changes.append(air if air > now else air + timedelta(hours=1)) nxt = min(c for c in changes if c > now) @@ -407,6 +407,10 @@ 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))) ) + hourly = hourly or [] + if (observed := await observed_now(region, now)) is not None: # 히어로의 지금은 관측값 + overlay = with_observed({h.forecast_at: h for h in hourly}, observed) + hourly = [overlay[h.forecast_at] for h in hourly] _, 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 []) card_ids = [p.ref_id for p in posts if PostType(p.post_type) is PostType.CARD and p.ref_id is not None] diff --git a/backend/services/index_service.py b/backend/services/index_service.py index 68f92cf..869ca2c 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -241,23 +241,30 @@ def slot_results( hours_by_slot = slot_hours(day, sunset_at) hours_by_slot[EARLY] = set(range(NIGHT_END_HOUR)) cur = _trim_passed(hours_by_slot, day, sunset_at, now) if now else None + # 화면이 지금 구간으로 보여 주는 칸. 구간 경계 직전(예: 낮이 15:20 에 끝나는데 15시 행은 저녁 칸)에는 cur 와 다를 수 있다 + shown = current_slot(now, sunset_at) if now else None + now_hour = int((now - kst_midnight(day)).total_seconds() // 3600) if now else None activity = [{h % 24 for h in w} for w in window_hours(defn, day, region)] + rest_of_day = defn.factor_rules["rain"].get("span") == "rest_of_day" out = {} for key, hours in hours_by_slot.items(): if not hours: continue matches = any(any(h % 24 in w for h in hours) for w in activity) # 시간대 일치 여부와 날씨 평가를 분리해 하루 점수로 대체하지 않는다. - # 우산각은 구간이 아니라 그 구간 시작(지금 구간은 지금)부터 자정까지의 비를 본다. - seen = set(range(min(hours), 24)) if defn.factor_rules["rain"].get("span") == "rest_of_day" else hours + # 우산각은 구간이 아니라 그 구간 시작(화면이 보여 주는 지금 구간은 지금)부터 자정까지의 비를 본다. + if rest_of_day: + seen = set(range(now_hour if key == shown else min(hours), 24)) + else: + seen = hours window = SimpleNamespace(windows=[{"from": min(seen), "to": max(seen) + 1}]) windows = windows_for(window, day, region, by_at, by_om, only=seen) # 지금 시각의 예보 행이 있을 때만 '지금'이다 (없으면 첫 행은 더 뒤 시각이다) - at_now = key == cur and bool(windows and windows[0]) and windows[0][0].hour == int((now - kst_midnight(day)).total_seconds() // 3600) + at_now = key == shown and bool(windows and windows[0]) and windows[0][0].hour == now_hour result = evaluate(defn, windows, replace(ctx, time_matches=matches, at_now=at_now)) if result is not None: # 지금 구간 줄은 남은 시간의 가운데가 아니라 지금 시각 날씨로 - if key == cur and windows and windows[0]: + if (key == cur or (rest_of_day and key == shown)) and windows and windows[0]: result.summary = summary_line(windows[0][0]) out[key] = result return out diff --git a/backend/tests/test_day_slot.py b/backend/tests/test_day_slot.py index 2b9a1fb..10f6957 100644 --- a/backend/tests/test_day_slot.py +++ b/backend/tests/test_day_slot.py @@ -185,6 +185,21 @@ def test_umbrella_raining_now_comes_from_the_observed_weather(): assert (dry, wet) == (30, 81) +def test_umbrella_now_follows_the_slot_the_screen_shows_even_at_a_slot_boundary(): + """일몰 17:20 이면 낮은 15:20 까지인데 15시 행은 15:30 기준으로 저녁 칸에 든다. 15:11 에 화면이 보이는 구간은 낮이고, 그 점수가 '지금 비'를 알아야 한다.""" + from common.enums import RainType + from services.weather_service import Observed, with_observed + + sunset = datetime(2026, 10, 8, 17, 20, tzinfo=KST) + now = datetime(2026, 10, 8, 15, 11, tzinfo=KST) + observed = Observed(at=kst_midnight(DAY) + timedelta(hours=15), rain_type=RainType.RAIN, rain_mm=1.0, temp_c=9.7, humidity=92, wind_ms=2.3) + by_at = with_observed({r.forecast_at: r for r in (_hourly(h) for h in range(5, 30))}, observed) + parts = slot_results(_umbrella_defn(), DAY, REGION, by_at, {}, CTX, sunset, now) + assert current_slot(now, sunset) == "day" + assert parts["day"].score == 81 # 15시부터 자정까지 9시간: 70 + 30 × (100 + 30 × 8) ÷ 9 ÷ 100 + assert parts["day"].summary.startswith("오후 3시"), parts["day"].summary # 문구도 남은 시간의 가운데(밤)가 아니라 지금 + + def test_umbrella_other_slots_have_no_raining_now_bonus(): """13:30 에 낮 구간이 지금. 저녁 구간(16시~)은 16시에만 비가 와도 지금 비 보너스 없이 평균 × 100 → 약 12점.""" now = datetime(2026, 10, 8, 13, 30, tzinfo=KST) diff --git a/backend/tests/test_feed.py b/backend/tests/test_feed.py index 72f883d..c143789 100644 --- a/backend/tests/test_feed.py +++ b/backend/tests/test_feed.py @@ -106,6 +106,33 @@ def test_feed_cache_expires_when_ultra_forecast_arrives(): assert feed_ttl_sec(now, sunset) == 25 * 60 +def test_feed_cache_expires_when_the_new_hours_observation_arrives(): + """15:02 에 만든 피드는 15시 실황이 나오는 15:10 에 끝나야 한다. 안 그러면 미세먼지(15:20)까지 히어로가 지난 시각 값이다.""" + from datetime import datetime + + from common.utils.kma_time import KST + from services.feed_service import feed_ttl_sec + + now = datetime(2026, 10, 2, 15, 2, tzinfo=KST) + sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST) + assert feed_ttl_sec(now, sunset) == 8 * 60 + + +@pytest.mark.anyio +async def test_hero_shows_the_observed_current_weather(offline, monkeypatch): + """예보는 20도·습도 50% 인데 실황이 3.3도·88% 로 관측했으면 히어로의 지금은 관측값이다.""" + import services.weather_service as weather_service + + async def observed(*_a): + return [{"category": c, "obsrValue": v} for c, v in {"PTY": "0", "REH": "88", "RN1": "0", "T1H": "3.3", "WSD": "2.0"}.items()] + + monkeypatch.setattr(weather_service, "fetch_ncst", observed) + monkeypatch.setattr(weather_service, "latest_ncst_base", lambda now: now.replace(minute=0, second=0, microsecond=0)) # 매시 00~10분에도 같게 + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: + hero = (await client.get("/v1/feed", params={"region": REGION})).json()["hero"] + assert (hero["temp_c"], hero["humidity"]) == (3.3, 88) + + def _card(post_type, post_id=1): from datetime import datetime