Compare commits

...
15 Commits
Author SHA1 Message Date
skkim 0edb7059c8 feat: 주말 나들이 점수를 평균 60 정규분포로 보정, 지금 날씨·나들이 점수 100점은 완벽한 날만
- 나들이 점수(주말 전국 순위·당일치기)에 지금 날씨 점수와 같은 방식의 바꾸기 표를 적용: 원래 점수를 1년 치 분포의 순위로 보고 평균 60·표준편차 15 정규분포 점수로 바꿈 (weekend_rank.py, outing_score_table.json, scripts/gen_outing_score_table.py)
- 나들이 점수 만점 조건을 엄격하게: 체감온도 최적 21°±0.5°, 바람 초속 1m 이하일 때만 100점 (같은 예보를 받는 여러 지역이 한꺼번에 100점이 되던 것을 줄임)
- 표 맨 위가 100으로 잘려 비슷한 원래 점수(96·97·99)가 모두 100점이 되던 것을 막기 위해 straighten_top 추가: 표시 점수 83 이하인 마지막 원래 점수에서 100점까지 직선으로 이어, 100점은 구간에서 나올 수 있는 가장 높은 원래 점수(밤은 85)일 때만 나옴. 지금 날씨 점수 표도 다시 만듦 (90점 이상 약 2.4% → 1.5%)
- 당일치기 최소 점수는 원래 50점과 같은 날씨 수준(표시 62점)으로 옮김
- 주말 순위 캐시 키를 weekend_rank:v2:<날짜>로 올려 옛 점수 캐시를 쓰지 않게 함
- 테스트 추가: test_outing_score_table, test_weather_score_table(straighten_top·100점 조건)
- docs/점수_계산식.md의 지금 날씨 점수·나들이 점수 항목을 새 기준과 숫자로 갱신
2026-10-23 15:02:09 +09:00
minaChoi b2470d80ed chore: main 병합 — 점수 근거 버튼·지금 상태 2026-10-23 11:54:40 +09:00
minaChoi eb84a72c2f feat: 날씨 점수 근거 버튼을 구름에 가리던 해 구석 '?'에서 상태 줄 끝 '점수 근거 ›'로(해를 눌러도 열림), 근거 창에 지금 상태(습도·불쾌지수·자외선·미세먼지) 실제 값과 기준 추가 2026-10-23 11:14:56 +09:00
minaChoi fdd2200ae2 chore: main 병합 — 단풍 지도 페이지·검수 반영 2026-10-23 10:59:41 +09:00
minaChoi 1888dd6cf3 feat: 단풍 지도 디자인 검수 반영 — 카드 2장(지도·순위), 라벨 눌러 고르기, 엑스 없앤 선택 줄, 명소마다 공유 이미지, 시·도 이름, 밤 화면 글자, 확대할수록 이름 2026-10-23 10:44:01 +09:00
minaChoi d75144a6ac feat: 단풍 지도 페이지(/foliage) — 카드는 절정만 잎 아이콘, 누르면 페이지에서 확대·이동·목록, 확대할수록 이름 더, 뒤로 가면 피드 위치 그대로 2026-10-23 09:49:43 +09:00
minaChoi 446af2e9b5 fix: 단풍 지도 점이 빽빽해 보이던 문제 — 절정만 테두리 점으로 띄우고 나머지는 작은 점으로, 지도를 누르면 가장 가까운 명소가 열리게 2026-10-23 09:22:23 +09:00
minaChoi 9a75b02d1a fix: 단풍 지도에서 겹쳐 안 보이고 못 누르던 점 — 겹친 점을 서로 밀어 65곳 모두 보이고 눌리게 2026-10-23 09:16:53 +09:00
skkim d5f8b148b4 fix: 각 점수에 중요도 배율을 반영해 화면 점수와 순위를 일치시킴 2026-10-23 09:14:52 +09:00
minaChoi 199e834227 feat: 단풍 지도 제목을 '지금 절정: 시·도'로, 보여 주는 기간을 명소 절정일에 맞춰(첫 단풍 시작~마지막 절정 7일 뒤) 2026-10-23 09:13:12 +09:00
minaChoi 1306c43740 fix: 단풍 지도 이름표를 눌러도 명소 정보가 나오게 2026-10-23 09:07:51 +09:00
minaChoi 8ca38f1806 feat: 단풍 지도를 점으로 — 단계별 점 색, 절정 단풍은 이름표(겹치면 생략), 지도 색 옅게, 절정 7일 뒤부터는 회색 2026-10-23 08:54:07 +09:00
skkim 621a0cf90d chore: main 병합 — 지금 날씨 점수 보정을 바꾸기 표로 통일
- index_service.py 충돌: main 의 오늘·내일 날씨 점수 계산은 그대로 쓰고, 보정만 strict_weather 에서 구간별 바꾸기 표(weather_slot_scores)로 바꿈
- weather_slot_scores 는 main 의 weather_why 가 쓰는 점수 근거(factors)를 그대로 둔 Result 를 돌려줌
- strict_weather 와 그 테스트(test_weather_score_is_strict_near_top) 삭제 (바꾸기 표로 통일하기로 정함)
- test_board_activates_gak_outside_its_time_window 의 ensure 스텁을 main 의 {날짜: {구간: Result}} 모양으로 맞춤
2026-10-22 13:58:36 +09:00
skkim 799a46f53c fix: 각을 시간대와 관계없이 활성화하고 시간 적합도를 가중치로 반영 2026-10-22 13:38:39 +09:00
skkim 3b5afba8a1 feat: 지금 날씨 점수를 평균 60 정규분포로 (가장 낮은 요소로 깎기 제거, 구간별 바꾸기 표, 90점 이상 약 2.4%)
- 지금 날씨 점수는 '가장 낮은 요소로 깎기'를 하지 않는다 (밤엔 해 난 비율이 늘 0점이라 밤 점수가 62점을 못 넘었음). 각 점수는 그대로
- 원래 점수를 구간(아침·낮·저녁·밤)마다 1년 치 분포의 순위로 보고 평균 60·표준편차 15 정규분포 점수로 바꿔 보여 준다
- 바꾸기 표는 scripts/gen_weather_score_table.py 가 Open-Meteo 과거 예보로 만든다 (weather_score_table.json)
2026-10-22 13:33:50 +09:00
36 changed files with 2206 additions and 257 deletions

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
# Product
<!-- impeccable:product-schema 1 -->
## Platform
web
## Users
휴대폰으로 오늘·내일 뭘 할지 정하려는 2040 일반인. 아침이나 외출 전에 잠깐 열어 봐요.
## Product Purpose
동네(구) 날씨를 '빨래각·소맥각' 같은 활동 점수로 바꿔 보여 줘요. 피드로 훑어보고 친구에게 보내요.
## Positioning
날씨 숫자가 아니라 '지금 ○○하기 좋은지'를 알려 주고, 귀엽고 공유하고 싶은 카드로 보여 줘요.
## Constraints
- 모바일 웹 우선(토스 미니앱, 홈 화면 추가).
- 로그인은 글쓰기에만 요구해요.
- 화면 문구는 반말 없는 '해요'체예요.
+3
View File
@@ -66,6 +66,9 @@
| [ ] | '○○구 내일 날씨' 검색 태깅 — 스위치 뒤 내용은 눌러야 보여 구글이 읽는지 공식 문서로 확인 필요. 구 페이지(SEO)에 내일 기온·습도 넣는 안과 비교 | 10/21 회의 결정 | `backend/router/v1/seo/` | | [ ] | '○○구 내일 날씨' 검색 태깅 — 스위치 뒤 내용은 눌러야 보여 구글이 읽는지 공식 문서로 확인 필요. 구 페이지(SEO)에 내일 기온·습도 넣는 안과 비교 | 10/21 회의 결정 | `backend/router/v1/seo/` |
| [x] | **운영 DB 반영(10/21 배포 때 init.sql로 적용 확인)** — 댓글 표 `user_id` NULL 허용, `ip_hash`·`region_name` 칸, `idx_comment_ip` (init.sql에 추가, 로컬만 적용). 배포 전에 운영에 ALTER 실행 (운영 영향, 확인 받고) | 익명 댓글 | `backend/postgres-init/init.sql` | | [x] | **운영 DB 반영(10/21 배포 때 init.sql로 적용 확인)** — 댓글 표 `user_id` NULL 허용, `ip_hash`·`region_name` 칸, `idx_comment_ip` (init.sql에 추가, 로컬만 적용). 배포 전에 운영에 ALTER 실행 (운영 영향, 확인 받고) | 익명 댓글 | `backend/postgres-init/init.sql` |
| [ ] | **[결정 필요]** 새 화면 문구 검토: '보냈어요. 링크도 복사해 뒀어요', '글쓰기는 로그인한 뒤에 할 수 있어요.', '오늘'/'내일', '내일 낮 날씨 점수', '내일은 ○○각!'/'내일은 쉬어 가요', '최저'/'최고'/'습도', 익명 이름 '마포구 익명', 단풍 지도 '단풍 전'/'첫 단풍'/'절정'/'단풍'/'은행', '가까운 예측 지점 날짜예요', '지금 절정 ○곳: … 외' | 화면 문구 규칙 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/Sheets.tsx` | | [ ] | **[결정 필요]** 새 화면 문구 검토: '보냈어요. 링크도 복사해 뒀어요', '글쓰기는 로그인한 뒤에 할 수 있어요.', '오늘'/'내일', '내일 낮 날씨 점수', '내일은 ○○각!'/'내일은 쉬어 가요', '최저'/'최고'/'습도', 익명 이름 '마포구 익명', 단풍 지도 '단풍 전'/'첫 단풍'/'절정'/'단풍'/'은행', '가까운 예측 지점 날짜예요', '지금 절정 ○곳: … 외' | 화면 문구 규칙 | `frontend/src/b/TodayPage.tsx`, `frontend/src/b/Sheets.tsx` |
| [ ] | 단풍 지도 페이지(`/foliage`) 검색 등록 — 사이트맵 추가, 미리 그린 HTML(제목·설명), 공식 문서로 확인 후 | 페이지 따로 만든 이유(공유·검색), 사용자 10/23 | `backend/services/seo_service.py`, `frontend/src/b/FoliagePage.tsx` |
| [ ] | 단풍 지도 그림 고해상도로 다시(지금 1024px라 확대하면 흐림) — Codex | 단풍 지도 페이지 확대 | `frontend/public/foliage/korea-map.webp` |
| [ ] | **[결정 필요]** 단풍 지도 페이지 문구: '단풍 절정'/'은행 절정', '지도 크게 보기 ›', '지금 절정'/'곧 절정'/'아직'/'절정 지남', '전체'/'단풍'/'은행', '절정 예상'/'가까운 지점 날짜', '링크를 복사했어요' | 화면 문구 규칙 | `frontend/src/b/FoliagePage.tsx`, `frontend/src/b/foliageMap.tsx` |
| [ ] | 익명 댓글이 링크·하루 제한에 걸려도 '댓글을 올리지 못했어요'만 나옴 — 이유별 안내 | 익명 댓글 작업 중 발견 | `frontend/src/b/Sheets.tsx` | | [ ] | 익명 댓글이 링크·하루 제한에 걸려도 '댓글을 올리지 못했어요'만 나옴 — 이유별 안내 | 익명 댓글 작업 중 발견 | `frontend/src/b/Sheets.tsx` |
| [ ] | 매일 대표에게 진행 보고 (미완료 포함) | 10/21 회의 결정 | | | [ ] | 매일 대표에게 진행 보고 (미완료 포함) | 10/21 회의 결정 | |
+3 -2
View File
@@ -35,9 +35,10 @@ class IndexCRUD:
return await s.scalar(stmt) return await s.scalar(stmt)
async def has_unslotted(self, s: AsyncSession, region_code: str, day: date) -> bool: async def has_unslotted(self, s: AsyncSession, region_code: str, day: date) -> bool:
"""그날 행 중 구간 점수가 비어 있는 행(구간 계산 전 행)이 있는지.""" """현재 방식으로 모든 구간을 계산하지 않은 행이 있는지."""
stmt = select(IndexScore.index_id).where( stmt = select(IndexScore.index_id).where(
IndexScore.region_code == region_code, IndexScore.score_date == day, text("index_score.slots = '{}'::jsonb") IndexScore.region_code == region_code, IndexScore.score_date == day,
text("NOT (index_score.slots ?& ARRAY['morning', 'day', 'evening', 'night', 'early'])")
).limit(1) ).limit(1)
return (await s.scalar(stmt)) is not None return (await s.scalar(stmt)) is not None
+3 -2
View File
@@ -86,7 +86,7 @@ class WeekDay(WebPacketProtocol):
temp_min_c: Optional[float] = None temp_min_c: Optional[float] = None
temp_max_c: Optional[float] = None temp_max_c: Optional[float] = None
rain_prob: Optional[int] = None rain_prob: Optional[int] = None
gaks: list[WeekGak] = Field(default_factory=list, description="그날 대표 각 (점수 × 중요도 순 3개). 각 점수가 아직 없는 날은 비어 있음") gaks: list[WeekGak] = Field(default_factory=list, description="그날 대표 각 (중요도 배율을 반영한 최종 표시 점수 내림차순 3개, 동점이면 중요도 순). 각 점수가 아직 없는 날은 비어 있음")
class WeekSlide(WebPacketProtocol): class WeekSlide(WebPacketProtocol):
@@ -154,7 +154,7 @@ class TopIndex(WebPacketProtocol):
summary: Optional[str] = None summary: Optional[str] = None
active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수") active: bool = Field(default=True, description="지금 구간이 이 각의 시간대와 겹침. false 면 순위 밖, score 는 하루 점수")
slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음") slots: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 점수 {morning·day·evening·night: 점수}. 각 시간대와 안 겹치는 구간은 없음")
slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음") slot_ranks: dict[str, int] = Field(default_factory=dict, description="오늘 구간별 순위 (중요도 배율을 반영한 최종 표시 점수 내림차순, 동점이면 중요도 순)")
class HeroStat(WebPacketProtocol): class HeroStat(WebPacketProtocol):
@@ -162,6 +162,7 @@ class HeroStat(WebPacketProtocol):
label: str label: str
value: str value: str
tone: Literal["normal", "warn", "rain"] = Field(description="normal=기본, warn=조심(노랑), rain=비(파랑)") tone: Literal["normal", "warn", "rain"] = Field(description="normal=기본, warn=조심(노랑), rain=비(파랑)")
detail: Optional[str] = Field(default=None, description="단계 이름 밑의 실제 값 (예: 68%, 72, 2, 초미세먼지 15㎍/㎥). 상태 줄에만")
class WeatherWhy(WebPacketProtocol): class WeatherWhy(WebPacketProtocol):
+2 -2
View File
@@ -5,7 +5,7 @@ import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT) sys.path.insert(0, ROOT)
from services.calc.index_calc import PRIORITY_WEIGHT, _cond # noqa: E402 from services.calc.index_calc import _cond # noqa: E402
SEED = os.path.join(ROOT, "seed", "index_definition.json") SEED = os.path.join(ROOT, "seed", "index_definition.json")
OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md") OUT = os.path.join(os.path.dirname(ROOT), "docs", "각_계산기준.md")
@@ -109,7 +109,7 @@ def main() -> None:
P("- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.") P("- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.")
P("- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.") P("- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.")
P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.") P("- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.")
P("- 순위는 점수 × 중요도 가중치(" + " · ".join(f"{PRIO[k]} {v}" for k, v in PRIORITY_WEIGHT.items()) + ")로 정합니다. 화면에 보이는 점수는 그대로입니다.\n") P("- 최종 점수는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시 모두 이 최종 점수를 사용합니다.\n")
P("## 한눈에 보기\n") P("## 한눈에 보기\n")
P("| 순서 | 각 | 코드 | 분류 | 중요도 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |") P("| 순서 | 각 | 코드 | 분류 | 중요도 | 시간대 | 기온 | 비 | 바람 | 습도 | 미세먼지 | 시간 | 재미 각 | 계절 핵심 |")
P("|---:|---|---|---|:---:|---|---:|---:|---:|---:|---:|---:|:---:|:---:|") P("|---:|---|---|---|:---:|---|---:|---:|---:|---:|---:|---:|:---:|:---:|")
+76
View File
@@ -0,0 +1,76 @@
"""나들이 점수 바꾸기 표(services/calc/outing_score_table.json)를 다시 만든다.
나들이 점수(index_calc.outing: 낮 10~17시, 기온·비·하늘·바람)의 원래 점수를 1년 치 분포의 순위로 보고,
평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾼다 (지금 날씨 점수와 같은 방식, scripts/gen_weather_score_table.py).
1년 치 날씨는 Open-Meteo 과거 예보로, region.csv 에서 8개마다 1곳(32곳)을 쓴다. 하늘은 구름양 40%·80% 이상을 구름 많음·흐림으로 본다.
나들이 점수 규칙(OUTING_*)이 바뀌면 실행: cd backend && python scripts/gen_outing_score_table.py
"""
import csv
import json
import os
import sys
import time
from datetime import date, timedelta
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from common.enums import RainType, Sky # noqa: E402
from common.logger import LOG # noqa: E402
from scripts.gen_weather_score_table import _WEATHER, DAYS, EVERY, MEAN, SIGMA, fetch, straighten_top, table # noqa: E402
from services.calc.index_calc import OUTING_HOURS, Hour, outing # noqa: E402
BACKEND = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REGIONS = os.path.join(BACKEND, "seed", "region.csv")
OUT = os.path.join(BACKEND, "services", "calc", "outing_score_table.json")
_HOURLY = "apparent_temperature,precipitation,precipitation_probability,wind_speed_10m,cloud_cover"
def region_scores(lat: float, lon: float, start: date, end: date) -> list[int]:
"""한 지점의 날마다 나들이 점수(원래 점수). 10~17시가 모두 있는 날만."""
base = dict(latitude=lat, longitude=lon, start_date=start.isoformat(), end_date=end.isoformat(), timezone="Asia/Seoul")
w = fetch(_WEATHER, base | dict(hourly=_HOURLY, wind_speed_unit="ms"))["hourly"]
at_index = {t: i for i, t in enumerate(w["time"])}
out = []
day = start
while day <= end:
hours = []
for h in range(*OUTING_HOURS):
i = at_index.get(f"{day.isoformat()}T{h:02d}:00")
if i is None or w["apparent_temperature"][i] is None:
break
cloud = w["cloud_cover"][i] or 0
hours.append(Hour(
hour=h, feels_c=w["apparent_temperature"][i], rain_type=RainType.RAIN if (w["precipitation"][i] or 0) >= 0.1 else RainType.NONE,
rain_prob=int(w["precipitation_probability"][i] or 0), wind_ms=w["wind_speed_10m"][i], humidity=50,
sky=Sky.CLOUDY if cloud >= 80 else Sky.PARTLY if cloud >= 40 else Sky.CLEAR,
))
result = outing(hours) if len(hours) == OUTING_HOURS[1] - OUTING_HOURS[0] else None
if result is not None:
out.append(result.score)
day += timedelta(days=1)
return out
def main() -> None:
end = date.today() - timedelta(days=2)
start = end - timedelta(days=DAYS)
regions = list(csv.DictReader(open(REGIONS, encoding="utf-8")))[::EVERY]
scores: list[int] = []
for r in regions:
scores += region_scores(float(r["lat"]), float(r["lon"]), start, end)
LOG.info(f"[outing-table] {r['name']} 완료")
time.sleep(1)
doc = {
"about": f"나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 {MEAN}·표준편차 {SIGMA}. scripts/gen_outing_score_table.py 가 만든다",
"period": [start.isoformat(), end.isoformat()], "regions": len(regions), "samples": len(scores),
"table": straighten_top(table(scores)), # 100점은 원래 점수 100(완벽한 날)일 때만
}
with open(OUT, "w", encoding="utf-8") as f:
json.dump(doc, f, ensure_ascii=False, indent=1)
print(len(regions), "regions", len(scores), "samples")
if __name__ == "__main__":
main()
+148
View File
@@ -0,0 +1,148 @@
"""지금 날씨 점수 바꾸기 표(services/calc/weather_score_table.json)를 다시 만든다.
지금 날씨 점수 공식(WEATHER_SCORE_DEF)으로 나온 원래 점수를 구간(아침·낮·저녁·밤)마다 1년 치 분포의 순위로 바꾼 뒤,
평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾼다. 90점 이상은 구간마다 약 2.5%가 나온다. 맨 위는 straighten_top 으로 100점이 가장 좋은 원래 점수에서만 나오게 한다.
1년 치 날씨는 Open-Meteo 과거 예보(강수확률 포함)와 대기질(초미세먼지)로, region.csv 에서 8개마다 1곳(32곳)을 쓴다.
WEATHER_SCORE_DEF 가 바뀌면 실행: cd backend && python scripts/gen_weather_score_table.py
"""
import csv
import json
import os
import sys
import time
import urllib.parse
import urllib.request
from datetime import date, datetime, timedelta
from statistics import NormalDist
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from common.enums import RainType, Sky # noqa: E402
from common.logger import LOG # noqa: E402
from services.calc.day_slot import SLOTS, slot_hours # noqa: E402
from services.calc.index_calc import Context, Hour, evaluate # noqa: E402
from services.calc.sun import sun_times # noqa: E402
from services.index_service import WEATHER_SCORE_DEF # noqa: E402
BACKEND = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
REGIONS = os.path.join(BACKEND, "seed", "region.csv")
OUT = os.path.join(BACKEND, "services", "calc", "weather_score_table.json")
MEAN, SIGMA = 60, 15
DAYS = 364
EVERY = 8
_WEATHER = "https://historical-forecast-api.open-meteo.com/v1/forecast"
_AIR = "https://air-quality-api.open-meteo.com/v1/air-quality"
_HOURLY = "apparent_temperature,precipitation,snowfall,precipitation_probability,wind_speed_10m,relative_humidity_2m,sunshine_duration,cloud_cover"
def fetch(url: str, params: dict) -> dict:
"""잠깐 막히면 쉬었다가 다시 부른다. 네 번 모두 안 되면 멈춘다."""
query = urllib.parse.urlencode(params)
for attempt in range(4):
try:
with urllib.request.urlopen(f"{url}?{query}", timeout=60) as r:
return json.load(r)
except OSError as e:
LOG.error(f"[weather-table] {url} 실패 {attempt + 1}회: {e}")
time.sleep(10 * (attempt + 1))
raise RuntimeError(f"{url} 를 받지 못함")
def region_scores(lat: float, lon: float, start: date, end: date) -> dict[str, list[int]]:
"""한 지점의 날마다 구간별 원래 점수. 앱과 같은 입력으로 맞춘다 (일조는 그 시각을 덮는 3시간 합 ÷ 3시간, 미세먼지는 구간 평균)."""
base = dict(latitude=lat, longitude=lon, start_date=start.isoformat(), end_date=(end + timedelta(days=1)).isoformat(), timezone="Asia/Seoul")
w = fetch(_WEATHER, base | dict(hourly=_HOURLY, wind_speed_unit="ms"))["hourly"]
air = fetch(_AIR, base | dict(hourly="pm2_5"))["hourly"]
pm = dict(zip(air["time"], air["pm2_5"]))
at_index = {t: i for i, t in enumerate(w["time"])}
def key(at: datetime) -> str:
return at.strftime("%Y-%m-%dT%H:%M")
def hour_at(at: datetime, h: int) -> tuple[Hour | None, float | None]:
i = at_index.get(key(at))
if i is None or w["apparent_temperature"][i] is None:
return None, None
end_at = datetime.combine(at.date(), datetime.min.time()) + timedelta(hours=(at.hour + 3) // 3 * 3)
sun = [w["sunshine_duration"][j] for j in (at_index.get(key(end_at - timedelta(hours=k))) for k in (3, 2, 1)) if j is not None and w["sunshine_duration"][j] is not None]
wet = (w["precipitation"][i] or 0) >= 0.1
cloud = w["cloud_cover"][i] or 0
return Hour(
hour=h, feels_c=w["apparent_temperature"][i],
rain_type=(RainType.SNOW if (w["snowfall"][i] or 0) > 0 else RainType.RAIN) if wet else RainType.NONE,
rain_prob=int(w["precipitation_probability"][i] or 0), wind_ms=w["wind_speed_10m"][i], humidity=int(w["relative_humidity_2m"][i]),
sky=Sky.CLOUDY if cloud >= 80 else Sky.PARTLY if cloud >= 40 else Sky.CLEAR,
sunshine_ratio=min(sum(sun) / 10800, 1.0) if len(sun) == 3 else None,
), pm.get(key(at))
out: dict[str, list[int]] = {s: [] for s in SLOTS}
day = start
while day <= end:
midnight = datetime.combine(day, datetime.min.time())
for slot, hours in slot_hours(day, sun_times(day, lat, lon).sunset_at).items():
got = [hour_at(midnight + timedelta(hours=h), h) for h in sorted(hours)]
if any(x is None for x, _ in got):
continue
pms = [p for _, p in got if p is not None]
ctx = Context(day=day, is_holiday=False, pm25=round(sum(pms) / len(pms)) if pms else None, air_label=None, moon=0, sunset_score=None,
wind_warning=False, lookahead_rain_prob=0)
r = evaluate(WEATHER_SCORE_DEF, [[x for x, _ in got]], ctx)
if r is not None:
out[slot].append(r.score)
day += timedelta(days=1)
return out
def table(scores: list[int]) -> list[int]:
"""원래 점수 0~100 각각을 '분포에서의 가운데 순위'로 정규분포 점수에 맞춘다. 순서는 그대로 (줄어들지 않게)."""
n = len(scores)
out = []
for v in range(101):
below = sum(1 for s in scores if s < v)
same = sum(1 for s in scores if s == v)
out.append(max(0, min(100, round(MEAN + SIGMA * NormalDist().inv_cdf((below + same / 2 + 0.5) / (n + 1))))))
for i in range(1, 101):
out[i] = max(out[i], out[i - 1])
return out
ANCHOR_SCORE = 83 # 위쪽 끝을 직선으로 잇기 시작하는 표시 점수
def straighten_top(t: list[int], top: int = 100) -> list[int]:
"""표 맨 위가 100으로 잘려 비슷한 원래 점수(96·97·99)가 모두 100점이 되던 것을 막는다.
표시 점수가 ANCHOR_SCORE 이하인 마지막 원래 점수에서 top(그 구간에서 나올 수 있는 가장 높은 원래 점수)의 100점까지 직선으로 잇는다.
100점은 원래 점수가 top 이상일 때만 나온다. 그 아래 점수는 바뀌지 않는다."""
anchor = max(i for i, v in enumerate(t[: top + 1]) if v <= ANCHOR_SCORE)
out = list(t)
for raw in range(anchor + 1, 101):
out[raw] = 100 if raw >= top else min(99, round(t[anchor] + (100 - t[anchor]) * (raw - anchor) / (top - anchor)))
return out
def main() -> None:
end = date.today() - timedelta(days=2)
start = end - timedelta(days=DAYS)
regions = list(csv.DictReader(open(REGIONS, encoding="utf-8")))[::EVERY]
scores: dict[str, list[int]] = {s: [] for s in SLOTS}
for r in regions:
for slot, got in region_scores(float(r["lat"]), float(r["lon"]), start, end).items():
scores[slot] += got
LOG.info(f"[weather-table] {r['name']} 완료")
time.sleep(1)
doc = {
"about": f"지금 날씨 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 {MEAN}·표준편차 {SIGMA}. scripts/gen_weather_score_table.py 가 만든다",
"period": [start.isoformat(), end.isoformat()], "regions": len(regions), "samples": {s: len(v) for s, v in scores.items()},
# 밤은 해 난 비율이 늘 0점이라 원래 점수가 100 - 그 비중까지만 나온다
"slots": {s: straighten_top(table(v), 100 - WEATHER_SCORE_DEF.weight_sun if s == "night" else 100) for s, v in scores.items()},
}
with open(OUT, "w", encoding="utf-8") as f:
json.dump(doc, f, ensure_ascii=False, indent=1)
print(len(regions), "regions", doc["samples"])
if __name__ == "__main__":
main()
+22 -11
View File
@@ -18,13 +18,17 @@ _FALL_FLOOR = exp(-0.5)
# 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p) # 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p)
_TEMP_PLATEAU = 2 _TEMP_PLATEAU = 2
_HUMIDITY_PLATEAU = 5 _HUMIDITY_PLATEAU = 5
# 각 중요도(index_definition.priority)별 순위 가중치: 1=상 2=중 3=하. 순위만 바꾸고 보이는 점수는 그대로 둔다.
PRIORITY_WEIGHT = {1: 1.0, 2: 0.85, 3: 0.7} PRIORITY_WEIGHT = {1: 1.0, 2: 0.85, 3: 0.7}
def rank_score(score: int, priority: int) -> float: def priority_score(score: int, priority: int) -> int:
"""각 순위를 정하는 값 = 점수 × 중요도 가중치.""" """중요도 배율을 한 번 적용하고 정수로 반올림한 표시·순위 공통 점수."""
return score * PRIORITY_WEIGHT[priority] return round(score * PRIORITY_WEIGHT[priority])
def rank_score(score: int, priority: int) -> tuple[int, int]:
"""중요도 반영이 끝난 표시 점수 내림차순. 동점이면 중요도 순."""
return score, -priority
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -57,6 +61,7 @@ class Context:
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간 moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각) sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지' rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지'
time_matches: bool = True # 평가하는 시간대가 각의 활동 시간대에 해당하는지
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -209,7 +214,7 @@ def time_score(rule: dict, ctx: Context) -> tuple[int, str]:
return (ctx.sunrise_score if ctx.sunrise_score is not None else _UNKNOWN), ( 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}점으로 둬요" f"일출 하늘 점수 {ctx.sunrise_score}" if ctx.sunrise_score is not None else f"일출 하늘 점수 계산 전이라 {_UNKNOWN}점으로 둬요"
) )
return _clamp(rule["value"]), f"날짜와 상관없이 이 시간대 기본 점수 {_clamp(rule['value'])}점" return (100, "활동 시간대에 해당해요") if ctx.time_matches else (0, "활동 시간대가 아니에요")
_TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"} _TEMP_LABEL = {"range": "기온 알맞음", "away": "덥거나 추움", "lower": "추움", "higher": "더움"}
@@ -296,9 +301,14 @@ def _summary(hours: list[Hour]) -> str:
return f"{hour_label(mid.hour % 24)} {round(mid.feels_c)}°, {tag}" return f"{hour_label(mid.hour % 24)} {round(mid.feels_c)}°, {tag}"
def _weighted(factors: dict[str, int], weights: dict[str, int]) -> int: def _weighted(factors: dict[str, int], weights: dict[str, int], worst_pull: bool = True, time_is_binary: bool = False) -> int:
worst = min((factors[a] for a in AXES if weights[a]), default=100) """비중대로 섞고, worst_pull 이면 가장 낮은 요소로 최대 25% 깎는다 (지금 날씨 점수는 깎지 않는다)."""
return round(sum(factors[a] * weights[a] for a in AXES) / 100 * (1 - _WORST_PULL + _WORST_PULL * worst / 100)) mixed = sum(factors[a] * weights[a] for a in AXES) / 100
if not worst_pull:
return round(mixed)
# 시간대 불일치는 해당 가중치만 잃으며, 최저 요소에 따른 추가 감점에는 넣지 않는다.
worst = min((factors[a] for a in AXES if weights[a] and not (time_is_binary and a == "time")), default=100)
return round(mixed * (1 - _WORST_PULL + _WORST_PULL * worst / 100))
def _until(definition) -> str: def _until(definition) -> str:
@@ -338,7 +348,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
} }
factors = {a: v for a, (v, _) in scored.items()} factors = {a: v for a, (v, _) in scored.items()}
notes = {a: n for a, (_, n) in scored.items()} notes = {a: n for a, (_, n) in scored.items()}
score = _weighted(factors, weights) score = _weighted(factors, weights, getattr(definition, "worst_pull", True), rules["time"]["type"] == "fixed")
agg = { agg = {
"rain_prob": max_prob, "wind_ms": max(winds) if winds else None, "pm25": ctx.pm25, "rain_prob": max_prob, "wind_ms": max(winds) if winds else None, "pm25": ctx.pm25,
"feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)), "feels_c": (min(h.feels_c for h in hours), max(h.feels_c for h in hours)),
@@ -395,7 +405,7 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
} }
factors = {a: v for a, (v, _) in scored.items()} factors = {a: v for a, (v, _) in scored.items()}
notes = {a: n for a, (_, n) in scored.items()} notes = {a: n for a, (_, n) in scored.items()}
score = _weighted(factors, weights) score = _weighted(factors, weights, getattr(definition, "worst_pull", True), rules["time"]["type"] == "fixed")
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다 # 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
# 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다 # 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다
known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"} known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"}
@@ -413,7 +423,8 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
# 나들이 날씨 점수: 낮 10~17시에 바깥에서 놀기 좋은 정도. 주말 전국 순위·당일치기 추천에 쓴다. # 나들이 날씨 점수: 낮 10~17시에 바깥에서 놀기 좋은 정도. 주말 전국 순위·당일치기 추천에 쓴다.
OUTING_HOURS = (10, 18) OUTING_HOURS = (10, 18)
_OUTING_WEIGHTS = {"temp": 35, "rain": 40, "sky": 15, "wind": 10} _OUTING_WEIGHTS = {"temp": 35, "rain": 40, "sky": 15, "wind": 10}
_OUTING_RULES = {"temp": {"type": "range", "lo": 17, "hi": 24, "best": 21}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 4, "limit": 12}} # 만점 조건을 엄격하게: 기온은 최적 21° ±0.5°, 바람은 초속 1m 이하(ok/2)여야 100점 — 같은 예보를 받는 여러 지역이 한꺼번에 100점이 되던 것을 줄인다
_OUTING_RULES = {"temp": {"type": "range", "lo": 17, "hi": 24, "best": 21, "plateau": 0.5}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 2, "limit": 12}}
_OUTING_SKY = {Sky.CLEAR: 100, Sky.PARTLY: 80, Sky.CLOUDY: 50} _OUTING_SKY = {Sky.CLEAR: 100, Sky.PARTLY: 80, Sky.CLOUDY: 50}
_OUTING_RAIN_PROB, _OUTING_RAIN_CAP = 60, 30 _OUTING_RAIN_PROB, _OUTING_RAIN_CAP = 60, 30
@@ -0,0 +1,112 @@
{
"about": "나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 60·표준편차 15. scripts/gen_outing_score_table.py 가 만든다",
"period": [
"2025-10-22",
"2026-10-21"
],
"regions": 32,
"samples": 11680,
"table": [
1,
1,
1,
1,
1,
1,
1,
1,
1,
8,
13,
17,
22,
25,
28,
30,
32,
34,
36,
37,
37,
38,
38,
39,
39,
40,
41,
41,
42,
42,
47,
50,
50,
50,
50,
50,
50,
50,
50,
50,
50,
51,
51,
51,
51,
52,
54,
57,
61,
62,
62,
62,
63,
63,
63,
63,
63,
64,
64,
64,
64,
64,
64,
65,
65,
65,
65,
66,
66,
66,
66,
67,
67,
67,
68,
68,
68,
69,
69,
70,
70,
71,
72,
73,
74,
75,
76,
78,
79,
81,
83,
85,
86,
88,
90,
92,
93,
95,
97,
98,
100
]
}
@@ -0,0 +1,428 @@
{
"about": "지금 날씨 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수. 평균 60·표준편차 15. scripts/gen_weather_score_table.py 가 만든다",
"period": [
"2025-10-22",
"2026-10-21"
],
"regions": 32,
"samples": {
"morning": 11680,
"day": 11680,
"evening": 11680,
"night": 11680
},
"slots": {
"morning": [
1,
1,
1,
1,
1,
1,
1,
4,
5,
5,
9,
11,
14,
16,
17,
18,
20,
21,
23,
25,
26,
28,
29,
31,
31,
32,
33,
33,
34,
34,
35,
35,
35,
36,
37,
37,
38,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
47,
48,
49,
50,
52,
53,
54,
55,
57,
59,
61,
62,
63,
64,
64,
65,
65,
66,
66,
67,
67,
68,
68,
69,
69,
70,
71,
71,
72,
73,
73,
74,
74,
75,
76,
77,
78,
79,
80,
82,
83,
84,
86,
87,
88,
90,
91,
92,
93,
95,
96,
97,
99,
100
],
"day": [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
4,
6,
9,
12,
15,
19,
22,
24,
26,
27,
28,
29,
30,
31,
31,
32,
32,
33,
33,
34,
35,
36,
37,
37,
38,
39,
40,
41,
41,
42,
42,
43,
43,
44,
44,
45,
45,
46,
46,
47,
47,
47,
48,
48,
48,
49,
49,
50,
50,
51,
52,
54,
56,
59,
61,
62,
63,
63,
64,
64,
64,
65,
65,
66,
66,
66,
67,
67,
68,
68,
69,
70,
71,
72,
73,
74,
76,
77,
79,
81,
83,
86,
89,
92,
94,
97,
100
],
"evening": [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
7,
11,
14,
17,
20,
23,
25,
27,
28,
29,
30,
31,
32,
32,
33,
34,
34,
35,
36,
37,
38,
38,
39,
39,
40,
40,
41,
41,
42,
42,
43,
43,
44,
45,
45,
46,
46,
47,
47,
48,
48,
48,
49,
50,
50,
51,
52,
53,
55,
56,
59,
60,
62,
63,
63,
64,
64,
65,
65,
66,
66,
67,
67,
68,
69,
69,
70,
71,
71,
72,
74,
75,
76,
78,
79,
81,
83,
85,
87,
89,
92,
94,
96,
98,
100
],
"night": [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
4,
7,
10,
11,
13,
15,
17,
20,
22,
26,
28,
30,
32,
33,
34,
34,
35,
35,
35,
36,
36,
37,
38,
38,
39,
40,
41,
41,
42,
43,
44,
45,
46,
48,
49,
50,
52,
53,
55,
57,
60,
62,
63,
65,
65,
66,
66,
66,
67,
68,
68,
69,
69,
70,
70,
71,
71,
72,
73,
74,
74,
75,
77,
78,
80,
82,
84,
86,
88,
90,
92,
94,
96,
98,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100,
100
]
}
}
+5 -4
View File
@@ -148,6 +148,7 @@ def _hero_input(
now=now, night=slot in ("evening", "night"), after_dark=slot == "night", rain_at=rainy[0].at if rainy else None, now=now, night=slot in ("evening", "night"), after_dark=slot == "night", rain_at=rainy[0].at if rainy else None,
rain_later_at=later, today_known=bool(ahead), rain_later_at=later, today_known=bool(ahead),
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, 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,
pm25=now_w.air.pm25 if now_w and now_w.air else None, pm10=now_w.air.pm10 if now_w and now_w.air else None,
temp_min=min(temps, default=None), temp_max=max(temps, default=None), 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, temp=float(cur.temp_c) if cur else None, feels=float(cur.feels_c) if cur else None,
moon=moon, humidity=cur.humidity if cur else None, discomfort=cur.discomfort_index if cur else None, moon=moon, humidity=cur.humidity if cur else None, discomfort=cur.discomfort_index if cur else None,
@@ -242,7 +243,7 @@ def _by_position(posts: list[Post]) -> list[Post]:
def _tomorrow_best(board: IndexBoard, day: date) -> Optional[tuple[IndexItem, IndexScore]]: def _tomorrow_best(board: IndexBoard, day: date) -> Optional[tuple[IndexItem, IndexScore]]:
"""내일 하루 점수로 1위인 각과 그 점수 (점수 × 중요도).""" """내일 하루 점수로 1위인 각과 그 점수 (동점이면 중요도 순)."""
best = None best = None
for i in board.items: for i in board.items:
s = next((x for x in i.trend if x.score_date == day), None) s = next((x for x in i.trend if x.score_date == day), None)
@@ -340,7 +341,7 @@ class FeedService:
now = now_kst() now = now_kst()
sunset_at = sun_times(now.date(), float(region.lat), float(region.lon)).sunset_at sunset_at = sun_times(now.date(), float(region.lat), float(region.lon)).sunset_at
slot = slot_of(now, sunset_at) slot = slot_of(now, sunset_at)
key = f"feed:{region.code}:{slot}" key = f"feed:{region.code}:priority-score-v4:{slot}"
try: try:
cached = await REDIS.conn.get(key) cached = await REDIS.conn.get(key)
if cached: if cached:
@@ -475,7 +476,7 @@ class FeedService:
top1=_top(top) if top else None, bubble=bubble, 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, 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(x_in)], 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)], status=[HeroStat(icon=x.icon, label=x.label, value=x.value, tone=x.tone, detail=x.detail) for x in hero_status(x_in)],
tomorrow=_hero_tomorrow(now.date() + timedelta(days=1), board) if board else None, tomorrow=_hero_tomorrow(now.date() + timedelta(days=1), board) if board else None,
) )
@@ -813,7 +814,7 @@ _CLOUDY = {Sky.CLEAR: 0.0, Sky.PARTLY: 0.5, Sky.CLOUDY: 1.0}
def _day_gaks(board: Optional[IndexBoard], day: date, n: int = 3) -> list[WeekGak]: def _day_gaks(board: Optional[IndexBoard], day: date, n: int = 3) -> list[WeekGak]:
"""그날 대표 각: 각 상세의 날짜별 점수(하루 중 가장 좋은 시간대)를 점수 × 중요도 순으로.""" """그날 대표 각: 날짜별 표시 점수 내림차순, 동점이면 중요도 순으로."""
scored = [(i.definition, s) for i in (board.items if board else []) for s in i.trend if s.score_date == day] scored = [(i.definition, s) for i in (board.items if board else []) for s in i.trend if s.score_date == day]
scored.sort(key=lambda x: rank_score(x[1].score, x[0].priority), reverse=True) scored.sort(key=lambda x: rank_score(x[1].score, x[0].priority), reverse=True)
return [WeekGak(index_id=d.index_id, name=d.name, icon=d.icon, score=s.score) for d, s in scored[:n]] return [WeekGak(index_id=d.index_id, name=d.name, icon=d.icon, score=s.score) for d, s in scored[:n]]
+8 -4
View File
@@ -24,6 +24,7 @@ class HeroStatItem:
label: str label: str
value: str value: str
tone: Tone = "normal" tone: Tone = "normal"
detail: Optional[str] = None # 단계 이름 밑의 실제 값 (예: 68%, 72, 2, 초미세먼지 15㎍/㎥)
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -34,6 +35,8 @@ class HeroInput:
rain_later_at: Optional[datetime] = None # 그 뒤 오늘 안에 비 오는 첫 시각 (단기예보) rain_later_at: Optional[datetime] = None # 그 뒤 오늘 안에 비 오는 첫 시각 (단기예보)
today_known: bool = False # 오늘 남은 시간 예보가 있어 '오늘 비 안 와요'라고 말할 수 있는지 today_known: bool = False # 오늘 남은 시간 예보가 있어 '오늘 비 안 와요'라고 말할 수 있는지
air: Optional[AirGrade] = None air: Optional[AirGrade] = None
pm25: Optional[int] = None
pm10: Optional[int] = None
uv: Optional[float] = None uv: Optional[float] = None
temp_min: Optional[float] = None temp_min: Optional[float] = None
temp_max: Optional[float] = None temp_max: Optional[float] = None
@@ -69,13 +72,14 @@ def hero_status(x: HeroInput) -> list[HeroStatItem]:
"""히어로 상태 한 줄: 습도·불쾌지수(늘)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn.""" """히어로 상태 한 줄: 습도·불쾌지수(늘)·자외선(해 있을 때, 저녁 포함)·미세먼지를 단계 이름으로. 값이 없는 칸은 뺀다. 조심할 것만 warn."""
out: list[HeroStatItem] = [] out: list[HeroStatItem] = []
if x.humidity is not None: if x.humidity is not None:
out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity))) out.append(HeroStatItem("humidity", "muggy", "습도", humidity_label(x.humidity), detail=f"{x.humidity}%"))
if x.discomfort is not None: if x.discomfort is not None:
out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal")) out.append(HeroStatItem("discomfort", "muggy", "불쾌지수", discomfort_label(x.discomfort), "warn" if x.discomfort >= MUGGY_DI else "normal", detail=str(x.discomfort)))
if not x.after_dark and x.uv is not None: if not x.after_dark and x.uv is not None:
out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal")) out.append(HeroStatItem("uv", "glasses", "자외선", uv_label(x.uv), "warn" if x.uv >= UV_HIGH else "normal", detail=f"{x.uv:g}"))
if x.air is not None: 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")) pm = " · ".join(s for s in (f"초미세먼지 {x.pm25}㎍/㎥" if x.pm25 is not None else "", f"미세먼지 {x.pm10}㎍/㎥" if x.pm10 is not None else "") if s) or None
out.append(HeroStatItem("air", "mask", "미세먼지", GRADE_LABEL[x.air], "warn" if x.air in (AirGrade.BAD, AirGrade.VERY_BAD) else "normal", detail=pm))
return out return out
+50 -41
View File
@@ -1,6 +1,8 @@
import asyncio import asyncio
import json
from dataclasses import dataclass, field, replace from dataclasses import dataclass, field, replace
from datetime import date, datetime, time, timedelta from datetime import date, datetime, time, timedelta
from pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
from typing import Optional from typing import Optional
@@ -17,7 +19,7 @@ from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD from crud.week_crud import WeekCRUD
from services.air_service import GRADE_LABEL, AirService from services.air_service import GRADE_LABEL, AirService
from services.calc.day_slot import NIGHT_END_HOUR, SLOTS, slot_hours, slot_of from services.calc.day_slot import NIGHT_END_HOUR, SLOTS, slot_hours, slot_of
from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, rank_score from services.calc.index_calc import AXES, Context, DayForecast, Hour, Result, estimate, evaluate, priority_score, rank_score
from services.calc.moon import night, up_ratio, view_line from services.calc.moon import night, up_ratio, view_line
from services.calc.sun import sun_times from services.calc.sun import sun_times
from services.external.open_meteo import is_dark_slot from services.external.open_meteo import is_dark_slot
@@ -39,15 +41,12 @@ WEATHER_SCORE_DEF = SimpleNamespace(
"air": {"zero": 75, "full": 10}, "sun": {"zero": 0.2, "full": 0.9}, "time": {"type": "fixed", "value": 100}, "air": {"zero": 75, "full": 10}, "sun": {"zero": 0.2, "full": 0.9}, "time": {"type": "fixed", "value": 100},
}, },
zero_rules=[], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}], zero_rules=[], windows=[{"from": NIGHT_END_HOUR, "to": 24 + NIGHT_END_HOUR}],
# 가장 낮은 요소로 깎지 않는다: 밤엔 해 난 비율이 늘 0점이라 깎기가 밤 점수를 눌렀다
worst_pull=False,
) )
WEATHER_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "sun": "햇볕"} WEATHER_AXIS_NAME = {"temp": "기온", "rain": "비", "wind": "바람", "humidity": "습도", "air": "미세먼지", "sun": "햇볕"}
def strict_weather(raw: int) -> int:
"""날씨 점수는 높을수록 깐깐하게: 90점까지는 8/9, 그 위는 두 배로 깎아 100점은 모든 조건이 완벽할 때만 (96 → 92)."""
return round(raw * 8 / 9) if raw <= 90 else round(80 + (raw - 90) * 2)
@dataclass @dataclass
class WeatherWhy: class WeatherWhy:
label: str label: str
@@ -61,6 +60,9 @@ def weather_why(r: Result) -> list[WeatherWhy]:
axes = sorted((a for a in WEATHER_AXIS_NAME if getattr(WEATHER_SCORE_DEF, f"weight_{a}")), key=lambda a: -getattr(WEATHER_SCORE_DEF, f"weight_{a}")) axes = sorted((a for a in WEATHER_AXIS_NAME if getattr(WEATHER_SCORE_DEF, f"weight_{a}")), key=lambda a: -getattr(WEATHER_SCORE_DEF, f"weight_{a}"))
return [WeatherWhy(label=WEATHER_AXIS_NAME[a], weight=getattr(WEATHER_SCORE_DEF, f"weight_{a}"), score=r.factors[a], note=r.notes.get(a, "")) for a in axes] return [WeatherWhy(label=WEATHER_AXIS_NAME[a], weight=getattr(WEATHER_SCORE_DEF, f"weight_{a}"), score=r.factors[a], note=r.notes.get(a, "")) for a in axes]
# 지금 날씨 점수 바꾸기 표: 구간마다 원래 점수 0~100 → 표시 점수(평균 60, 90점 이상은 드물게). scripts/gen_weather_score_table.py 가 만든다
WEATHER_SCORE_TABLE: dict[str, list[int]] = json.loads((Path(__file__).parent / "calc" / "weather_score_table.json").read_text(encoding="utf-8"))["slots"]
SEASONS = ("겨울", "봄", "여름", "가을") SEASONS = ("겨울", "봄", "여름", "가을")
@@ -90,8 +92,8 @@ class IndexItem:
trend: list[IndexScore] trend: list[IndexScore]
slot: Optional[str] = None slot: Optional[str] = None
slots: dict[str, int] = field(default_factory=dict) slots: dict[str, int] = field(default_factory=dict)
slot_ranks: dict[str, int] = field(default_factory=dict) # 구간별 순위. 그 구간과 안 겹치는 각은 없음 slot_ranks: dict[str, int] = field(default_factory=dict) # 각 구간의 날씨·시간대 적합도로 계산한 순위
active: bool = True # 지금 구간이 이 각의 시간대와 겹치는지. 아니면 순위·피드에서 빼고 목록 끝에 하루 점수로 둔다 active: bool = True # 시간대와 관계없이 활성화. 제철이 아닌 각만 제외
season: Optional[str] = None # 지금 제철이면 계절 이름 (화면 표시) season: Optional[str] = None # 지금 제철이면 계절 이름 (화면 표시)
in_season: bool = True # 제철이 아니면 순위·피드에서 빼고 목록 맨 끝에 둔다 in_season: bool = True # 제철이 아니면 순위·피드에서 빼고 목록 맨 끝에 둔다
@@ -109,7 +111,7 @@ class IndexBoard:
@property @property
def ranked(self) -> list[IndexItem]: def ranked(self) -> list[IndexItem]:
"""지금 구간에 해당하는 각만 (순위·피드용).""" """활성화된 각 (순위·피드용)."""
return [i for i in self.items if i.active] return [i for i in self.items if i.active]
@@ -199,7 +201,6 @@ def windows_for(
EARLY = "early" # 0~5시: 전날 밤 구간 EARLY = "early" # 0~5시: 전날 밤 구간
MIN_SLOT_HOURS = 2 # 각 시간대가 구간과 이만큼은 겹쳐야 그 구간 점수를 낸다 (한 시간짜리 각은 한 시간)
def current_slot(now: datetime, sunset_at: datetime) -> str: def current_slot(now: datetime, sunset_at: datetime) -> str:
@@ -216,6 +217,16 @@ def _shown_parts(parts: dict, cur: str) -> dict:
return {k: shown[k] for k in SLOTS if k in shown} return {k: shown[k] for k in SLOTS if k in shown}
def calibrated_weather(slot: str, score: int) -> int:
"""지금 날씨 점수의 원래 점수를 그 구간 표로 바꾼다. 0~5시(전날 밤 구간)는 밤 표."""
return WEATHER_SCORE_TABLE[shown_slot(slot)][score]
def weather_slot_scores(results: dict[str, Result]) -> dict[str, Result]:
"""구간별 날씨 점수 결과의 점수를 표시 점수로 바꾼다 (점수 근거 factors 는 그대로)."""
return {k: replace(r, score=calibrated_weather(k, r.score)) for k, r in results.items()}
def rain_hours(by_at: dict[datetime, WeatherHourly], day: date) -> frozenset[int]: def rain_hours(by_at: dict[datetime, WeatherHourly], day: date) -> frozenset[int]:
"""그날 비·눈 오는 시각(0~23).""" """그날 비·눈 오는 시각(0~23)."""
start = kst_midnight(day) start = kst_midnight(day)
@@ -226,16 +237,21 @@ def slot_results(
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime, defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
now: Optional[datetime] = None, now: Optional[datetime] = None,
) -> dict[str, Result]: ) -> dict[str, Result]:
"""그날 아침·낮·저녁·밤과 0~5시(전날 밤) 점수. 각 시간대와 겹치지 않는 구간은 빠진다. now 를 주면 지금 구간은 지금 시각부터만 본다.""" """각 구간의 날씨로 평가한다. 활동 시간대와 안 겹쳐도 계산하되 시간 요소는 0점. now 가 있으면 현재 구간은 남은 시각만 본다."""
hours_by_slot = slot_hours(day, sunset_at) hours_by_slot = slot_hours(day, sunset_at)
cur = _trim_passed(hours_by_slot, day, sunset_at, now) if now else None hours_by_slot[EARLY] = set(range(NIGHT_END_HOUR))
parts = {k: windows_for(defn, day, region, by_at, by_om, only=hours) for k, hours in hours_by_slot.items()} if now:
parts[EARLY] = windows_for(defn, day - timedelta(days=1), region, by_at, by_om, only=set(range(24, 24 + NIGHT_END_HOUR))) _trim_passed(hours_by_slot, day, sunset_at, now)
need = min(MIN_SLOT_HOURS, max((len(h) for h in window_hours(defn, day, region)), default=0)) activity = [{h % 24 for h in w} for w in window_hours(defn, day, region)]
out = {} out = {}
for key, windows in parts.items(): for key, hours in hours_by_slot.items():
k_need = min(need, len(hours_by_slot[key])) if key == cur else need if not hours:
result = evaluate(defn, [w for w in windows if len(w) >= k_need], ctx) continue
matches = any(any(h % 24 in w for h in hours) for w in activity)
# 시간대 일치 여부와 날씨 평가를 분리해 하루 점수로 대체하지 않는다.
window = SimpleNamespace(windows=[{"from": min(hours), "to": max(hours) + 1}])
windows = windows_for(window, day, region, by_at, by_om, only=hours)
result = evaluate(defn, windows, replace(ctx, time_matches=matches))
if result is not None: if result is not None:
out[key] = result out[key] = result
return out return out
@@ -263,6 +279,13 @@ def _with_slot(row: IndexScore, data: dict) -> IndexScore:
return out return out
def _with_priority(row: IndexScore, priority: int) -> IndexScore:
"""DB의 원점수·요소 점수는 보존하고 응답용 사본의 최종 점수에만 중요도를 적용한다."""
out = IndexScore(**{c.key: getattr(row, c.key, None) for c in IndexScore.__table__.columns})
out.score = priority_score(row.score, priority)
return out
def day_forecast(d: WeatherDaily) -> DayForecast: def day_forecast(d: WeatherDaily) -> DayForecast:
return DayForecast( return DayForecast(
temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None, temp_min_c=float(d.temp_min_c) if d.temp_min_c is not None else None,
@@ -344,37 +367,23 @@ class IndexService:
month = today.month month = today.month
out_season = [d for d in defs if not in_season(d, 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)] defs = [d for d in defs if in_season(d, month)]
# 오늘 점수는 지금 구간 점수. 구간 점수가 없는 행(예전 계산분)은 하루 점수 그대로, 지금 구간과 안 겹치는 각은 뺀다 # 현재 구간의 날씨와 시간 요소로 계산한 점수만 사용한다.
now_score: dict[int, IndexScore] = {} now_score: dict[int, IndexScore] = {}
for d in defs: for d in defs:
row = by_key.get((d.index_id, today)) row = by_key.get((d.index_id, today))
if row is None: if row is None or cur not in row.slots:
continue continue
if not row.slots: now_score[d.index_id] = _with_priority(_with_slot(row, row.slots[cur]), d.priority)
now_score[d.index_id] = row
elif cur in row.slots:
now_score[d.index_id] = _with_slot(row, row.slots[cur])
ranked = sorted((d for d in defs if d.index_id in now_score), key=lambda d: rank_score(now_score[d.index_id].score, d.priority), reverse=True) ranked = sorted((d for d in defs if d.index_id in now_score), key=lambda d: rank_score(now_score[d.index_id].score, d.priority), reverse=True)
items = [] items = []
for i, d in enumerate(ranked): for i, d in enumerate(ranked):
row = by_key[(d.index_id, today)] row = by_key[(d.index_id, today)]
parts = _shown_parts({k: v["score"] for k, v in row.slots.items()}, cur) parts = _shown_parts({k: priority_score(v["score"], d.priority) for k, v in row.slots.items()}, cur)
items.append(IndexItem( items.append(IndexItem(
definition=d, score=now_score[d.index_id], rank=i + 1, 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], trend=[now_score[d.index_id] if day == today else _with_priority(by_key[(d.index_id, day)], d.priority) for day in slots if (d.index_id, day) in by_key],
slot=shown_slot(cur), slots=parts, season=season_badge(d, month), 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),
key=lambda d: rank_score(by_key[(d.index_id, today)].score, d.priority), reverse=True,
)
for d in off:
row = by_key[(d.index_id, today)]
items.append(IndexItem(
definition=d, score=row, rank=len(items) + 1,
trend=[by_key[(d.index_id, day)] for day in slots if (d.index_id, day) in by_key],
slots=_shown_parts({k: v["score"] for k, v in row.slots.items()}, cur), active=False, season=season_badge(d, month),
))
for k in SLOTS: 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) 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): for n, i in enumerate(in_slot):
@@ -383,8 +392,8 @@ class IndexService:
for d in sorted((d for d in out_season if (d.index_id, today) in by_key), key=lambda d: d.sort_order): 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)] row = by_key[(d.index_id, today)]
items.append(IndexItem( items.append(IndexItem(
definition=d, score=row, rank=len(items) + 1, definition=d, score=_with_priority(row, d.priority), 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, trend=[_with_priority(by_key[(d.index_id, day)], d.priority) for day in slots if (d.index_id, day) in by_key], active=False, in_season=False,
)) ))
return ErrorType.SUCCESS, IndexBoard( return ErrorType.SUCCESS, IndexBoard(
region=region, day=today, weather_score=weather_parts[cur].score if cur in weather_parts else None, items=items, region=region, day=today, weather_score=weather_parts[cur].score if cur in weather_parts else None, items=items,
@@ -459,8 +468,8 @@ class IndexService:
tomorrow_ctx = Context(day=tomorrow, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, tomorrow), **base_ctx) tomorrow_ctx = Context(day=tomorrow, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, tomorrow), **base_ctx)
tomorrow_sunset = sun_times(tomorrow, float(region.lat), float(region.lon)).sunset_at tomorrow_sunset = sun_times(tomorrow, float(region.lat), float(region.lon)).sunset_at
weather_parts = { weather_parts = {
today: {k: replace(r, score=strict_weather(r.score)) for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()}, today: weather_slot_scores(slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now)),
tomorrow: {k: replace(r, score=strict_weather(r.score)) for k, r in slot_results(WEATHER_SCORE_DEF, tomorrow, region, by_at, by_om, tomorrow_ctx, tomorrow_sunset).items()}, tomorrow: weather_slot_scores(slot_results(WEATHER_SCORE_DEF, tomorrow, region, by_at, by_om, tomorrow_ctx, tomorrow_sunset)),
} }
issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []]) issued = max([r.issued_at for r in rows] + [d.issued_at for d in daily_rows or []])
+3 -3
View File
@@ -22,7 +22,7 @@ from crud.index_crud import IndexCRUD
from crud.region_crud import RegionCRUD from crud.region_crud import RegionCRUD
from crud.weather_crud import WeatherCRUD from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD from crud.week_crud import WeekCRUD
from services.calc.index_calc import rank_score from services.calc.index_calc import priority_score, rank_score
from services.external.culture_api import IMAGE_CREDIT as CULTURE_CREDIT from services.external.culture_api import IMAGE_CREDIT as CULTURE_CREDIT
from services.external.culture_api import SOURCE_PREFIX as CULTURE_PREFIX from services.external.culture_api import SOURCE_PREFIX as CULTURE_PREFIX
from services.external.culture_api import CONCERT, EXHIBITION, fetch_exhibitions, parse_exhibitions from services.external.culture_api import CONCERT, EXHIBITION, fetch_exhibitions, parse_exhibitions
@@ -291,14 +291,14 @@ class WeekService:
for d in daily: for d in daily:
rows = [r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d.forecast_date] rows = [r for r in hourly or [] if r.forecast_at.astimezone(KST).date() == d.forecast_date]
rain_hours = _rain_hours(rows) rain_hours = _rain_hours(rows)
top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: rank_score(x.score, priority.get(x.index_id, 2)), reverse=True)[:2] top = sorted((x for x in scores or [] if x.score_date == d.forecast_date and not x.estimated), key=lambda x: rank_score(priority_score(x.score, priority.get(x.index_id, 2)), priority.get(x.index_id, 2)), reverse=True)[:2]
holiday = (holidays or {}).get(d.forecast_date) holiday = (holidays or {}).get(d.forecast_date)
weekday = _WEEKDAY_KO[d.forecast_date.weekday()] weekday = _WEEKDAY_KO[d.forecast_date.weekday()]
word = _weather_word(d, rain_hours) word = _weather_word(d, rain_hours)
temps = f" {round(float(d.temp_min_c))}~{round(float(d.temp_max_c))}°" if d.temp_min_c is not None and d.temp_max_c is not None else "" temps = f" {round(float(d.temp_min_c))}~{round(float(d.temp_max_c))}°" if d.temp_min_c is not None and d.temp_max_c is not None else ""
is_rainy = d.rain_type != RainType.NONE.value is_rainy = d.rain_type != RainType.NONE.value
if top: if top:
summary = ", ".join(f"{names.get(x.index_id, '')} {x.score}점" for x in top) summary = ", ".join(f"{names.get(x.index_id, '')} {priority_score(x.score, priority.get(x.index_id, 2))}점" for x in top)
pick = "비 오는 날, 실내 일정이 좋아요" if is_rainy else f"{names.get(top[0].index_id, '')} 추천" pick = "비 오는 날, 실내 일정이 좋아요" if is_rainy else f"{names.get(top[0].index_id, '')} 추천"
else: else:
summary, pick = f"비 확률 {d.rain_prob}%", ("실내 일정이 좋아요" if is_rainy else "바깥 일정 잡기 좋아요") summary, pick = f"비 확률 {d.rain_prob}%", ("실내 일정이 좋아요" if is_rainy else "바깥 일정 잡기 좋아요")
+19 -4
View File
@@ -22,7 +22,7 @@ from crud.region_crud import RegionCRUD
from crud.sky_crud import SkyCRUD from crud.sky_crud import SkyCRUD
from crud.weather_crud import WeatherCRUD from crud.weather_crud import WeatherCRUD
from crud.week_crud import WeekCRUD from crud.week_crud import WeekCRUD
from services.calc.index_calc import OUTING_HOURS, outing, outing_estimate from services.calc.index_calc import OUTING_HOURS, Outing, outing, outing_estimate
from services.index_service import day_forecast, windows_for from services.index_service import day_forecast, windows_for
from services.weather_service import WeatherService from services.weather_service import WeatherService
from services.week_service import _icon from services.week_service import _icon
@@ -30,14 +30,29 @@ from services.week_service import _icon
# 주말 전국 날씨 순위·당일치기 추천. 대표 지역(노을 순위 30곳)과 당일치기 후보 도시의 토·일 나들이 점수를 # 주말 전국 날씨 순위·당일치기 추천. 대표 지역(노을 순위 30곳)과 당일치기 후보 도시의 토·일 나들이 점수를
# 워커가 하루 두 번(06:40·18:40) 미리 계산해 Redis 에 둔다. 없으면 순위 API 가 그 자리에서 계산한다. # 워커가 하루 두 번(06:40·18:40) 미리 계산해 Redis 에 둔다. 없으면 순위 API 가 그 자리에서 계산한다.
_SEED = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "trip_city.csv") _SEED = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "trip_city.csv")
_KEY = "weekend_rank:{:%Y%m%d}" _KEY = "weekend_rank:v2:{:%Y%m%d}" # v2: 점수를 바꾸기 표로 보정한 값 (옛 점수 캐시를 쓰지 않게 키를 바꿨다)
_TTL = 13 * 3600 _TTL = 13 * 3600
_PARALLEL = 4 # 기상청 동시 호출 수 _PARALLEL = 4 # 기상청 동시 호출 수
_WAIT_STEPS, _WAIT_SEC = 60, 0.5 _WAIT_STEPS, _WAIT_SEC = 60, 0.5
_WINDOW = SimpleNamespace(windows=[{"from": OUTING_HOURS[0], "to": OUTING_HOURS[1]}]) _WINDOW = SimpleNamespace(windows=[{"from": OUTING_HOURS[0], "to": OUTING_HOURS[1]}])
# 나들이 점수 바꾸기 표: 원래 점수 0~100 → 표시 점수(평균 60, 90점 이상은 드물게). scripts/gen_outing_score_table.py 가 만든다
OUTING_SCORE_TABLE: list[int] = json.loads(
open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "calc", "outing_score_table.json"), encoding="utf-8").read()
)["table"]
def calibrated_outing(score: int) -> int:
return OUTING_SCORE_TABLE[score]
def outing_day_score(result: Outing) -> int:
"""순위·당일치기에 쓰는 하루 나들이 점수. 시간별 예보로 낸 점수와 중기예보 예상 점수 모두 같은 표를 거친다."""
return calibrated_outing(result.score)
# 당일치기: 내 지역에서 직선 이 거리 안의 후보 도시만 (1~2시간 거리), 너무 가까운 곳(같은 동네)은 뺀다. # 당일치기: 내 지역에서 직선 이 거리 안의 후보 도시만 (1~2시간 거리), 너무 가까운 곳(같은 동네)은 뺀다.
TRIP_MIN_KM, TRIP_MAX_KM = 20, 200 TRIP_MIN_KM, TRIP_MAX_KM = 20, 200
TRIP_MIN_SCORE = 50 TRIP_MIN_SCORE = calibrated_outing(50) # 원래 점수 50점과 같은 날씨 수준
@dataclass @dataclass
@@ -205,7 +220,7 @@ class WeekendRank:
if result is None or row is None: if result is None or row is None:
continue continue
out.append(DayScore( out.append(DayScore(
region_code=region.code, day=d, score=result.score, reason=result.reason, icon=_icon(Sky(row.sky), RainType(row.rain_type)), region_code=region.code, day=d, score=outing_day_score(result), reason=result.reason, icon=_icon(Sky(row.sky), RainType(row.rain_type)),
temp_min_c=float(row.temp_min_c) if row.temp_min_c is not None else None, temp_min_c=float(row.temp_min_c) if row.temp_min_c is not None else None,
temp_max_c=float(row.temp_max_c) if row.temp_max_c is not None else None, temp_max_c=float(row.temp_max_c) if row.temp_max_c is not None else None,
rain_prob=row.rain_prob, estimated=result.estimated, rain_prob=row.rain_prob, estimated=result.estimated,
+21 -9
View File
@@ -48,11 +48,10 @@ def test_current_slot_before_5_is_previous_night():
assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening" assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening"
def test_gak_hidden_in_slots_outside_its_window(): def test_gak_scores_every_slot_and_time_match_is_binary():
parts = slot_results(_defn([{"from": 17, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET) parts = slot_results(_defn([{"from": 17, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
assert set(parts) == {"evening", "night"} assert set(parts) == {"morning", "day", "evening", "night", EARLY}
# 18시 한 시간만 저녁 구간(16~18시)과 겹치면 저녁 점수는 내지 않는다 assert {k: r.factors["time"] for k, r in parts.items()} == {"morning": 0, "day": 0, "evening": 100, "night": 100, EARLY: 0}
assert set(slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)) == {"night"}
def test_rain_in_evening_lowers_only_later_slots(): def test_rain_in_evening_lowers_only_later_slots():
@@ -102,12 +101,25 @@ def test_ultra_rain_lowers_slot_score():
assert wet < dry assert wet < dry
def test_slot_needs_two_overlapping_hours(): def test_time_match_includes_one_overlapping_hour():
"""10~17시 각은 아침 구간(5~11시)과 10시 한 시간만 겹쳐서 아침 점수를 내지 않는다. 한 시간짜리 각은 한 시간이면 된다."""
by_at = _rows() by_at = _rows()
assert "morning" not in slot_results(_defn([{"from": 10, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET) for start, end in ((10, 17), (9, 17), (10, 11)):
assert "morning" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET) assert slot_results(_defn([{"from": start, "to": end}]), DAY, REGION, by_at, {}, CTX, SUNSET)["morning"].factors["time"] == 100
assert "morning" in slot_results(_defn([{"from": 10, "to": 11}]), DAY, REGION, by_at, {}, CTX, SUNSET)
def test_outside_window_uses_current_weather_instead_of_daily_weather():
parts = slot_results(_defn([{"from": 7, "to": 11}]), DAY, REGION, _rows(rain_from=16), {}, CTX, SUNSET)
assert parts["morning"].score == 100
assert parts["night"].score < parts["morning"].score
assert parts["night"].factors["rain"] == 0 and parts["night"].factors["time"] == 0
def test_early_hours_match_windows_crossing_midnight():
parts = slot_results(_defn([{"from": 21, "to": 26}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
assert parts[EARLY].factors["time"] == 100
now = datetime(2026, 10, 8, 2, 0, tzinfo=KST)
parts = slot_results(_defn([{"from": 21, "to": 26}]), DAY, REGION, _rows(), {}, CTX, SUNSET, now)
assert parts[EARLY].factors["time"] == 0
def test_current_slot_skips_passed_hours(): def test_current_slot_skips_passed_hours():
+6 -1
View File
@@ -8,10 +8,12 @@ from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import PostType from common.enums import PostType
from common.utils.kma_time import now_kst from common.utils.kma_time import now_kst
from crud.feed_crud import FeedCRUD from crud.feed_crud import FeedCRUD
from crud.index_crud import IndexCRUD
from crud.region_crud import RegionCRUD from crud.region_crud import RegionCRUD
from crud.season_crud import SeasonCRUD from crud.season_crud import SeasonCRUD
from router.router import app from router.router import app
from services.feed_service import build_feed_day from services.feed_service import build_feed_day
from services.index_service import in_season
from services.week_service import collect_events from services.week_service import collect_events
REGION = "1114000000" REGION = "1114000000"
@@ -61,7 +63,10 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
body = (await client.get("/v1/feed", params={"region": REGION})).json() body = (await client.get("/v1/feed", params={"region": REGION})).json()
assert body["result"]["success"] is True 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 body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"]
assert len(body["stories"]) == 40 _, definitions = await DB_SESSION_MNG.execute_lambda(lambda s: IndexCRUD().definitions(s))
expected = {d.code for d in definitions if in_season(d, now_kst().month)}
assert {g["code"] for g in body["stories"]} == expected
assert all(g["active"] for g in body["stories"])
assert body["hero"]["weather_score"] == body["hero"]["weather_slots"][body["slot"]] 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"]) 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) weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
+54 -13
View File
@@ -8,7 +8,7 @@ import services.air_service as air_service
import services.warning_service as warning_service import services.warning_service as warning_service
import services.weather_service as weather_service import services.weather_service as weather_service
from common.database.db_session_manager import DB_SESSION_MNG from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import OpenMeteoHourly, WeatherHourly from common.database.model.models import IndexScore, OpenMeteoHourly, WeatherHourly
from common.enums import ErrorType from common.enums import ErrorType
from common.utils.kma_time import kst_midnight, now_kst from common.utils.kma_time import kst_midnight, now_kst
from crud.region_crud import RegionCRUD from crud.region_crud import RegionCRUD
@@ -27,6 +27,14 @@ async def _async(v):
return v return v
def _board_score(index_id, day, score, slot_score=None):
value = score if slot_score is None else slot_score
return IndexScore(index_id=index_id, score_date=day, score=score, slots={
k: {"score": value, "summary": "", "factors": {}, "zero_reason": None, "notes": {}}
for k in ("morning", "day", "evening", "night", "early")
})
def _vilage(*_): def _vilage(*_):
start = kst_midnight(now_kst().date()) start = kst_midnight(now_kst().date())
items = [] items = []
@@ -64,14 +72,17 @@ async def test_index_list_ranks_every_gak_with_today_tomorrow_weekend_trend(fake
assert body["result"]["success"] is True assert body["result"]["success"] is True
assert len(body["items"]) == len(_seed()) 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()} priority = {d["code"]: d["priority"] for d in _seed()}
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤, 제철 아닌 각은 맨 끝. 앞 두 묶음 안에서는 점수 × 중요도 순 # 시간대와 관계없이 제철인 각은 모두 활성화하고, 제철 아닌 각은 맨 끝.
assert all(i["active"] for i in body["items"] if i["in_season"])
actives = [i["active"] for i in body["items"]] actives = [i["active"] for i in body["items"]]
assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"]) assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"])
seasons = [i["in_season"] for i in body["items"]] 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"]) 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): for group in (True, False):
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]] scores = [i["score"] for i in body["items"] if i["active"] is group and i["in_season"]]
assert weighted == sorted(weighted, reverse=True) assert scores == sorted(scores, reverse=True)
order = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]]
assert order == sorted(order, reverse=True)
today = now_kst().date() today = now_kst().date()
for i in body["items"]: for i in body["items"]:
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)] assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
@@ -142,7 +153,7 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
SimpleNamespace(index_id=2, code="now", priority=2, months=[today.month], sort_order=2), 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), 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))] scores = [_board_score(x, today, v) for x, v in ((1, 50), (2, 60), (3, 99))]
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores)) crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None) service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {now_kst().date(): _WEATHER_50}))) monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {now_kst().date(): _WEATHER_50})))
@@ -155,30 +166,38 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
@pytest.mark.anyio @pytest.mark.anyio
async def test_board_ranks_by_score_times_priority_weight(monkeypatch): async def test_board_displays_and_ranks_by_priority_adjusted_score(monkeypatch):
today = now_kst().date() today = now_kst().date()
defs = [ defs = [
SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=1, code="low", priority=3),
SimpleNamespace(index_id=2, code="mid", priority=2), SimpleNamespace(index_id=2, code="mid", priority=2),
SimpleNamespace(index_id=3, code="high", priority=1), SimpleNamespace(index_id=3, code="high", priority=1),
] ]
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))] scores = [_board_score(x, today, v) for x, v in ((1, 90), (2, 80), (3, 70))]
scores += [_board_score(x, today + timedelta(days=1), v) for x, v in ((1, 90), (2, 80), (3, 70))]
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores)) crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None) service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {now_kst().date(): _WEATHER_50}))) monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {now_kst().date(): _WEATHER_50})))
err, board = await service.board(REGION) err, board = await service.board(REGION)
assert err is ErrorType.SUCCESS 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", 68, 2), ("low", 63, 3)]
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 80, 2), ("low", 90, 3)] for item in board.items:
assert item.trend[0].score == item.score.score
assert item.trend[1].score == item.score.score
assert all(value == item.score.score for value in item.slots.values())
# 응답용 보정은 DB에서 읽은 원점수를 바꾸지 않으며, 같은 요청을 다시 해도 중복 적용하지 않는다.
assert [row.score for row in scores] == [90, 80, 70, 90, 80, 70]
_, again = await service.board(REGION)
assert [i.score.score for i in again.items] == [70, 68, 63]
@pytest.mark.anyio @pytest.mark.anyio
async def test_board_ranks_each_slot_with_priority_weight(monkeypatch): async def test_board_ranks_each_slot_by_displayed_score(monkeypatch):
today = now_kst().date() today = now_kst().date()
defs = [SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=2, code="high", priority=1)] defs = [SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=2, code="high", priority=1)]
every = ("morning", "day", "evening", "night", "early") every = ("morning", "day", "evening", "night", "early")
slots = {1: {k: {"score": 90, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every}, 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")}} 2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every}}
scores = [SimpleNamespace(index_id=x, score_date=today, score=80, slots=slots[x]) for x in (1, 2)] 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)) crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None) service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
@@ -186,10 +205,32 @@ async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
monkeypatch.setattr("services.index_service._with_slot", lambda row, data: SimpleNamespace(score=data["score"])) monkeypatch.setattr("services.index_service._with_slot", lambda row, data: SimpleNamespace(score=data["score"]))
_, board = await service.board(REGION) _, board = await service.board(REGION)
ranks = {i.definition.code: i.slot_ranks for i in board.items} ranks = {i.definition.code: i.slot_ranks for i in board.items}
# 아침: 하 90(63) > 상 20(20). 낮: 상 70(70) > 하 90(63). 상은 밤 구간이 없어 밤 순위도 없다 # 하 90점은 표시 63점, 상 70점은 표시 70점으로 순위와 화면 숫자가 일치한다.
assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2 assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2
assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2 assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2
assert "night" not in ranks["high"] assert ranks["high"]["night"] == 1 and ranks["low"]["night"] == 2
@pytest.mark.anyio
@pytest.mark.parametrize("cur", ["morning", "day", "evening", "night", "early"])
async def test_board_activates_gak_outside_its_time_window(monkeypatch, cur):
today = now_kst().date()
defs = [SimpleNamespace(index_id=1, code="outside", priority=1)]
row = _board_score(1, today, 85, slot_score=65)
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async([row]))
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {today: {cur: _RESULT_50}})))
monkeypatch.setattr("services.index_service.current_slot", lambda *a: cur)
err, board = await service.board(REGION)
assert err is ErrorType.SUCCESS
assert len(board.ranked) == 1
item = board.ranked[0]
assert item.active and item.score.score == 65 and item.rank == 1
assert item.trend == [item.score] and item.slot == ("night" if cur == "early" else cur)
assert item.slots == {k: 65 for k in ("morning", "day", "evening", "night")}
assert item.slot_ranks == {k: 1 for k in item.slots}
def _om_row(at, **over): def _om_row(at, **over):
+31 -13
View File
@@ -9,7 +9,7 @@ import pytest
from common.enums import RainType, Sky from common.enums import RainType, Sky
from services.calc.index_calc import ( from services.calc.index_calc import (
OUTING_HOURS, Context, DayForecast, Hour, air_score, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score, OUTING_HOURS, Context, DayForecast, Hour, air_score, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
uv_score, view_score, zero_rules_text, priority_score, rank_score, uv_score, view_score, zero_rules_text,
) )
from services.calc.moon import illumination from services.calc.moon import illumination
@@ -38,6 +38,36 @@ def test_perfect_evening_scores_100():
assert r.notes["temp"] == "체감 21°, 편한 범위 18~24° 안" assert r.notes["temp"] == "체감 21°, 편한 범위 18~24° 안"
def test_rank_and_display_share_priority_adjusted_screenshot_scores():
items = [(83, 1), (82, 1), (80, 1), (91, 2), (77, 1), (77, 1), (76, 1), (89, 2), (87, 2)]
shown = [(priority_score(score, priority), priority) for score, priority in items]
ranked = sorted(shown, key=lambda item: rank_score(*item), reverse=True)
assert [score for score, _ in ranked] == [83, 82, 80, 77, 77, 77, 76, 76, 74]
assert priority_score(91, 2) == 77
assert priority_score(89, 2) == 76
def test_rank_uses_priority_only_to_break_ties():
items = [(80, 3), (80, 1), (81, 3), (80, 2)]
assert sorted(items, key=lambda item: rank_score(*item), reverse=True) == [(81, 3), (80, 1), (80, 2), (80, 3)]
@pytest.mark.parametrize("weight", [5, 10, 20])
def test_time_match_adds_only_its_weight_without_extra_penalty(weight):
rules = _defn().factor_rules | {"time": {"type": "fixed", "value": 55}}
defn = _defn(weight_temp=100 - weight, weight_rain=0, weight_wind=0, weight_humidity=0, weight_air=0,
weight_time=weight, factor_rules=rules)
hours = [[_h(12)]]
matched = evaluate(defn, hours, replace(CTX, time_matches=True))
unmatched = evaluate(defn, hours, replace(CTX, time_matches=False))
assert matched.factors["time"] == 100 and unmatched.factors["time"] == 0
assert matched.score == 100 and unmatched.score == 100 - weight
def test_time_matching_does_not_replace_weekday_score():
assert evaluate(_defn(), [[_h(12)]], replace(CTX, time_matches=False)).factors["time"] == 100
def test_good_but_not_perfect_stays_below_100(): def test_good_but_not_perfect_stays_below_100():
assert evaluate(_defn(), [[_h(19, feels=23, hum=58, wind=1.8)]], CTX).score < 95 assert evaluate(_defn(), [[_h(19, feels=23, hum=58, wind=1.8)]], CTX).score < 95
@@ -342,18 +372,6 @@ def test_umbrella_lost_needs_rain_that_stopped():
assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0 assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0
def test_weather_score_is_strict_near_top():
"""좋은 날(96)도 92 수준, 100점은 모든 조건이 완벽할 때만. 낮은 점수도 조금씩 내려간다."""
from services.index_service import strict_weather
assert strict_weather(100) == 100
assert strict_weather(96) == 92
assert strict_weather(99) < 100
assert strict_weather(75) < 75
scores = [strict_weather(s) for s in range(101)]
assert scores == sorted(scores)
def test_weather_why_lists_every_condition_heaviest_first(): def test_weather_why_lists_every_condition_heaviest_first():
from services.index_service import WEATHER_SCORE_DEF, weather_why from services.index_service import WEATHER_SCORE_DEF, weather_why
+58
View File
@@ -0,0 +1,58 @@
from common.enums import RainType, Sky
from services.calc.index_calc import Hour, Outing, outing
from services.weekend_rank import OUTING_SCORE_TABLE, TRIP_MIN_SCORE, calibrated_outing, outing_day_score
def test_table_is_a_monotonic_0_to_100_lookup():
assert len(OUTING_SCORE_TABLE) == 101
assert all(0 <= v <= 100 for v in OUTING_SCORE_TABLE)
assert all(a <= b for a, b in zip(OUTING_SCORE_TABLE, OUTING_SCORE_TABLE[1:]))
assert OUTING_SCORE_TABLE[0] < OUTING_SCORE_TABLE[100] == 100
def test_table_makes_top_scores_rare_and_centers_60():
"""원래 점수가 높을수록 표시 점수가 오르되, 90점 이상으로 가는 원래 점수는 위쪽 일부뿐."""
assert any(55 <= v <= 65 for v in OUTING_SCORE_TABLE)
assert sum(v >= 90 for v in OUTING_SCORE_TABLE) <= 15
# 맑고 알맞은 날(원래 100)과 조금 못 미치는 날(원래 97)이 모두 100점으로 몰리지 않는다
assert calibrated_outing(95) < 100
def test_calibrated_outing_reads_the_table():
assert calibrated_outing(70) == OUTING_SCORE_TABLE[70]
assert calibrated_outing(0) == OUTING_SCORE_TABLE[0]
def test_day_score_uses_calibrated_value_for_hourly_and_estimated_results():
for estimated in (False, True):
r = Outing(score=80, factors={}, notes={}, reason="비 0% · 체감 21° · 맑음", capped=False, estimated=estimated)
assert outing_day_score(r) == OUTING_SCORE_TABLE[80]
def test_trip_min_score_keeps_the_same_weather_quality():
"""당일치기 최소 기준은 원래 점수 50과 같은 날씨 수준을 표시 점수로 옮긴 값."""
assert TRIP_MIN_SCORE == calibrated_outing(50)
# 표는 가까운 원래 점수끼리 같은 값이 될 수 있어, 눈에 띄게 낮은 날은 빠지고 높은 날은 들어가는지만 본다
assert calibrated_outing(45) < TRIP_MIN_SCORE <= calibrated_outing(55)
def _day(feels: float = 21.0, wind: float = 0.5, prob: int = 0, sky: Sky = Sky.CLEAR) -> list[Hour]:
return [Hour(hour=h, feels_c=feels, rain_type=RainType.NONE, rain_prob=prob, wind_ms=wind, humidity=50, sky=sky) for h in range(10, 18)]
def test_outing_100_needs_exact_temperature_and_very_calm_wind():
"""맑고 비 없는 날도 체감 21° 근처(±0.5°)·바람 초속 1m 이하여야 100점. 그래야 같은 예보의 여러 지역이 한꺼번에 100점이 되지 않는다."""
assert outing(_day()).score == 100
assert outing(_day(feels=21.4)).factors["temp"] == 100
assert outing(_day(feels=22.3)).factors["temp"] < 100
assert outing(_day(wind=1.0)).factors["wind"] == 100
assert outing(_day(wind=1.8)).factors["wind"] < 95
assert outing(_day(wind=1.2)).score > outing(_day(wind=1.8)).score > outing(_day(wind=2.0)).score
def test_100_only_for_a_perfect_original_score_and_top_scores_stay_distinct():
"""맨 위가 100으로 잘려 원래 96·97·99가 모두 100점이 되던 것을 막는다: 100점은 원래 100뿐, 그 아래는 서로 다른 점수."""
assert OUTING_SCORE_TABLE[100] == 100
assert OUTING_SCORE_TABLE[99] < 100
top = OUTING_SCORE_TABLE[90:]
assert all(a < b for a, b in zip(top, top[1:]))
+74
View File
@@ -0,0 +1,74 @@
from dataclasses import replace
from datetime import date
from services.calc.index_calc import Context, evaluate
from scripts.gen_weather_score_table import straighten_top
from services.index_service import EARLY, WEATHER_SCORE_DEF, WEATHER_SCORE_TABLE, calibrated_weather, weather_slot_scores
from tests.test_index_calc import _defn, _h
PERFECT = Context(day=date(2026, 10, 2), is_holiday=False, pm25=8, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
SLOTS = ("morning", "day", "evening", "night")
def test_weather_score_has_no_worst_factor_pull():
"""해 난 비율만 0점(밤)이어도 나머지가 만점이면 비중대로 85점. 가장 낮은 요소로 25% 더 깎지 않는다."""
hours = [_h(h, feels=21.0, prob=0, wind=0.8, hum=50, sunshine_ratio=0.0) for h in range(19, 23)]
r = evaluate(WEATHER_SCORE_DEF, [hours], PERFECT)
assert r.factors["sun"] == 0
assert r.score == 85
def test_gak_scores_keep_worst_factor_pull():
"""각 점수는 그대로: 한 요소가 0점이면 섞은 점수에서 25% 깎인다."""
defn = _defn(zero_rules=[])
r = evaluate(defn, [[_h(19, wind=12.0)]], PERFECT)
assert r.factors["wind"] == 0
plain = round(sum(r.factors[a] * getattr(defn, f"weight_{a}", 0) for a in r.factors) / 100)
assert r.score == round(plain * 0.75)
def test_table_covers_every_slot_and_never_goes_down():
for slot in SLOTS:
table = WEATHER_SCORE_TABLE[slot]
assert len(table) == 101
assert all(0 <= v <= 100 for v in table)
assert all(a <= b for a, b in zip(table, table[1:]))
assert table[100] == 100
def test_table_makes_90_rare_and_centers_60():
"""구간마다 원래 점수 중앙값 근처가 60점 근처로, 90점 이상은 원래 점수 상위 몇 칸뿐."""
for slot in SLOTS:
table = WEATHER_SCORE_TABLE[slot]
assert any(55 <= v <= 65 for v in table)
assert sum(v >= 90 for v in table) < sum(v < 90 for v in table)
def test_calibrated_uses_slot_table_and_last_night_for_early():
assert calibrated_weather("day", 70) == WEATHER_SCORE_TABLE["day"][70]
assert calibrated_weather(EARLY, 70) == WEATHER_SCORE_TABLE["night"][70]
def test_weather_slot_scores_keeps_results_with_calibrated_scores():
"""점수 근거(factors)는 그대로 두고 점수만 표시 점수로 바꾼 결과를 돌려준다."""
results = {k: replace(evaluate(WEATHER_SCORE_DEF, [[_h(12)]], PERFECT), score=s) for k, s in {"morning": 40, "night": 60, EARLY: 60}.items()}
shown = weather_slot_scores(results)
assert {k: r.score for k, r in shown.items()} == {"morning": WEATHER_SCORE_TABLE["morning"][40], "night": WEATHER_SCORE_TABLE["night"][60], EARLY: WEATHER_SCORE_TABLE["night"][60]}
assert all(shown[k].factors == results[k].factors for k in results)
assert results["morning"].score == 40 # 원래 결과는 바뀌지 않는다
def test_straighten_top_makes_100_only_at_the_top_and_keeps_the_rest():
clamped = list(range(0, 80)) + [85, 90, 95] + [100] * 18 # 맨 위가 100으로 잘린 표 (원래 80~82 → 85·90·95, 83 이상은 모두 100)
fixed = straighten_top(clamped, top=100)
assert fixed[:80] == clamped[:80] # 아래쪽은 그대로
assert fixed[100] == 100 and max(fixed[:100]) < 100
above = fixed[80:]
assert all(a < b for a, b in zip(above, above[1:])) or above[-1] == 100 # 위쪽은 구별되는 점수로 오른다
assert straighten_top(clamped, top=90)[90] == 100 # 완벽한 점수가 100보다 낮은 구간(밤)은 거기서 100
def test_weather_table_gives_100_only_at_the_best_reachable_original_score():
assert WEATHER_SCORE_TABLE["day"][99] < 100 == WEATHER_SCORE_TABLE["day"][100]
night_top = 100 - WEATHER_SCORE_DEF.weight_sun # 밤은 해 난 비율이 늘 0점이라 원래 점수가 85까지만 나온다
assert WEATHER_SCORE_TABLE["night"][night_top - 1] < 100 == WEATHER_SCORE_TABLE["night"][night_top]
+1 -1
View File
@@ -10,7 +10,7 @@
- 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다. - 시간대가 여러 개면 그중 가장 좋은 시간대 점수를 씁니다.
- 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다. - 미세먼지는 초미세먼지 15㎍/㎥ 이하 100점 → 75㎍/㎥ 이상 0점입니다. 집콕각처럼 규칙을 따로 적은 각만 거꾸로(탁할수록 좋음) 셉니다.
- 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다. - 바람·미세먼지·노을 정보가 없으면 70점으로 둡니다.
- 순위는 점수 × 중요도 가중치(상 1.0 · 중 0.85 · 하 0.7)로 정합니다. 화면에 보이는 점수는 그대로입니다. - 최종 점수는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시 모두 이 최종 점수를 사용합니다.
## 한눈에 보기 ## 한눈에 보기
+5 -5
View File
@@ -175,21 +175,21 @@
### 2-7. 각 점수 (오늘의 각 34개) ### 2-7. 각 점수 (오늘의 각 34개)
- **식은 2-2~2-4와 같습니다.** 각마다 요소별 비중, 방식(2-3), 조건, 하기 좋은 시간대가 다릅니다. 34개 각의 시간대와 주요 비중은 [부록](#부록-각-34개-한눈에-보기)에 있습니다. - **식은 2-2~2-4와 같습니다.** 각마다 요소별 비중, 방식(2-3), 조건, 하기 좋은 시간대가 다릅니다. 34개 각의 시간대와 주요 비중은 [부록](#부록-각-34개-한눈에-보기)에 있습니다.
- **오늘 점수 = 지금 구간 점수.** 각의 시간대 중 지금 구간에 드는 시간만 골라 계산합니다. 예: 오후 5시(저녁 구간)의 야장각(18~24시)은 18시대만 봅니다. - **오늘 점수 = 지금 구간 점수.** 지금 구간의 날씨로 계산하며, 현재 구간은 이미 지난 시각을 제외합니다.
- 각의 시간대가 지금 구간과 겹치지 않으면(예: 아침의 야장각) 순위, 피드 카드, 맨 위 1위에서 빠집니다. 각 탭 전체 목록에는 맨 뒤에 '지금 아님'으로, 하루 점수와 함께 남습니다. - 각의 시간대가 지금 구간과 겹치지 않아도 현재 구간의 날씨 점수로 활성화하고 순위, 피드 카드, 맨 위 1위 후보에 포함합니다. 시간대 미리보기도 각 구간의 날씨로 계산합니다. 제철이 아닌 각의 비활성화는 유지합니다.
- **하루 점수**(내일·토·일 칸, '지금 아님' 각): 각의 시간대 전체로 계산한 점수입니다. - **하루 점수**(내일·토·일 칸): 각의 시간대 전체로 계산한 점수입니다.
- **햇빛·자외선·가시거리:** 10개 각(피크닉, 등산, 세차, 별보기, 빨래, 자전거, 가드닝, 사진산책, 드라이브, 물놀이)은 이 요소도 봅니다. 모두 2-3의 ② 방식입니다. - **햇빛·자외선·가시거리:** 10개 각(피크닉, 등산, 세차, 별보기, 빨래, 자전거, 가드닝, 사진산책, 드라이브, 물놀이)은 이 요소도 봅니다. 모두 2-3의 ② 방식입니다.
- **'시간' 요소**는 날씨가 아닌 것을 넣는 칸입니다. - **'시간' 요소**는 날씨가 아닌 것을 넣는 칸입니다.
| 종류 | 식 | 쓰는 각 | | 종류 | 식 | 쓰는 각 |
|---|---|---| |---|---|---|
| 요일 | 요일·공휴일마다 정한 점수 | 19개 | | 요일 | 요일·공휴일마다 정한 점수 | 19개 |
| 고정 | 정한 점수 하나 | 13개 | | 시간대 알맞음 | 활동 시간대와 겹치면 100점, 아니면 0점. 가중치 10%라면 10점 또는 0점 반영(불일치 추가 감점 없음) | fixed 유형 |
| 달 | 20 + 80 × (1 − 달이 비추는 정도). 달이 비추는 정도 = 달의 빛나는 면 × 21~26시 중 달이 떠 있는 비율 | 별보기각 | | 달 | 20 + 80 × (1 − 달이 비추는 정도). 달이 비추는 정도 = 달의 빛나는 면 × 21~26시 중 달이 떠 있는 비율 | 별보기각 |
| 노을 | 그날 노을 점수 (2-9) | 사진산책각 | | 노을 | 그날 노을 점수 (2-9) | 사진산책각 |
- **며칠 뒤 비까지 보는 각:** 세차각은 비 올 확률을 2일 뒤까지 보고, 그중 가장 높은 값을 씁니다. - **며칠 뒤 비까지 보는 각:** 세차각은 비 올 확률을 2일 뒤까지 보고, 그중 가장 높은 값을 씁니다.
- **순위** = 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면에 보이는 숫자는 곱하기 전 점수입니다. - **최종 점수**는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시에 같은 점수를 사용합니다.
- **먼 날의 예상 점수:** 단기예보가 닿지 않는 날(주말 등)은 중기예보의 최저·최고 기온으로 시간별 기온을 어림합니다(새벽 6시 최저, 오후 3시 최고, 그 사이는 코사인 곡선). 비 확률은 오전·오후 값을 쓰고, 바람·습도·미세먼지·햇빛은 정보 없음(70점)입니다. 조건은 비 확률만 봅니다. - **먼 날의 예상 점수:** 단기예보가 닿지 않는 날(주말 등)은 중기예보의 최저·최고 기온으로 시간별 기온을 어림합니다(새벽 6시 최저, 오후 3시 최고, 그 사이는 코사인 곡선). 비 확률은 오전·오후 값을 쓰고, 바람·습도·미세먼지·햇빛은 정보 없음(70점)입니다. 조건은 비 확률만 봅니다.
### 2-8. 나들이 점수 (주말 전국 순위, 당일치기) ### 2-8. 나들이 점수 (주말 전국 순위, 당일치기)
+27 -10
View File
@@ -56,7 +56,7 @@
## 3. 지금 날씨 점수 ## 3. 지금 날씨 점수
**지금 구간**의 모든 시각이 밖에 나가기 좋은 정도. 1의 방식으로 계산합니다. 밤에는 밤 날씨 기준이라 낮보다 낮게 나오기 쉽습니다. **지금 구간**의 모든 시각이 밖에 나가기 좋은 정도. 1의 방식으로 섞되 **'가장 낮은 요소로 깎기'(1의 3번)는 하지 않고**, 섞은 점수를 아래 '표시 점수로 바꾸기'로 바꿔 보여 줍니다. 밤엔 해 난 비율이 늘 0점이라 깎기를 하면 밤 점수가 62점을 못 넘었습니다 (`WEATHER_SCORE_DEF.worst_pull = False`).
| 요소 | 비중 | 100점 조건 | | 요소 | 비중 | 100점 조건 |
|---|---:|---| |---|---:|---|
@@ -67,18 +67,32 @@
| 초미세먼지 | 10% | 10㎍/㎥ 이하 (75에서 0점) | | 초미세먼지 | 10% | 10㎍/㎥ 이하 (75에서 0점) |
| 해 난 비율 (Open-Meteo) | 15% | 90% 이상 (20%에서 0점), 정보 없으면 70점 | | 해 난 비율 (Open-Meteo) | 15% | 90% 이상 (20%에서 0점), 정보 없으면 70점 |
여섯 가지가 동시에 맞아야 100점입니다. 기준값은 눈대중으로 잡은 것이며 (낮 기준 최적값을 밤에도 똑같이 씀), 실제로 1년에 며칠 나오는지는 확인하지 않았습니다. 위 표의 점수가 **원래 점수**입니다. 밤엔 해 난 비율이 0점이라 나머지가 모두 만점이어도 85점이 최대입니다.
### 표시 점수로 바꾸기
원래 점수는 40~60점대에 몰리고 좋은 계절 낮에 90점 이상이 자주 나와 점수 분포가 고르지 않았습니다. 그래서 원래 점수를 **구간(아침·낮·저녁·밤)마다 1년 치 분포에서의 순위**로 보고, 평균 60·표준편차 15인 정규분포의 같은 위치 점수로 바꿔 보여 줍니다. 순서는 그대로라 더 좋은 날씨가 더 낮은 점수를 받는 일은 없습니다.
- 표시 점수 평균은 구간마다 60. 90점 이상은 약 1.5% (낮 약 2.7%, 그 밖 구간 약 1%), 80점 이상은 약 9%, 40점 미만도 약 9%입니다. 100점은 구간에서 나올 수 있는 가장 높은 원래 점수일 때만 나와 1년에 거의 안 나옵니다. 계절 차이는 남습니다 (가을 평균 약 68, 겨울 약 54).
- **위쪽 끝은 직선으로 이어 100점이 잘리지 않게 합니다.** 순위로만 바꾸면 위쪽 0.4%가 한꺼번에 100점으로 잘려 비슷한 원래 점수(96·97·99)가 모두 100점이 됩니다. 그래서 표시 점수 83 이하인 마지막 원래 점수에서 100점까지 직선으로 이어(`straighten_top`), 100점은 원래 점수 100(밤은 해 난 비율이 0점이라 85)에서만, 그 아래는 서로 다른 점수가 되게 했습니다.
- 구간마다 따로 바꾸는 이유: 한 표로 하면 밤 점수가 최대 70점대 초반에 머뭅니다. 구간별 표는 "그 시간대치고 얼마나 좋은 날씨인가"를 뜻합니다.
- 0~5시(전날 밤 구간)는 밤 표를 씁니다.
- 바꾸기 표: `backend/services/calc/weather_score_table.json` (`calibrated_weather`). 만드는 법: `cd backend && python scripts/gen_weather_score_table.py`. 지금 날씨 점수의 요소·비중·기준값(`WEATHER_SCORE_DEF`)이 바뀌면 다시 만들어야 합니다.
- 표 재료: Open-Meteo 과거 예보로 32개 지역(region.csv 8곳마다 1곳)의 최근 364일을 계산. 실제 앱은 기상청 단기예보를 쓰므로 분포가 조금 다를 수 있어, 기상청 자료가 쌓이면 다시 만드는 게 좋습니다.
- **각 점수에는 적용하지 않습니다.**
예: 체감 22.5°, 비 10%, 바람 2.5m, 습도 62%, 초미세먼지 15, 해 70% → 원래 점수는 95점 미만(깎기를 뺀 값).
예: 체감 22.5°, 비 10%, 바람 2.5m, 습도 62%, 초미세먼지 15, 해 70% → 95점 미만.
## 4. 각 점수 ## 4. 각 점수
- 1의 방식. 요소·비중·시간대·0점 조건은 각마다 다르며 [각_계산기준.md](각_계산기준.md)에 있습니다. - 1의 방식. 요소·비중·시간대·0점 조건은 각마다 다르며 [각_계산기준.md](각_계산기준.md)에 있습니다.
- **오늘 점수 = 지금 구간 점수.** 각의 시간대 중 지금 구간에 드는 시각만으로 계산합니다(시간대가 여러 개면 그중 가장 좋은 쪽). 비가 오면 그 뒤 구간 점수가 내려갑니다. - **오늘 점수 = 지금 구간 점수.** 지금 구간의 날씨로 계산하며, 현재 구간은 이미 지난 시각을 제외합니다. 비가 오면 그 뒤 구간 점수가 내려갑니다.
- 각의 시간대가 지금 구간과 겹치지 않으면(예: 아침의 야장각) **순위·피드 카드·히어로 1위에서 빠집니다.** 스토리·각 탭 '전체'에는 맨 뒤에 '지금 아님'으로 남고, 점수는 하루 점수(가장 좋은 시간대)입니다. - 각의 시간대가 지금 구간과 겹치지 않아도 **현재 구간의 날씨 점수로 활성화하고 순위·피드 카드·히어로 1위 후보에 포함합니다.** 제철이 아닌 각의 비활성화는 유지합니다.
- 각 상세 창에 오늘 아침·낮·저녁·밤 점수를 보여 줍니다. 안 겹치는 구간은 '–'. - **시간대 알맞음:** 활동 시간대와 겹치면 요소 점수 100점, 아니면 0점입니다. 가중치가 10%라면 10점 또는 0점을 반영하고, 불일치에 따른 추가 최저 요소 감점은 없습니다. 요일·달·노을·일출 요소는 기존 계산을 유지합니다.
- 각 상세 창과 시간대 미리보기의 아침·낮·저녁·밤 점수도 각 구간의 날씨로 계산하며 하루 점수로 대체하지 않습니다.
- 내일·토·일 칸은 하루 점수(가장 좋은 시간대)입니다. - 내일·토·일 칸은 하루 점수(가장 좋은 시간대)입니다.
- 순위는 점수 × 중요도(상 1.0 · 중 0.85 · 하 0.7). 화면 숫자는 점수 그대로입니다. - 최종 점수는 원점수 × 중요도 배율(상 1.0 · 중 0.85 · 하 0.7)을 정수로 반올림한 값입니다. 순위와 화면 표시 모두 이 최종 점수를 사용합니다.
- 단기예보가 닿지 않는 날(토·일 등)은 중기예보의 최저·최고 기온으로 시각별 기온을 어림하고(새벽 6시 최저, 오후 3시 최고, 코사인 곡선), 바람·습도·미세먼지는 정보 없음으로 둔 '예상 점수'입니다. - 단기예보가 닿지 않는 날(토·일 등)은 중기예보의 최저·최고 기온으로 시각별 기온을 어림하고(새벽 6시 최저, 오후 3시 최고, 코사인 곡선), 바람·습도·미세먼지는 정보 없음으로 둔 '예상 점수'입니다.
## 5. 나들이 점수 (주말 순위·당일치기) ## 5. 나들이 점수 (주말 순위·당일치기)
@@ -88,15 +102,18 @@
| 요소 | 비중 | 계산 | | 요소 | 비중 | 계산 |
|---|---:|---| |---|---:|---|
| 비 | 40% | 마른 날 규칙 (1 참고) | | 비 | 40% | 마른 날 규칙 (1 참고) |
| 체감온도 | 35% | 편한 범위 17~24°, 최적 21° | | 체감온도 | 35% | 편한 범위 17~24°, 최적 21° (21°±0.5°만 100점, 만점 폭을 좁혀 같은 예보의 여러 지역이 다 100점이 되지 않게 함) |
| 하늘 | 15% | 시간마다 맑음 100 · 구름많음 80 · 흐림 50의 평균 | | 하늘 | 15% | 시간마다 맑음 100 · 구름많음 80 · 흐림 50의 평균 |
| 바람 | 10% | 4m/s 이하 100 → 12m/s 0 | | 바람 | 10% | 초속 1m 이하 100 → 2m에서 85 → 12m에서 0 |
- 1처럼 가장 낮은 요소로 깎습니다. - 1처럼 가장 낮은 요소로 깎습니다.
- 비 소식이 있거나 비 확률 60% 이상이면 **최대 30점**. - 비 소식이 있거나 비 확률 60% 이상이면 **최대 30점**.
- 중기예보뿐인 날은 기온을 어림하고 바람은 70점입니다. - 중기예보뿐인 날은 기온을 어림하고 바람은 70점입니다.
- 위 계산으로 나온 점수가 **원래 점수**이고, 화면에는 지금 날씨 점수(3절)와 같은 방식으로 **표시 점수로 바꿔** 보여 줍니다. 1년 치 원래 점수 분포의 순위를 평균 60·표준편차 15 정규분포의 같은 위치 점수로 바꾸는 것으로, 순서는 그대로입니다. 구간은 낮 하나라 표도 하나입니다. 원래 점수 50은 62점이고, 90점 이상은 원래 점수 94 이상에서만 나옵니다. 위쪽 끝은 3절처럼 직선으로 이어(`straighten_top`) **100점은 원래 점수 100(완벽한 날)일 때만** 나오고, 그 아래는 99→98, 97→95, 96→93, 95→92, 94→90처럼 서로 다른 점수가 됩니다. 맑고 알맞은 날이 100점으로 몰려 동점이 되던 것을 막습니다.
- 바꾸기 표: `backend/services/calc/outing_score_table.json` (`calibrated_outing`, `weekend_rank.py`). 만드는 법: `cd backend && python scripts/gen_outing_score_table.py`. 나들이 점수 규칙이 바뀌면 다시 만들어야 합니다. 표는 Open-Meteo 과거 예보(32개 지역, 364일)로 만들어 기상청 예보와 분포가 조금 다를 수 있습니다. 중기예보로 어림한 예상 점수에도 같은 표를 씁니다.
- 순위 캐시(`weekend_rank:v2:<토요일 날짜>`)는 표시 점수를 담습니다. 바꾸기 표를 적용하면서 키를 올려 옛 점수 캐시를 쓰지 않게 했습니다.
- 전국 순위: 노을 순위 대표 30곳을 점수순으로 정렬합니다. - 전국 순위: 노을 순위 대표 30곳을 점수순으로 정렬합니다.
- 당일치기: 내 지역에서 직선 20~200km 안 후보 도시 중 토·일 중 더 좋은 날 점수가 가장 높은 곳입니다. 동점이면 비 확률이 낮은 곳 → 이른 날 → 가까운 곳 순입니다. 1위가 50점 미만이면 카드를 보이지 않습니다. - 당일치기: 내 지역에서 직선 20~200km 안 후보 도시 중 토·일 중 더 좋은 날 점수가 가장 높은 곳입니다. 동점이면 비 확률이 낮은 곳 → 이른 날 → 가까운 곳 순입니다. 1위가 50점 미만이면 카드를 보이지 않습니다. 표시 점수 기준 최소 62점(원래 점수 50과 같은 날씨 수준, `TRIP_MIN_SCORE`) 이상이어야 추천합니다.
## 6. 노을 점수 ## 6. 노을 점수
+3 -3
View File
@@ -107,13 +107,13 @@
- 각 점수와 순위 자체는 새 예보·미세먼지가 들어올 때 다시 계산되므로(하루 8번 예보 + 매시 미세먼지), 그때 캐시가 끝나면 1·2·3위가 바뀔 수 있다. - 각 점수와 순위 자체는 새 예보·미세먼지가 들어올 때 다시 계산되므로(하루 8번 예보 + 매시 미세먼지), 그때 캐시가 끝나면 1·2·3위가 바뀔 수 있다.
**히어로·띠의 순서** **히어로·띠의 순서**
- 오늘의 각 줄(34개): 지금 구간(아침·낮·저녁·밤) 점수 높은 순. 각 시간대가 지금 구간과 안 겹치는 각은 맨 뒤에 '지금 아님'으로. - 오늘의 각 줄(34개): 지금 구간(아침·낮·저녁·밤)의 날씨 점수로 순위를 매깁니다. 시간대 알맞음은 활동 시간대와 겹치면 가중치만큼, 아니면 0점을 반영합니다. 제철이 아닌 각은 비활성화합니다.
- 띠의 각 순위(5개)·피드 각 카드 1~3위·히어로 1위 각: 지금 구간에 해당하는 각만, 지금 구간 점수 순. - 띠의 각 순위(5개)·피드 각 카드 1~3위·히어로 1위 각: 제철인 각을 시간대와 관계없이 포함하고, 지금 구간 점수로 순위를 매깁니다.
- 띠의 행사: 30km 안 행사 중 시작일이 오늘과 가까운 순(같으면 가까운 거리 순) 4개. 계절 소식: 이번 주 글. - 띠의 행사: 30km 안 행사 중 시작일이 오늘과 가까운 순(같으면 가까운 거리 순) 4개. 계절 소식: 이번 주 글.
### 같이 만드는 것 ### 같이 만드는 것
- 히어로: 지금 날씨 점수, 아래 네 칸(지금 기온·습도·불쾌지수·챙길 것 한 칸), 1위 각, 말풍선, 오늘 밤 달 모양·잘 보이는지 - 히어로: 지금 날씨 점수, 아래 네 칸(지금 기온·습도·불쾌지수·챙길 것 한 칸), 1위 각, 말풍선, 오늘 밤 달 모양·잘 보이는지
- 오늘의 각 줄: 34개 이름·점수·순위 (지금 구간에 안 맞는 각은 '지금 아님') - 오늘의 각 줄: 34개 이름·점수·순위 (시간대와 관계없이 활성화, 각 구간의 날씨·시간대 적합도로 계산)
- 띠: 행사 4개, 각 순위 5개, 계절 소식 - 띠: 행사 4개, 각 순위 5개, 계절 소식
## 3. 저장과 갱신 ## 3. 저장과 갱신
+2
View File
@@ -1,5 +1,6 @@
import { BrowserRouter, Route, Routes } from 'react-router' import { BrowserRouter, Route, Routes } from 'react-router'
import { BLayout } from './b/BLayout' import { BLayout } from './b/BLayout'
import { FoliagePage } from './b/FoliagePage'
import { GakPage } from './b/GakPage' import { GakPage } from './b/GakPage'
import { SeasonPage } from './b/SeasonPage' import { SeasonPage } from './b/SeasonPage'
import { SkyPage } from './b/SkyPage' import { SkyPage } from './b/SkyPage'
@@ -18,6 +19,7 @@ export default function App() {
<Route path="sky" element={<SkyPage />} /> <Route path="sky" element={<SkyPage />} />
<Route path="week" element={<WeekPage />} /> <Route path="week" element={<WeekPage />} />
<Route path="season" element={<SeasonPage />} /> <Route path="season" element={<SeasonPage />} />
<Route path="foliage" element={<FoliagePage />} />
<Route path="*" element={<TodayPage />} /> <Route path="*" element={<TodayPage />} />
</Route> </Route>
</Routes> </Routes>
+8 -2
View File
@@ -687,6 +687,12 @@ export type HeroStat = {
* normal=기본, warn=조심(노랑), rain=비(파랑) * normal=기본, warn=조심(노랑), rain=비(파랑)
*/ */
tone: 'normal' | 'warn' | 'rain'; tone: 'normal' | 'warn' | 'rain';
/**
* Detail
*
* 단계 이름 밑의 실제 값 (예: 68%, 72, 2, 초미세먼지 15㎍/㎥). 상태 줄에만
*/
detail?: string | null;
}; };
/** /**
@@ -2974,7 +2980,7 @@ export type TopIndex = {
/** /**
* Slot Ranks * Slot Ranks
* *
* 오늘 구간별 순위 (점수 × 중요도 가중치). 각 시간대와 안 겹치는 구간은 없음 * 오늘 구간별 순위 (중요도 배율을 반영한 최종 표시 점수 내림차순, 동점이면 중요도 순)
*/ */
slot_ranks?: { slot_ranks?: {
[key: string]: number; [key: string]: number;
@@ -3339,7 +3345,7 @@ export type WeekDay = {
/** /**
* Gaks * Gaks
* *
* 그날 대표 각 (점수 × 중요도 순 3개). 각 점수가 아직 없는 날은 비어 있음 * 그날 대표 각 (중요도 배율을 반영한 최종 표시 점수 내림차순 3개, 동점이면 중요도 순). 각 점수가 아직 없는 날은 비어 있음
*/ */
gaks?: Array<WeekGak>; gaks?: Array<WeekGak>;
}; };
+33 -4
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react' import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
import { NavLink, Outlet, useLocation } from 'react-router' import { NavLink, Outlet, useLocation, useNavigationType } from 'react-router'
import { useIsFetching, useQuery } from '@tanstack/react-query' import { useIsFetching, useQuery } from '@tanstack/react-query'
import { getSeasonWeekOptions } from '../api/client/@tanstack/react-query.gen' import { getSeasonWeekOptions } from '../api/client/@tanstack/react-query.gen'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
@@ -202,12 +202,41 @@ function FirstLoad() {
) )
} }
// 페이지마다 마지막 스크롤 위치: 뒤로 가기로 돌아오면 그 자리로
const scrolled = new Map<string, number>()
function Shell() { function Shell() {
const { pathname } = useLocation() const { pathname, key } = useLocation()
const navType = useNavigationType()
const { kind } = useSky() const { kind } = useSky()
useEffect(() => { useEffect(() => {
window.scrollTo({ top: 0 }) const save = () => scrolled.set(key, window.scrollY)
}, [pathname]) window.addEventListener('scroll', save, { passive: true })
return () => window.removeEventListener('scroll', save)
}, [key])
useEffect(() => {
const top = navType === 'POP' ? scrolled.get(key) : undefined
if (top == null) {
window.scrollTo({ top: 0 })
return
}
// 피드가 다시 그려져 그 높이가 될 때까지 최대 3초 맞추고, 그 사이 사람이 화면을 만지면 멈춘다
let tries = 0
let raf = 0
const stop = () => cancelAnimationFrame(raf)
const go = () => {
window.scrollTo({ top })
if (Math.abs(window.scrollY - top) > 2 && ++tries < 180) raf = requestAnimationFrame(go)
}
go()
window.addEventListener('touchstart', stop, { once: true, passive: true })
window.addEventListener('wheel', stop, { once: true, passive: true })
return () => {
stop()
window.removeEventListener('touchstart', stop)
window.removeEventListener('wheel', stop)
}
}, [pathname, key, navType])
// 지금 보고 있는 탭을 다시 누르면 맨 위로 // 지금 보고 있는 탭을 다시 누르면 맨 위로
const toTopIfHere = (to: string) => () => { const toTopIfHere = (to: string) => () => {
if (pathname === to) window.scrollTo({ top: 0, behavior: 'smooth' }) if (pathname === to) window.scrollTo({ top: 0, behavior: 'smooth' })
+480
View File
@@ -0,0 +1,480 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router'
import { cx } from '../lib/utils'
import { ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, STAGE, headline, md, placeLabels, spread, useFoliage, useLabelSize, type Box, type Kind, type Pt, type Spot, type Stage } from './foliage'
import { useSheet } from './sheetContext'
import { FoliageMapShare, FoliageSpotShare } from './shareCards'
import { SendIcon } from './svg'
import { Chips, Ic, TAP44 } from './ui'
type View = { s: number; tx: number; ty: number }
type Filter = 'all' | Kind
const DOT_R: Record<Stage, number> = { peak: ICON_R, first: 4, before: 3, gone: 3 }
const MAX_ZOOM = 5
const FIT_TOP = 30
const FIT_BOTTOM = 14
// 이름 우선순위(절정 단풍 > 절정 은행 > 첫 단풍 > 나머지)와 그 이름이 나오기 시작하는 배율(처음 화면 대비)
const pri = (m: Spot) => (m.stage === 'peak' ? (m.kind === 'maple' ? 0 : 1) : m.stage === 'first' ? 2 : 3)
const LABEL_FROM = [1, 1.6, 2.5, 3.5]
// 점이 나오기 시작하는 배율: 처음엔 절정 잎만 보여 차분하게
const DOT_FROM: Record<Stage, number> = { peak: 1, first: 1.6, before: 2.5, gone: 2.5 }
const TAP_R = 24
const SHARE_ICON = 'relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-(--ink2) [&_svg]:stroke-[1.9]'
const SHARE_BTN = `${SHARE_ICON} bg-white/80`
const GROUPS: [Stage, string][] = [
['peak', '지금 절정'],
['first', '곧 절정'],
['before', '아직'],
['gone', '절정 지남'],
]
const FILTERS: [Filter, string][] = [
['all', '전체'],
['maple', '단풍'],
['ginkgo', '은행'],
]
// 단계 표시: 절정은 잎, 첫 단풍은 주황 점, 단풍 전·지남은 회색 점(고르면 점을 크게)
const DOT_CLASS: Record<Stage, string> = { peak: '', first: 'bg-[#d9772e]/85', before: 'bg-[#8f8a80]/60', gone: 'bg-[#8f8a80]/60' }
function StageMark({ m, big }: { m: Spot; big?: boolean }) {
if (m.stage === 'peak') return <Ic name={m.kind} className={cx('relative', big ? 'size-8' : 'size-5', LEAF_SHADOW)} />
return <i className={cx('b-keep-bg relative rounded-full', DOT_CLASS[m.stage], big ? 'size-3.5' : m.stage === 'first' ? 'size-[7px]' : 'size-[5px]')} />
}
function Marker({ p, sel }: { p: Pt; sel: boolean }) {
return (
<span className={cx('pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center', sel && 'z-[3]')} style={{ left: p.x, top: p.y }}>
{/* 고른 명소는 속이 빈 고리만: 옆 명소를 가리지 않게 */}
{sel && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
<StageMark m={p.m} big={sel && p.m.stage !== 'peak'} />
</span>
)
}
/** 단풍 지도 페이지: 명소 65곳을 지도에서 확대해 보고 목록으로 고른다. 한 손가락은 확대 전엔 페이지 스크롤, 확대 뒤엔 지도 이동 */
export function FoliagePage() {
const navigate = useNavigate()
const [params] = useSearchParams()
const { today, spots } = useFoliage()
const [filter, setFilter] = useState<Filter>('all')
const [sel, setSel] = useState<string | null>(params.get('spot'))
const linked = useRef(params.get('spot'))
const { open } = useSheet()
const [shareSpot, setShareSpot] = useState<Spot | null>(null)
const [shareReq, setShareReq] = useState(0)
const spotShotRef = useRef<HTMLDivElement>(null)
const mapShotRef = useRef<HTMLDivElement>(null)
const shown = useMemo(() => spots.filter((m) => filter === 'all' || m.kind === filter), [spots, filter])
const vpRef = useRef<HTMLDivElement>(null)
const [box, setBox] = useState({ W: 0, H: 0 })
const [view, setView] = useState<View>({ s: 1, tx: 0, ty: 0 })
const viewRef = useRef(view)
useLayoutEffect(() => {
viewRef.current = view
}, [view])
const size = useLabelSize(vpRef, spots)
// 처음 화면: 명소가 다 들어오는 만큼 확대해 가운데
const fit = useMemo<View>(() => {
const { W, H } = box
if (!W) return { s: 1, tx: 0, ty: 0 }
const xs = spots.map((m) => m.x)
const ys = spots.map((m) => m.y)
const [x0, x1, y0, y1] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)]
// 위쪽은 맨 북쪽 이름표가 잘리지 않게 FIT_TOP 만큼 띄우고, 아래는 제주까지만
const h = H - FIT_TOP - FIT_BOTTOM
const s = Math.min(W / ((x1 - x0 + 0.14) * W), h / ((y1 - y0) * W))
return { s, tx: W / 2 - ((x0 + x1) / 2) * W * s, ty: FIT_TOP + h / 2 - ((y0 + y1) / 2) * W * s }
}, [box, spots])
const clamp = useCallback(
(v: View): View => {
const { W, H } = box
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s))
const w = W * s
// 지도 그림 가장자리가 화면 안쪽으로 너무 들어오지 않게
const tx = Math.min(W * 0.25, Math.max(W * 0.75 - w, v.tx))
const ty = Math.min(H * 0.25, Math.max(H * 0.75 - w, v.ty))
return { s, tx, ty }
},
[box, fit],
)
const anim = useRef(0)
const set = useCallback((v: View) => {
cancelAnimationFrame(anim.current)
setView(v)
}, [])
const animateTo = useCallback(
(to: View) => {
cancelAnimationFrame(anim.current)
const from = viewRef.current
const target = clamp(to)
const start = performance.now()
const step = (now: number) => {
const k = Math.min(1, (now - start) / 280)
const e = 1 - (1 - k) ** 3
setView({ s: from.s + (target.s - from.s) * e, tx: from.tx + (target.tx - from.tx) * e, ty: from.ty + (target.ty - from.ty) * e })
if (k < 1) anim.current = requestAnimationFrame(step)
}
anim.current = requestAnimationFrame(step)
},
[clamp],
)
const zoomAt = useCallback(
(f: number, cx: number, cy: number, smooth = false) => {
const v = viewRef.current
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, v.s * f))
const k = s / v.s
const next = clamp({ s, tx: cx - (cx - v.tx) * k, ty: cy - (cy - v.ty) * k })
if (smooth) animateTo(next)
else set(next)
},
[fit, clamp, animateTo, set],
)
const focus = useCallback(
(m: Spot) => {
const { W, H } = box
const s = Math.max(viewRef.current.s, fit.s * 2.5)
animateTo({ s, tx: W / 2 - m.x * W * s, ty: H * 0.42 - m.y * W * s })
},
[box, fit, animateTo],
)
useLayoutEffect(() => {
const el = vpRef.current
if (!el) return
const ro = new ResizeObserver(() => setBox({ W: el.clientWidth, H: el.clientHeight }))
ro.observe(el)
return () => ro.disconnect()
}, [])
// 크기가 정해지면 처음 화면으로, 링크로 고른 명소가 있으면 그곳으로
const started = useRef(false)
useEffect(() => {
if (!box.W) return
if (started.current) {
set(clamp(viewRef.current))
return
}
started.current = true
set(fit)
const m = spots.find((s) => s.name === linked.current)
if (m) focus(m)
}, [box, fit, spots, set, clamp, focus])
const pts = useMemo(() => {
const ratio = view.s / fit.s
const visible = shown.filter((m) => m.name === sel || ratio >= DOT_FROM[m.stage] - 0.01)
return spread(visible.map((m) => ({ m, x: view.tx + m.x * box.W * view.s, y: view.ty + m.y * box.W * view.s, r: DOT_R[m.stage] })))
}, [shown, view, box.W, fit.s, sel])
const ptsRef = useRef(pts)
useLayoutEffect(() => {
ptsRef.current = pts
}, [pts])
const labelAt = useMemo(() => {
const ratio = view.s / fit.s
const order = pts.filter((p) => p.m.name === sel || ratio >= LABEL_FROM[pri(p.m)]).sort((a, b) => Number(b.m.name === sel) - Number(a.m.name === sel) || pri(a.m) - pri(b.m))
const blocked: Box[] = [{ l: box.W - 52, t: 0, r: box.W, b: 100 }]
return placeLabels(order, pts, size, { l: 4, t: 4, r: box.W - 4, b: box.H - 4 }, blocked, (p) => p.m.stage === 'peak' || p.m.name === sel)
}, [pts, size, sel, view.s, fit.s, box])
const provs = useMemo(
() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: view.tx + v.x * box.W * view.s, y: view.ty + v.y * box.W * view.s })), pts, labelBoxes(labelAt, size)),
[view, box.W, pts, labelAt, size],
)
const pickAt = useCallback((x: number, y: number) => {
let best: string | null = null
let bestD = TAP_R
for (const p of ptsRef.current) {
const d = Math.hypot(p.x - x, p.y - y)
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setSel((cur) => (best && best !== cur ? best : null))
}, [])
// 손가락: 두 손가락은 확대·이동, 한 손가락은 확대했을 때만 지도 이동(아니면 페이지 스크롤), 두 번 누르면 확대
useEffect(() => {
const el = vpRef.current
if (!el) return
let pinch: { d: number; x: number; y: number } | null = null
let one: { x: number; y: number; moved: boolean; scroll: boolean } | null = null
let lastTap = 0
const local = (t: { clientX: number; clientY: number }) => {
const r = el.getBoundingClientRect()
return { x: t.clientX - r.left, y: t.clientY - r.top }
}
const zoomed = () => viewRef.current.s > fit.s * 1.01
const onStart = (e: TouchEvent) => {
if ((e.target as HTMLElement).closest('button')) {
one = null
return
}
cancelAnimationFrame(anim.current)
if (e.touches.length === 2) {
const [a, b] = [local(e.touches[0]), local(e.touches[1])]
pinch = { d: Math.hypot(a.x - b.x, a.y - b.y), x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
one = null
} else if (e.touches.length === 1) {
one = { ...local(e.touches[0]), moved: false, scroll: false }
}
}
const onMove = (e: TouchEvent) => {
if (e.touches.length === 2 && pinch) {
e.preventDefault()
const [a, b] = [local(e.touches[0]), local(e.touches[1])]
const d = Math.hypot(a.x - b.x, a.y - b.y)
const x = (a.x + b.x) / 2
const y = (a.y + b.y) / 2
const v = viewRef.current
const s = Math.min(fit.s * MAX_ZOOM, Math.max(fit.s, (v.s * d) / pinch.d))
const k = s / v.s
set(clamp({ s, tx: x - (pinch.x - v.tx) * k, ty: y - (pinch.y - v.ty) * k }))
pinch = { d, x, y }
return
}
if (e.touches.length !== 1 || !one) return
const p = local(e.touches[0])
const first = !one.moved
if (Math.hypot(p.x - one.x, p.y - one.y) > 6) one.moved = true
if (!zoomed() || one.scroll) return
const v = viewRef.current
const next = clamp({ s: v.s, tx: v.tx + p.x - one.x, ty: v.ty + p.y - one.y })
// 첫 움직임이 세로인데 지도가 그쪽 끝에 닿아 더 못 가면 이번 손짓은 페이지 스크롤로 넘긴다
if (first && Math.abs(p.y - one.y) > Math.abs(p.x - one.x) && next.ty === v.ty) {
one.scroll = true
return
}
e.preventDefault()
set(next)
one = { ...p, moved: one.moved, scroll: false }
}
const onEnd = (e: TouchEvent) => {
if (e.touches.length < 2) pinch = null
if (e.touches.length || !one || one.moved) {
if (!e.touches.length) one = null
return
}
e.preventDefault()
const now = Date.now()
if (now - lastTap < 300) {
lastTap = 0
zoomAt(2, one.x, one.y, true)
} else {
lastTap = now
pickAt(one.x, one.y)
}
one = null
}
// 마우스: 끌어서 이동, 누르면 고르기, 두 번 누르면 확대, 트랙패드 오므리기(ctrl+휠)로 확대
let drag: { x: number; y: number; moved: boolean } | null = null
const onDown = (e: PointerEvent) => {
if (e.pointerType !== 'mouse' || (e.target as HTMLElement).closest('button')) return
cancelAnimationFrame(anim.current)
drag = { ...local(e), moved: false }
}
const onPMove = (e: PointerEvent) => {
if (!drag) return
const p = local(e)
if (Math.hypot(p.x - drag.x, p.y - drag.y) > 3) drag.moved = true
const v = viewRef.current
set(clamp({ s: v.s, tx: v.tx + p.x - drag.x, ty: v.ty + p.y - drag.y }))
drag = { ...p, moved: drag.moved }
}
const onUp = () => {
if (drag && !drag.moved) pickAt(drag.x, drag.y)
drag = null
}
const onDbl = (e: MouseEvent) => {
const p = local(e)
zoomAt(2, p.x, p.y, true)
}
const onWheel = (e: WheelEvent) => {
if (!e.ctrlKey) return
e.preventDefault()
const p = local(e)
zoomAt(Math.exp(-e.deltaY * 0.01), p.x, p.y)
}
el.addEventListener('touchstart', onStart, { passive: true })
el.addEventListener('touchmove', onMove, { passive: false })
el.addEventListener('touchend', onEnd, { passive: false })
el.addEventListener('pointerdown', onDown)
window.addEventListener('pointermove', onPMove)
window.addEventListener('pointerup', onUp)
el.addEventListener('dblclick', onDbl)
el.addEventListener('wheel', onWheel, { passive: false })
return () => {
el.removeEventListener('touchstart', onStart)
el.removeEventListener('touchmove', onMove)
el.removeEventListener('touchend', onEnd)
el.removeEventListener('pointerdown', onDown)
window.removeEventListener('pointermove', onPMove)
window.removeEventListener('pointerup', onUp)
el.removeEventListener('dblclick', onDbl)
el.removeEventListener('wheel', onWheel)
}
}, [fit, clamp, set, zoomAt, pickAt])
const chosen = spots.find((m) => m.name === sel)
const pickFromList = (m: Spot) => {
setSel(m.name)
const el = vpRef.current
if (el) window.scrollTo({ top: window.scrollY + el.getBoundingClientRect().top - 120, behavior: 'smooth' })
focus(m)
}
// 보내기: 공유 창이 이미지(명소 하나면 그 명소 지도 조각, 아니면 전체 지도)와 링크를 같이 보낸다
const share = (m?: Spot) => {
setShareSpot(m ?? null)
setShareReq((n) => n + 1)
}
useEffect(() => {
if (!shareReq) return
const el = shareSpot ? spotShotRef.current : mapShotRef.current
if (el) open({ type: 'share', share: { title: shareSpot ? `${shareSpot.name} 단풍` : '단풍 지도', slides: [el] } })
}, [shareReq, shareSpot, open])
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
const peakSpots = spots.filter((m) => m.stage === 'peak')
const peakCount = peakSpots.length
const ranked = rankNow(spots)
return (
<div className="pb-6">
<div className="flex items-start gap-1 px-3 pt-1">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative mt-0.5 grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<div className="min-w-0 flex-1 px-1">
<p className="m-0 flex items-center gap-1 text-[13px] font-extrabold opacity-75">
<Ic name="maple" className="size-4" />
단풍 지도 · {md(today)}
</p>
<h2 className="m-0 mt-0.5 font-jua text-[26px] leading-tight font-normal text-balance">{headline(spots)}</h2>
</div>
<button type="button" onClick={() => share()} aria-label="단풍 지도 보내기" className={cx(SHARE_BTN, 'mt-0.5 shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
<SendIcon />
</button>
</div>
<div ref={vpRef} className="b-keep-bg relative mt-2 h-[min(122vw,calc(100dvh-330px),560px)] min-h-[300px] touch-pan-y overflow-hidden bg-[#fff6ea] select-none">
<img src={MAP_SRC} alt="단풍 지도" draggable={false} className={cx(MAP_IMG, 'max-w-none')} style={{ inset: 'auto', left: view.tx, top: view.ty, width: box.W * view.s, height: box.W * view.s }} />
{provs.map((v) => (
<span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
{v.name}
</span>
))}
{[...pts].sort((a, b) => Number(a.m.stage === 'peak') - Number(b.m.stage === 'peak')).map((p) => (
<Marker key={p.m.name} p={p} sel={p.m.name === sel} />
))}
{spots.map((m) => (
<button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 고르기`}
onClick={() => setSel(m.name === sel ? null : m.name)}
className={cx(LABEL, 'cursor-pointer border-0', m.name === sel ? 'z-[3] bg-[#28304a] text-[#ffffff]' : m.stage === 'peak' ? LABEL_INK[m.kind] : 'bg-[#ffffffeb] text-[#5b6075]', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name}
</button>
))}
<div className="absolute top-2.5 right-2.5 z-[4] flex flex-col gap-2">
{(
[
['+', '확대', 1.6],
['−', '축소', 1 / 1.6],
] as const
).map(([t, label, f]) => (
<button key={t} type="button" aria-label={label} onClick={() => zoomAt(f, box.W / 2, box.H / 2, true)} className="b-keep-bg grid size-9 cursor-pointer place-items-center rounded-full bg-[#ffffff] text-[20px] font-bold text-[#28304a] shadow-[0_2px_6px_rgb(40_48_74/0.2)]">
{t}
</button>
))}
</div>
</div>
{/* 고른 명소는 범례 자리에: 지도 위를 가리지 않고, 다시 누르거나 빈 곳을 누르면 풀린다 */}
{chosen ? (
<div className="mx-3 mt-2 flex h-[60px] items-center gap-3 rounded-[18px] bg-white px-3.5 shadow-[inset_0_-4px_0_var(--shade)]">
<span className="grid size-8 shrink-0 place-items-center">
<StageMark m={chosen} big />
</span>
<div className="min-w-0 flex-1">
<p className="m-0 flex items-center gap-1.5">
<b className="truncate font-jua text-[18px] leading-tight font-normal">{chosen.name}</b>
<span className={cx('shrink-0 rounded-full px-1.5 py-px text-[11px] font-extrabold', chosen.stage === 'peak' ? 'bg-[#ffe3db] text-[#b5321f]' : chosen.stage === 'first' ? 'bg-[#ffe8d2] text-[#a34f12]' : 'bg-(--chip) text-(--ink2)')}>{STAGE[chosen.stage]}</span>
</p>
<p className="m-0 flex gap-1 text-[12px] font-bold text-(--ink3)">
<span className="truncate">{chosen.region}</span>
<span className="shrink-0">· 절정 예상 {md(chosen.peak)}</span>
</p>
</div>
<button type="button" onClick={() => share(chosen)} aria-label={`${chosen.name} 보내기`} className={cx(SHARE_BTN, TAP44)}>
<SendIcon />
</button>
</div>
) : (
<div className="mx-3 mt-2 flex h-[60px] flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold">
<span className="flex items-center gap-1">
<Ic name="maple" className={cx('size-4', LEAF_SHADOW)} />
단풍 절정
</span>
<span className="flex items-center gap-1">
<Ic name="ginkgo" className={cx('size-4', LEAF_SHADOW)} />
은행 절정
</span>
<span className="flex items-center gap-1">
<i className="b-keep-bg size-[7px] rounded-full bg-[#d9772e]/85" />첫 단풍
</span>
<span className="flex items-center gap-1">
<i className="b-keep-bg size-[5px] rounded-full bg-[#8f8a80]/60" />단풍 전
</span>
</div>
)}
<Chips label="종류" items={FILTERS} value={filter} onChange={setFilter} />
<div className="px-4">
{GROUPS.map(([g, title]) => {
const rows = shown.filter((m) => m.stage === g).sort((a, b) => a.peak.localeCompare(b.peak))
if (!rows.length) return null
return (
<section key={g} aria-label={title} className="pt-5">
<h3 className="m-0 flex items-baseline gap-1.5 px-1 pb-1.5 font-jua text-[19px] font-normal">
{title}
<span className="font-sans text-[13px] font-extrabold text-(--ink3)">{rows.length}곳</span>
</h3>
<ul className="m-0 list-none border-t border-(--line) p-0">
{rows.map((m) => (
<li key={m.name} className={cx('flex items-center border-b border-(--line)', m.name === sel && 'bg-[rgb(255_122_69/0.08)]')}>
<button type="button" onClick={() => pickFromList(m)} aria-current={m.name === sel || undefined} className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 py-2.5 pl-1 text-left">
<span className="grid size-7 shrink-0 place-items-center">
<StageMark m={m} big />
</span>
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-(--ink3)">
{m.region} · {m.own ? '절정 예상' : '가까운 지점 날짜'}
</small>
</span>
<b className={cx('shrink-0 font-jua text-[18px] font-normal tabular-nums', g === 'peak' ? 'text-(--orange)' : 'text-(--ink2)')}>{md(m.peak)}</b>
</button>
<button type="button" onClick={() => share(m)} aria-label={`${m.name} 보내기`} className={cx(SHARE_ICON, 'ml-1', TAP44)}>
<SendIcon />
</button>
</li>
))}
</ul>
</section>
)
})}
<FoliageSpotShare spot={shareSpot} peak={peakSpots} ref={spotShotRef} />
<FoliageMapShare title={headline(spots)} peak={peakSpots} ranked={ranked} ref={mapShotRef} />
<p className="m-0 px-1.5 pt-4 text-[11.5px] leading-relaxed font-semibold text-(--ink3)">
출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요{peakCount ? ` · 지금 절정 ${peakCount}곳` : ''}
</p>
</div>
</div>
)
}
+1 -1
View File
@@ -363,7 +363,7 @@ function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string)
</div> </div>
<b className={cx('ml-auto font-bagel text-[42px] font-normal', g.active ? 'text-(--orange)' : 'text-(--ink3)')}>{g.score}</b> <b className={cx('ml-auto font-bagel text-[42px] font-normal', g.active ? 'text-(--orange)' : 'text-(--ink3)')}>{g.score}</b>
</div> </div>
{!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금 시간대엔 해당 없어요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>} {!g.active && <p className="mt-2 text-[13px] font-bold text-(--ink2)">지금은 제철이 아니에요. 점수는 오늘 가장 좋은 시간대 기준이에요.</p>}
{now && ( {now && (
<p className="mt-3 rounded-2xl bg-[#fff4ec] px-3.5 py-2.5 text-[14.5px] font-bold"> <p className="mt-3 rounded-2xl bg-[#fff4ec] px-3.5 py-2.5 text-[14.5px] font-bold">
<b className="mr-1.5 font-jua font-normal text-(--orange)">{now.low}~{now.high}점</b> <b className="mr-1.5 font-jua font-normal text-(--orange)">{now.low}~{now.high}점</b>
+29 -25
View File
@@ -106,7 +106,7 @@ const SLOT_KEY: Record<TimeKind, string> = {
night: 'night', night: 'night',
} }
/** 미리보기 시간대면 이미 받은 구간 점수·순위로 다시 줄 세운다. 그 구간과 안 겹치는 각은 흐리게 끝으로. 구간 값이 없으면(예전 캐시) 그대로 */ /** 미리보기 시간대면 서버가 해당 구간의 날씨·시간대 적합도로 계산한 점수·순위로 다시 줄 세운다. 구간 값이 없으면(예전 캐시) 그대로 */
function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] { function atSlot(items: TopIndex[], kind: TimeKind | null): TopIndex[] {
const k = kind && SLOT_KEY[kind] const k = kind && SLOT_KEY[kind]
if (!k || !items.some((g) => Object.keys(g.slot_ranks ?? {}).length)) return items if (!k || !items.some((g) => Object.keys(g.slot_ranks ?? {}).length)) return items
@@ -373,30 +373,29 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
<path d={moonPath(moon.pct, 1, false)} fill={kind === 'sunset' ? 'rgb(96 40 86 / .55)' : 'rgb(34 30 86 / .62)'} transform={moon.waning ? 'scale(-1,1)' : undefined} /> <path d={moonPath(moon.pct, 1, false)} fill={kind === 'sunset' ? 'rgb(96 40 86 / .55)' : 'rgb(34 30 86 / .62)'} transform={moon.waning ? 'scale(-1,1)' : undefined} />
</svg> </svg>
)} )}
<span className={cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')}> {/* 점수 근거가 있으면 해를 눌러도 근거 창: 구석 버튼은 구름에 가려져서 상태 줄 끝으로 옮김 */}
<small className="block font-jua text-[12px]"> {(() => {
{failed(feedLoad) ? '점수를 못 불러왔어요' : `${tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`} const body = (
</small> <>
<b className="block font-bagel text-[52px] leading-[0.95] font-normal">{heroVal(feedLoad, score, 'w-[84px]')}</b> <small className="block font-jua text-[12px]">
</span> {failed(feedLoad) ? '점수를 못 불러왔어요' : `${tmr && mode !== 'now' ? `내일 ${PREVIEW[mode].label}` : slotScore != null && mode !== 'now' ? PREVIEW[mode].label : '지금'} 날씨 점수`}
{why && score != null && ( </small>
<button <b className="block font-bagel text-[52px] leading-[0.95] font-normal">{heroVal(feedLoad, score, 'w-[84px]')}</b>
type="button" </>
onClick={() => )
open({ const cls = cx('relative', moon && '[text-shadow:0_0_6px_#fff,0_0_12px_#fff]')
type: 'weatherWhy', if (!why || score == null) return <span className={cls}>{body}</span>
why: { label: whyLabel, score, why }, return (
}) <button
} type="button"
aria-label={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`} onClick={() => open({ type: 'weatherWhy', why: { label: whyLabel, score, why, status } })}
className={cx( aria-label={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`}
'absolute right-0 bottom-1 z-[2] grid size-7 cursor-pointer place-items-center rounded-full bg-white font-jua text-[16px] text-(--orange-deep) shadow-[0_2px_6px_rgb(40_48_74/0.25)]', className={cx(cls, 'flex cursor-pointer flex-col items-center')}
TAP44, >
)} {body}
> </button>
? )
</button> })()}
)}
</div> </div>
</div> </div>
</div> </div>
@@ -429,6 +428,11 @@ function Hero({ hero, post, today, ranked, all, feedLoad, todayLoad }: HeroProps
</span> </span>
</Fragment> </Fragment>
))} ))}
{why && score != null && (
<button type="button" onClick={() => open({ type: 'weatherWhy', why: { label: whyLabel, score, why, status } })} aria-label={`${whyLabel} 날씨 점수 ${score}점, 어떻게 나왔는지 보기`} className={cx('relative cursor-pointer whitespace-nowrap text-(--orange-deep)', TAP44)}>
· 점수 근거 ›
</button>
)}
</p> </p>
)} )}
</div> </div>
+2 -1
View File
@@ -611,7 +611,8 @@ html.b-sheet-open .b-app :is(.b-fall, .b-bob, .b-blob, .b-skystars i, .b-shoot,
.b-app[data-t='night'] .bg-\(--ink\) .text-\[\#ffb3c4\] { .b-app[data-t='night'] .bg-\(--ink\) .text-\[\#ffb3c4\] {
color: #ffd0dc; color: #ffd0dc;
} }
.b-app[data-t='night'] .text-\[\#28304a\] { /* b-keep-bg(밤에도 밝은 바탕 그대로) 안은 글자도 그대로 */
.b-app[data-t='night'] .text-\[\#28304a\]:not(.b-keep-bg, .b-keep-bg *) {
color: var(--ink); color: var(--ink);
} }
.b-app[data-t='night'] :is(.text-\[\#1f9d62\], .text-\[\#1f7a4f\]) { .b-app[data-t='night'] :is(.text-\[\#1f9d62\], .text-\[\#1f7a4f\]) {
+213
View File
@@ -0,0 +1,213 @@
import { useLayoutEffect, useMemo, useState, type RefObject } from 'react'
import data from '../../seo/foliage_2026.json'
import { kst } from './lib'
export type Kind = 'maple' | 'ginkgo'
export type Stage = 'before' | 'first' | 'peak' | 'gone'
type Raw = { name: string; kind: Kind; region: string; lat: number; lon: number; peak: string; basis: string }
/** x·y 는 지도 그림 안 위치(0~1), own 은 산림청 예측 지점 자기 날짜인지(아니면 가까운 지점에서 빌린 날짜) */
export type Spot = Omit<Raw, 'basis' | 'lat' | 'lon'> & { stage: Stage; d: number; x: number; y: number; own: boolean }
// 지도 그림(public/foliage/korea-map.webp, 정사각형)의 위경도 → 그림 위 위치. generated-images/foliage-map/south_outline.json 과 같은 값
const MAP = { lon0: 124.5, lat1: 38.75, k: 0.809017, s: 153.5327, ox: 40, oy: 62.92, size: 1024 }
export const MAP_SRC = '/foliage/korea-map.webp'
// 발표에 시작일이 없어 절정 FIRST_DAYS 일 전부터 첫 단풍, PEAK_DAYS 일 전부터 PEAK_AFTER 일 뒤까지 절정으로 본다
const FIRST_DAYS = 14
const PEAK_DAYS = 3
const PEAK_AFTER = 7
export const STAGE: Record<Stage, string> = { before: '단풍 전', first: '첫 단풍', peak: '절정', gone: '절정 지남' }
export const KIND: Record<Kind, string> = { maple: '단풍', ginkgo: '은행' }
const DAY = 86_400_000
const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY)
function stage(peak: string, today: string): Stage {
const d = days(today, peak)
if (d < -PEAK_AFTER) return 'gone'
if (d <= PEAK_DAYS) return 'peak'
return d <= FIRST_DAYS ? 'first' : 'before'
}
const toXY = (lat: number, lon: number) => ({ x: (MAP.ox + (lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size, y: (MAP.oy + (MAP.lat1 - lat) * MAP.s) / MAP.size })
// 지도 위 시·도 이름 자리(위경도). 서울·경기는 겹치지 않게 경기를 북쪽으로 조금 올림
export const PROVINCES = (
[
['서울', 37.56, 126.98],
['경기', 37.95, 127.05],
['강원', 37.65, 128.35],
['충북', 36.8, 127.75],
['충남', 36.45, 126.85],
['전북', 35.72, 127.1],
['전남', 34.85, 126.9],
['경북', 36.3, 128.75],
['경남', 35.3, 128.2],
['제주', 33.38, 126.55],
] as const
).map(([name, lat, lon]) => ({ name, ...toXY(lat, lon) }))
export const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`
const province = (m: Spot) => m.region.split(' ')[0].split('·')
/** 오늘(한국 시각) 기준 명소 65곳과 단계. 단풍철이 아니면 inSeason 이 false */
export function useFoliage() {
const [today] = useState(() => {
const t = kst(new Date())
return `${t.y}-${String(t.mo).padStart(2, '0')}-${String(t.d).padStart(2, '0')}`
})
return useMemo(() => {
const spots: Spot[] = (data.spots as Raw[]).map(({ basis, lat, lon, ...m }) => ({
...m,
stage: stage(m.peak, today),
d: days(today, m.peak),
...toXY(lat, lon),
own: basis.startsWith('산림청'),
}))
// 가장 이른 명소가 첫 단풍에 들 때부터 가장 늦은 명소의 절정이 끝날 때까지
const peaks = spots.map((m) => m.peak).sort()
const inSeason = days(peaks[0], today) >= -FIRST_DAYS && days(peaks[peaks.length - 1], today) <= PEAK_AFTER
return { today, spots, inSeason }
}, [today])
}
/** 절정 명소가 많은 시·도 3곳, 절정이 없으면 가장 먼저 올 절정, 다 지났으면 지는 중 */
export function headline(spots: Spot[]) {
const peak = spots.filter((m) => m.stage === 'peak')
if (peak.length) {
const count = new Map<string, number>()
for (const p of peak.flatMap(province)) count.set(p, (count.get(p) ?? 0) + 1)
return `지금 절정: ${[...count].sort((a, b) => b[1] - a[1]).slice(0, 3).map(([p]) => p).join('·')}`
}
if (spots.some((m) => m.stage === 'gone')) return '올해 단풍이 지고 있어요'
const first = spots.reduce((a, b) => (b.peak < a.peak ? b : a))
return `첫 절정은 ${province(first)[0]}, ${md(first.peak)}쯤`
}
/** 지금 가기 좋은 순: 절정인 곳 중 절정 예상일이 오늘과 가까운 순, 같으면 자기 예측 날짜 먼저, 그다음 이름 순 */
export const rankNow = (spots: Spot[]) =>
spots.filter((m) => m.stage === 'peak').sort((a, b) => Math.abs(a.d) - Math.abs(b.d) || Number(b.own) - Number(a.own) || a.name.localeCompare(b.name))
/** 시·도 이름 자리(명소 이름표를 먼저 놓은 뒤): 원래 자리가 잎·점·이름표에 덮이면 둘레를 돌며 가장 가까운 빈자리로 옮긴다(최대 반경 R, 바다 쪽도 됨) */
export function placeProvinces(provs: { name: string; x: number; y: number }[], pts: Pt[], labels: Box[] = [], R = 90) {
// 앞에서 놓은 시·도 이름도 피한다(서울·경기처럼 붙은 곳)
const placed: Box[] = []
const free = (x: number, y: number) =>
pts.every((p) => Math.abs(p.x - x) > p.r + 17 || Math.abs(p.y - y) > p.r + 10) && [...labels, ...placed].every((b) => !overlaps(provinceBox(x, y), b))
return provs.map((v) => {
const at = pick(v)
placed.push(provinceBox(at.x, at.y))
return at
})
function pick(v: { name: string; x: number; y: number }) {
if (free(v.x, v.y)) return v
for (let d = 5; d <= R; d += 5)
for (let a = 0; a < 24; a++) {
const x = v.x + Math.cos((a / 24) * 2 * Math.PI) * d
const y = v.y + Math.sin((a / 24) * 2 * Math.PI) * d
if (free(x, y)) return { ...v, x, y }
}
return v
}
}
export function provinceBox(x: number, y: number): Box {
return { l: x - 16, t: y - 9, r: x + 16, b: y + 9 }
}
/** placeLabels 결과를 상자로: 시·도 이름이 피해 갈 자리 */
export const labelBoxes = (at: Record<string, { left: number; top: number }>, size: Record<string, { w: number; h: number }>) =>
Object.entries(at).map(([n, a]) => ({ l: a.left, t: a.top, r: a.left + (size[n]?.w ?? 0), b: a.top + (size[n]?.h ?? 0) }))
export type Pt = { m: Spot; x: number; y: number; r: number }
const LABEL_GAP = 4
export type Box = { l: number; t: number; r: number; b: number }
const overlaps = (a: Box, b: Box) => a.l < b.r && b.l < a.r && a.t < b.b && b.t < a.b
/** 화면 위 점끼리 겹치면 서로 밀어 떼어 놓는다 (pts 를 고쳐서 돌려줌) */
export function spread(pts: Pt[], gap = 1.5) {
for (let it = 0; it < 60; it++) {
let moved = false
for (let i = 0; i < pts.length; i++)
for (let j = i + 1; j < pts.length; j++) {
const a = pts[i]
const b = pts[j]
let dx = b.x - a.x
let dy = b.y - a.y
let d = Math.hypot(dx, dy)
const need = a.r + b.r + gap
if (d >= need) continue
if (d < 0.01) [dx, dy, d] = [Math.cos(i + j), Math.sin(i + j), 1]
const push = (need - d) / 2
a.x -= (dx / d) * push
a.y -= (dy / d) * push
b.x += (dx / d) * push
b.y += (dy / d) * push
moved = true
}
if (!moved) break
}
return pts
}
/** 이름표를 점 오른쪽·왼쪽 순으로 놓아 보고(잎과 짝이 헷갈리지 않게 옆 먼저), 점·다른 이름표·막힌 칸과 겹치거나 영역 밖이면 그 이름은 뺀다. 앞 순서가 먼저 자리를 잡는다 */
export function placeLabels(order: Pt[], all: Pt[], size: Record<string, { w: number; h: number }>, area: Box, blocked: Box[] = [], vertical: (p: Pt) => boolean = () => false) {
const dots = all.map((p) => ({ name: p.m.name, box: { l: p.x - p.r, t: p.y - p.r, r: p.x + p.r, b: p.y + p.r } }))
const taken = [...blocked.map((box) => ({ name: '', box })), ...dots]
const out: Record<string, { left: number; top: number }> = {}
for (const p of order) {
const s = size[p.m.name]
if (!s || p.x < area.l || p.x > area.r || p.y < area.t || p.y > area.b) continue
// 옆 자리가 없을 때 vertical 인 명소(절정)만 위·아래도 써 본다
const tries = [
[p.r + 2, -s.h / 2],
[-s.w - p.r - 2, -s.h / 2],
...(vertical(p) ? [[-s.w / 2, -s.h - p.r - 1], [-s.w / 2, p.r + 1]] : []),
]
for (const [dx, dy] of tries) {
const r = { l: p.x + dx, t: p.y + dy, r: p.x + dx + s.w, b: p.y + dy + s.h }
if (r.l < area.l || r.t < area.t || r.r > area.r || r.b > area.b) continue
// 이름표끼리는 LABEL_GAP 만큼 띄워 손가락으로 옆 이름을 잘못 누르지 않게
const pad = { l: r.l - LABEL_GAP, t: r.t - LABEL_GAP, r: r.r + LABEL_GAP, b: r.b + LABEL_GAP }
if (taken.some((o) => o.name !== p.m.name && overlaps(o.name ? r : pad, o.box))) continue
// 위·아래 자리는 이름표에서 가장 가까운 표시가 자기 것일 때만: 아니면 다른 점의 이름처럼 읽힌다
const cx = (r.l + r.r) / 2
const cy = (r.t + r.b) / 2
const mine = Math.hypot(cx - p.x, cy - p.y)
if (dy !== -s.h / 2 && all.some((q) => q.m.name !== p.m.name && Math.hypot(cx - q.x, cy - q.y) < mine)) continue
taken.push({ name: '', box: r })
out[p.m.name] = { left: r.l, top: r.t }
break
}
}
return out
}
/** 이름표 크기를 재 둔다: host 안 data-label 이 붙은 요소의 폭·높이 (host 크기가 바뀌면 다시) */
export function useLabelSize(host: RefObject<HTMLElement | null>, key: unknown) {
const [size, setSize] = useState<Record<string, { w: number; h: number }>>({})
useLayoutEffect(() => {
const el = host.current
if (!el) return
const ro = new ResizeObserver(() => {
const out: Record<string, { w: number; h: number }> = {}
el.querySelectorAll<HTMLElement>('[data-label]').forEach((l) => {
out[l.dataset.label ?? ''] = { w: l.offsetWidth, h: l.offsetHeight }
})
setSize(out)
})
ro.observe(el)
return () => ro.disconnect()
}, [host, key])
return size
}
export const LEAF_SHADOW = 'drop-shadow-[0_0_1.5px_#fff] drop-shadow-[0_1px_1px_rgb(40_48_74/0.45)]'
// 밤 화면에서도 지도는 밝은 종이 그대로라 이름표도 흰 바탕 그대로(b-keep-bg)
export const LABEL = "b-keep-bg absolute rounded-[7px] before:absolute before:-inset-x-1 before:-inset-y-2 before:content-[''] px-[5px] py-px text-[11.5px] leading-[1.35] font-extrabold whitespace-nowrap shadow-[0_1px_3px_rgb(40_48_74/0.18)]"
export const LABEL_INK: Record<Kind, string> = { maple: 'bg-[#ffffffeb] text-[#b5321f]', ginkgo: 'bg-[#ffffffeb] text-[#8a6508]' }
// 지도 그림 색을 빼서 단풍 아이콘이 묻히지 않게
export const MAP_IMG = 'pointer-events-none absolute inset-0 size-full select-none mix-blend-multiply brightness-[1.08] saturate-[.3]'
export const ICON_R = 10
// 시·도 이름: 지도에 옅게 깔리는 글자
// 어두운 산 무늬 위에서도 읽히게 종이색 테두리를 두른다
export const PROVINCE = 'pointer-events-none absolute -translate-x-1/2 -translate-y-1/2 font-jua text-[13px] leading-none whitespace-nowrap text-[#5c4a36]/85 [text-shadow:0_0_2px_#fff6ea,0_0_4px_#fff6ea,0_0_6px_#fff6ea]'
+145 -95
View File
@@ -1,108 +1,158 @@
import { useState } from 'react' import { useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react'
import data from '../../seo/foliage_2026.json' import { useNavigate } from 'react-router'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import { kst } from './lib' import { useCarousel } from './carousel'
import { headline, ICON_R, LABEL, LABEL_INK, LEAF_SHADOW, MAP_IMG, MAP_SRC, md, placeLabels, PROVINCE, PROVINCES, labelBoxes, placeProvinces, rankNow, spread, useFoliage, useLabelSize } from './foliage'
import { PostFrame } from './Post' import { PostFrame } from './Post'
import { useSheet } from './sheetContext'
import { FoliageSpotShare } from './shareCards'
import { SendIcon } from './svg'
import { Ic } from './ui' import { Ic } from './ui'
type Kind = 'maple' | 'ginkgo' const TAP_R = 24
type Spot = { name: string; kind: Kind; region: string; lat: number; lon: number; peak: string; basis: string } const RANK_N = 7
type Stage = 'before' | 'first' | 'peak'
// 지도 그림(public/foliage/korea-map.webp, 정사각형)의 위경도 → 그림 위 위치. generated-images/foliage-map/south_outline.json 과 같은 값 /** 피드의 단풍 지도 카드: 1장은 지금 절정인 곳만 잎 아이콘으로(누르면 카드 안에 정보), 2장은 지금 가기 좋은 순위. '지도 크게 보기'로 단풍 지도 페이지 */
const MAP = { lon0: 124.5, lat1: 38.75, k: 0.809017, s: 153.5327, ox: 40, oy: 62.92, size: 1024 }
// 발표에 시작일이 없어 절정 FIRST_DAYS 일 전부터 첫 단풍, PEAK_DAYS 일 전부터 절정으로 본다
const FIRST_DAYS = 14
const PEAK_DAYS = 3
const SEASON = { from: '09-20', to: '11-25' }
const SEOUL = { lat: 37.566, lon: 126.978 }
const STAGE: Record<Stage, { label: string; icon: string }> = {
before: { label: '단풍 전', icon: 'size-3 opacity-60 grayscale' },
first: { label: '첫 단풍', icon: 'size-3.5' },
peak: { label: '절정', icon: 'size-[18px]' },
}
const KIND: Record<Kind, { label: string; icon: string }> = {
maple: { label: '단풍', icon: 'maple' },
ginkgo: { label: '은행', icon: 'ginkgo' },
}
const pos = (m: Spot) => ({
left: `${((MAP.ox + (m.lon - MAP.lon0) * MAP.k * MAP.s) / MAP.size) * 100}%`,
top: `${((MAP.oy + (MAP.lat1 - m.lat) * MAP.s) / MAP.size) * 100}%`,
})
const DAY = 86_400_000
const days = (from: string, to: string) => Math.round((Date.parse(to) - Date.parse(from)) / DAY)
function stage(m: Spot, today: string): Stage {
const d = days(today, m.peak)
if (d <= PEAK_DAYS) return 'peak'
return d <= FIRST_DAYS ? 'first' : 'before'
}
const md = (iso: string) => `${Number(iso.slice(5, 7))}/${Number(iso.slice(8, 10))}`
/** 단풍철에만 나오는 단풍 지도 카드. 산마다 절정 예측일로 지금 절정·곧·아직·지남을 점으로 */
export function FoliageCard() { export function FoliageCard() {
const [now] = useState(() => new Date()) const navigate = useNavigate()
const t = kst(now) const { today, spots, inSeason } = useFoliage()
const today = `${t.y}-${String(t.mo).padStart(2, '0')}-${String(t.d).padStart(2, '0')}` const peak = useMemo(() => spots.filter((m) => m.stage === 'peak').sort((a, b) => Number(a.kind === 'ginkgo') - Number(b.kind === 'ginkgo') || a.y - b.y), [spots])
const mapRef = useRef<HTMLDivElement>(null)
const size = useLabelSize(mapRef, peak)
const [W, setW] = useState(0)
const [picked, setPicked] = useState<string | null>(null) const [picked, setPicked] = useState<string | null>(null)
const mmdd = today.slice(5) const { open } = useSheet()
if (mmdd < SEASON.from || mmdd > SEASON.to) return null const spotShotRef = useRef<HTMLDivElement>(null)
const spots = (data.spots as Spot[]).map((m) => ({ ...m, stage: stage(m, today) })) const { ref: sliderRef, index } = useCarousel({ align: 'start' })
const peakNow = spots.filter((m) => m.stage === 'peak').map((m) => m.name)
// 발표 지도에 서울 안 산은 없어 서울 시청에서 가장 가까운 단풍 예측 산으로 useLayoutEffect(() => {
const forecast = spots.filter((m) => m.kind === 'maple' && m.basis.startsWith('산림청')) const el = mapRef.current
const seoul = forecast.reduce((a, b) => (Math.hypot(b.lat - SEOUL.lat, b.lon - SEOUL.lon) < Math.hypot(a.lat - SEOUL.lat, a.lon - SEOUL.lon) ? b : a)) if (!el) return
const sel = spots.find((m) => m.name === picked) const ro = new ResizeObserver(() => setW(el.clientWidth))
ro.observe(el)
return () => ro.disconnect()
}, [inSeason])
const pts = useMemo(() => spread(peak.map((m) => ({ m, x: m.x * W, y: m.y * W, r: ICON_R }))), [peak, W])
const labelAt = useMemo(() => placeLabels(pts, pts, size, { l: 0, t: 0, r: W, b: W }, [], () => true), [pts, size, W])
const provs = useMemo(() => placeProvinces(PROVINCES.map((v) => ({ name: v.name, x: v.x * W, y: v.y * W })), pts, labelBoxes(labelAt, size)), [pts, W, labelAt, size])
if (!inSeason) return null
const go = (name?: string) => navigate(name ? `/foliage?spot=${encodeURIComponent(name)}` : '/foliage')
const toggle = (name: string) => setPicked(name === picked ? null : name)
// 잎이 작아 손가락으로 겨냥하기 어려우니 누른 자리에서 가까운 명소를 고른다
const tapMap = (e: MouseEvent<HTMLDivElement>) => {
const r = e.currentTarget.getBoundingClientRect()
let best: string | null = null
let bestD = TAP_R
for (const p of pts) {
const d = Math.hypot(p.x - (e.clientX - r.left), p.y - (e.clientY - r.top))
if (d < bestD) [best, bestD] = [p.m.name, d]
}
setPicked(best && best !== picked ? best : null)
}
const sel = peak.find((m) => m.name === picked)
// 2번째 장: 지금 절정인 곳을 절정 예상일이 오늘과 가까운 순서로
const ranked = rankNow(spots).slice(0, RANK_N)
return ( return (
<PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" caption={peakNow.length ? `지금 절정 ${peakNow.length}곳: ${peakNow.slice(0, 5).join(' · ')}${peakNow.length > 5 ? ' 외' : ''}` : undefined}> <PostFrame title="단풍 지도" account="단풍 지도" avatar="maple" caption={peak.length ? `지금 절정 ${peak.length}곳: ${peak.slice(0, 5).map((m) => m.name).join(' · ')}${peak.length > 5 ? ' 외' : ''}` : undefined}>
<div className="relative bg-[#fff6ea] px-4 pt-4 pb-3"> <div className="b-keep-bg relative bg-[#fff6ea] px-4 pt-4 pb-3 text-[#28304a]">
<p className="m-0 text-[13px] font-extrabold opacity-75">단풍 지도 · {md(today)}</p> <p className="m-0 text-[13px] font-extrabold opacity-75">단풍 지도 · {md(today)}</p>
<p className="m-0 mt-1 font-jua text-[24px] leading-tight">서울 근교 {seoul.name} 절정 예상 {md(seoul.peak)}</p> <p className="m-0 mt-1 font-jua text-[24px] leading-tight">{headline(spots)}</p>
<div className="relative mx-auto mt-1 aspect-square w-full"> <div className="relative mt-1">
<img src="/foliage/korea-map.webp" alt="단풍 지도" className="absolute inset-0 size-full" /> <span data-noshot aria-hidden="true" className="absolute top-0 right-0 z-[4] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white">
{spots.map((m) => ( {index + 1}/2
<button </span>
key={m.name} <div ref={sliderRef} className="overflow-hidden" role="region" aria-label="슬라이드 2장, 옆으로 넘겨 보세요">
type="button" <div className="flex">
onClick={() => setPicked(m.name === picked ? null : m.name)} <div className="min-w-0 shrink-0 grow-0 basis-full">
aria-label={`${m.name} ${KIND[m.kind].label} ${STAGE[m.stage].label}, 절정 예상 ${md(m.peak)}`} <div ref={mapRef} onClick={tapMap} className="b-keep-bg relative mx-auto aspect-square w-full bg-[#fff6ea]">
className={cx('absolute grid -translate-x-1/2 -translate-y-1/2 cursor-pointer place-items-center p-0.5', m.name === picked && 'z-[2] scale-150')} <img src={MAP_SRC} alt="" className={MAP_IMG} />
style={pos(m)} {provs.map((v) => (
> <span key={v.name} aria-hidden="true" className={PROVINCE} style={{ left: v.x, top: v.y }}>
<Ic name={KIND[m.kind].icon} className={cx('drop-shadow-[0_0_1.5px_#fff] drop-shadow-[0_1px_1px_rgb(40_48_74/0.4)]', STAGE[m.stage].icon)} /> {v.name}
</button> </span>
))} ))}
{sel && ( {pts.map((p) => (
<p className="absolute right-0 bottom-0 z-[3] m-0 max-w-[75%] rounded-[14px] bg-white/95 px-3 py-2 text-[13px] font-bold shadow-[0_4px_12px_rgb(40_48_74/0.15)]"> <span key={p.m.name} className="pointer-events-none absolute grid -translate-x-1/2 -translate-y-1/2 place-items-center" style={{ left: p.x, top: p.y }}>
<b className="font-jua text-[16px] font-normal">{sel.name}</b> {sel.region} {p.m.name === picked && <i className="b-keep-bg absolute size-8 rounded-full border-[2.5px] border-[#28304a] bg-[#ffffff4d]" />}
<br /> <Ic name={p.m.kind} className={cx('relative size-5', LEAF_SHADOW)} />
{KIND[sel.kind].label} {STAGE[sel.stage].label} · 절정 예상 {md(sel.peak)} </span>
{!sel.basis.startsWith('산림청') && <small className="block text-[11px] font-semibold text-(--ink3)">가까운 예측 지점 날짜예요</small>} ))}
</p> {peak.map((m) => (
)} <button
key={m.name}
type="button"
data-label={m.name}
aria-label={`${m.name} 정보 보기`}
onClick={(e) => {
e.stopPropagation()
toggle(m.name)
}}
className={cx(LABEL, LABEL_INK[m.kind], 'cursor-pointer border-0', !labelAt[m.name] && 'invisible')}
style={labelAt[m.name] ?? { left: 0, top: 0 }}
>
{m.name}
</button>
))}
</div>
{/* 고른 명소 정보는 지도 밖, 범례 자리에: 지도 위 잎을 가리지 않게 */}
{sel ? (
<div className="b-keep-bg mt-2 flex items-center gap-3 rounded-[16px] bg-[#ffffff] px-3 py-2.5 shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
<Ic name={sel.kind} className="size-8 shrink-0" />
<div className="min-w-0 flex-1">
<b className="block truncate font-jua text-[18px] leading-tight font-normal">{sel.name}</b>
<span className="flex gap-1 text-[12px] font-bold text-[#6b7189]">
<span className="shrink-0">{sel.region.split(' ')[0]}</span>
<span className="shrink-0">· 절정 예상 {md(sel.peak)}</span>
</span>
</div>
<button type="button" onClick={() => sel && open({ type: 'share', share: { title: `${sel.name} 단풍`, slides: spotShotRef.current ? [spotShotRef.current] : [] } })} aria-label={`${sel.name} 보내기`} className="relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full [&_svg]:size-[19px] [&_svg]:fill-none [&_svg]:stroke-[#28304a] [&_svg]:stroke-[1.9]">
<SendIcon />
</button>
<button type="button" onClick={() => go(sel.name)} className="b-keep-bg shrink-0 cursor-pointer rounded-full bg-[#28304a] px-3 py-1.5 text-[12.5px] font-extrabold text-[#ffffff]">
지도에서 보기 ›
</button>
</div>
) : (
<span className="mt-2 flex h-[52px] items-center gap-3 text-[12.5px] font-bold">
<span className="flex items-center gap-1">
<Ic name="maple" className="size-4" />
단풍 절정
</span>
<span className="flex items-center gap-1">
<Ic name="ginkgo" className="size-4" />
은행 절정
</span>
</span>
)}
</div>
<div className="flex min-w-0 shrink-0 grow-0 basis-full flex-col pl-1">
<p className="m-0 font-jua text-[20px] leading-tight">지금 가기 좋은 곳</p>
<p className="m-0 mt-0.5 text-[12px] font-bold text-[#6b7189]">절정 예상일이 오늘과 가까운 순서예요</p>
<ol className="m-0 mt-2 flex flex-1 list-none flex-col justify-between p-0">
{ranked.map((m, i) => (
<li key={m.name}>
<button type="button" onClick={() => go(m.name)} className="flex w-full cursor-pointer items-center gap-2.5 border-0 bg-transparent py-1.5 text-left">
<b className={cx('w-6 shrink-0 text-center font-jua text-[22px] font-normal', i < 3 ? 'text-[#b5321f]' : 'text-[#9a8f80]')}>{i + 1}</b>
<Ic name={m.kind} className={cx('size-7 shrink-0', LEAF_SHADOW)} />
<span className="min-w-0 flex-1">
<b className="block truncate text-[15px] font-extrabold">{m.name}</b>
<small className="block truncate text-[12px] font-semibold text-[#6b7189]">{m.region}</small>
</span>
<span className="shrink-0 text-[14px] font-extrabold tabular-nums">{md(m.peak)}</span>
</button>
</li>
))}
</ol>
</div>
</div>
</div>
</div> </div>
<div className="mt-2 flex flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[12.5px] font-bold"> <FoliageSpotShare spot={sel ?? null} peak={peak} ref={spotShotRef} />
{(Object.keys(KIND) as Kind[]).map((k) => ( <button type="button" onClick={() => go()} className="b-keep-bg mt-2 w-full cursor-pointer rounded-full bg-[#ffffff] py-2 text-[14px] font-extrabold text-[#28304a] shadow-[inset_0_-3px_0_rgb(40_48_74/0.08)]">
<span key={k} className="flex items-center gap-1"> 지도 크게 보기 ›
<Ic name={KIND[k].icon} className="size-4" /> </button>
{KIND[k].label}
</span>
))}
<span className="opacity-30" aria-hidden="true">|</span>
{(Object.keys(STAGE) as Stage[]).map((st) => (
<span key={st} className="flex items-center gap-1">
<Ic name="maple" className={cx('size-4', STAGE[st].icon)} />
{STAGE[st].label}
</span>
))}
</div>
<p className="m-0 mt-1.5 text-center text-[11px] font-semibold text-(--ink3)">
출처: 산림청 2026 단풍절정 예측 · 잎 절반이 물든 때를 절정으로, 그 2주 전부터 첫 단풍으로 봐요
</p>
</div> </div>
</PostFrame> </PostFrame>
) )
+71
View File
@@ -2,6 +2,7 @@ import type { Ref } from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { cx } from '../lib/utils' import { cx } from '../lib/utils'
import type { TopIndex } from '../api/client/types.gen' import type { TopIndex } from '../api/client/types.gen'
import { LEAF_SHADOW, MAP_IMG, MAP_SRC, md, PROVINCE, PROVINCES, STAGE, type Spot } from './foliage'
import { MEDALS, type TimeKind } from './lib' import { MEDALS, type TimeKind } from './lib'
import { Ic } from './ui' import { Ic } from './ui'
@@ -114,3 +115,73 @@ export function GakShareCard({ items, title, ref }: { items: TopIndex[]; title:
</Offscreen> </Offscreen>
) )
} }
/** 단풍 명소 하나 공유: 그 명소를 가운데 둔 지도 조각(둘레 시·도 이름과 다른 절정 잎) 위에 큰 잎, 아래에 이름·지역·절정 예상일 */
export function FoliageSpotShare({ spot, peak, ref }: { spot: Spot | null; peak: Spot[]; ref: Ref<HTMLDivElement> }) {
if (!spot) return null
const near = peak.filter((m) => m.name !== spot.name)
return (
<Offscreen>
<div ref={ref} className="flex aspect-[4/5] flex-col bg-[#fff6ea] text-[#28304a]">
<div className="relative flex-1 overflow-hidden">
{/* 명소가 가운데 오게 지도 그림을 3배로 키워 옮긴다 */}
<div className="absolute top-1/2 left-1/2 aspect-square w-[220%] bg-[#fff6ea]" style={{ transform: `translate(-${spot.x * 100}%, -${spot.y * 100}%)` }}>
<img src={MAP_SRC} alt="" className={MAP_IMG} />
{PROVINCES.map((v) => (
<span key={v.name} className={cx(PROVINCE, 'text-[15px]')} style={{ left: `${v.x * 100}%`, top: `${v.y * 100}%` }}>
{v.name}
</span>
))}
{near.map((m) => (
<Ic key={m.name} name={m.kind} className={cx('absolute size-5 -translate-x-1/2 -translate-y-1/2', LEAF_SHADOW)} style={{ left: `${m.x * 100}%`, top: `${m.y * 100}%` }} />
))}
</div>
<span className="absolute top-1/2 left-1/2 grid size-[92px] -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full border-[3px] border-[#28304a] bg-[#ffffff99]">
<Ic name={spot.kind} className={cx('w-[60px]', LEAF_SHADOW)} />
</span>
</div>
<div className="px-5 pt-3 pb-4">
<p className="m-0 flex items-center gap-2">
<b className="font-jua text-[34px] leading-tight font-normal">{spot.name}</b>
<span className={cx('rounded-full px-2 py-0.5 text-[14px] font-extrabold', spot.stage === 'peak' ? 'bg-[#ffe3db] text-[#b5321f]' : 'bg-[#efe6d8] text-[#5b6075]')}>{STAGE[spot.stage]}</span>
</p>
<p className="m-0 mt-0.5 text-[15px] font-bold text-[#6b7189]">{spot.region}</p>
<p className="m-0 mt-2 font-jua text-[22px]">절정 예상 {md(spot.peak)}</p>
</div>
</div>
</Offscreen>
)
}
/** 단풍 지도 전체 공유: 지금 절정 제목, 절정 잎만 찍힌 지도, 가기 좋은 곳 1~3위 */
export function FoliageMapShare({ title, peak, ranked, ref }: { title: string; peak: Spot[]; ranked: Spot[]; ref: Ref<HTMLDivElement> }) {
return (
<Offscreen>
<div ref={ref} className="flex aspect-[4/5] flex-col bg-[#fff6ea] px-4 pt-4 pb-3 text-[#28304a]">
<p className="m-0 font-jua text-[24px] leading-tight">{title}</p>
<div className="relative mx-auto mt-1 aspect-square w-[78%] bg-[#fff6ea]">
<img src={MAP_SRC} alt="" className={MAP_IMG} />
{PROVINCES.map((v) => (
<span key={v.name} className={PROVINCE} style={{ left: `${v.x * 100}%`, top: `${v.y * 100}%` }}>
{v.name}
</span>
))}
{peak.map((m) => (
<Ic key={m.name} name={m.kind} className={cx('absolute size-4 -translate-x-1/2 -translate-y-1/2', LEAF_SHADOW)} style={{ left: `${m.x * 100}%`, top: `${m.y * 100}%` }} />
))}
</div>
<ol className="m-0 mt-auto grid list-none gap-1.5 p-0">
{ranked.slice(0, 3).map((m, i) => (
<li key={m.name} className="flex items-center gap-2.5 rounded-[14px] bg-[#ffffff] px-3 py-1.5">
<Ic name={MEDALS[i]} className="w-[22px] shrink-0" />
<Ic name={m.kind} className="w-[22px] shrink-0" />
<b className="min-w-0 flex-1 truncate font-jua text-[17px] font-normal">{m.name}</b>
<span className="shrink-0 text-[13px] font-bold text-[#6b7189]">{m.region.split(' ')[0]}</span>
<span className="shrink-0 font-jua text-[16px] text-[#b5321f]">{md(m.peak)}</span>
</li>
))}
</ol>
</div>
</Offscreen>
)
}
+35 -1
View File
@@ -1,6 +1,8 @@
import type { WeatherWhy } from '../api/client/types.gen' import type { WeatherWhy } from '../api/client/types.gen'
import { cx } from '../lib/utils'
export type WeatherWhyPayload = { label: string; score: number; why: WeatherWhy[] } /** status: 히어로 상태 줄 그대로 (단계 이름, 실제 값) */
export type WeatherWhyPayload = { label: string; score: number; why: WeatherWhy[]; status?: { label: string; value: string; tone?: string; detail?: string | null }[] }
// 조건마다 같은 색을 막대 칸과 아래 줄 점에 같이 써서 이어 보이게 // 조건마다 같은 색을 막대 칸과 아래 줄 점에 같이 써서 이어 보이게
const COLOR: Record<string, string> = { const COLOR: Record<string, string> = {
@@ -13,6 +15,14 @@ const COLOR: Record<string, string> = {
} }
const colorOf = (label: string) => COLOR[label] ?? '#9aa3b8' const colorOf = (label: string) => COLOR[label] ?? '#9aa3b8'
// 상태 줄 항목마다 단계를 나누는 기준 (backend/services/hero_stats.py 와 같은 값)
const RULE: Record<string, string> = {
습도: '30% 아래는 건조, 60% 넘으면 습함이에요',
불쾌지수: '68 아래는 쾌적, 75부터 불쾌예요',
자외선: '3 아래는 낮음, 6부터 높음이에요',
미세먼지: '에어코리아 기준 등급이에요',
}
/** 날씨 점수 근거: 비중만큼 나눈 막대(채운 만큼 얻은 점수)와 조건별 지금 값 */ /** 날씨 점수 근거: 비중만큼 나눈 막대(채운 만큼 얻은 점수)와 조건별 지금 값 */
export function WeatherWhySheet({ d }: { d: WeatherWhyPayload }) { export function WeatherWhySheet({ d }: { d: WeatherWhyPayload }) {
return ( return (
@@ -46,6 +56,30 @@ export function WeatherWhySheet({ d }: { d: WeatherWhyPayload }) {
))} ))}
</ul> </ul>
{d.status && d.status.length > 0 && (
<>
<h4 className="m-0 mt-5 font-jua text-[17px] font-normal">지금 상태</h4>
<ul className="m-0 mt-2 flex list-none flex-col gap-1.5 p-0">
{d.status.map((s) => (
<li key={s.label} className="flex items-center gap-3 rounded-2xl bg-[#f5f8fc] px-3.5 py-2.5">
<span className="min-w-0 flex-1">
<b className="block font-jua text-[16px] leading-tight font-normal">{s.label}</b>
{RULE[s.label] && <small className="block text-[12.5px] font-semibold text-(--ink3)">{RULE[s.label]}</small>}
</span>
<span className="shrink-0 text-right">
<b className={cx('block font-jua text-[18px] leading-tight font-normal', s.tone === 'warn' && 'b-warn')}>{s.value}</b>
{s.detail?.split(' · ').map((x) => (
<small key={x} className="block text-[12px] font-bold whitespace-nowrap text-(--ink2) tabular-nums">
{x}
</small>
))}
</span>
</li>
))}
</ul>
</>
)}
<p className="m-0 mt-3 text-[13px] leading-relaxed font-semibold text-(--ink2)"> <p className="m-0 mt-3 text-[13px] leading-relaxed font-semibold text-(--ink2)">
조건마다 점수를 매겨 비중대로 합쳐요. 유난히 아쉬운 조건이 있으면 조금 더 깎고, 모든 조건이 완벽할 때만 만점이 나와요. 조건마다 점수를 매겨 비중대로 합쳐요. 유난히 아쉬운 조건이 있으면 조금 더 깎고, 모든 조건이 완벽할 때만 만점이 나와요.
</p> </p>