feat: 워치용 묶음 API /v1/watch/summary 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
HyeongBaeYangandClaude Opus 5.5 committed 2026-10-06 11:12:01 +09:00
1 parent be8f827556
commit 6ee2893745
5 files changed
+207

No files matched your search

+2
View File
@@ -14,6 +14,7 @@ from router.v1.reaction.reaction import router as reaction_router
from router.v1.region.region import router as region_router
from router.v1.season.season import router as season_router
from router.v1.sky.sky import router as sky_router
from router.v1.watch.watch import router as watch_router
from router.v1.weather.weather import router as weather_router
from router.v1.week.week import router as week_router
@@ -39,6 +40,7 @@ app.include_router(season_router)
app.include_router(feed_router)
app.include_router(auth_router)
app.include_router(reaction_router)
app.include_router(watch_router)
class Res_Health(Res_WebPacketProtocol):
View File
Whitespace-only changes.
+47
View File
@@ -0,0 +1,47 @@
from datetime import datetime
from typing import Literal, Optional
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
from router.v1.feed.protocol import TopIndex
class WatchNow(WebPacketProtocol):
temp_c: Optional[float] = None
icon: Optional[str] = None
rain_2h: Optional[bool] = None
text: Optional[str] = None
class WatchSunset(WebPacketProtocol):
is_today: bool
score: int
grade_label: str
sunset_at: datetime
best_at: datetime
class WatchSlot(WebPacketProtocol):
at: datetime
icon: str
temp_c: Optional[float] = None
rain_prob: Optional[int] = None
class WatchTimeline(WebPacketProtocol):
start_at: datetime
kind: Literal["gak", "sunset"]
class Res_WatchSummary(Res_WebPacketProtocol):
region_code: Optional[str] = None
region_name: Optional[str] = None
issued_at: Optional[datetime] = None
refresh_at: Optional[datetime] = None
mode: Optional[Literal["morning", "day", "evening", "night"]] = None
now: Optional[WatchNow] = None
warning: Optional[str] = None
top: list[TopIndex] = []
picks: list[TopIndex] = []
sunset: Optional[WatchSunset] = None
slots: list[WatchSlot] = []
timeline: list[WatchTimeline] = []
+96
View File
@@ -0,0 +1,96 @@
import asyncio
from datetime import datetime, timedelta
from typing import Optional
from fastapi import APIRouter, Depends, Query
from common.database.model.models import SkyScore
from common.enums import ErrorType, SkyGrade
from common.models.errors import error_info
from common.utils.kma_time import KST, now_kst
from router.v1.watch.protocol import Res_WatchSummary, WatchNow, WatchSlot, WatchSunset, WatchTimeline
from services.calc.sky_score import GRADE_LABEL
from services.calc.sun import sun_times
from services.feed_service import _SUNSET_FULL, _top, feed_ttl_sec, slot_of
from services.index_service import IndexService
from services.now_service import NowService
from services.sky_service import SkyService
from services.weather_service import WeatherService
router = APIRouter(prefix="/v1/watch", tags=["watch"])
MAX_PICKS = 3
def _best(score: SkyScore, kind: str) -> datetime:
return datetime.fromisoformat(next(b["at"] for b in score.best_times if b["kind"] == kind)).astimezone(KST)
def timeline(now: datetime, sunset: Optional[SkyScore], is_today: bool) -> list[WatchTimeline]:
"""컴플리케이션이 언제 무엇을 보여줄지. 오늘 노을이 볼 만하면(60점 이상) 일몰 2시간 전부터 보랏빛 하늘까지 노을, 나머지는 각."""
if sunset is None or not is_today or sunset.score < _SUNSET_FULL:
return [WatchTimeline(start_at=now, kind="gak")]
start, end = _best(sunset, "sun") - timedelta(hours=2), _best(sunset, "twilight")
if now >= end:
return [WatchTimeline(start_at=now, kind="gak")]
items = [WatchTimeline(start_at=now, kind="gak")] if now < start else []
return items + [WatchTimeline(start_at=max(start, now), kind="sunset"), WatchTimeline(start_at=end, kind="gak")]
@router.get("/summary", response_model=Res_WatchSummary, response_model_exclude_none=True, summary="워치 한 번에: 지금 날씨, 각 1~3위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표")
async def get_watch_summary(
region: str = Query(..., description="구 행정코드"),
pick: Optional[str] = Query(None, description="내 각 코드, 쉼표로 최대 3개 (예: running,laundry)"),
weather: WeatherService = Depends(),
now_service: NowService = Depends(),
sky: SkyService = Depends(),
index: IndexService = Depends(),
) -> Res_WatchSummary:
(err_t, today), (err_n, now_w), (err_s, view), (err_i, board) = await asyncio.gather(
weather.today(region), now_service.now(region), sky.view(region), index.board(region),
)
today = today if err_t is ErrorType.SUCCESS else None
now_w = now_w if err_n is ErrorType.SUCCESS else None
view = view if err_s is ErrorType.SUCCESS else None
board = board if err_i is ErrorType.SUCCESS else None
found = next((x.region for x in (today, now_w, view, board) if x is not None), None)
if found is None:
return Res_WatchSummary(result=error_info(err_t))
now = now_kst()
sunset_at = sun_times(now.date(), float(found.lat), float(found.lon)).sunset_at
res = Res_WatchSummary(
region_code=found.code, region_name=found.name, issued_at=now, refresh_at=now + timedelta(seconds=feed_ttl_sec(now, sunset_at)),
mode=slot_of(now, sunset_at),
)
if today is not None:
past = [s for s in today.slots if s.at <= now]
cur = past[-1] if past else (today.slots[0] if today.slots else None)
if cur is not None:
res.now = WatchNow(temp_c=float(cur.row.temp_c) if cur.row else None, icon=cur.icon)
res.slots = [
WatchSlot(at=s.at.astimezone(KST), icon=s.icon, temp_c=float(s.row.temp_c) if s.row else None, rain_prob=s.row.rain_prob if s.row else None)
for s in today.slots if s.at > now
]
if now_w is not None:
res.now = (res.now or WatchNow()).model_copy(update={"rain_2h": now_w.will_rain_2h, "text": now_w.rain_2h_text})
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[:3]]
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]
target, is_today = None, False
if view is not None:
is_today = now < sunset_at
target = view.sunset if is_today else next((x for x in view.days if x.score_date > now.date()), None)
if target is not None:
res.sunset = WatchSunset(
is_today=is_today, score=target.score, grade_label=GRADE_LABEL[SkyGrade(target.grade)],
sunset_at=_best(target, "sun"), best_at=_best(target, "peak"),
)
res.timeline = timeline(now, target, is_today)
return res
+62
View File
@@ -0,0 +1,62 @@
from datetime import datetime, timedelta
from types import SimpleNamespace
import pytest
from httpx import ASGITransport, AsyncClient
from common.utils.kma_time import KST
from router.router import app
from router.v1.watch.watch import timeline
REGION = "1141000000"
SUN = datetime(2026, 10, 6, 18, 0, tzinfo=KST)
def _sunset(score: int) -> SimpleNamespace:
return SimpleNamespace(score=score, best_times=[
{"at": SUN.isoformat(), "kind": "sun", "label": "해 져요"},
{"at": (SUN + timedelta(minutes=15)).isoformat(), "kind": "peak", "label": "가장 붉을 때"},
{"at": (SUN + timedelta(minutes=30)).isoformat(), "kind": "twilight", "label": "보랏빛 하늘"},
])
def test_timeline_switches_to_sunset_two_hours_before_and_back_after_twilight():
now = SUN.replace(hour=12)
assert [(t.start_at.hour, t.start_at.minute, t.kind) for t in timeline(now, _sunset(80), True)] == [
(12, 0, "gak"), (16, 0, "sunset"), (18, 30, "gak"),
]
def test_timeline_starts_with_sunset_inside_window():
now = SUN.replace(hour=17)
assert [t.kind for t in timeline(now, _sunset(80), True)] == ["sunset", "gak"]
def test_timeline_skips_weak_tomorrow_or_finished_sunset():
noon, late = SUN.replace(hour=12), SUN.replace(hour=19)
assert [t.kind for t in timeline(noon, _sunset(59), True)] == ["gak"]
assert [t.kind for t in timeline(noon, _sunset(80), False)] == ["gak"]
assert [t.kind for t in timeline(late, _sunset(80), True)] == ["gak"]
assert [t.kind for t in timeline(noon, None, True)] == ["gak"]
@pytest.mark.anyio
async def test_watch_summary_bundles_now_top_picks_sunset(offline):
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/watch/summary", params={"region": REGION, "pick": "laundry, nope,running,carwash,bike"})).json()
assert body["result"]["success"] is True
assert body["region_code"] == REGION and body["mode"] in ("morning", "day", "evening", "night")
assert body["refresh_at"] > body["issued_at"]
assert body["now"]["rain_2h"] is False and body["now"]["temp_c"] == 20.0
assert len(body["top"]) == 3
assert [p["code"] for p in body["picks"]] == ["laundry", "running"]
assert body["sunset"]["best_at"] > body["sunset"]["sunset_at"]
assert all(s["at"] > body["issued_at"] for s in body["slots"])
assert body["timeline"][0]["start_at"] == body["issued_at"]
@pytest.mark.anyio
async def test_watch_summary_unknown_region_fails(offline):
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/watch/summary", params={"region": "0000000000"})).json()
assert body["result"]["success"] is False