From 5c05824ce0ff53141683accb28172f5a98734340 Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Mon, 12 Oct 2026 17:20:00 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EA=B3=84=EC=A0=88=20=EA=B0=81=20?= =?UTF-8?q?=E2=80=94=20=EA=B0=81=EB=A7=88=EB=8B=A4=20=EC=A0=9C=EC=B2=A0=20?= =?UTF-8?q?=EB=8B=AC(months),=20=EC=A0=9C=EC=B2=A0=20=EA=B0=81=EC=97=90=20?= =?UTF-8?q?=EC=A7=80=EA=B8=88=20=EA=B3=84=EC=A0=88=20=ED=91=9C=EC=8B=9C?= =?UTF-8?q?=C2=B7=EC=B2=A0=20=EC=A7=80=EB=82=9C=20=EA=B0=81=EC=9D=80=20?= =?UTF-8?q?=EC=88=9C=EC=9C=84=20=EB=B0=96=20=EB=A7=A8=20=EB=81=9D,=20?= =?UTF-8?q?=EC=83=88=20=EA=B0=81=2012=EA=B0=9C(=EA=BD=83=EA=B5=AC=EA=B2=BD?= =?UTF-8?q?=C2=B7=EC=9D=B4=EB=B6=88=EB=B9=A8=EB=9E=98=C2=B7=EB=B9=99?= =?UTF-8?q?=EC=88=98=C2=B7=EC=8B=A4=EB=82=B4=EA=B1=B4=EC=A1=B0=C2=B7?= =?UTF-8?q?=ED=95=9C=EA=B0=95=EB=B0=A4=EB=B0=94=EB=9E=8C=C2=B7=EB=8B=A8?= =?UTF-8?q?=ED=92=8D=C2=B7=EC=96=B5=EC=83=88=C2=B7=EA=B5=B0=EA=B3=A0?= =?UTF-8?q?=EA=B5=AC=EB=A7=88=C2=B7=ED=95=B4=EB=8F=8B=EC=9D=B4=C2=B7?= =?UTF-8?q?=EB=88=88=EC=82=AC=EB=9E=8C=C2=B7=EB=B6=95=EC=96=B4=EB=B9=B5?= =?UTF-8?q?=C2=B7=EA=B7=A4=EA=B9=8C=EB=A8=B9=EA=B8=B0),=20=ED=95=B4=20?= =?UTF-8?q?=EB=9C=B0=20=EB=AC=B4=EB=A0=B5=20=EC=8B=9C=EA=B0=84=EB=8C=80?= =?UTF-8?q?=C2=B7=EC=9D=BC=EC=B6=9C=20=EC=A0=90=EC=88=98=C2=B7=EB=88=88=20?= =?UTF-8?q?=EC=A1=B0=EA=B1=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 5 +- backend/common/database/model/models.py | 1 + backend/postgres-init/init.sql | 4 +- backend/router/v1/index/index.py | 6 +- backend/router/v1/index/protocol.py | 2 + backend/seed/index_definition.json | 966 +++++++++++++++++++++++- backend/services/calc/index_calc.py | 16 +- backend/services/feed_service.py | 3 +- backend/services/index_service.py | 46 +- backend/tests/test_index_api.py | 45 +- backend/tests/test_index_calc.py | 16 + backend/tests/test_index_season.py | 55 ++ frontend/src/api/client/types.gen.ts | 16 +- frontend/src/b/GakPage.tsx | 15 +- 14 files changed, 1130 insertions(+), 66 deletions(-) create mode 100644 backend/tests/test_index_season.py diff --git a/TODO.md b/TODO.md index d173629..f221be3 100644 --- a/TODO.md +++ b/TODO.md @@ -97,7 +97,10 @@ | [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` | | [ ] | **[결정 필요]** 각 목록 '지금 아님' 문구 — 계절이 아니라 각 시간대(등산 7~12시·피크닉 11~16시)가 지났다는 뜻인데 '가을' 표시 옆에 있어 비활성처럼 읽힘. 그 각의 시간('오전에 좋아요' 등)으로 바꿀지 | 사용자 지적 | `frontend/src/b/GakPage.tsx`, `frontend/src/b/TodayPage.tsx` | -| [ ] | **[결정 필요]** 계절별 각 늘리기 — 지금 '가을' 표시는 `is_core` 4개(피크닉·등산·캠핑·별보기)에 글자로 박혀 있고 계절 전환이 없음. 계절마다 각 후보 목록을 만들어 검토받고, 계절 필드로 바꾸기 | 사용자 요청 | `backend/seed/index_definition.json`, `frontend/src/b/GakPage.tsx` | +| [x] | **[결정 필요]** 계절별 각 늘리기 — 지금 '가을' 표시는 `is_core` 4개(피크닉·등산·캠핑·별보기)에 글자로 박혀 있고 계절 전환이 없음. 계절마다 각 후보 목록을 만들어 검토받고, 계절 필드로 바꾸기 → 10/12 `months` 칸 + 새 각 12개, 계절 표시는 서버 `season` | 사용자 요청 | `backend/seed/index_definition.json`, `frontend/src/b/GakPage.tsx` | +| [ ] | 운영 DB에 `index_definition.months` 칸 추가 — `deploy.sh` 가 배포 때 `init.sql`(`ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS months JSONB NOT NULL DEFAULT '[]';`)과 `load_seed.py` 를 돌려서 자동으로 들어감. 배포 뒤 각 탭에 계절 표시가 나오는지만 확인 | 계절 각 | `backend/postgres-init/init.sql`, `deploy.sh` | +| [ ] | **[검토 필요]** 새 각 12개 문구 — 설명·한 줄 문장(0/30/60/80)·한계 문구, '제철 아님' 표시 문구 | 계절 각 | `backend/seed/index_definition.json`, `frontend/src/b/GakPage.tsx` | +| [ ] | 새 각 전용 아이콘 — 꽃구경(화분)·이불빨래/실내건조(빨래)·빙수(아이스커피)·한강밤바람(야장)·억새(볏단)·해돋이(노을)·붕어빵/군고구마(고구마)는 있는 그림 재사용 중 | 계절 각 | `frontend/public/icons/` | | [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/common/database/model/models.py b/backend/common/database/model/models.py index 21f320b..3e2bca0 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.py @@ -185,6 +185,7 @@ class IndexDefinition(Base): sentences: Mapped[dict] = mapped_column(JSONB) sort_order: Mapped[int] = mapped_column(SmallInteger) priority: Mapped[int] = mapped_column(SmallInteger, default=2, server_default="2") + months: Mapped[list] = mapped_column(JSONB, default=list, server_default="[]") # 제철 달. 비면 일 년 내내 class IndexScore(Base): diff --git a/backend/postgres-init/init.sql b/backend/postgres-init/init.sql index b18e791..14452c1 100644 --- a/backend/postgres-init/init.sql +++ b/backend/postgres-init/init.sql @@ -292,12 +292,14 @@ CREATE TABLE IF NOT EXISTS public.index_definition ( limit_description VARCHAR(200) NULL, -- 반영 못 한 것 sentences JSONB NOT NULL DEFAULT '{}', -- 문장 틀 {summary, headline, rabbit, bear, notes} sort_order SMALLINT NOT NULL DEFAULT 0, - priority SMALLINT NOT NULL DEFAULT 2 -- 중요도: 1=상 2=중 3=하. 순위는 점수 × 가중치로 정한다 + priority SMALLINT NOT NULL DEFAULT 2, -- 중요도: 1=상 2=중 3=하. 순위는 점수 × 가중치로 정한다 + months JSONB NOT NULL DEFAULT '[]' -- 제철 달 [9, 10, 11]. 비어 있으면 일 년 내내. 제철이 아니면 순위·피드에서 빠진다 ); ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_uv SMALLINT NOT NULL DEFAULT 0; ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_sun SMALLINT NOT NULL DEFAULT 0; ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS weight_view SMALLINT NOT NULL DEFAULT 0; ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 2; +ALTER TABLE public.index_definition ADD COLUMN IF NOT EXISTS months JSONB NOT NULL DEFAULT '[]'; -- 노을 명소. CREATE TABLE IF NOT EXISTS public.sunset_spot ( diff --git a/backend/router/v1/index/index.py b/backend/router/v1/index/index.py index efcbc6f..c62aef5 100644 --- a/backend/router/v1/index/index.py +++ b/backend/router/v1/index/index.py @@ -17,7 +17,7 @@ def _summary(i: IndexItem, today: date) -> IndexSummary: d = i.definition return 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, + is_core=d.is_core, season=i.season, in_season=i.in_season, 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()], ) @@ -27,7 +27,7 @@ def _summary(i: IndexItem, today: date) -> IndexSummary: async def list_indices( region: str = Query(..., description="구 행정코드"), category: Optional[IndexCategory] = Query(None), - core: bool = Query(False, description="이번 계절 핵심 지수만"), + core: bool = Query(False, description="지금 제철인 각만"), service: IndexService = Depends(), ) -> Res_IndexList: err, board = await service.board(region) @@ -35,7 +35,7 @@ async def list_indices( 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)] + filtered = [x for x in items if (category is None or x.category is category) and (not core or x.season)] return Res_IndexList(region_code=board.region.code, day=board.day, weather_score=board.weather_score, top3=top3, items=filtered) diff --git a/backend/router/v1/index/protocol.py b/backend/router/v1/index/protocol.py index 29f3296..1c1ac86 100644 --- a/backend/router/v1/index/protocol.py +++ b/backend/router/v1/index/protocol.py @@ -28,6 +28,8 @@ class IndexSummary(WebPacketProtocol): category: IndexCategory is_fun: bool is_core: bool + season: Optional[str] = Field(default=None, description="지금 제철이면 계절 이름(봄·여름·가을·겨울). 일 년 내내인 각은 없음") + in_season: bool = Field(default=True, description="false 면 제철이 아니라 순위 밖, 목록 맨 끝") score: int rank: int summary: str diff --git a/backend/seed/index_definition.json b/backend/seed/index_definition.json index 1beecf4..aa1c345 100644 --- a/backend/seed/index_definition.json +++ b/backend/seed/index_definition.json @@ -71,7 +71,8 @@ "80": "18~24°에 바람 살랑, 비 걱정 없음! 오늘은 무조건 바깥 자리 🍻" }, "sort_order": 1, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "picnic", @@ -148,7 +149,15 @@ "80": "20~26°에 바람 잔잔, 김밥 싸서 당장 출발! 🧺" }, "sort_order": 2, - "priority": 1 + "priority": 1, + "months": [ + 3, + 4, + 5, + 9, + 10, + 11 + ] }, { "code": "chimaek", @@ -221,7 +230,8 @@ "80": "20~27°의 선선한 저녁, 치킨에 맥주 부르는 날 🍗" }, "sort_order": 3, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "walk", @@ -292,7 +302,8 @@ "80": "15~23°에 공기 맑고 바람 살랑, 동네 한 바퀴 무조건 🚶" }, "sort_order": 4, - "priority": 1 + "priority": 1, + "months": [] }, { "code": "vent", @@ -368,7 +379,8 @@ "80": "공기 맑고 바람도 적당, 창문 활짝 열 시간 🌬️" }, "sort_order": 5, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "hiking", @@ -455,7 +467,15 @@ "80": "산 위도 선선하고 바람 잔잔, 정상 인증각 ⛰️" }, "sort_order": 6, - "priority": 1 + "priority": 1, + "months": [ + 3, + 4, + 5, + 9, + 10, + 11 + ] }, { "code": "carwash", @@ -528,7 +548,8 @@ "80": "비 걱정 없고 공기도 맑아요. 반짝반짝 오래가는 날 ✨" }, "sort_order": 7, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "camping", @@ -603,7 +624,15 @@ "80": "밤새 12~22°에 바람 잔잔, 불멍하기 딱 좋은 밤 🔥" }, "sort_order": 8, - "priority": 1 + "priority": 1, + "months": [ + 4, + 5, + 6, + 9, + 10, + 11 + ] }, { "code": "running", @@ -675,7 +704,8 @@ "80": "8~18°에 공기 보송, 기록 갱신각 🏃" }, "sort_order": 9, - "priority": 1 + "priority": 1, + "months": [] }, { "code": "stars", @@ -741,7 +771,15 @@ "80": "달은 어둡고 공기는 맑아요. 은하수 노려볼 만한 밤 ✨" }, "sort_order": 10, - "priority": 2 + "priority": 2, + "months": [ + 9, + 10, + 11, + 12, + 1, + 2 + ] }, { "code": "jjamppong", @@ -800,7 +838,8 @@ "80": "춥고 비까지! 얼큰한 짬뽕 한 그릇 무조건 🍜" }, "sort_order": 11, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "makgeolli", @@ -857,7 +896,8 @@ "80": "비 오고 선선한 저녁, 파전에 막걸리 확정 🍶" }, "sort_order": 12, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "iced_hot", @@ -912,7 +952,8 @@ "80": "아침이 한 자릿수, 따뜻한 커피 없인 못 버텨요 ☕" }, "sort_order": 13, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "laundry", @@ -977,7 +1018,8 @@ "80": "따뜻하고 보송한데 바람까지 솔솔, 이불 빨래 가능한 날 ☀️" }, "sort_order": 14, - "priority": 1 + "priority": 1, + "months": [] }, { "code": "bike", @@ -1064,7 +1106,8 @@ "80": "15~24°에 바람 잔잔, 멀리 달려도 좋은 날 🚲" }, "sort_order": 15, - "priority": 1 + "priority": 1, + "months": [] }, { "code": "dog", @@ -1144,7 +1187,8 @@ "80": "5~22°에 공기 맑음, 멍멍이 신나는 날 🐶" }, "sort_order": 16, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "glasses", @@ -1199,7 +1243,8 @@ "80": "영하권 아침에 습하기까지, 문 열자마자 앞이 하얘져요 👓" }, "sort_order": 17, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "makeup", @@ -1254,7 +1299,8 @@ "80": "30° 넘는 찜통에 습도까지, 기름종이 필수 🫠" }, "sort_order": 18, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "naengmyeon", @@ -1311,7 +1357,12 @@ "80": "30° 넘는 한낮, 살얼음 동동 냉면 확정 🥶" }, "sort_order": 19, - "priority": 3 + "priority": 3, + "months": [ + 6, + 7, + 8 + ] }, { "code": "taxi", @@ -1368,7 +1419,8 @@ "80": "비 오는 추운 밤, 택시 전쟁이에요. 막차 타세요 🚕" }, "sort_order": 20, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "delivery", @@ -1426,7 +1478,8 @@ "80": "비 오는 추운 저녁, 배달 한참 걸려요. 지금 바로 주문! 🛵" }, "sort_order": 21, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "garden", @@ -1500,7 +1553,8 @@ "80": "12~25°의 보송한 아침, 분갈이까지 해도 되는 날 🌱" }, "sort_order": 22, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "photo", @@ -1569,7 +1623,8 @@ "80": "노을 점수 높고 공기 맑음, 인생샷 각 📸" }, "sort_order": 23, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "baseball", @@ -1636,7 +1691,8 @@ "80": "15~25°에 비 걱정 없음, 응원가 목청껏 부르는 날 ⚾" }, "sort_order": 24, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "study", @@ -1694,7 +1750,8 @@ "80": "비 오고 춥거나 더워서 나갈 맛이 안 나요. 집중각 📚" }, "sort_order": 25, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "netflix", @@ -1751,7 +1808,8 @@ "80": "비 오는 주말 앞 밤, 정주행 시작각 🍿" }, "sort_order": 26, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "chestnut", @@ -1806,7 +1864,14 @@ "80": "영하 가까운 저녁, 군밤 품고 걷는 날 🌰" }, "sort_order": 27, - "priority": 3 + "priority": 3, + "months": [ + 10, + 11, + 12, + 1, + 2 + ] }, { "code": "golf", @@ -1889,7 +1954,8 @@ "80": "15~24°에 바람 잔잔, 인생 라운딩 노려볼 날 ⛳" }, "sort_order": 28, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "jipkok", @@ -1951,7 +2017,8 @@ "80": "비 오고 공기까지 탁해요. 이불 밖은 위험해 🛋️" }, "sort_order": 29, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "fishing", @@ -2031,7 +2098,8 @@ "80": "12~24°에 물결 잔잔, 입질 기다리기 딱 좋은 날 🎣" }, "sort_order": 30, - "priority": 2 + "priority": 2, + "months": [] }, { "code": "drive", @@ -2105,7 +2173,8 @@ "80": "공기 맑고 멀리까지 보여요. 해안도로 달리고 싶은 날 🚗" }, "sort_order": 31, - "priority": 1 + "priority": 1, + "months": [] }, { "code": "kite", @@ -2180,7 +2249,8 @@ "80": "초속 2~5m 딱 좋은 바람, 연이 하늘 높이 쭉쭉 🪁" }, "sort_order": 32, - "priority": 3 + "priority": 3, + "months": [] }, { "code": "waterplay", @@ -2256,7 +2326,12 @@ "80": "30° 안팎에 쨍쨍, 튜브 들고 풍덩 🏖️" }, "sort_order": 33, - "priority": 2 + "priority": 2, + "months": [ + 6, + 7, + 8 + ] }, { "code": "kimjang", @@ -2323,6 +2398,827 @@ "80": "0~10°에 비 없고 바람 잔잔, 김장 날 잡는 날 🥬" }, "sort_order": 34, - "priority": 3 + "priority": 3, + "months": [ + 11, + 12 + ] + }, + { + "code": "flower", + "name": "꽃구경각", + "icon": "garden", + "category": 1, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "오전 10시~오후 5시, 꽃 보러 나들이 가기 좋은 정도", + "windows": [ + { + "from": 10, + "to": 17 + } + ], + "weight_temp": 20, + "weight_rain": 25, + "weight_wind": 10, + "weight_humidity": 0, + "weight_air": 15, + "weight_uv": 0, + "weight_sun": 20, + "weight_view": 5, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "range", + "lo": 14, + "hi": 24 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "calm", + "ok": 4, + "limit": 10 + }, + "humidity": { + "type": "ignore" + }, + "sun": { + "zero": 0.2, + "full": 0.8 + }, + "view": { + "zero": 5, + "full": 20 + }, + "time": { + "type": "weekday", + "sat": 100, + "sun": 100, + "holiday": 100, + "default": 60 + } + }, + "zero_rules": [ + { + "field": "rain_prob", + "op": ">=", + "value": 60 + } + ], + "limit_description": "꽃이 피었는지(개화 시기)는 반영하지 못해요", + "sentences": { + "0": "비 소식이 있어요. 꽃구경은 다음 맑은 날로!", + "30": "쌀쌀하거나 공기가 탁해요. 잠깐 보고 오기 좋아요.", + "60": "꽃 보러 나가기 괜찮은 날이에요.", + "80": "햇살 좋고 바람 잔잔, 꽃길 걷기 딱 좋아요 🌸" + }, + "sort_order": 35, + "priority": 2, + "months": [ + 3, + 4, + 5 + ] + }, + { + "code": "blanket", + "name": "이불빨래각", + "icon": "laundry", + "category": 3, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "이불처럼 두꺼운 빨래가 하루 만에 마르는 정도", + "windows": [ + { + "from": 9, + "to": 16 + } + ], + "weight_temp": 10, + "weight_rain": 30, + "weight_wind": 15, + "weight_humidity": 15, + "weight_air": 10, + "weight_uv": 0, + "weight_sun": 20, + "weight_view": 0, + "weight_time": 0, + "factor_rules": { + "temp": { + "type": "higher", + "zero": 8, + "full": 22 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "moderate" + }, + "humidity": { + "type": "lower" + }, + "sun": { + "zero": 0.3, + "full": 0.9 + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [ + { + "field": "rain_prob", + "op": ">=", + "value": 40 + } + ], + "limit_description": "베란다 방향·햇빛 드는 시간은 반영하지 못해요", + "sentences": { + "0": "비 소식이 있어요. 이불은 다음에!", + "30": "두꺼운 건 덜 마를 수 있어요. 얇은 이불만!", + "60": "이불 널기 괜찮은 날이에요. 오후에 한 번 뒤집어요.", + "80": "햇볕 쨍쨍에 바람 솔솔, 이불 빨래하는 날 ☀️" + }, + "sort_order": 36, + "priority": 2, + "months": [ + 3, + 4, + 5 + ] + }, + { + "code": "bingsu", + "name": "빙수각", + "icon": "iced_hot", + "category": 2, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "오후 1~6시, 시원한 빙수가 당기는 정도", + "windows": [ + { + "from": 13, + "to": 18 + } + ], + "weight_temp": 60, + "weight_rain": 10, + "weight_wind": 5, + "weight_humidity": 20, + "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "higher", + "zero": 22, + "full": 33 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "calm", + "ok": 4, + "limit": 12 + }, + "humidity": { + "type": "higher" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [], + "limit_description": "재미로 보는 지수예요", + "sentences": { + "0": "아직 선선해요. 빙수는 더운 날에!", + "30": "시원한 게 살짝 당기는 정도예요.", + "60": "오후가 덥네요. 빙수 한 그릇 생각나요!", + "80": "푹푹 찌는 오후, 팥빙수 확정 🍧" + }, + "sort_order": 37, + "priority": 3, + "months": [ + 6, + 7, + 8 + ] + }, + { + "code": "indoordry", + "name": "실내건조각", + "icon": "laundry", + "category": 3, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "밖에 못 너는 날, 집 안에서 빨래 말리기 좋은 정도", + "windows": [ + { + "from": 9, + "to": 21 + } + ], + "weight_temp": 15, + "weight_rain": 40, + "weight_wind": 0, + "weight_humidity": 40, + "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "higher", + "zero": 15, + "full": 28 + }, + "rain": { + "dir": "wet" + }, + "wind": { + "type": "ignore" + }, + "humidity": { + "type": "lower" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [], + "limit_description": "집 안 습도·환기·제습기 여부는 반영하지 못해요", + "sentences": { + "0": "밖에 널어도 되는 날이에요. 빨래각을 봐요!", + "30": "눅눅해서 실내에서도 잘 안 말라요. 선풍기를 같이 틀어요.", + "60": "비 와도 실내에선 그럭저럭 말라요.", + "80": "비는 오지만 덜 습해서, 실내 건조로 충분해요 👕" + }, + "sort_order": 38, + "priority": 3, + "months": [ + 6, + 7, + 8 + ] + }, + { + "code": "riverwind", + "name": "한강밤바람각", + "icon": "yajang", + "category": 1, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "저녁 7~11시, 강가에서 밤바람 쐬기 좋은 정도", + "windows": [ + { + "from": 19, + "to": 23 + } + ], + "weight_temp": 30, + "weight_rain": 30, + "weight_wind": 20, + "weight_humidity": 10, + "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "range", + "lo": 20, + "hi": 28, + "best": 24 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "moderate" + }, + "humidity": { + "type": "range", + "lo": 40, + "hi": 75, + "best": 55 + }, + "time": { + "type": "weekday", + "sat": 100, + "sun": 100, + "holiday": 100, + "default": 60 + } + }, + "zero_rules": [ + { + "field": "rain_prob", + "op": ">=", + "value": 60 + } + ], + "limit_description": "강가 모기·혼잡도는 반영하지 못해요", + "sentences": { + "0": "비 소식이 있어요. 오늘 밤은 집에서!", + "30": "바람이 없거나 너무 눅눅해요. 잠깐만 나가요.", + "60": "밤바람 쐬러 나가기 괜찮아요.", + "80": "선선한 바람 솔솔, 강가 돗자리 각 🌙" + }, + "sort_order": 39, + "priority": 2, + "months": [ + 6, + 7, + 8 + ] + }, + { + "code": "foliage", + "name": "단풍각", + "icon": "maple", + "category": 1, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "오전 9시~오후 4시, 단풍 구경 가기 좋은 정도", + "windows": [ + { + "from": 9, + "to": 16 + } + ], + "weight_temp": 15, + "weight_rain": 25, + "weight_wind": 10, + "weight_humidity": 0, + "weight_air": 10, + "weight_uv": 0, + "weight_sun": 20, + "weight_view": 15, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "range", + "lo": 10, + "hi": 22 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "calm", + "ok": 4, + "limit": 12 + }, + "humidity": { + "type": "ignore" + }, + "sun": { + "zero": 0.2, + "full": 0.8 + }, + "view": { + "zero": 5, + "full": 20 + }, + "time": { + "type": "weekday", + "sat": 100, + "sun": 100, + "holiday": 100, + "default": 60 + } + }, + "zero_rules": [ + { + "field": "rain_prob", + "op": ">=", + "value": 60 + } + ], + "limit_description": "단풍이 얼마나 물들었는지는 반영하지 못해요. 계절 소식의 단풍 시기를 같이 봐요", + "sentences": { + "0": "비 소식이 있어요. 단풍은 다음 맑은 날로!", + "30": "하늘이 흐리거나 뿌예서 색이 덜 살아요.", + "60": "단풍 보러 가기 괜찮은 날이에요.", + "80": "하늘 맑고 멀리까지 잘 보여요, 단풍 나들이 각 🍁" + }, + "sort_order": 40, + "priority": 2, + "months": [ + 9, + 10, + 11 + ] + }, + { + "code": "silvergrass", + "name": "억새각", + "icon": "sheaf", + "category": 1, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "해 지기 전후, 억새밭 걷기 좋은 정도", + "windows": [ + { + "around": "sunset", + "hours": 2 + } + ], + "weight_temp": 10, + "weight_rain": 25, + "weight_wind": 15, + "weight_humidity": 0, + "weight_air": 10, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 10, + "weight_time": 30, + "factor_rules": { + "temp": { + "type": "range", + "lo": 10, + "hi": 24 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "moderate" + }, + "humidity": { + "type": "ignore" + }, + "view": { + "zero": 5, + "full": 20 + }, + "time": { + "type": "sunset_score" + } + }, + "zero_rules": [ + { + "field": "rain_prob", + "op": ">=", + "value": 70 + } + ], + "limit_description": "억새밭 위치·개화 정도는 반영하지 못해요", + "sentences": { + "0": "비 소식이 있어요. 억새는 다음에!", + "30": "노을이 약하거나 하늘이 흐려요. 낮에 잠깐 보고 와요.", + "60": "해 질 무렵 억새 보러 가기 괜찮아요.", + "80": "바람에 일렁이는 억새에 노을까지, 사진 각 🌾" + }, + "sort_order": 41, + "priority": 3, + "months": [ + 9, + 10, + 11 + ] + }, + { + "code": "sweetpotato", + "name": "군고구마각", + "icon": "sweet_potato", + "category": 2, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "오후 4~9시, 따끈한 군고구마가 당기는 정도", + "windows": [ + { + "from": 16, + "to": 21 + } + ], + "weight_temp": 60, + "weight_rain": 20, + "weight_wind": 10, + "weight_humidity": 0, + "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "lower", + "zero": 18, + "full": 2 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "strong" + }, + "humidity": { + "type": "ignore" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [], + "limit_description": "재미로 보는 지수예요", + "sentences": { + "0": "아직 포근해요. 군고구마는 더 추워지면!", + "30": "저녁이 선선해졌어요. 군고구마가 슬슬 생각나요.", + "60": "쌀쌀한 저녁, 군고구마 한 봉지 어때요?", + "80": "찬 바람 부는 저녁, 호호 불어 먹는 군고구마 🍠" + }, + "sort_order": 42, + "priority": 3, + "months": [ + 10, + 11, + 12, + 1, + 2 + ] + }, + { + "code": "sunrise", + "name": "해돋이각", + "icon": "sunset", + "category": 1, + "is_fun": false, + "is_core": false, + "has_detail": true, + "description": "해 뜰 무렵, 해돋이 보러 가기 좋은 정도", + "windows": [ + { + "around": "sunrise", + "hours": 1 + } + ], + "weight_temp": 10, + "weight_rain": 20, + "weight_wind": 10, + "weight_humidity": 0, + "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 15, + "weight_time": 40, + "factor_rules": { + "temp": { + "type": "higher", + "zero": -15, + "full": 5 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "calm", + "ok": 4, + "limit": 12 + }, + "humidity": { + "type": "ignore" + }, + "view": { + "zero": 5, + "full": 20 + }, + "time": { + "type": "sunrise_score" + } + }, + "zero_rules": [ + { + "field": "rain_prob", + "op": ">=", + "value": 60 + } + ], + "limit_description": "바다·산처럼 동쪽이 트인 곳인지는 반영하지 못해요", + "sentences": { + "0": "비나 눈 소식이 있어요. 해돋이는 다음에!", + "30": "구름이 많아 해가 가려질 수 있어요.", + "60": "해돋이 보러 가기 괜찮아요. 따뜻하게 입어요.", + "80": "하늘 맑고 멀리까지 보여요, 해돋이 각 🌅" + }, + "sort_order": 43, + "priority": 2, + "months": [ + 12, + 1, + 2 + ] + }, + { + "code": "snowman", + "name": "눈사람각", + "icon": "snow", + "category": 1, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "눈 온 날 낮, 눈사람 만들기 좋은 정도", + "windows": [ + { + "from": 9, + "to": 16 + } + ], + "weight_temp": 50, + "weight_rain": 10, + "weight_wind": 20, + "weight_humidity": 0, + "weight_air": 0, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 20, + "factor_rules": { + "temp": { + "type": "range", + "lo": -5, + "hi": 2, + "best": -1 + }, + "rain": { + "dir": "wet" + }, + "wind": { + "type": "calm", + "ok": 3, + "limit": 10 + }, + "humidity": { + "type": "ignore" + }, + "time": { + "type": "weekday", + "sat": 100, + "sun": 100, + "holiday": 100, + "default": 60 + } + }, + "zero_rules": [ + { + "field": "snow", + "op": "==", + "value": "no" + } + ], + "limit_description": "쌓인 눈의 양은 반영하지 못해요. 눈 오는 시간만 봐요", + "sentences": { + "0": "눈 소식이 없어요. 눈사람은 눈 오는 날에!", + "30": "눈은 오지만 너무 춥거나 녹아서 잘 안 뭉쳐요.", + "60": "눈사람 만들기 괜찮아요. 장갑 꼭 챙겨요.", + "80": "포슬포슬 잘 뭉쳐지는 눈, 눈사람 각 ⛄" + }, + "sort_order": 44, + "priority": 3, + "months": [ + 12, + 1, + 2 + ] + }, + { + "code": "bungeoppang", + "name": "붕어빵각", + "icon": "sweet_potato", + "category": 2, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "오후 3~9시, 붕어빵이 당기는 정도", + "windows": [ + { + "from": 15, + "to": 21 + } + ], + "weight_temp": 60, + "weight_rain": 15, + "weight_wind": 15, + "weight_humidity": 0, + "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "lower", + "zero": 12, + "full": -5 + }, + "rain": { + "dir": "dry" + }, + "wind": { + "type": "strong" + }, + "humidity": { + "type": "ignore" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [], + "limit_description": "붕어빵 노점이 있는지는 반영하지 못해요", + "sentences": { + "0": "아직 덜 추워요. 붕어빵은 더 추워지면!", + "30": "쌀쌀해졌어요. 붕어빵 노점이 생각나요.", + "60": "손이 시려요. 붕어빵 한 봉지 어때요?", + "80": "꽁꽁 언 오후, 따끈한 붕어빵 확정 🐟" + }, + "sort_order": 45, + "priority": 3, + "months": [ + 12, + 1, + 2 + ] + }, + { + "code": "tangerine", + "name": "귤까먹기각", + "icon": "tangerine", + "category": 3, + "is_fun": true, + "is_core": false, + "has_detail": true, + "description": "저녁 7시~자정, 이불 속에서 귤 까먹고 싶은 정도", + "windows": [ + { + "from": 19, + "to": 24 + } + ], + "weight_temp": 50, + "weight_rain": 20, + "weight_wind": 20, + "weight_humidity": 0, + "weight_air": 5, + "weight_uv": 0, + "weight_sun": 0, + "weight_view": 0, + "weight_time": 5, + "factor_rules": { + "temp": { + "type": "lower", + "zero": 12, + "full": -5 + }, + "rain": { + "dir": "wet" + }, + "wind": { + "type": "strong" + }, + "humidity": { + "type": "ignore" + }, + "time": { + "type": "fixed", + "value": 100 + } + }, + "zero_rules": [], + "limit_description": "재미로 보는 지수예요", + "sentences": { + "0": "밤이 포근해요. 산책이라도 나가 봐요!", + "30": "살짝 쌀쌀한 밤, 귤 한두 개 생각나요.", + "60": "추운 밤이에요. 이불 속 귤 까먹기 좋아요.", + "80": "바람 쌩쌩 추운 밤, 귤 한 상자 각 🍊" + }, + "sort_order": 46, + "priority": 3, + "months": [ + 12, + 1, + 2 + ] } -] \ No newline at end of file +] diff --git a/backend/services/calc/index_calc.py b/backend/services/calc/index_calc.py index 5416f66..db52844 100644 --- a/backend/services/calc/index_calc.py +++ b/backend/services/calc/index_calc.py @@ -55,6 +55,7 @@ class Context: wind_warning: bool lookahead_rain_prob: int moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간 + sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각) @dataclass(frozen=True) @@ -203,13 +204,17 @@ def time_score(rule: dict, ctx: Context) -> tuple[int, str]: return (ctx.sunset_score if ctx.sunset_score is not None else _UNKNOWN), ( f"노을 점수 {ctx.sunset_score}" if ctx.sunset_score is not None else f"노을 점수 계산 전이라 {_UNKNOWN}점으로 둬요" ) + if kind == "sunrise_score": + return (ctx.sunrise_score if ctx.sunrise_score is not None else _UNKNOWN), ( + f"일출 하늘 점수 {ctx.sunrise_score}" if ctx.sunrise_score is not None else f"일출 하늘 점수 계산 전이라 {_UNKNOWN}점으로 둬요" + ) return _clamp(rule["value"]), f"날짜와 상관없이 이 시간대 기본 점수 {_clamp(rule['value'])}점" _TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"} _WIND_LABEL = {"calm": "바람 잔잔", "moderate": "바람 적당", "strong": "바람 셈", "ignore": "바람 무관"} _HUMIDITY_LABEL = {"range": "습도 알맞음", "higher": "습도 높음", "lower": "습도 낮음", "ignore": "습도 무관"} -_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "fixed": "시간대 알맞음"} +_TIME_LABEL = {"weekday": "요일 알맞음", "moon": "달 어두움", "sunset_score": "노을 예쁨", "sunrise_score": "일출 하늘 예쁨", "fixed": "시간대 알맞음"} # Open-Meteo 보조 축. 비중이 있는 지수에만 나온다. _OM_LABEL = {"uv": "자외선 약함", "sun": "햇빛", "view": "가시거리"} @@ -253,6 +258,8 @@ def _cond(r: dict) -> tuple[str, str, str]: """조건 하나를 (이유, '…이거나', '…이면') 꼴로.""" if r["field"] == "warning": return "강풍 특보가 있어", "강풍 특보가 있거나", "강풍 특보가 있으면" + if r["field"] == "snow": + return "눈 소식이 없어", "눈 소식이 없거나", "눈 소식이 없으면" base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}" return f"{base}이라", f"{base}이거나", f"{base}이면" @@ -333,6 +340,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re "cloudy_ratio": round(100 * sum(h.sky is Sky.CLOUDY for h in hours) / len(hours)), "warning": "wind" if ctx.wind_warning else None, "gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None), + "snow": "yes" if any(h.rain_type in (RainType.SNOW, RainType.SLEET) for h in hours) else "no", } reason, cap = _zero(definition.zero_rules, agg) if reason is not None: @@ -351,7 +359,7 @@ def hour_temp(lo: float, hi: float, hour: int) -> float: def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context, next_fc: Optional[DayForecast] = None) -> Optional[Result]: - """중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률만 본다.""" + """중기예보로 내는 예상 점수. 기온·비는 정의 규칙 그대로, 바람·습도·미세먼지·자외선·햇빛·가시거리는 정보 없음으로 둔다. 0점 조건은 비 확률과 눈(늘 없음으로 봄)만 본다.""" if fc.temp_min_c is None or fc.temp_max_c is None: return None best: Optional[Result] = None @@ -381,7 +389,9 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context factors = {a: v for a, (v, _) in scored.items()} notes = {a: n for a, (_, n) in scored.items()} score = _weighted(factors, weights) - reason, cap = _zero([r for r in definition.zero_rules if r["field"] == "rain_prob"], {"rain_prob": max_prob}) + # 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다 + known = {"rain_prob": max_prob, "snow": "no"} + reason, cap = _zero([r for r in definition.zero_rules if r["field"] in known], known) if reason is not None: score = min(score, cap) mid = hours[len(hours) // 2] diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index 4a34504..b2c4ce1 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -371,7 +371,8 @@ class FeedService: for p, item in zip(gak_posts, gak): cards.append(self._gak(p, item)) has_warning = bool(now_w and now_w.warnings) - items = board.items if board else [] + # 오늘 이야기 줄엔 제철인 각만 (철 지난 각은 각 탭 목록 끝에만) + items = [i for i in board.items if i.in_season] if board else [] feed = 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, today, await self._uv(region.code, hour), _moon_view(region, now, hourly or [])), diff --git a/backend/services/index_service.py b/backend/services/index_service.py index 3cb8ccf..2bf7d89 100644 --- a/backend/services/index_service.py +++ b/backend/services/index_service.py @@ -42,6 +42,26 @@ WEATHER_SCORE_DEF = SimpleNamespace( ) +SEASONS = ("겨울", "봄", "여름", "가을") + + +def season_of(month: int) -> str: + """봄 3–5 · 여름 6–8 · 가을 9–11 · 겨울 12–2.""" + return SEASONS[month % 12 // 3] + + +def in_season(defn, month: int) -> bool: + """제철 달이 없으면 일 년 내내.""" + months = getattr(defn, "months", None) + return not months or month in months + + +def season_badge(defn, month: int) -> Optional[str]: + """제철이 정해진 각이 지금 제철이면 그 계절 이름. 일 년 내내인 각은 없음.""" + months = getattr(defn, "months", None) + return season_of(month) if months and month in months else None + + @dataclass class IndexItem: definition: IndexDefinition @@ -52,6 +72,8 @@ class IndexItem: slots: dict[str, int] = field(default_factory=dict) slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음 active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다 + season: Optional[str] = None # 지금 제철이면 계절 이름 (화면 표시) + in_season: bool = True # 제철이 아니면 순위·피드에서 빼고 목록 맨 끝에 둔다 @dataclass @@ -92,11 +114,12 @@ def slot_label(day: date, today: date) -> str: def window_hours(defn, day: date, region: Region) -> list[list[int]]: - """시간대 정의를 그날 기준 시각 목록으로. 24 이상은 다음 날 시각.""" + """시간대 정의를 그날 기준 시각 목록으로. 24 이상은 다음 날 시각. around 는 일몰·일출 시각 ±hours.""" out = [] for w in defn.windows: - if w.get("around") == "sunset": - h = sun_times(day, float(region.lat), float(region.lon)).sunset_at.astimezone(KST).hour + if w.get("around") in ("sunset", "sunrise"): + sun = sun_times(day, float(region.lat), float(region.lon)) + h = (sun.sunset_at if w["around"] == "sunset" else sun.sunrise_at).astimezone(KST).hour out.append(list(range(h - w.get("hours", 1), h + w.get("hours", 1) + 1))) else: out.append(list(range(w["from"], w["to"]))) @@ -272,6 +295,9 @@ class IndexService: 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} + month = today.month + out_season = [d for d in defs if not in_season(d, month)] + defs = [d for d in defs if in_season(d, month)] # 오늘 점수는 지금 구간 점수. 구간 점수가 없는 행(예전 계산분)은 하루 점수 그대로, 지금 구간과 안 겹치는 각은 뺀다 now_score: dict[int, IndexScore] = {} for d in defs: @@ -290,7 +316,7 @@ class IndexService: 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=parts, + slot=shown_slot(cur), slots=parts, season=season_badge(d, month), )) off = sorted( (d for d in defs if d.index_id not in now_score and (d.index_id, today) in by_key), @@ -301,12 +327,19 @@ 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_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False, + slots=_shown_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False, season=season_badge(d, month), )) 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 + # 제철이 아닌 각은 구간 순위 없이 맨 끝에 + for d in sorted((d for d in out_season if (d.index_id, today) in by_key), key=lambda d: d.sort_order): + 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], active=False, in_season=False, + )) return ErrorType.SUCCESS, IndexBoard( region=region, day=today, weather_score=weather_parts.get(cur), items=items, weather_slots=_shown_parts(weather_parts, cur), ) @@ -359,6 +392,7 @@ class IndexService: _, holidays = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.holidays(s, today, days[-1])) _, sky_scores = await DB_SESSION_MNG.execute_lambda(lambda s: self.sky.scores(s, [region.code], today)) sunset = {x.score_date: x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNSET.value} + sunrise = {x.score_date: x.score for x in sky_scores or [] if x.sky_type == SkyType.SUNRISE.value} if err is not ErrorType.SUCCESS: return err, None out = [] @@ -366,7 +400,7 @@ class IndexService: m = night(day, float(region.lat), float(region.lon)) ctx = Context( day=day, is_holiday=day in (holidays or set()), moon=m.lit * up_ratio(m, _STARS_HOURS), moon_note=f"{m.name}, {view_line(m, None)}", - sunset_score=sunset.get(day), lookahead_rain_prob=0, **base_ctx, + sunset_score=sunset.get(day), sunrise_score=sunrise.get(day), lookahead_rain_prob=0, **base_ctx, ) for d in defs: result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om) diff --git a/backend/tests/test_index_api.py b/backend/tests/test_index_api.py index edc0ce2..d4ecba8 100644 --- a/backend/tests/test_index_api.py +++ b/backend/tests/test_index_api.py @@ -15,7 +15,7 @@ from crud.region_crud import RegionCRUD from crud.weather_crud import WeatherCRUD from router.router import app from services.calc.index_calc import rank_score -from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for +from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, season_of, slot_days, slot_label, windows_for REGION = "1141000000" @@ -54,17 +54,19 @@ def fakes(monkeypatch): @pytest.mark.anyio -async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes): +async def test_index_list_ranks_every_gak_with_today_tomorrow_weekend_trend(fakes): async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: body = (await client.get("/v1/index/list", params={"region": REGION})).json() assert body["result"]["success"] is True - assert len(body["items"]) == 34 and len(body["top3"]) == 3 + assert len(body["items"]) == len(_seed()) and len(body["top3"]) == 3 priority = {d["code"]: d["priority"] for d in _seed()} - # 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤. 각 묶음 안에서는 점수 × 중요도 순 + # 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤, 제철 아닌 각은 맨 끝. 앞 두 묶음 안에서는 점수 × 중요도 순 actives = [i["active"] for i in body["items"]] assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"]) + seasons = [i["in_season"] for i in body["items"]] + assert seasons == sorted(seasons, reverse=True) and all(i["active"] is False for i in body["items"] if not i["in_season"]) for group in (True, False): - weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group] + weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]] assert weighted == sorted(weighted, reverse=True) today = now_kst().date() for i in body["items"]: @@ -75,10 +77,12 @@ async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes): @pytest.mark.anyio -async def test_index_list_filters_core(fakes): +async def test_index_list_filters_core_to_gak_in_season_now(fakes): async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: body = (await client.get("/v1/index/list", params={"region": REGION, "core": True})).json() - assert {i["code"] for i in body["items"]} == {"picnic", "hiking", "camping", "stars"} + month = now_kst().month + assert {i["code"] for i in body["items"]} == {d["code"] for d in _seed() if month in d["months"]} + assert all(i["season"] == season_of(month) for i in body["items"]) @pytest.mark.anyio @@ -119,6 +123,33 @@ def test_every_index_has_priority(): assert all(d["priority"] in (1, 2, 3) for d in _seed()) +def test_every_index_has_valid_months_and_weights(): + for d in _seed(): + assert isinstance(d["months"], list) and all(1 <= m <= 12 for m in d["months"]), d["code"] + assert sum(d[f"weight_{a}"] for a in ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")) == 100, d["code"] + + +@pytest.mark.anyio +async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypatch): + today = now_kst().date() + other = [m for m in range(1, 13) if m != today.month] + defs = [ + SimpleNamespace(index_id=1, code="always", priority=2, months=[], sort_order=1), + SimpleNamespace(index_id=2, code="now", priority=2, months=[today.month], sort_order=2), + SimpleNamespace(index_id=3, code="off", priority=1, months=other[:3], sort_order=3), + ] + scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 50), (2, 60), (3, 99))] + 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, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50}))) + _, board = await service.board(REGION) + view = [(i.definition.code, i.active, i.in_season, i.season) for i in board.items] + # 점수가 가장 높아도 제철이 아니면 순위 밖 맨 끝. 계절 표시는 제철 달이 정해진 각에만 + assert view == [("now", True, True, season_of(today.month)), ("always", True, True, None), ("off", False, False, None)] + assert [i.definition.code for i in board.ranked] == ["now", "always"] + assert all(not i.slot_ranks for i in board.items if not i.in_season) + + @pytest.mark.anyio async def test_board_ranks_by_score_times_priority_weight(monkeypatch): today = now_kst().date() diff --git a/backend/tests/test_index_calc.py b/backend/tests/test_index_calc.py index fa0c774..9556ae2 100644 --- a/backend/tests/test_index_calc.py +++ b/backend/tests/test_index_calc.py @@ -259,6 +259,22 @@ def test_new_gak_good_day_high_bad_day_low(code, good, bad): assert _seed_score(code, **bad) <= 30 +@pytest.mark.parametrize("code, good, bad", [ + ("flower", dict(feels=19.0, wind=2.0, sunshine_ratio=0.8, visibility_km=20.0), dict(feels=8.0, prob=80, rain=RainType.RAIN, sunshine_ratio=0.1, visibility_km=4.0)), + ("blanket", dict(feels=22.0, wind=3.0, hum=35, sunshine_ratio=0.9), dict(feels=10.0, prob=70, rain=RainType.RAIN, hum=90, sunshine_ratio=0.1)), + ("bingsu", dict(feels=33.0, hum=75), dict(feels=18.0, hum=40)), + ("indoordry", dict(feels=27.0, prob=90, rain=RainType.RAIN, hum=55), dict(feels=14.0, hum=90)), + ("riverwind", dict(feels=24.0, wind=3.0, hum=55), dict(feels=20.0, prob=80, rain=RainType.RAIN, wind=0.5, hum=90)), + ("foliage", dict(feels=16.0, wind=2.0, sunshine_ratio=0.8, visibility_km=20.0), dict(feels=8.0, prob=80, rain=RainType.RAIN, sunshine_ratio=0.1, visibility_km=4.0)), + ("sweetpotato", dict(feels=2.0, wind=6.0), dict(feels=20.0, wind=1.0)), + ("bungeoppang", dict(feels=-5.0, wind=6.0), dict(feels=15.0, wind=1.0)), + ("tangerine", dict(feels=-5.0, wind=7.0, prob=80, rain=RainType.SNOW), dict(feels=15.0, wind=1.0)), +]) +def test_seasonal_gak_good_day_high_bad_day_low(code, good, bad): + assert _seed_score(code, **good) >= 80 + assert _seed_score(code, **bad) <= 30 + + def test_new_gak_100_only_when_every_factor_is_perfect(): perfect = dict(feels=19.5, wind=1.0, hum=35) assert _seed_score("golf", **perfect) == 100 diff --git a/backend/tests/test_index_season.py b/backend/tests/test_index_season.py new file mode 100644 index 0000000..623b176 --- /dev/null +++ b/backend/tests/test_index_season.py @@ -0,0 +1,55 @@ +from datetime import date +from types import SimpleNamespace + +from common.enums import RainType, Sky +from common.utils.kma_time import KST +from services.calc.index_calc import Context, DayForecast, Hour, estimate, evaluate, time_score, zero_rules_text +from services.calc.sun import sun_times +from services.index_service import in_season, season_badge, season_of, window_hours + +CTX = Context(day=date(2027, 1, 9), is_holiday=False, pm25=10, air_label="좋음", moon=0.5, sunset_score=None, wind_warning=False, lookahead_rain_prob=0) +SNOWMAN = SimpleNamespace( + weight_temp=50, weight_rain=10, weight_wind=20, weight_humidity=0, weight_air=0, weight_time=20, + factor_rules={"temp": {"type": "range", "lo": -5, "hi": 2, "best": -1}, "rain": {"dir": "wet"}, "wind": {"type": "calm", "ok": 3, "limit": 10}, + "humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100}}, + zero_rules=[{"field": "snow", "op": "==", "value": "no"}], windows=[{"from": 9, "to": 16}], +) + + +def _h(hour, rain=RainType.NONE, feels=-1.0): + return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=80 if rain is not RainType.NONE else 0, wind_ms=1.0, humidity=70, sky=Sky.CLOUDY) + + +def test_season_names_and_in_season(): + assert [season_of(m) for m in (1, 3, 6, 9, 12)] == ["겨울", "봄", "여름", "가을", "겨울"] + always, winter = SimpleNamespace(months=[]), SimpleNamespace(months=[12, 1, 2]) + assert in_season(always, 7) and in_season(winter, 1) and not in_season(winter, 7) + # 일 년 내내인 각엔 계절 표시가 없다 + assert season_badge(always, 1) is None and season_badge(winter, 1) == "겨울" and season_badge(winter, 7) is None + assert in_season(SimpleNamespace(), 5) + + +def test_snowman_is_zero_without_snow_and_high_when_snowing_near_zero(): + dry = evaluate(SNOWMAN, [[_h(h) for h in range(9, 16)]], CTX) + assert dry.score == 0 and dry.zero_reason == "눈 소식이 없어 0점" + snowy = evaluate(SNOWMAN, [[_h(h, RainType.SNOW) for h in range(9, 16)]], CTX) + assert snowy.score >= 80 and snowy.zero_reason is None + assert zero_rules_text(SNOWMAN.zero_rules) == "눈 소식이 없으면 0점" + + +def test_snowman_estimate_from_mid_forecast_is_zero(): + fc = DayForecast(temp_min_c=-4, temp_max_c=1, rain_prob_am=70, rain_prob_pm=70, sky=Sky.CLOUDY) + assert estimate(SNOWMAN, fc, [list(range(9, 16))], CTX).score == 0 + + +def test_sunrise_score_time_rule(): + assert time_score({"type": "sunrise_score"}, Context(**{**CTX.__dict__, "sunrise_score": 72})) == (72, "일출 하늘 점수 72") + assert time_score({"type": "sunrise_score"}, CTX)[0] == 70 + + +def test_window_around_sunrise_covers_sunrise_hour(): + region = SimpleNamespace(lat=37.56, lon=126.97) + day = date(2027, 1, 1) + h = sun_times(day, region.lat, region.lon).sunrise_at.astimezone(KST).hour + assert window_hours(SimpleNamespace(windows=[{"around": "sunrise", "hours": 1}]), day, region) == [[h - 1, h, h + 1]] + diff --git a/frontend/src/api/client/types.gen.ts b/frontend/src/api/client/types.gen.ts index db8f6a9..17f3389 100644 --- a/frontend/src/api/client/types.gen.ts +++ b/frontend/src/api/client/types.gen.ts @@ -629,7 +629,7 @@ export type Hero = { /** * Status * - * 히어로 상태 한 줄: 습도·불쾌지수·자외선(낮에만)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로) + * 히어로 상태 한 줄: 습도·불쾌지수·자외선(밤 구간 빼고)·미세먼지 단계 이름. tone=warn 이면 조심(앱이 주황 글자로) */ status?: Array; }; @@ -755,6 +755,18 @@ export type IndexSummary = { * Is Core */ is_core: boolean; + /** + * Season + * + * 지금 제철이면 계절 이름(봄·여름·가을·겨울). 일 년 내내인 각은 없음 + */ + season?: string | null; + /** + * In Season + * + * false 면 제철이 아니라 순위 밖, 목록 맨 끝 + */ + in_season?: boolean; /** * Score */ @@ -3077,7 +3089,7 @@ export type ListIndicesData = { /** * Core * - * 이번 계절 핵심 지수만 + * 지금 제철인 각만 */ core?: boolean; }; diff --git a/frontend/src/b/GakPage.tsx b/frontend/src/b/GakPage.tsx index e35261c..d4de47e 100644 --- a/frontend/src/b/GakPage.tsx +++ b/frontend/src/b/GakPage.tsx @@ -3,21 +3,22 @@ import { useQuery } from '@tanstack/react-query' import { listArticlesOptions, listIndicesOptions } from '../api/client/@tanstack/react-query.gen' import { ArticleCategory, IndexCategory } from '../api/client/types.gen' import { cx } from '../lib/utils' -import { loadOf, MEDALS } from './lib' +import { kst, loadOf, MEDALS, seasonOf } from './lib' import { useRegion } from './regionContext' import { useSheet } from './sheetContext' import { Chips, Ic, Sec, Skel, StateBox } from './ui' type Cat = 'all' | 'out' | 'food' | 'home' | 'life' | 'core' -const CATS = [ +// 마지막 칩은 지금 계절의 제철 각 (예: 가을 각) +const CATS: readonly (readonly [Cat, string])[] = [ ['all', '전체'], ['out', '밖에서 놀기'], ['food', '먹고 마시기'], ['home', '집안일'], ['life', '생활 고민'], - ['core', '가을 각'], -] as const + ['core', `${seasonOf(kst(new Date()).mo)[0]} 각`], +] const CAT_PARAM: Partial> = { out: IndexCategory.OUTSIDE, food: IndexCategory.FOOD, home: IndexCategory.HOME, life: IndexCategory.LIFE } @@ -124,15 +125,15 @@ export function GakPage() {
{items.map((g) => { return ( - )