Compare commits

..
Author SHA1 Message Date
minaChoi 0a16c5329d feat: 지역 바꾸기 목록을 지역 페이지 링크(a href)로, 시트가 닫혀 있어도 지역 페이지 링크를 HTML에 둔다 2026-10-19 16:25:48 +09:00
minaChoi aad8784b48 fix: 홈 첫 HTML의 숨긴 지역 페이지 링크 제거 (사람에게 안 보이고 로봇만 읽는 링크) 2026-10-19 14:19:45 +09:00
minaChoi 3c9b163dd4 feat: 홈 첫 HTML에 시도별 지역 페이지 링크(230개)를 넣어 검색 로봇이 홈에서 지역 페이지로 이어지게 2026-10-19 10:54:06 +09:00
minaChoi b0cd5ef1ef feat: 지역 검색 페이지 keywords 를 지역별로 (성남 날씨·성남시 날씨·분당구 날씨…), 본문 첫 줄에 '성남 날씨' 꼴 2026-10-14 11:07:54 +09:00
minaChoi 0d6ab29552 fix: 검색 결과 요약에 화면 글(시간대 칸·행사·게시물)이 뽑히던 것 (앱 영역 전체 data-nosnippet, 요약은 description 으로) 2026-10-14 10:48:49 +09:00
minaChoi ba94a381a9 fix: '날씨각' 검색 요약에 게시물 글이 뽑히던 것 (게시물 data-nosnippet, 홈 설명을 '날씨각은'으로 시작) 2026-10-14 10:18:17 +09:00
minaChoi 882932a51b feat: 지역 검색 페이지 제목을 '성남시 오늘 날씨'로 시작, 요약 앞에 최저·최고·강수확률·하늘 2026-10-14 10:11:29 +09:00
minaChoi a68268234d feat: 지역 검색 페이지에 오늘 날씨·각을 서버가 채워 준다 (nginx → /v1/seo/today, 실패하면 정적 HTML) 2026-10-14 09:32:23 +09:00
minaChoi 2ca060b626 Merge remote-tracking branch 'origin/main' into feat/region-seo-pages
# Conflicts:
#	frontend/src/b/BLayout.tsx
2026-10-14 09:16:08 +09:00
minaChoi 3975e41f56 Merge remote-tracking branch 'origin/fix/first-region-feed' into feat/region-seo-pages 2026-10-14 09:15:37 +09:00
minaChoi 422e354f61 Merge remote-tracking branch 'origin/main' into feat/meeting-1008 2026-10-14 09:08:50 +09:00
minaChoi 0aeceac257 feat: 우산분실각(비 그친 뒤 우산 두고 오기 쉬운 정도)·교통체증각(출퇴근길 비·눈·추위) 추가, '앞서 비 옴' 조건(rain_before) 2026-10-14 09:08:50 +09:00
minaChoi b586db0de7 feat: 보고 있는 탭을 다시 누르면 맨 위로 스크롤 2026-10-14 09:08:49 +09:00
minaChoi 599ef05dcf fix: 처음 온 지역의 각이 비어 보이던 것 (예보 받는 동안 3초만 기다리고 빈 피드를 1분 저장하던 것) 2026-10-13 17:02:41 +09:00
19 changed files with 466 additions and 26 deletions

No files matched your search

+3
View File
@@ -31,6 +31,9 @@ class Settings(BaseSettings):
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr"
# 지역 검색 페이지의 정적 HTML 을 받아 올 프론트 주소 (같은 docker 망 안)
frontend_internal_url: str = "http://frontend"
jwt_access_secret: str = ""
jwt_refresh_secret: str = ""
jwt_access_minutes: int = 60
+2
View File
@@ -14,6 +14,7 @@ from router.v1.index.index import router as index_router
from router.v1.reaction.reaction import router as reaction_router
from router.v1.region.region import router as region_router
from router.v1.season.season import router as season_router
from router.v1.seo.seo import router as seo_router
from router.v1.sky.sky import router as sky_router
from router.v1.watch.watch import router as watch_router
from router.v1.weather.weather import router as weather_router
@@ -43,6 +44,7 @@ app.include_router(auth_router)
app.include_router(reaction_router)
app.include_router(watch_router)
app.include_router(image_router)
app.include_router(seo_router)
class Res_Health(Res_WebPacketProtocol):
View File
Whitespace-only changes.
+17
View File
@@ -0,0 +1,17 @@
from fastapi import APIRouter, Depends, Path
from fastapi.responses import HTMLResponse
from common.enums import ErrorType
from services.seo_service import SeoService
router = APIRouter(prefix="/v1/seo", tags=["seo"])
_SLUG = r"^[a-z]+$"
@router.get("/today/{sido}/{place}", response_class=HTMLResponse, summary="지역 검색 페이지: 정적 HTML 에 오늘 날씨·각을 채워 돌려준다 (nginx 가 /today/... 를 넘김)")
async def get_today_page(sido: str = Path(..., pattern=_SLUG), place: str = Path(..., pattern=_SLUG), service: SeoService = Depends()) -> HTMLResponse:
err, html = await service.page(f"today/{sido}/{place}")
if err is not ErrorType.SUCCESS:
return HTMLResponse("not found", status_code=404)
return HTMLResponse(html, headers={"Cache-Control": "no-cache"})
+154
View File
@@ -3730,5 +3730,159 @@
"sort_order": 51,
"priority": 3,
"months": []
},
{
"code": "umbrella_lost",
"name": "우산분실각",
"icon": "umbrella",
"category": 4,
"is_fun": false,
"is_core": false,
"has_detail": true,
"description": "오전 9시~밤 10시, 비가 그쳐서 우산을 두고 오기 쉬운 정도",
"windows": [
{
"from": 9,
"to": 11
},
{
"from": 11,
"to": 13
},
{
"from": 13,
"to": 15
},
{
"from": 15,
"to": 17
},
{
"from": 17,
"to": 19
},
{
"from": 19,
"to": 22
}
],
"weight_temp": 0,
"weight_rain": 80,
"weight_wind": 0,
"weight_humidity": 0,
"weight_air": 0,
"weight_uv": 0,
"weight_sun": 0,
"weight_view": 0,
"weight_time": 20,
"factor_rules": {
"temp": {
"type": "range",
"lo": 0,
"hi": 40
},
"rain": {
"dir": "dry"
},
"wind": {
"type": "ignore"
},
"humidity": {
"type": "ignore"
},
"time": {
"type": "fixed",
"value": 100
}
},
"zero_rules": [
{
"field": "rain_before",
"op": "==",
"value": "no"
},
{
"field": "rain",
"op": "==",
"value": "yes"
}
],
"limit_description": "비가 언제 그칠지는 예보만큼만 맞아요",
"sentences": {
"0": "우산 두고 올 일 없는 날이에요.",
"30": "비가 오락가락해요. 우산 손에 꼭 쥐어요.",
"60": "비가 그쳤어요. 카페·버스에 우산 두고 오기 딱 좋아요.",
"80": "비 끝, 하늘 맑음! 일어날 때 우산부터 챙겨요 ☂️"
},
"sort_order": 52,
"priority": 2,
"months": []
},
{
"code": "traffic",
"name": "교통체증각",
"icon": "drive",
"category": 4,
"is_fun": false,
"is_core": false,
"has_detail": true,
"description": "출퇴근길 비·눈·추위로 차가 막히는 정도",
"windows": [
{
"from": 7,
"to": 10
},
{
"from": 17,
"to": 20
}
],
"weight_temp": 10,
"weight_rain": 70,
"weight_wind": 0,
"weight_humidity": 0,
"weight_air": 0,
"weight_uv": 0,
"weight_sun": 0,
"weight_view": 0,
"weight_time": 20,
"factor_rules": {
"temp": {
"type": "lower",
"zero": 10,
"full": -5
},
"rain": {
"dir": "wet"
},
"wind": {
"type": "ignore"
},
"humidity": {
"type": "ignore"
},
"time": {
"type": "weekday",
"mon": 100,
"tue": 100,
"wed": 100,
"thu": 100,
"fri": 100,
"sat": 40,
"sun": 40,
"holiday": 30
}
},
"zero_rules": [],
"limit_description": "사고·공사·행사로 막히는 건 반영하지 못해요",
"sentences": {
"0": "길이 수월해요. 평소처럼 나가요.",
"30": "조금 더뎌 수 있어요. 10분 일찍!",
"60": "빗길에 차가 막혀요. 대중교통이 나아요.",
"80": "출퇴근길 주차장 예상! 30분 일찍 나서요 🚗"
},
"sort_order": 53,
"priority": 2,
"months": []
}
]
+6 -1
View File
@@ -56,6 +56,7 @@ class Context:
lookahead_rain_prob: int
moon_note: str = "" # 별보기각 근거 문구: 그날 밤 달 모양·보이는 시간
sunrise_score: Optional[int] = None # 그날 아침 일출 하늘 점수 (해돋이각)
rain_hours: frozenset[int] = frozenset() # 그날 비 오는 시각(0~23). 우산분실각의 '앞서 비가 왔는지'
@dataclass(frozen=True)
@@ -262,6 +263,8 @@ def _cond(r: dict) -> tuple[str, str, str]:
return "눈 소식이 없어", "눈 소식이 없거나", "눈 소식이 없으면"
if r["field"] == "rain":
return "비 소식이 있어", "비 소식이 있거나", "비 소식이 있으면"
if r["field"] == "rain_before":
return "앞서 내린 비가 없어", "앞서 내린 비가 없거나", "앞서 내린 비가 없으면"
base = f"{_FIELD_TEXT[r['field']]} {r['value']}{_UNIT[r['field']]} {'이상' if r['op'] == '>=' else '미만'}"
return f"{base}이라", f"{base}이거나", f"{base}이면"
@@ -344,6 +347,7 @@ def evaluate(definition, windows: list[list[Hour]], ctx: Context) -> Optional[Re
"gust_ms": max(gusts, default=None), "ground_c": max(grounds, default=None),
"snow": "yes" if any(h.rain_type in (RainType.SNOW, RainType.SLEET) for h in hours) else "no",
"rain": "yes" if raining else "no", "humidity": round(mean(h.humidity for h in hours)),
"rain_before": "yes" if any(h < hours[0].hour for h in ctx.rain_hours) else "no",
}
reason, cap = _zero(definition.zero_rules, agg)
if reason is not None:
@@ -393,7 +397,8 @@ def estimate(definition, fc: DayForecast, windows: list[list[int]], ctx: Context
notes = {a: n for a, (_, n) in scored.items()}
score = _weighted(factors, weights)
# 중기예보엔 눈 여부가 없어서, 눈이 와야 하는 각은 0점으로 둔다
known = {"rain_prob": max_prob, "snow": "no"}
# 하루 예보로는 비가 언제 그치는지 몰라 '앞서 비 옴'은 없는 것으로 본다
known = {"rain_prob": max_prob, "snow": "no", "rain_before": "no"}
reason, cap = _zero([r for r in definition.zero_rules if r["field"] in known], known)
if reason is not None:
score = min(score, cap)
+3
View File
@@ -323,6 +323,9 @@ class FeedService:
async with redis_lock("lock:feed:build", ttl_sec=20):
await build_feed_day(day, self.crud, self.season_crud, self.regions)
res, partial = await self._assemble(region, now, day, slot, sunset_at)
# 각을 못 낸 피드는 저장하지 않는다. 처음 온 지역은 예보를 받는 중이라 다음 요청에서 바로 채운다
if not res.bands.top5:
return ErrorType.SUCCESS, res
try:
await REDIS.conn.set(key, res.model_dump_json(), ex=_PARTIAL_TTL if partial else feed_ttl_sec(now, sunset_at))
except RedisError as e:
+8 -2
View File
@@ -193,6 +193,12 @@ def _shown_parts(parts: dict[str, int], cur: str) -> dict[str, int]:
return {k: shown[k] for k in SLOTS if k in shown}
def rain_hours(by_at: dict[datetime, WeatherHourly], day: date) -> frozenset[int]:
"""그날 비·눈 오는 시각(0~23)."""
start = kst_midnight(day)
return frozenset(h for h in range(24) if (r := by_at.get(start + timedelta(hours=h))) is not None and r.rain_type != RainType.NONE.value)
def slot_results(
defn, day: date, region: Region, by_at: dict[datetime, WeatherHourly], by_om: dict[datetime, OpenMeteoHourly], ctx: Context, sunset_at: datetime,
now: Optional[datetime] = None,
@@ -388,7 +394,7 @@ class IndexService:
air_label=GRADE_LABEL[AirGrade(air.grade)] if air and air.grade else None,
wind_warning=any(w.warning_type is WarningType.WIND for w in warnings or []),
)
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, **base_ctx)
today_ctx = Context(day=today, is_holiday=False, moon=0, sunset_score=None, lookahead_rain_prob=0, rain_hours=rain_hours(by_at, today), **base_ctx)
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at
weather_parts = {k: r.score for k, r in slot_results(WEATHER_SCORE_DEF, today, region, by_at, by_om, today_ctx, sunset_at, now).items()}
@@ -419,7 +425,7 @@ class IndexService:
m = night(day, float(region.lat), float(region.lon))
ctx = Context(
day=day, is_holiday=day in (holidays or set()), moon=m.lit * up_ratio(m, _STARS_HOURS), moon_note=f"{m.name}, {view_line(m, None)}",
sunset_score=sunset.get(day), sunrise_score=sunrise.get(day), lookahead_rain_prob=0, **base_ctx,
sunset_score=sunset.get(day), sunrise_score=sunrise.get(day), lookahead_rain_prob=0, rain_hours=rain_hours(by_at, day), **base_ctx,
)
for d in defs:
result = day_result(d, day, region, by_at, daily, ctx, short=day < today + timedelta(days=DAYS), by_om=by_om)
+106
View File
@@ -0,0 +1,106 @@
import re
from datetime import datetime, timedelta
from html import escape
from typing import Optional
import httpx
from fastapi import Depends
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import WeatherHourly
from common.enums import ErrorType, RainType, Sky
from common.logger import LOG
from common.utils.kma_time import KST, kst_midnight, now_kst
from config.settings import settings
from crud.region_crud import RegionCRUD
from crud.weather_crud import WeatherCRUD
from router.v1.feed.protocol import Res_Feed
from services.calc.day_slot import SLOT_LABEL
from services.calc.sun import sun_times
from services.feed_service import FeedService
_CODE = re.compile(r'<meta name="region-code" content="(\d+)"')
_DESC = re.compile(r'(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"')
_NAME = re.compile(r"<h1>(.+?) 오늘 날씨")
_H1 = re.compile(r"(<main><h1>[^<]*</h1>)")
def _clock(at: datetime) -> str:
at = at.astimezone(KST)
h = at.hour % 12 or 12
return f"{'오전' if at.hour < 12 else '오후'} {h}시" + (f" {at.minute}분" if at.minute else "")
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
_RAIN_WORD = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
def day_summary(rows: list[WeatherHourly]) -> str:
"""오늘 하루 예보 요약: 최저·최고, 강수확률, 하늘 (비·눈이 있으면 그것)."""
if not rows:
return ""
temps = [float(r.temp_c) for r in rows]
wet = next((RainType(r.rain_type) for r in rows if r.rain_type != RainType.NONE.value), None)
day = [r for r in rows if 9 <= r.forecast_at.astimezone(KST).hour <= 18] or rows
sky = _RAIN_WORD[wet] if wet else _SKY_WORD[Sky(max({r.sky for r in day}, key=[r.sky for r in day].count))]
return f"최저 {round(min(temps))}°·최고 {round(max(temps))}°, 강수확률 {max(r.rain_prob for r in rows)}%, {sky}."
def today_line(feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
"""검색 결과 요약에 보일 오늘 한 줄: 하루 예보, 지금 기온·상태, 구간별 1위 각, 해 지는 시각."""
parts = [day_summary(rows)] if rows else []
h = feed.hero
if h and h.temp_c is not None:
status = "·".join(f"{s.label} {s.value}" for s in h.status)
parts.append(f"지금 {round(h.temp_c)}°" + (f", {status}" if status else "") + ".")
firsts = [f"{label}은 {s.name}" for slot, label in SLOT_LABEL.items() for s in feed.stories if s.slot_ranks.get(slot) == 1]
if firsts:
parts.append(", ".join(firsts) + ".")
if sunset_at:
parts.append(f"해 지는 시각 {_clock(sunset_at)}.")
return " ".join(parts)
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
line = today_line(feed, rows, sunset_at)
if not line:
return template
top = feed.bands.top5 if feed.bands else []
ranks = f"<h2>오늘 {escape(name)} 각 순위</h2><ol>{''.join(f'<li>{escape(t.name)} {t.score}점</li>' for t in top)}</ol>" if top else ""
html = _DESC.sub(lambda m: f'{m.group(1)}{escape(line, quote=True)}"', template)
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{ranks}", html, count=1)
class SeoService:
def __init__(
self, feed: FeedService = Depends(FeedService), regions: RegionCRUD = Depends(RegionCRUD), weather: WeatherCRUD = Depends(WeatherCRUD)
) -> None:
self.feed, self.regions, self.weather = feed, regions, weather
async def template(self, path: str) -> Optional[str]:
"""프론트가 빌드한 정적 지역 페이지 (today/gyeonggi/seongnam.html)."""
try:
async with httpx.AsyncClient(timeout=5) as client:
r = await client.get(f"{settings.frontend_internal_url}/{path}.html")
except httpx.HTTPError as e:
LOG.error(f"[seo] template {path}: {e}")
return None
return r.text if r.status_code == 200 and _CODE.search(r.text) else None
async def page(self, path: str) -> tuple[ErrorType, Optional[str]]:
template = await self.template(path)
if template is None:
return ErrorType.NOT_FOUND, None
code = _CODE.search(template).group(1)
err, feed = await self.feed.feed(code)
if err is not ErrorType.SUCCESS or feed is None:
LOG.error(f"[seo] feed {code}: {err}")
return ErrorType.SUCCESS, template
_, region = await DB_SESSION_MNG.execute_lambda(lambda s: self.regions.get(s, code))
today = now_kst().date()
sunset_at = sun_times(today, float(region.lat), float(region.lon)).sunset_at if region else None
start = kst_midnight(today)
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, code, start, start + timedelta(days=1)))
name = _NAME.search(template)
return ErrorType.SUCCESS, fill(template, feed, rows or [], name.group(1) if name else (feed.region_name or ""), sunset_at)
+1 -1
View File
@@ -25,7 +25,7 @@ from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestF
from services.external.kma import day_start_base, fetch_mid, fetch_ultra, fetch_vilage, latest_mid_base, parse_mid, parse_ultra, parse_vilage
SLOT_HOURS = range(0, 24, 3)
_WAIT_STEPS, _WAIT_SEC = 15, 0.2
_WAIT_STEPS, _WAIT_SEC = 75, 0.2 # 처음 온 지역은 다른 요청이 예보를 받아 오는 동안 최대 15초 기다린다
# 단기예보 끝날 몇 시간만 있는 날은 하루 값을 만들지 않는다 (중기예보 값을 덮어쓰지 않게).
_MIN_DAY_HOURS = 8
MID_DAYS = 11 # 중기예보가 닿는 오늘+10일까지
+2 -3
View File
@@ -204,7 +204,7 @@ def test_gak_key_handles_sunset_window():
@pytest.mark.anyio
async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch):
async def test_feed_missing_gak_is_not_cached(offline, monkeypatch):
from common.cache.redis_client import REDIS
from common.enums import ErrorType
from services.index_service import IndexService
@@ -216,8 +216,7 @@ async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch):
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/feed", params={"region": REGION})).json()
assert PostType.GAK.value not in [p["post_type"] for p in body["posts"]]
keys = [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")]
assert keys and 0 < await REDIS.conn.ttl(keys[0]) <= 60
assert [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")] == []
def _alert_ctx(warnings=(), rain_prob=0):
+10
View File
@@ -308,3 +308,13 @@ def test_humidity_cap():
def test_axis_label_can_be_overridden():
assert axis_label("temp", {"temp": {"type": "higher", "label": "덜 추움"}}) == "덜 추움"
def test_umbrella_lost_needs_rain_that_stopped():
"""우산분실각: 앞서 비가 왔다가 그친 시간대만 점수가 난다. 비가 안 온 날, 아직 비가 오는 시간대는 0점."""
defn = _defn(weight_temp=0, weight_rain=80, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=20,
zero_rules=[{"field": "rain_before", "op": "==", "value": "no"}, {"field": "rain", "op": "==", "value": "yes"}])
after_rain = replace(CTX, rain_hours=frozenset({9, 10}))
assert evaluate(defn, [[_h(13), _h(14)]], after_rain).score >= 80
assert evaluate(defn, [[_h(13), _h(14)]], CTX).zero_reason == "앞서 내린 비가 없어 0점"
assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0
+67
View File
@@ -0,0 +1,67 @@
from datetime import datetime
import pytest
from httpx import ASGITransport, AsyncClient
from common.utils.kma_time import KST
from common.database.model.models import WeatherHourly
from router.router import app
from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex
from services.seo_service import SeoService, day_summary, fill, today_line
REGION = "1114000000"
TEMPLATE = (
'<html><head><meta name="description" content="소개" /><meta property="og:description" content="소개" />'
f'<meta name="region-code" content="{REGION}" />\n </head><body><main><h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>소개 글</p></main></body></html>'
)
def _top(name: str, score: int, ranks: dict[str, int]) -> TopIndex:
return TopIndex(index_id=1, code="x", name=name, icon="x", score=score, rank=1, slot_ranks=ranks)
def _feed() -> Res_Feed:
stories = [_top("러닝각", 80, {"morning": 1, "day": 2}), _top("빨래각", 77, {"day": 1}), _top("별보기각", 70, {"night": 1})]
hero = Hero(now_at=datetime(2026, 10, 14, 9), sky_mode="morning", temp_c=13.4,
status=[HeroStat(icon="m", label="습도", value="보통", tone="normal"), HeroStat(icon="m", label="미세먼지", value="좋음", tone="normal")])
return Res_Feed(hero=hero, stories=stories, bands=Bands(top5=stories[:2]))
def _hour(h: int, temp: float, sky: int = 1, rain: int = 1, prob: int = 0) -> WeatherHourly:
return WeatherHourly(forecast_at=datetime(2026, 10, 14, h, tzinfo=KST), temp_c=temp, sky=sky, rain_type=rain, rain_prob=prob)
def test_day_summary_min_max_prob_and_daytime_sky():
rows = [_hour(3, 8.6, sky=4), _hour(9, 12, sky=3), _hour(12, 19.5, sky=1, prob=10), _hour(15, 20.2, sky=1), _hour(21, 14)]
assert day_summary(rows) == "최저 9°·최고 20°, 강수확률 10%, 맑음."
assert day_summary([_hour(12, 15, rain=2, prob=70)]) == "최저 15°·최고 15°, 강수확률 70%, 비."
def test_today_line_has_day_now_slot_firsts_and_sunset():
line = today_line(_feed(), [_hour(12, 19.5, prob=10)], datetime(2026, 10, 14, 17, 52, tzinfo=KST))
assert line == "최저 20°·최고 20°, 강수확률 10%, 맑음. 지금 13°, 습도 보통·미세먼지 좋음. 아침은 러닝각, 낮은 빨래각, 밤은 별보기각. 해 지는 시각 오후 5시 52분."
def test_fill_puts_today_into_description_and_body():
html = fill(TEMPLATE, _feed(), [], "서울 중구", None)
assert html.count('content="지금 13°, 습도 보통·미세먼지 좋음.') == 2
assert "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>지금 13°" in html
assert "<li>러닝각 80점</li><li>빨래각 77점</li>" in html
def test_fill_keeps_template_when_no_weather():
assert fill(TEMPLATE, Res_Feed(), [], "서울 중구", None) == TEMPLATE
@pytest.mark.anyio
async def test_today_page_fills_real_feed(offline, monkeypatch):
async def template(self, path):
return TEMPLATE if path == "today/seoul/jung" else None
monkeypatch.setattr(SeoService, "template", template)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
page = await client.get("/v1/seo/today/seoul/jung")
missing = await client.get("/v1/seo/today/seoul/nowhere")
assert page.status_code == 200 and "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>최저 " in page.text and "지금 20°" in page.text
assert "해 지는 시각 오후" in page.text and "<ol><li>" in page.text
assert missing.status_code == 404
+7 -6
View File
@@ -15,14 +15,14 @@
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
<meta name="theme-color" content="#d6ebff" />
<meta name="description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
<meta name="description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
<meta name="keywords" content="날씨각, 오늘 날씨, 날씨 지수, 세차하기 좋은 날, 빨래하기 좋은 날, 러닝하기 좋은 날씨, 오늘 노을, 노을 시간, 일몰 시간, 노을 명소, 주말 날씨, 주말 나들이, 이번 주말 축제, 미세먼지, 오늘 밤 달" />
<title>날씨각 · 오늘 날씨 지수, 노을, 주말 행사</title>
<link rel="manifest" href="/manifest.webmanifest" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="날씨각" />
<meta property="og:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
<meta property="og:description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
<meta property="og:description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
<meta property="og:url" content="%VITE_SITE_URL%/" />
<link rel="canonical" href="%VITE_SITE_URL%/" />
<meta property="og:image" content="%VITE_SITE_URL%/og.png" />
@@ -31,7 +31,7 @@
<meta property="og:image:alt" content="날씨각, 오늘 날씨에 맞는 일을 점수로 알려 주는 서비스" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="날씨각 · 오늘 날씨 지수, 노을, 주말 행사" />
<meta name="twitter:description" content="세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요." />
<meta name="twitter:description" content="날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요." />
<meta name="twitter:image" content="%VITE_SITE_URL%/og.png" />
<meta property="og:locale" content="ko_KR" />
<meta name="google-site-verification" content="ageFc5cYyqCTlRxsQTu4d3uetA4WG7y7yUPR1f7muVk" />
@@ -60,7 +60,7 @@
"@type": "WebApplication",
"name": "날씨각",
"url": "%VITE_SITE_URL%/",
"description": "세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 날씨각에서 확인하세요.",
"description": "날씨각은 세차각·빨래각·러닝각처럼 오늘 날씨에 맞는 일을 점수로 알려 줘요. 노을이 예쁜 시간과 명소, 이번 주말 가까운 축제까지 확인하세요.",
"applicationCategory": "WeatherApplication",
"operatingSystem": "All",
"inLanguage": "ko-KR",
@@ -98,11 +98,12 @@
</head>
<body>
<!-- 앱이 뜨기 전 첫 화면: 정적 소개 글이 잠깐 보이지 않게 덮는다. 앱이 뜨면 지운다 -->
<div id="boot" role="status" style="position:fixed;inset:0;z-index:60;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;background:#d6ebff;color:#28304a;font:19px Jua,sans-serif">
<div id="boot" data-nosnippet role="status" style="position:fixed;inset:0;z-index:60;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;background:#d6ebff;color:#28304a;font:19px Jua,sans-serif">
<img src="/icons/rabbit.png" alt="" width="88" height="88" />
<p style="margin:0">날씨 불러오는 중…</p>
</div>
<div id="root">
<!-- 검색 결과 요약은 화면 글 대신 description 을 쓰게 한다 (지역 페이지는 서버가 오늘 날씨로 채움) -->
<div id="root" data-nosnippet>
<main>
<h1>날씨각</h1>
<p>오늘 하고 싶은 일이 날씨에 맞는지 점수로 알려 드려요. 세차, 빨래, 러닝, 피크닉처럼 일상의 일을 우리 동네 날씨로 바로 확인하세요.</p>
+17
View File
@@ -31,6 +31,23 @@ server {
proxy_set_header X-Forwarded-Proto $scheme;
}
# 지역 검색 페이지: 백엔드가 정적 HTML(today/…/….html)에 오늘 날씨를 채워 준다. 백엔드가 안 되면 정적 HTML 그대로
location ~ ^/today/[a-z]+/[a-z]+$ {
resolver 127.0.0.11 valid=10s ipv6=off;
set $api http://backend:9800;
proxy_pass $api/v1/seo$uri;
proxy_set_header Host $host;
proxy_connect_timeout 3s;
proxy_read_timeout 20s;
proxy_intercept_errors on;
error_page 404 500 502 503 504 = @static;
}
location @static {
add_header Cache-Control "no-cache";
try_files $uri.html /index.html;
}
# SPA: /gak 처럼 빌드 때 만든 페이지별 HTML(gak.html)이 있으면 그것을, 없으면 index.html. 폴더는 안 찾는다 (/season 이 이미지 폴더 public/season 과 겹쳐 403)
location / {
add_header Cache-Control "no-cache";
+8
View File
@@ -202,5 +202,13 @@
{
"name": "싱잉인더레인각",
"description": "비 오는 날 우산 쓰고 노래하며 걷기 좋은 정도"
},
{
"name": "우산분실각",
"description": "오전 9시~밤 10시, 비가 그쳐서 우산을 두고 오기 쉬운 정도"
},
{
"name": "교통체증각",
"description": "출퇴근길 비·눈·추위로 차가 막히는 정도"
}
]
+10 -6
View File
@@ -48,17 +48,17 @@ function TopBar() {
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
return (
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2.5 px-4 pt-[env(safe-area-inset-top,0px)]">
<header className="sticky top-0 z-20 flex h-[calc(54px+env(safe-area-inset-top,0px))] items-center justify-between gap-2 px-4 pt-[env(safe-area-inset-top,0px)]">
{tab?.title ? <h1 className="shrink-0 font-jua text-[22px] font-normal">{tab.title}</h1> : <h1 className="shrink-0 font-jua text-[25px] font-normal text-(--orange)">날씨각</h1>}
<SeasonChip />
<button
type="button"
onClick={() => open({ type: 'region' })}
aria-label={`위치 바꾸기, 지금 ${region.name}`}
className="ml-auto flex cursor-pointer items-center gap-1 rounded-full bg-white px-3 pt-1 pb-2 text-[13.5px] font-bold shadow-[inset_0_-4px_0_var(--shade),0_6px_12px_rgb(40_48_74/0.07)]"
className="ml-auto flex shrink-0 cursor-pointer items-center gap-1 rounded-full bg-white px-3 pt-1 pb-2 text-[13.5px] font-bold shadow-[inset_0_-4px_0_var(--shade),0_6px_12px_rgb(40_48_74/0.07)]"
>
<PinIcon className="size-3.5" />
{locateStatus === 'locating' ? <Skel className="w-[72px]" /> : region.name}
<PinIcon className="size-3.5 shrink-0" />
{locateStatus === 'locating' ? <Skel className="w-[72px]" /> : <span className="truncate whitespace-nowrap"><span className="max-[399px]:hidden">{region.name}</span><span className="min-[400px]:hidden">{region.name.split(' ').at(-1)}</span></span>}
</button>
{mePending ? (
<Skel shape className="size-9 shrink-0 rounded-full" />
@@ -208,6 +208,10 @@ function Shell() {
useEffect(() => {
window.scrollTo({ top: 0 })
}, [pathname])
// 지금 보고 있는 탭을 다시 누르면 맨 위로
const toTopIfHere = (to: string) => () => {
if (pathname === to) window.scrollTo({ top: 0, behavior: 'smooth' })
}
useEffect(() => {
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', NOTCH_BG[kind])
}, [kind])
@@ -228,14 +232,14 @@ function Shell() {
{TABS.map((t) =>
t.key === 'today' ? (
// 메인 탭: 막대 위로 솟은 큰 주황 동그라미
<NavLink key={t.key} to={t.to} end className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive || pathname.startsWith('/today/') ? 'text-(--orange)' : 'text-(--ink3)')}>
<NavLink key={t.key} to={t.to} end onClick={toTopIfHere(t.to)} className={({ isActive }) => cx('b-tab-main relative -mt-6 flex flex-col items-center gap-1 text-[12px] font-extrabold', isActive || pathname.startsWith('/today/') ? 'text-(--orange)' : 'text-(--ink3)')}>
<span className="b-keep-bg grid size-[60px] place-items-center rounded-full bg-[linear-gradient(160deg,#ffb067,var(--orange)_55%,var(--orange-deep))] text-white shadow-[0_8px_18px_rgb(255_122_69/0.45),inset_0_-4px_0_rgb(0_0_0/0.12)] ring-4 ring-white/85 [&_svg]:stroke-[2.6]">
<TabIcon name={t.key} className="size-[30px]" />
</span>
{t.label}
</NavLink>
) : (
<NavLink key={t.key} to={t.to} className={({ isActive }) => cx('flex flex-col items-center gap-0.5 text-[11px] font-extrabold', isActive ? 'text-(--ink) [&_svg]:stroke-[2.4]' : 'text-(--ink3) [&_svg]:stroke-[1.9]')}>
<NavLink key={t.key} to={t.to} onClick={toTopIfHere(t.to)} className={({ isActive }) => cx('flex flex-col items-center gap-0.5 text-[11px] font-extrabold', isActive ? 'text-(--ink) [&_svg]:stroke-[2.4]' : 'text-(--ink3) [&_svg]:stroke-[1.9]')}>
<TabIcon name={t.key} className="size-[25px]" />
{t.label}
</NavLink>
+28 -4
View File
@@ -1,5 +1,6 @@
import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query'
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
import regionPages from '../../seo/region.json'
import { setTokens, subscribeAuth } from '../api/auth'
import { SITE_URL } from '../api/setup'
import {
@@ -133,6 +134,7 @@ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void
{state.type === 'region' && <RegionSheet onDone={onClose} />}
</div>
)}
{!state && <RegionLinks />}
</dialog>
)
}
@@ -987,6 +989,27 @@ function MeSheet({ onDone }: { onDone: () => void }) {
/* ---------- 지역 ---------- */
const LOCATE_TEXT = { idle: '', locating: '위치를 찾는 중이에요…', denied: '위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요.', error: '위치를 찾지 못했어요. 아래 목록에서 골라 주세요.' } as const
/** 구 코드 → 그 구가 속한 지역 페이지 주소 */
const pageHref = (code: string) => {
const p = regionPages.find((g) => g.regions.some((r) => r.code === code))
return p ? `/today/${p.path}` : '/'
}
/** 지역 바꾸기가 닫혀 있을 때도 지역 페이지 링크를 HTML에 둔다 (검색 로봇이 링크를 따라가게) */
function RegionLinks() {
return (
<nav aria-label="지역별 오늘 날씨">
<ul>
{regionPages.map((p) => (
<li key={p.path}>
<a href={`/today/${p.path}`}>{p.name} 오늘 날씨</a>
</li>
))}
</ul>
</nav>
)
}
function RegionSheet({ onDone }: { onDone: () => void }) {
const { region, setRegion, locate, locateStatus } = useRegion()
const { me, logout } = useAuth()
@@ -1018,10 +1041,11 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
<ul className={cx('mt-2 flex flex-col transition-opacity', list.isPlaceholderData && 'opacity-60')}>
{regions.map((r) => (
<li key={r.code}>
<button
type="button"
<a
href={pageHref(r.code)}
aria-current={r.code === region.code ? 'true' : undefined}
onClick={() => {
onClick={(e) => {
e.preventDefault()
setRegion(r)
track('region_change', { region_name: r.name, method: 'list' })
onDone()
@@ -1030,7 +1054,7 @@ function RegionSheet({ onDone }: { onDone: () => void }) {
>
{r.name}
{r.code === region.code && <small className="font-sans text-xs font-extrabold">지금 보는 곳</small>}
</button>
</a>
</li>
))}
</ul>
+17 -3
View File
@@ -12,7 +12,7 @@ const gakList = `<ul>${gaks.map((g) => `<li><b>${g.name}</b>: ${g.description}</
const regionPages: RegionPage[] = JSON.parse(readFileSync(resolve(import.meta.dirname, 'seo/region.json'), 'utf8'))
/** 검색 로봇이 처음 받는 페이지별 HTML. 바뀌지 않는 소개 글만 넣고, 날씨 값은 앱이 뜬 뒤 불러온다 */
const PAGES: { path: string; title: string; description: string; body: string }[] = [
const PAGES: { path: string; title: string; description: string; body: string; code?: string; keywords?: string }[] = [
{
path: 'gak',
title: '오늘의 각 · 세차각·빨래각·러닝각 점수 | 날씨각',
@@ -39,16 +39,27 @@ const PAGES: { path: string; title: string; description: string; body: string }[
},
]
/** 제목 앞자리: 검색어처럼 시군구 이름부터 (경기 성남시 → 성남시) */
const headName = (name: string) => name.split(' ').at(-1)!
/** 검색어로 많이 치는 꼴: 성남시 → 성남. 중구처럼 두 글자는 그대로 */
const bareName = (name: string) => (name.length > 2 ? name.slice(0, -1) : name)
/** 지역마다 한 장: /today/gyeonggi/seongnam. 같은 시도의 다른 지역으로 이어 검색 로봇이 모두 찾게 한다 */
for (const r of regionPages) {
const sido = r.path.split('/')[0]
const near = regionPages.filter((o) => o !== r && o.path.startsWith(`${sido}/`))
const parts = r.regions.length > 1 ? `<p>${r.name}는 ${r.regions.map((g) => g.name.split(' ').at(-1)).join(', ')}별로 따로 계산해요.</p>` : ''
const head = headName(r.name)
const bare = bareName(head)
const guNames = r.regions.length > 1 ? r.regions.map((g) => g.name.split(' ').at(-1)!) : []
const keywords = [...new Set([`${bare} 날씨`, `${head} 날씨`, `${bare} 오늘 날씨`, `${r.name} 날씨`, ...guNames.flatMap((g) => [`${g} 날씨`, `${bareName(g)} 날씨`]), '날씨각'])].join(', ')
PAGES.push({
path: `today/${r.path}`,
title: `오늘 ${r.name} 날씨, 뭐 할까? | 날씨각`,
code: r.main,
keywords,
title: `${headName(r.name)} 오늘 날씨, 뭐 할까?${r.name.includes(' ') ? ` · ${r.name.split(' ')[0]}` : ''} | 날씨각`,
description: `오늘 ${r.name} 날씨로 세차·빨래·러닝·피크닉 하기 좋은지 아침·낮·저녁·밤 점수로 알려 드려요. 노을 시각과 미세먼지도 함께 확인하세요.`,
body: `<h1>오늘 ${r.name} 날씨, 뭐 할까?</h1><p>${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.</p>${parts}<p>세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.</p>${near.length ? `<h2>${r.name.split(' ')[0]} 다른 지역 날씨</h2><ul>${near.map((o) => `<li><a href="/today/${o.path}">${o.name}</a></li>`).join('')}</ul>` : ''}`,
body: `<h1>${r.name} 오늘 날씨, 뭐 할까?</h1><p>${bare} 날씨, 오늘 ${head}에서는 뭐 하기 좋을까요? ${r.name}의 기상청 예보와 미세먼지로 오늘 하기 좋은 일을 점수로 알려 드려요. 아침, 낮, 저녁, 밤마다 따로 계산해요.</p>${parts}<p>세차각, 빨래각, 러닝각, 우산각처럼 하고 싶은 일이 오늘 날씨에 맞는지 매일 새로 계산하고, 노을이 가장 붉은 시각과 가까운 노을 명소도 알려 드려요.</p>${near.length ? `<h2>${r.name.split(' ')[0]} 다른 지역 날씨</h2><ul>${near.map((o) => `<li><a href="/today/${o.path}">${o.name}</a></li>`).join('')}</ul>` : ''}`,
})
}
@@ -71,9 +82,12 @@ function seoPages(): Plugin {
.replace(/<title>[^<]*<\/title>/, `<title>${p.title}</title>`)
.replace(/(<meta (?:name|property)="(?:description|og:description|twitter:description)" content=")[^"]*"/g, `$1${attr(p.description)}"`)
.replace(/(<meta (?:property|name)="(?:og:title|twitter:title)" content=")[^"]*"/g, `$1${attr(p.title)}"`)
.replace(/(<meta name="keywords" content=")[^"]*"/, (m, head) => (p.keywords ? `${head}${attr(p.keywords)}"` : m))
.replace(/(<meta property="og:url" content=")[^"]*"/, `$1${url}"`)
.replace(/(<link rel="canonical" href=")[^"]*"/, `$1${url}"`)
.replace(/<main>[\s\S]*<\/main>/, `<main>${p.body}<p><a href="/">날씨각 처음으로</a></p></main>`)
// 서버가 오늘 날씨를 채울 때 이 페이지의 구를 알아보는 표시
.replace('</head>', p.code ? `<meta name="region-code" content="${p.code}" />\n </head>` : '</head>')
const file = resolve(outDir, `${p.path}.html`)
mkdirSync(dirname(file), { recursive: true })
writeFileSync(file, html)