From aa774c2a446153efc4bd99c0b49de5bc8cb195e0 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Mon, 12 Oct 2026 15:35:34 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EC=98=A4=EB=8A=98=20=ED=9E=88=EC=96=B4?= =?UTF-8?q?=EB=A1=9C=20D4-2=20=E2=80=94=20=ED=95=B4=20=EC=95=88=20?= =?UTF-8?q?=EC=A0=90=EC=88=98,=20=EC=83=81=ED=83=9C=20=ED=95=9C=20?= =?UTF-8?q?=EC=A4=84(=EC=8A=B5=EB=8F=84=C2=B7=EB=B6=88=EC=BE=8C=EC=A7=80?= =?UTF-8?q?=EC=88=98=C2=B7=EC=9E=90=EC=99=B8=EC=84=A0=C2=B7=EB=AF=B8?= =?UTF-8?q?=EC=84=B8=EB=A8=BC=EC=A7=80=20=EB=8B=A8=EA=B3=84),=20=ED=95=98?= =?UTF-8?q?=EB=A3=A8=20=ED=9D=90=EB=A6=84=20=EC=B9=B8=EC=9D=B4=20=EB=AF=B8?= =?UTF-8?q?=EB=A6=AC=EB=B3=B4=EA=B8=B0=20=ED=83=AD,=20=EA=B5=AC=EB=A6=84?= =?UTF-8?q?=C2=B7=EB=B9=84=C2=B7=EB=88=88=20=EC=97=B0=EC=B6=9C=20/=20?= =?UTF-8?q?=EA=B0=81=20=EC=8B=9C=EA=B0=84=EB=8C=80=EB=B3=84=20=EC=A0=90?= =?UTF-8?q?=EC=88=98=C2=B7=EC=88=9C=EC=9C=84=20=EB=AF=B8=EB=A6=AC=EB=B3=B4?= =?UTF-8?q?=EA=B8=B0=20/=20=EC=9E=90=EC=99=B8=EC=84=A0=20=EC=8B=9C?= =?UTF-8?q?=EA=B0=84=ED=91=9C=20=EB=8B=A8=EA=B3=84=20=EC=83=89=20=EC=B9=A9?= =?UTF-8?q?=20/=20=EB=B0=A4=20=ED=99=94=EB=A9=B4=20=EC=96=B4=EB=91=90?= =?UTF-8?q?=EC=9A=B4=20=EC=95=84=EC=9D=B4=EC=BD=98=20=EB=B9=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 3 +- backend/router/v1/feed/protocol.py | 5 + backend/services/feed_service.py | 42 +++--- backend/services/hero_stats.py | 36 ++++- backend/services/index_service.py | 34 +++-- backend/tests/test_day_slot.py | 8 +- backend/tests/test_feed.py | 7 +- backend/tests/test_hero_stats.py | 18 ++- backend/tests/test_index_api.py | 22 ++- frontend/src/api/client/types.gen.ts | 30 ++++ frontend/src/b/TodayPage.tsx | 202 ++++++++++++++++----------- frontend/src/b/b.css | 97 +++++++++---- frontend/src/b/ui.tsx | 18 ++- 13 files changed, 367 insertions(+), 155 deletions(-) diff --git a/TODO.md b/TODO.md index 807aa30..ae4e7a5 100644 --- a/TODO.md +++ b/TODO.md @@ -94,7 +94,8 @@ | [ ] | 행사 수집이 사용자 한 명당 주변 시도 2~4곳으로 늘어 TourAPI·문화정보 API 호출이 시도 수만큼 늘어남(시도별 하루 1회 캐시) — 운영 배포 때 일일 호출 한도 확인 | 행사 거리 기준 작업 중 발견 | `backend/services/week_service.py` (`_ensure_events`), `backend/docs/load-estimate.md` | | [ ] | 다른 문서의 포스트 종류 목록·행사 시도 기준 설명 갱신 (`PostType` 12 미세먼지, 30km 행사) — `docs/포스트_종류별_내용.html`만 고침 | 문서 점검 | `backend/docs/`, `docs/화면별_데이터_출처.html`, `docs/데이터_흐름.html`, `docs/콘텐츠_설계서.md` | | [ ] | **[결정 필요]** 스켈레톤 작업에서 바뀐 디자인 — 댓글 없음 안내가 글자 두 줄 → 상자(스켈레톤 3줄 크기) | 스켈레톤 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentsSheet`) | -| [ ] | **[결정 필요]** 히어로 시안 A/B/C 중 선택 — 지금은 이전 히어로로 롤백 | 히어로 다듬기 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` | +| [x] | **[결정 필요]** 히어로 시안 A/B/C 중 선택 — 지금은 이전 히어로로 롤백 → 10/12 D4-2로 결정(해 안 점수 + 문장 두 줄은 서버 값 그대로 + 상태 한 줄 + 하루 흐름 칸, 높이는 지금 그대로 약 400px) | 히어로 다듬기 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/b.css` | +| [x] | **[결정 필요]** 히어로 D4-2 상태 한 줄 — ① 습도는 서버가 %만 줘서 단계 기준을 새로 정해야 함 ② 불쾌지수 '불쾌'처럼 판정 이름을 그대로 쓸지 ③ 미세먼지·자외선은 늘 보일지, 조심할 때만 보일지 → 10/12 결정: 습도 건조(30% 미만)·보통(60% 이하)·습함, 불쾌지수 단계 이름 그대로, 늘 4개(밤엔 자외선 빼기) | 히어로 D4-2 시안 | `backend/services/hero_stats.py`, `backend/services/feed_service.py`, `frontend/src/b/TodayPage.tsx` | | [x] | 댓글 좋아요 실패 시 알림 없음 (연결·서버 오류면 줄에 안내, 지워진 댓글이면 목록 새로고침) (화면은 되돌아감) | 댓글 대기 표시 작업 중 발견 | `frontend/src/b/Sheets.tsx` (`CommentRow`) | | [x] | **[결정 필요]** 노을 탭 재정리에서 정한 것 — ① 노을 등급 '흐림' → '잿빛'(피드 노을 포스트 문구도 같이 바뀜) ② 히어로에 '가장 붉을 때' 시각 하나는 결론('몇 시에')으로 남기고 나머지 시각은 시간표 한 곳에만 ③ '나가 볼 만해요/애매해요/쉬어요' 기준 60·40점, 내일·모레는 10점 넘게 높을 때만 '더 나아요' ④ '쉬어요'면 명소 추천 안 함 ⑤ 블루아워 시각은 시민박명 끝(-6°), 골든아워는 해 고도 6° → 10/7 노을 탭 다시 기획으로 대체: 점수 대신 하늘 상황 5가지, 결론은 상황 기준 | 노을 탭 재정리 | `backend/services/calc/sky_score.py`, `backend/services/sky_service.py`, `frontend/src/b/SkyPage.tsx` | | [x] | 노을 히어로 맨 윗줄("오늘 노을 · 구")이 보라 배경 위 흰 13px라 대비 약 3.9:1 (AA 4.5 미달) — 결론·근거·시각·점수는 어두운 상자 안으로 옮김, → 어두운 바탕을 깔아 6.7:1 | 노을 탭 재정리 중 발견 | `frontend/src/b/SkyPage.tsx` | diff --git a/backend/router/v1/feed/protocol.py b/backend/router/v1/feed/protocol.py index b088dcd..d9970f6 100644 --- a/backend/router/v1/feed/protocol.py +++ b/backend/router/v1/feed/protocol.py @@ -11,6 +11,7 @@ class Row(WebPacketProtocol): label: str value: str place: Optional[str] = Field(default=None, description="위치가 정해진 장소면 지도에서 찾을 이름 (앱이 네이버 지도 링크를 건다)") + level: Optional[int] = Field(default=None, description="자외선 단계 1 낮음 ~ 5 위험. 있으면 앱이 값을 단계 색 칩으로 그린다") class HourCell(WebPacketProtocol): @@ -142,6 +143,8 @@ class TopIndex(WebPacketProtocol): rank: int summary: Optional[str] = None active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수") + slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음") + slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음") class HeroStat(WebPacketProtocol): @@ -162,11 +165,13 @@ class Hero(WebPacketProtocol): rain_2h_text: Optional[str] = None will_rain_2h: Optional[bool] = None weather_score: Optional[int] = None + weather_slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 날씨 점수 {morning·day·evening·night: 점수}") top1: Optional[TopIndex] = None bubble: Optional[str] = None moon_name: Optional[str] = Field(default=None, description="오늘 밤 달 모양: 삭·초승달·상현달·차오르는 달·보름달·기우는 달·하현달·그믐달") moon_pct: Optional[int] = Field(default=None, description="달에서 빛나는 면의 비율 0~100 (모양 그림용, 밝기 아님)") stats: list[HeroStat] = Field(default_factory=list, description="히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저") + status: list[HeroStat] = Field(default_factory=list, description="히어로 상태 한 줄: 습도·불쾌지수·자외선(낮에만)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로)") class BandEvent(WebPacketProtocol): diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index 4826c0e..e8864c1 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -30,7 +30,7 @@ from services.calc.index_calc import rank_score from services.calc.moon import MoonNight, nearest, night, view_line from services.calc.sky_score import GRADE_LABEL, sky_title from services.calc.sun import sun_times -from services.hero_stats import UV_HIGH, HeroInput, hero_stats, uv_label +from services.hero_stats import UV_HIGH, HeroInput, discomfort_label, hero_stats, hero_status, uv_label, uv_level from services.index_service import IndexBoard, IndexItem, IndexService from services.now_service import NowService, NowWeather from services.season_service import SeasonService @@ -130,10 +130,6 @@ def _pick(articles: list[Article], day: date) -> Optional[Article]: return articles[day.toordinal() % len(articles)] if articles else None -def _discomfort_label(v: int) -> str: - return "쾌적" if v < 68 else "보통" if v < 75 else "불쾌" if v < 80 else "매우 불쾌" - - def _hero_input( now: datetime, slot: str, cur: Optional[WeatherHourly], now_w: Optional[NowWeather], today: Optional[TodayWeather], uv: Optional[float], moon: Optional[str], ) -> HeroInput: @@ -147,7 +143,7 @@ def _hero_input( air=AirGrade(now_w.air.grade) if now_w and now_w.air and now_w.air.grade is not None else None, uv=uv, temp_min=min(temps, default=None), temp_max=max(temps, default=None), temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None, - moon=moon, + moon=moon, humidity=cur.humidity if cur else None, discomfort=cur.discomfort_index if cur else None, ) @@ -238,7 +234,8 @@ 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, active=i.active) + 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, + slots=i.slots, slot_ranks=i.slot_ranks) async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, regions: RegionCRUD) -> ErrorType: @@ -418,10 +415,10 @@ class FeedService: return [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else [] async def _uv(self, region_code: str, hour: datetime) -> Optional[float]: - err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour, hour)) - if err is not ErrorType.SUCCESS or not rows or rows[0].uv_index is None: - return None - return float(rows[0].uv_index) + """지금 칸의 자외선. Open-Meteo 는 3시간 칸이라 지금 시각을 넘지 않는 마지막 칸을 쓴다.""" + err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather_crud.openmeteo_between(s, region_code, hour - timedelta(hours=2), hour)) + rows = [r for r in rows or [] if r.uv_index is not None] if err is ErrorType.SUCCESS else [] + return float(max(rows, key=lambda r: r.forecast_at).uv_index) if rows else None 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, moon: Optional[tuple[MoonNight, str]] = None) -> Hero: @@ -429,16 +426,18 @@ class FeedService: bubble = None if top is not None: bubble = f"오늘은 {top.definition.name}!" if top.score.score >= 70 else "오늘은 쉬어 가요" + x_in = _hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None) return Hero( now_at=now, sky_mode=_SKY_MODE[slot], temp_c=float(cur.temp_c) if cur else None, feels_c=float(cur.feels_c) if cur else None, humidity=cur.humidity if cur else None, - discomfort=cur.discomfort_index if cur else None, discomfort_label=_discomfort_label(cur.discomfort_index) if cur else None, + discomfort=cur.discomfort_index if cur else None, discomfort_label=discomfort_label(cur.discomfort_index) if cur else None, rain_2h_text=now_w.rain_2h_text if now_w else None, will_rain_2h=now_w.will_rain_2h if now_w else None, - weather_score=board.weather_score if board else None, top1=_top(top) if top else None, bubble=bubble, + weather_score=board.weather_score if board else None, weather_slots=board.weather_slots if board else {}, + top1=_top(top) if top else None, bubble=bubble, moon_name=moon[0].name if moon else None, moon_pct=round(moon[0].lit * 100) if moon else None, - stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) - for x in hero_stats(_hero_input(now, slot, cur, now_w, today, uv, f"{moon[0].name}, {moon[1]}" if moon else None))], + stats=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_stats(x_in)], + status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone) for x in hero_status(x_in)], ) @staticmethod @@ -627,14 +626,13 @@ class FeedService: return None label = uv_label(top) at = peak.forecast_at.astimezone(KST) - rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=f"{round(float(r.uv_index))} · {uv_label(float(r.uv_index))}") for r in c.uv] - high = top >= UV_HIGH - if high: - rows.append(Row(label="이렇게 해요", value="선크림 바르고, 모자·선글라스 챙겨요")) - line = f"{hour_label(at.hour)} 무렵 자외선 {label},\n" + ("선크림 꼭 챙겨요" if high else "오래 밖에 있으면 선크림") - return PostData(**base, title=f"자외선 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)} · {round(top)}", + rows = [Row(label=f"{r.forecast_at.astimezone(KST).hour}시", value=uv_label(float(r.uv_index)), level=uv_level(float(r.uv_index))) for r in c.uv] + when = "점심때" if at.hour == 12 else f"{hour_label(at.hour)} 무렵" + todo = "선크림·모자·선글라스 챙기고 그늘로 다녀요" if top >= UV_HIGH else "선크림·모자 챙겨요" + line = f"오늘 자외선 지수 {label}\n{when} 나가면 {todo}" + return PostData(**base, title=f"자외선 지수 {label}", icon="glasses", caption=f"가장 셀 때 {hour_label(at.hour)}", slides=[RowsSlide(kind="rows", eyebrow=f"오늘 자외선 · {c.region.short_name}", line=line, icon="glasses", rows=rows)], - share_messages=[f"오늘 자외선 {label}, 선크림 챙겨!"]) + share_messages=[f"오늘 자외선 지수 {label}, 선크림 챙겨!"]) def _air(self, base: dict, c: "_Ctx") -> Optional[PostData]: """가까운 측정소의 지금 초미세먼지·미세먼지. 측정값이 없거나 3시간 넘게 지났으면 끈다.""" diff --git a/backend/services/hero_stats.py b/backend/services/hero_stats.py index 031f777..bdac3c6 100644 --- a/backend/services/hero_stats.py +++ b/backend/services/hero_stats.py @@ -10,6 +10,8 @@ from services.air_service import GRADE_LABEL Tone = Literal["normal", "warn", "rain"] UV_HIGH = 6.0 +MUGGY_DI = 75 # 불쾌지수 '불쾌'가 시작되는 값 +HUMID_DRY, HUMID_WET = 30, 60 # 습도 % : 이 아래 건조, 이 위 습함 TEMP_SWING_C = 10.0 WIND_CHILL_C = 3.0 SHOWN = 1 @@ -38,10 +40,42 @@ class HeroInput: temp: Optional[float] = None feels: Optional[float] = None moon: Optional[str] = None + humidity: Optional[int] = None + discomfort: Optional[int] = None + + +_UV_LABELS = ("낮음", "보통", "높음", "매우 높음", "위험") + + +def uv_level(uv: float) -> int: + """기상청 자외선 단계 1 낮음 ~ 5 위험.""" + return 1 if uv < 3 else 2 if uv < 6 else 3 if uv < 8 else 4 if uv < 11 else 5 def uv_label(uv: float) -> str: - return "낮음" if uv < 3 else "보통" if uv < 6 else "높음" if uv < 8 else "매우 높음" if uv < 11 else "위험" + return _UV_LABELS[uv_level(uv) - 1] + + +def discomfort_label(v: int) -> str: + return "쾌적" if v < 68 else "보통" if v < MUGGY_DI else "불쾌" if v < 80 else "매우 불쾌" + + +def humidity_label(h: int) -> str: + return "건조" if h < HUMID_DRY else "보통" if h <= HUMID_WET else "습함" + + +def hero_status(x: HeroInput) -> list[HeroStatItem]: + """히어로 상태 한 줄: 습도·불쾌지수·자외선(낮에만)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn.""" + out: list[HeroStatItem] = [] + if x.humidity is not None: + out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity))) + if x.discomfort is not None: + out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal")) + if not x.night and x.uv is not None: + out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal")) + if x.air is not None: + out.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn" if x.air in (AirGrade.BAD, AirGrade.VERY_BAD) else "normal")) + return out def _rain_value(now: datetime, at: datetime) -> str: diff --git a/backend/services/index_service.py b/backend/services/index_service.py index 0e8608e..3cb8ccf 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -50,6 +50,7 @@ class IndexItem: trend: list[IndexScore] slot: Optional[str] = None slots: dict[str, int] = field(default_factory=dict) + slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음 active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다 @@ -59,6 +60,7 @@ class IndexBoard: day: date weather_score: Optional[int] items: list[IndexItem] + weather_slots: dict[str, int] = field(default_factory=dict) @property def ranked(self) -> list[IndexItem]: @@ -161,6 +163,12 @@ def shown_slot(key: str) -> str: return "night" if key == EARLY else key +def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]: + """구간 점수를 아침·낮·저녁·밤 순으로. 0~5시면 밤은 전날 밤 구간을 쓴다.""" + shown = {shown_slot(k): v for k, v in parts.items() if k != ("night" if cur == EARLY else EARLY)} + return {k: shown[k] for k in SLOTS if k in shown} + + 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]: @@ -253,7 +261,7 @@ class IndexService: if region is None: return ErrorType.NOT_FOUND, None now = now_kst() - err, weather_score = await self.ensure(region, now) + err, weather_parts = await self.ensure(region, now) if err is not ErrorType.SUCCESS: return err, None today = now.date() @@ -278,11 +286,11 @@ class IndexService: 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)} + parts = _shown_parts({k: v["score"] for k, v in row.slots.items()}, cur) 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}, + slot=shown_slot(cur), slots=parts, )) off = sorted( (d for d in defs if d.index_id not in now_score and (d.index_id, today) in by_key), @@ -293,12 +301,18 @@ class IndexService: 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, + slots=_shown_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False, )) - return ErrorType.SUCCESS, IndexBoard(region=region, day=today, weather_score=weather_score, items=items) + for k in SLOTS: + in_slot = sorted((i for i in items if k in i.slots), key=lambda i: rank_score(i.slots[k], i.definition.priority), reverse=True) + for n, i in enumerate(in_slot): + i.slot_ranks[k] = n + 1 + return ErrorType.SUCCESS, IndexBoard( + region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur), + ) - async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[int]]: - """재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 날씨 점수도 같이 낸다.""" + async def ensure(self, region: Region, now: datetime) -> tuple[ErrorType, Optional[dict[str, int]]]: + """재료(예보·미세먼지)가 지수 계산 뒤에 바뀌었으면 오늘~모레와 이번 주말을 다시 계산한다. 오늘 구간별 날씨 점수도 같이 낸다.""" _, _, _, warnings = await asyncio.gather( self.weather_service.ensure_vilage(region, now), self.weather_service.ensure_mid(region, now), self.air_service.ensure(now), self.warning_service.for_region(region, now), @@ -328,7 +342,7 @@ class IndexService: ) today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_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)) + weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at).items()} 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 @@ -339,7 +353,7 @@ class IndexService: _, 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()) and unslotted is False: - return ErrorType.SUCCESS, weather_result.score if weather_result else None + return ErrorType.SUCCESS, weather_parts err, defs = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.definitions(s)) _, holidays = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holidays(s, today, days[-1])) @@ -366,4 +380,4 @@ class IndexService: "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 + return err, weather_parts diff --git a/backend/tests/test_day_slot.py b/backend/tests/test_day_slot.py index ffd6b4f..887c59c 100644 --- a/backend/tests/test_day_slot.py +++ b/backend/tests/test_day_slot.py @@ -5,7 +5,7 @@ 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 +from services.index_service import EARLY, WEATHER_SCORE_DEF, _shown_parts, current_slot, slot_results DAY = date(2026, 10, 8) SUNSET = datetime(2026, 10, 8, 18, 0, tzinfo=KST) @@ -61,3 +61,9 @@ def test_rain_in_evening_lowers_only_later_slots(): 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} + + +def test_shown_parts_uses_last_night_before_five(): + parts = {"morning": 1, "day": 2, "evening": 3, "night": 4, EARLY: 5} + assert _shown_parts(parts, "day") == {"morning": 1, "day": 2, "evening": 3, "night": 4} + assert _shown_parts(parts, EARLY) == {"morning": 1, "day": 2, "evening": 3, "night": 5} diff --git a/backend/tests/test_feed.py b/backend/tests/test_feed.py index cac8684..bfcee06 100644 --- a/backend/tests/test_feed.py +++ b/backend/tests/test_feed.py @@ -62,6 +62,8 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline): assert body["result"]["success"] is True assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"] assert len(body["stories"]) == 34 + assert body["hero"]["weather_score"] == body["hero"]["weather_slots"][body["slot"]] + assert all(g["slots"][body["slot"]] == g["score"] and g["slot_ranks"][body["slot"]] == g["rank"] for g in body["stories"] if g["active"]) weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value) assert [s["kind"] for s in weather["slides"]] == ["hours", "hours"] assert len(weather["slides"][0]["hours"]) == 8 @@ -367,6 +369,9 @@ def test_uv_post_only_when_moderate_or_higher(): base = dict(post_id=1, post_type=PostType.UV, like_count=0, comment_count=0, published_at=at(9)) ctx = lambda vals: SimpleNamespace(region=SimpleNamespace(short_name="분당구"), uv=[SimpleNamespace(forecast_at=at(h), uv_index=v) for h, v in vals]) # noqa: E731 post = FeedService._uv_post(None, base, ctx([(9, 2.0), (12, 6.4), (15, 4.0)])) - assert post.title == "자외선 높음" and post.caption == "가장 셀 때 낮 12시 · 6" and post.slides[0].rows[-1].label == "이렇게 해요" + assert post.title == "자외선 지수 높음" and post.caption == "가장 셀 때 낮 12시" + assert post.slides[0].line == "오늘 자외선 지수 높음\n점심때 나가면 선크림·모자·선글라스 챙기고 그늘로 다녀요" + assert [(r.label, r.value, r.level) for r in post.slides[0].rows] == [("9시", "낮음", 1), ("12시", "높음", 3), ("15시", "보통", 2)] + assert FeedService._uv_post(None, base, ctx([(12, 2.0), (15, 3.4)])).slides[0].line == "오늘 자외선 지수 보통\n오후 3시 무렵 나가면 선크림·모자 챙겨요" assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None assert FeedService._uv_post(None, base, ctx([])) is None diff --git a/backend/tests/test_hero_stats.py b/backend/tests/test_hero_stats.py index fb0ef59..70fcc78 100644 --- a/backend/tests/test_hero_stats.py +++ b/backend/tests/test_hero_stats.py @@ -2,7 +2,7 @@ from datetime import datetime, timedelta from common.enums import AirGrade from common.utils.kma_time import KST -from services.hero_stats import HeroInput, hero_stats +from services.hero_stats import HeroInput, hero_stats, hero_status NOW = datetime(2026, 10, 7, 14, 20, tzinfo=KST) @@ -46,3 +46,19 @@ def test_one_coldwind_card_only(): def test_nothing_known_gives_nothing(): assert hero_stats(HeroInput(now=NOW, night=False)) == [] + + +def _status(x: HeroInput) -> list[tuple[str, str, str]]: + return [(s.label, s.value, s.tone) for s in hero_status(x)] + + +def test_status_line_has_four_by_day_and_warns_only_caution(): + x = HeroInput(now=NOW, night=False, humidity=55, discomfort=75, uv=4.2, air=AirGrade.GOOD) + assert _status(x) == [("습도", "보통", "normal"), ("불쾌지수", "불쾌", "warn"), ("자외선", "보통", "normal"), ("미세먼지", "좋음", "normal")] + x = HeroInput(now=NOW, night=False, humidity=72, discomfort=60, uv=6.0, air=AirGrade.BAD) + assert _status(x) == [("습도", "습함", "normal"), ("불쾌지수", "쾌적", "normal"), ("자외선", "높음", "warn"), ("미세먼지", "나쁨", "warn")] + + +def test_status_line_drops_uv_at_night_and_missing_values(): + assert _status(HeroInput(now=NOW, night=True, humidity=25, uv=3.0, air=AirGrade.NORMAL)) == [("습도", "건조", "normal"), ("미세먼지", "보통", "normal")] + assert _status(HeroInput(now=NOW, night=False)) == [] diff --git a/backend/tests/test_index_api.py b/backend/tests/test_index_api.py index 73b4c86..edc0ce2 100644 --- a/backend/tests/test_index_api.py +++ b/backend/tests/test_index_api.py @@ -130,13 +130,33 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch): 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))) + monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50}))) err, board = await service.board(REGION) assert err is ErrorType.SUCCESS # 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로 assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 80, 2), ("low", 90, 3)] +@pytest.mark.anyio +async def test_board_ranks_each_slot_with_priority_weight(monkeypatch): + today = now_kst().date() + defs = [SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=2, code="high", priority=1)] + every = ("morning", "day", "evening", "night", "early") + slots = {1: {k: {"score": 90, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every}, + 2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every if k not in ("night", "early")}} + scores = [SimpleNamespace(index_id=x, score_date=today, score=80, slots=slots[x]) for x in (1, 2)] + 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, {k: 50 for k in every}))) + monkeypatch.setattr("services.index_service._with_slot", lambda row, data: SimpleNamespace(score=data["score"])) + _, board = await service.board(REGION) + ranks = {i.definition.code: i.slot_ranks for i in board.items} + # 아침: 하 90(63) > 상 20(20). 낮: 상 70(70) > 하 90(63). 상은 밤 구간이 없어 밤 순위도 없다 + assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2 + assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2 + assert "night" not in ranks["high"] + + def _om_row(at, **over): row = { "region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0, diff --git a/frontend/src/api/client/types.gen.ts b/frontend/src/api/client/types.gen.ts index 451a8e0..db8f6a9 100644 --- a/frontend/src/api/client/types.gen.ts +++ b/frontend/src/api/client/types.gen.ts @@ -595,6 +595,14 @@ export type Hero = { * Weather Score */ weather_score?: number | null; + /** + * Weather Slots + * + * 오늘 구간별 날씨 점수 {morning·day·evening·night: 점수} + */ + weather_slots?: { + [key: string]: number; + }; top1?: TopIndex | null; /** * Bubble @@ -618,6 +626,12 @@ export type Hero = { * 히어로 상황 칸 1개. 지금 챙길 것(비·미세먼지·자외선·일교차·체감) 먼저 */ stats?: Array; + /** + * Status + * + * 히어로 상태 한 줄: 습도·불쾌지수·자외선(낮에만)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로) + */ + status?: Array; }; /** @@ -2409,6 +2423,22 @@ export type TopIndex = { * 지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수 */ active?: boolean; + /** + * Slots + * + * 오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음 + */ + slots?: { + [key: string]: number; + }; + /** + * Slot Ranks + * + * 오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음 + */ + slot_ranks?: { + [key: string]: number; + }; }; /** diff --git a/frontend/src/b/TodayPage.tsx b/frontend/src/b/TodayPage.tsx index 18ff165..1e6db7f 100644 --- a/frontend/src/b/TodayPage.tsx +++ b/frontend/src/b/TodayPage.tsx @@ -2,7 +2,7 @@ import { Fragment, useEffect, useState, type ReactNode } from 'react' import { Link } from 'react-router' import { useQuery } from '@tanstack/react-query' import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen' -import type { BandArticle, BandEvent, Hero as HeroData, HeroStat as HeroStatData, ResWeatherToday, TopIndex } from '../api/client/types.gen' +import { RainType, Sky, type BandArticle, type BandEvent, type Hero as HeroData, type ResWeatherToday, type TopIndex, type WeatherSlot } from '../api/client/types.gen' import { cx } from '../lib/utils' import { cardBg, fall, kindOfHour, kst, type Load, loadOf, MEDALS, type TimeKind, WEEKDAYS } from './lib' import { PostCard, PostCardSkel } from './Post' @@ -10,29 +10,22 @@ import { useRegion } from './regionContext' import { useSheet } from './sheetContext' import { useSky } from './skyContext' import { Ic, Rail, Sec, Skel, SkelRail, StateBox, Thumb } from './ui' -import { deg, skyText, slotAt } from './weatherText' +import { deg, slotAt } from './weatherText' type Mode = 'now' | TimeKind -const MODES: [Mode, string][] = [ - ['now', '지금'], - ['morning', '아침'], - ['day', '낮'], - ['sunset', '저녁'], - ['night', '밤'], -] - -// 미리보기 시간대마다 보여 줄 시계와 그 시각의 예보 칸 -const PREVIEW: Record = { - morning: { label: '아침', clock: '07:40', hour: 7 }, - day: { label: '낮', clock: '13:20', hour: 13 }, - sunset: { label: '저녁', clock: '18:25', hour: 18 }, - night: { label: '밤', clock: '22:10', hour: 22 }, +// 하루 흐름 칸 순서와 칸마다 볼 예보 시각 +const KINDS: TimeKind[] = ['morning', 'day', 'sunset', 'night'] +const PREVIEW: Record = { + morning: { label: '아침', hour: 7 }, + day: { label: '낮', hour: 13 }, + sunset: { label: '저녁', hour: 18 }, + night: { label: '밤', hour: 22 }, } -// 히어로 칸을 받아 오는 동안 자리만 잡아 둔다 -const STAT_HOLD = ['a'] -const MUGGY = 75 // 불쾌지수 이 이상이면 경고 색 +// 비·눈 줄기: 위치·주기를 엇갈려 고르게 +const DROPS = Array.from({ length: 22 }, (_, i) => ({ left: `${(i * 41) % 100}%`, '--top': `${(i * 29) % 90}%`, '--dl': `${((i * 37) % 100) / 100}s`, '--dur': `${0.55 + ((i * 13) % 5) / 10}s` })) +const FLAKES = Array.from({ length: 16 }, (_, i) => ({ left: `${(i * 47) % 100}%`, '--top': `${(i * 31) % 90}%`, '--dl': `${((i * 53) % 100) / 25}s`, '--dur': `${3.2 + ((i * 7) % 5) / 2}s` })) const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 })) // 별똥별 셋: 위치·길이·주기를 엇갈려 하나씩 떨어지게 @@ -71,33 +64,74 @@ function heroVal(load: Load, v: ReactNode, skel: string) { const failed = (load: Load) => load === 'error' || load === 'retrying' -type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; feedLoad: Load; todayLoad: Load } +// 미리보기 탭과 서버 구간 이름. 저녁 탭(노을 하늘)은 서버의 evening 구간 +const SLOT_KEY: Record = { morning: 'morning', day: 'day', sunset: 'evening', night: 'night' } -function Hero({ hero, today, feedLoad, todayLoad }: HeroProps) { +/** 미리보기 시간대면 이미 받은 구간 점수·순위로 다시 줄 세운다. 그 구간과 안 겹치는 각은 흐리게 끝으로. 구간 값이 없으면(예전 캐시) 그대로 */ +function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] { + const k = kind && SLOT_KEY[kind] + if (!k || !items.some((g) => Object.keys(g.slot_ranks ?? {}).length)) return items + const on = items.filter((g) => g.slot_ranks?.[k] != null && g.slots?.[k] != null) + return [ + ...on.map((g) => ({ ...g, score: g.slots![k], rank: g.slot_ranks![k], active: true })).sort((a, b) => a.rank - b.rank), + ...items.filter((g) => !on.includes(g)).map((g) => ({ ...g, active: false })), + ] +} + +type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday; ranked: TopIndex[]; feedLoad: Load; todayLoad: Load } + +type Weather = 'clear' | 'partly' | 'cloudy' | 'rain' | 'snow' | 'sleet' + +/** 예보 칸 하나의 하늘: 비·눈이 오면 그걸, 아니면 구름 양 */ +function weatherOf(slot?: WeatherSlot): Weather { + const r = slot?.rain_type + if (r === RainType.RAIN || r === RainType.SHOWER) return 'rain' + if (r === RainType.SNOW) return 'snow' + if (r === RainType.SLEET) return 'sleet' + return slot?.sky === Sky.CLOUDY ? 'cloudy' : slot?.sky === Sky.PARTLY ? 'partly' : 'clear' +} + +const WEATHER_ICON: Record = { clear: 'sun', partly: 'sun_cloud', cloudy: 'cloud', rain: 'rain', snow: 'snow', sleet: 'snow' } +// 구름 수: 구름 많음 둘, 흐림·비·눈 셋 +const CLOUDS = [ + { cls: 'top-9 left-[5%] h-8 w-[84px]', d: '.1s', f: '6s' }, + { cls: 'top-[96px] left-[63%] h-9 w-[96px]', d: '.25s', f: '6.4s' }, + { cls: 'top-[30px] left-[72%] h-7 w-[64px]', d: '.4s', f: '5.4s' }, +] +const CLOUD_N: Record = { clear: 0, partly: 2, cloudy: 3, rain: 3, snow: 3, sleet: 3 } + +function Hero({ hero, today, ranked, feedLoad, todayLoad }: HeroProps) { const { open } = useSheet() const { preview, setServerKind, setPreview } = useSky() const mode: Mode = preview ?? 'now' - const setMode = (m: Mode) => setPreview(m === 'now' ? null : m) const clock = useNow() const t = kst(clock) - const kind = mode === 'now' ? (hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi)) : mode + const nowKind = hero?.sky_mode ?? kindOfHour(t.h, t.mo, t.mi) + const kind = mode === 'now' ? nowKind : mode // 화면 전체 하늘 배경도 같은 시간대로 맞춘다 useEffect(() => setServerKind(hero?.sky_mode ?? null), [hero?.sky_mode, setServerKind]) const slots = today?.slots ?? [] - const slot = slots.length ? slotAt(slots, mode === 'now' ? t.h : PREVIEW[mode].hour) : undefined - // 지금은 /v1/feed hero 값을, 미리보기는 그 시각의 예보 칸을 쓴다 - const temp = mode === 'now' && hero ? hero.temp_c : slot?.temp_c - const top1 = hero?.top1 - const who = kind === 'night' ? 'bear' : 'rabbit' + // 그 시각 칸, 비어 있으면(지난 새벽 칸 등) 그 뒤 첫 예보 칸 + const slotOf = (k: TimeKind | 'now') => { + const h = k === 'now' ? t.h : PREVIEW[k].hour + const s = slots.length ? slotAt(slots, h) : undefined + return s?.temp_c != null ? s : (slots.find((x) => kst(x.at).h > h && x.temp_c != null) ?? s) + } + const weather = weatherOf(slotOf(mode)) + const slotScore = mode === 'now' ? undefined : hero?.weather_slots?.[SLOT_KEY[mode]] + const score = slotScore ?? hero?.weather_score + const slotTop = mode === 'now' ? undefined : ranked.find((g) => g.active) + const top1 = slotTop ?? hero?.top1 // 저녁(노을)부터는 가운데 동그라미가 오늘 밤 달 모양이 된다 const moon = (kind === 'sunset' || kind === 'night') && hero?.moon_name && hero.moon_pct != null ? { name: hero.moon_name, pct: hero.moon_pct, waning: WANING.includes(hero.moon_name) } : null - const tempLoad = mode === 'now' ? feedLoad : todayLoad - const tempChip = temp != null ? `${deg(temp)}${slot ? ` ${skyText(slot)}` : ''}` : null - const bubble = hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null + const bubble = slotTop ? (slotTop.score >= 70 ? `오늘은 ${slotTop.name}!` : '오늘은 쉬어 가요') : hero ? (hero.bubble ?? '오늘은 쉬어 가요') : failed(feedLoad) ? '앗, 날씨를 못 불러왔어요' : null + const status = hero?.status ?? [] + const rain = weather === 'rain' || weather === 'sleet' + const snow = weather === 'snow' || weather === 'sleet' - // 시안 A: 점수 해가 주인공. 위에 시간대 탭과 날짜, 가운데 큰 해, 아래 칩 한 줄과 캐릭터 말풍선(1위 각) + // 시안 D4-2: 가운데 해(점수)와 하늘 날씨, 결론 두 줄, 상태 한 줄, 아래 하루 흐름 칸(누르면 그 시간대 하늘로) return ( -
+
-
- {MODES.map(([m, l]) => ( - - ))} -
-

- {t.mo}월 {t.d}일 {WEEKDAYS[t.wd]} · {mode === 'now' ? `${String(t.h).padStart(2, '0')}:${String(t.mi).padStart(2, '0')}` : PREVIEW[mode].clock} + {(rain || snow) && ( +

+ )} +

+ {t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일

-
-