feat: 계절 지도 자리에 첫눈 지도·해돋이 지도 — 단풍 지도가 끝나면 첫눈 지도(~12/20, 지점 42곳 평년 첫눈 날짜 + 앞으로 7일 눈 예보, GET /v1/season/first-snow), 12/21부터 해돋이 지도(~2월, 명소 50곳 해 뜨는 시각, 12월엔 새해 첫날 기준). 오늘 탭 아이콘·피드 맨 앞 카드(foliage_post 좋아요·댓글 자리를 이어받음)·/first-snow·/sunrise 페이지·공유 이미지. 지도 확대·이동은 mapView.ts 로 꺼내 단풍 지도와 같이 씀 (GA first_snow_open·first_snow_spot·sunrise_open·sunrise_spot·sunrise_day)
This commit is contained in:
1 parent
4e69c4ac44
commit
d7dfc1ba82
30 files changed
+1973
-255
No files matched your search
@@ -42,3 +42,19 @@ class Res_ArticleList(Res_WebPacketProtocol):
|
||||
class Res_Article(Res_WebPacketProtocol):
|
||||
article: Optional[ArticleSummary] = None
|
||||
body: list[str] = []
|
||||
|
||||
|
||||
class FirstSnowSpot(WebPacketProtocol):
|
||||
name: str
|
||||
region: str # 시·도
|
||||
lat: float
|
||||
lon: float
|
||||
normal: str # 평년 첫눈 날짜 "MM-DD" (1991~2020 평균)
|
||||
top: bool = False # 처음 화면에 이름까지 보이는 대표 지점
|
||||
snow_date: Optional[date] = None # 앞으로 7일 안에 눈 예보가 있는 첫 날. 없으면 비움
|
||||
snow_cm: Optional[float] = None # 그날 눈 오는 양(cm)
|
||||
|
||||
|
||||
class Res_FirstSnow(Res_WebPacketProtocol):
|
||||
forecast: bool = False # 눈 예보를 받았는지. False 면 snow_date 는 모두 비어 있다(평년 날짜만)
|
||||
spots: list[FirstSnowSpot] = []
|
||||
@@ -5,7 +5,9 @@ from fastapi import APIRouter, Depends, Path, Query
|
||||
from common.database.model.models import Article
|
||||
from common.enums import ArticleCategory, ErrorType
|
||||
from common.models.errors import error_info
|
||||
from router.v1.season.protocol import ArticleSummary, Res_Article, Res_ArticleList, Res_SeasonWeek, TermData
|
||||
from common.utils.kma_time import now_kst
|
||||
from router.v1.season.protocol import ArticleSummary, FirstSnowSpot, Res_Article, Res_ArticleList, Res_FirstSnow, Res_SeasonWeek, TermData
|
||||
from services.first_snow_service import FirstSnowService
|
||||
from services.season_service import SeasonService
|
||||
|
||||
router = APIRouter(prefix="/v1/season", tags=["season"])
|
||||
@@ -44,3 +46,9 @@ async def get_article(article_id: int = Path(...), service: SeasonService = Depe
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_Article(result=error_info(err))
|
||||
return Res_Article(article=_summary(a), body=a.body)
|
||||
|
||||
|
||||
@router.get("/first-snow", response_model=Res_FirstSnow, response_model_exclude_none=True, summary="첫눈 지도: 지점별 평년 첫눈 날짜와 앞으로 7일 눈 예보")
|
||||
async def get_first_snow(service: FirstSnowService = Depends()) -> Res_FirstSnow:
|
||||
forecast, spots = await service.spots(now_kst())
|
||||
return Res_FirstSnow(forecast=forecast, spots=[FirstSnowSpot(**s.__dict__) for s in spots])
|
||||
+27
-1
@@ -1,5 +1,5 @@
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -87,6 +87,32 @@ async def _fetch_weather_chunk(client: httpx.AsyncClient, points: list[tuple[flo
|
||||
return await _get_forecast(client, params, len(points))
|
||||
|
||||
|
||||
async def fetch_snow(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int = 7) -> list[dict]:
|
||||
"""좌표마다 날짜별(한국 날짜) 눈 오는 양 (모델 지정 없음). 응답 순서는 좌표 순서와 같다."""
|
||||
chunks = [points[i:i + _CHUNK] for i in range(0, len(points), _CHUNK)]
|
||||
|
||||
async def all_chunks() -> list[dict]:
|
||||
results = await asyncio.gather(*[_fetch_snow_chunk(client, c, days) for c in chunks])
|
||||
return [d for r in results for d in r]
|
||||
|
||||
return await guarded("openmeteo:snow", all_chunks, OpenMeteoRequestFailed, _BUDGET_SEC)
|
||||
|
||||
|
||||
async def _fetch_snow_chunk(client: httpx.AsyncClient, points: list[tuple[float, float]], days: int) -> list[dict]:
|
||||
params = {
|
||||
"latitude": ",".join(f"{lat:.2f}" for lat, _ in points),
|
||||
"longitude": ",".join(f"{lon:.2f}" for _, lon in points),
|
||||
"daily": "snowfall_sum", "forecast_days": days, "timezone": "Asia/Seoul",
|
||||
}
|
||||
return await _get_forecast(client, params, len(points))
|
||||
|
||||
|
||||
def parse_snow(data: dict) -> list[tuple[date, float]]:
|
||||
"""날짜별 눈 오는 양(cm). 값이 없는 날은 뺀다."""
|
||||
d = data["daily"]
|
||||
return [(date.fromisoformat(t), float(v)) for t, v in zip(d["time"], d["snowfall_sum"]) if v is not None]
|
||||
|
||||
|
||||
def parse_clouds(point: tuple[float, float], data: dict) -> list[dict]:
|
||||
lat, lon = round(point[0], 2), round(point[1], 2)
|
||||
h = data["hourly"]
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"source": "기상청 「계절관측지침(2026.4.)」 부록 기후계절 평년값(1991~2020년) 첫눈. 북춘천은 춘천, 북강릉은 강릉으로 적음. 먼 섬(백령도·울릉도·흑산도)과 평년 첫눈이 해를 넘기는 거제(1/14)는 뺌",
|
||||
"basis": "normal 은 평년 첫눈 날짜(월-일). lat·lon 은 그 도시의 대략 위치(지도에 찍고 눈 예보를 받는 자리). top 은 처음 화면에 이름까지 보이는 대표 지점",
|
||||
"spots": [
|
||||
{ "name": "서울", "region": "서울", "lat": 37.57, "lon": 126.97, "normal": "11-20", "top": true },
|
||||
{ "name": "인천", "region": "인천", "lat": 37.48, "lon": 126.62, "normal": "11-23" },
|
||||
{ "name": "수원", "region": "경기", "lat": 37.27, "lon": 126.99, "normal": "11-21" },
|
||||
{ "name": "파주", "region": "경기", "lat": 37.89, "lon": 126.77, "normal": "11-20" },
|
||||
{ "name": "이천", "region": "경기", "lat": 37.26, "lon": 127.48, "normal": "11-20" },
|
||||
{ "name": "철원", "region": "강원", "lat": 38.15, "lon": 127.3, "normal": "11-18" },
|
||||
{ "name": "춘천", "region": "강원", "lat": 37.95, "lon": 127.75, "normal": "11-21", "top": true },
|
||||
{ "name": "원주", "region": "강원", "lat": 37.34, "lon": 127.95, "normal": "11-21" },
|
||||
{ "name": "대관령", "region": "강원", "lat": 37.68, "lon": 128.72, "normal": "11-05", "top": true },
|
||||
{ "name": "속초", "region": "강원", "lat": 38.25, "lon": 128.56, "normal": "12-10" },
|
||||
{ "name": "강릉", "region": "강원", "lat": 37.8, "lon": 128.86, "normal": "12-07", "top": true },
|
||||
{ "name": "동해", "region": "강원", "lat": 37.51, "lon": 129.12, "normal": "12-11" },
|
||||
{ "name": "태백", "region": "강원", "lat": 37.17, "lon": 128.99, "normal": "11-10" },
|
||||
{ "name": "서산", "region": "충남", "lat": 36.78, "lon": 126.49, "normal": "11-20" },
|
||||
{ "name": "천안", "region": "충남", "lat": 36.78, "lon": 127.12, "normal": "11-19" },
|
||||
{ "name": "보령", "region": "충남", "lat": 36.33, "lon": 126.56, "normal": "11-22" },
|
||||
{ "name": "청주", "region": "충북", "lat": 36.64, "lon": 127.44, "normal": "11-23" },
|
||||
{ "name": "충주", "region": "충북", "lat": 36.97, "lon": 127.95, "normal": "11-24" },
|
||||
{ "name": "추풍령", "region": "충북", "lat": 36.22, "lon": 127.99, "normal": "11-17" },
|
||||
{ "name": "대전", "region": "대전", "lat": 36.37, "lon": 127.37, "normal": "11-20", "top": true },
|
||||
{ "name": "전주", "region": "전북", "lat": 35.82, "lon": 127.15, "normal": "11-29", "top": true },
|
||||
{ "name": "군산", "region": "전북", "lat": 36.0, "lon": 126.76, "normal": "11-26" },
|
||||
{ "name": "남원", "region": "전북", "lat": 35.41, "lon": 127.33, "normal": "11-24" },
|
||||
{ "name": "광주", "region": "광주", "lat": 35.17, "lon": 126.89, "normal": "11-29", "top": true },
|
||||
{ "name": "목포", "region": "전남", "lat": 34.82, "lon": 126.38, "normal": "11-29" },
|
||||
{ "name": "순천", "region": "전남", "lat": 35.02, "lon": 127.37, "normal": "11-24" },
|
||||
{ "name": "여수", "region": "전남", "lat": 34.74, "lon": 127.74, "normal": "12-13" },
|
||||
{ "name": "완도", "region": "전남", "lat": 34.4, "lon": 126.7, "normal": "12-08" },
|
||||
{ "name": "안동", "region": "경북", "lat": 36.57, "lon": 128.71, "normal": "11-29" },
|
||||
{ "name": "구미", "region": "경북", "lat": 36.13, "lon": 128.32, "normal": "11-30" },
|
||||
{ "name": "울진", "region": "경북", "lat": 36.99, "lon": 129.41, "normal": "12-09" },
|
||||
{ "name": "포항", "region": "경북", "lat": 36.03, "lon": 129.38, "normal": "12-18" },
|
||||
{ "name": "대구", "region": "대구", "lat": 35.88, "lon": 128.62, "normal": "12-05", "top": true },
|
||||
{ "name": "거창", "region": "경남", "lat": 35.67, "lon": 127.91, "normal": "12-13" },
|
||||
{ "name": "진주", "region": "경남", "lat": 35.16, "lon": 128.04, "normal": "12-18" },
|
||||
{ "name": "창원", "region": "경남", "lat": 35.17, "lon": 128.57, "normal": "12-27" },
|
||||
{ "name": "통영", "region": "경남", "lat": 34.85, "lon": 128.44, "normal": "12-27" },
|
||||
{ "name": "울산", "region": "울산", "lat": 35.56, "lon": 129.32, "normal": "12-24" },
|
||||
{ "name": "부산", "region": "부산", "lat": 35.1, "lon": 129.03, "normal": "12-23", "top": true },
|
||||
{ "name": "제주", "region": "제주", "lat": 33.51, "lon": 126.53, "normal": "12-10", "top": true },
|
||||
{ "name": "서귀포", "region": "제주", "lat": 33.25, "lon": 126.57, "normal": "12-20" },
|
||||
{ "name": "성산", "region": "제주", "lat": 33.39, "lon": 126.88, "normal": "12-13" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.logger import LOG
|
||||
from common.utils.kma_time import KST
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_snow, parse_snow
|
||||
|
||||
# 지점별 평년 첫눈 날짜 (기상청 계절관측지침, 1991~2020). 출처·기준은 파일 안에 적혀 있다
|
||||
SPOTS: list[dict] = json.loads((Path(__file__).parent / "first_snow.json").read_text(encoding="utf-8"))["spots"]
|
||||
|
||||
_DAYS = 7
|
||||
# 하루 눈 오는 양이 이만큼(cm)은 돼야 '눈 예보'로 친다 (0 에 가까운 값은 뺀다)
|
||||
_MIN_CM = 0.1
|
||||
# 눈 예보는 3시간에 한 번만 받는다. 첫 사용자가 볼 때 받아 Redis 에 둔다
|
||||
_KEY = "firstsnow:forecast"
|
||||
_TTL_SEC = 3 * 3600
|
||||
|
||||
|
||||
@dataclass
|
||||
class SnowSpot:
|
||||
name: str
|
||||
region: str
|
||||
lat: float
|
||||
lon: float
|
||||
normal: str
|
||||
top: bool
|
||||
snow_date: Optional[date] = None
|
||||
snow_cm: Optional[float] = None
|
||||
|
||||
|
||||
def first_snow_day(days: list[tuple[date, float]], today: date) -> Optional[tuple[date, float]]:
|
||||
"""오늘부터 눈 예보가 있는 첫 날과 그날 양. 없으면 None."""
|
||||
return next(((d, cm) for d, cm in sorted(days) if d >= today and cm >= _MIN_CM), None)
|
||||
|
||||
|
||||
class FirstSnowService:
|
||||
async def spots(self, now: datetime) -> tuple[bool, list[SnowSpot]]:
|
||||
"""(눈 예보를 받았는지, 지점 목록). 예보를 못 받아도 평년 날짜는 돌려준다."""
|
||||
forecast = await self._forecast()
|
||||
today = now.astimezone(KST).date()
|
||||
out = []
|
||||
for s in SPOTS:
|
||||
hit = first_snow_day(forecast[s["name"]], today) if forecast and s["name"] in forecast else None
|
||||
out.append(SnowSpot(
|
||||
name=s["name"], region=s["region"], lat=s["lat"], lon=s["lon"], normal=s["normal"], top=bool(s.get("top")),
|
||||
snow_date=hit[0] if hit else None, snow_cm=round(hit[1], 1) if hit else None,
|
||||
))
|
||||
return forecast is not None, out
|
||||
|
||||
async def _forecast(self) -> Optional[dict[str, list[tuple[date, float]]]]:
|
||||
"""지점 이름 → 날짜별 눈 오는 양. Redis 에 있으면 그것을, 없으면 Open-Meteo 에서 받아 둔다. 못 받으면 None."""
|
||||
try:
|
||||
cached = await REDIS.conn.get(_KEY)
|
||||
if cached:
|
||||
return {name: [(date.fromisoformat(d), cm) for d, cm in days] for name, days in json.loads(cached).items()}
|
||||
except RedisError as e:
|
||||
LOG.error(f"[first_snow] cache read: {e}")
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
data = await fetch_snow(client, [(s["lat"], s["lon"]) for s in SPOTS], _DAYS)
|
||||
except OpenMeteoRequestFailed as e:
|
||||
LOG.error(f"[first_snow] {e}")
|
||||
return None
|
||||
forecast = {s["name"]: parse_snow(d) for s, d in zip(SPOTS, data)}
|
||||
try:
|
||||
await REDIS.conn.set(_KEY, json.dumps({name: [[d.isoformat(), cm] for d, cm in days] for name, days in forecast.items()}), ex=_TTL_SEC)
|
||||
except RedisError as e:
|
||||
LOG.error(f"[first_snow] cache write: {e}")
|
||||
return forecast
|
||||
@@ -0,0 +1,70 @@
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
import services.first_snow_service as first_snow_service
|
||||
from common.utils.kma_time import now_kst
|
||||
from router.router import app
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, parse_snow
|
||||
from services.first_snow_service import SPOTS, first_snow_day
|
||||
|
||||
|
||||
def _daily(start: date, cms: list) -> dict:
|
||||
return {"daily": {"time": [(start + timedelta(days=i)).isoformat() for i in range(len(cms))], "snowfall_sum": cms}}
|
||||
|
||||
|
||||
def test_parse_snow_skips_days_without_value():
|
||||
rows = parse_snow(_daily(date(2026, 11, 20), [0.0, None, 1.4]))
|
||||
assert rows == [(date(2026, 11, 20), 0.0), (date(2026, 11, 22), 1.4)]
|
||||
|
||||
|
||||
def test_first_snow_day_is_first_day_from_today_with_enough_snow():
|
||||
today = date(2026, 11, 22)
|
||||
days = [(date(2026, 11, 21), 3.0), (date(2026, 11, 22), 0.05), (date(2026, 11, 24), 0.7), (date(2026, 11, 25), 2.0)]
|
||||
assert first_snow_day(days, today) == (date(2026, 11, 24), 0.7) # 어제 눈과 0에 가까운 값은 뺀다
|
||||
assert first_snow_day([(date(2026, 11, 23), 0.0)], today) is None
|
||||
|
||||
|
||||
def test_spot_data_has_normal_dates_and_unique_names():
|
||||
names = [s["name"] for s in SPOTS]
|
||||
assert len(names) == len(set(names)) and len(names) >= 40
|
||||
for s in SPOTS:
|
||||
month, day = map(int, s["normal"].split("-"))
|
||||
assert month in (11, 12) and 1 <= day <= 31
|
||||
assert 33 <= s["lat"] <= 39 and 125 <= s["lon"] <= 130
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_first_snow_api_marks_spots_with_snow_forecast(monkeypatch):
|
||||
today = now_kst().date()
|
||||
calls = []
|
||||
|
||||
async def fake_fetch(client, points, days):
|
||||
calls.append(len(points))
|
||||
# 첫 지점만 모레 눈, 나머지는 눈 없음
|
||||
return [_daily(today, [0.0, 0.0, 1.2, 0.0] if i == 0 else [0.0] * 4) for i in range(len(points))]
|
||||
|
||||
monkeypatch.setattr(first_snow_service, "fetch_snow", fake_fetch)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/season/first-snow")).json()
|
||||
again = (await client.get("/v1/season/first-snow")).json()
|
||||
assert body["result"]["success"] is True and body["forecast"] is True
|
||||
assert len(body["spots"]) == len(SPOTS)
|
||||
first = body["spots"][0]
|
||||
assert first["name"] == SPOTS[0]["name"] and first["normal"] == SPOTS[0]["normal"]
|
||||
assert first["snow_date"] == (today + timedelta(days=2)).isoformat() and first["snow_cm"] == 1.2
|
||||
assert all("snow_date" not in s for s in body["spots"][1:])
|
||||
assert again == body and calls == [len(SPOTS)] # 두 번째는 Redis 에 둔 예보를 쓴다
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_first_snow_api_returns_normal_dates_when_forecast_fails(monkeypatch):
|
||||
async def failing_fetch(client, points, days):
|
||||
raise OpenMeteoRequestFailed("down")
|
||||
|
||||
monkeypatch.setattr(first_snow_service, "fetch_snow", failing_fetch)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/season/first-snow")).json()
|
||||
assert body["result"]["success"] is True and body["forecast"] is False
|
||||
assert len(body["spots"]) == len(SPOTS) and all("snow_date" not in s for s in body["spots"])
|
||||
Reference in new issue
Block a user