Merge branch 'feat/seo-ctr-copy' — 지역 페이지 절반에 검색 결과 새 문구, 클릭률 비교

# Conflicts:
#	docs/이벤트_추적.md
#	frontend/src/lib/analytics.ts
This commit is contained in:
minaChoi committed 2026-10-30 15:01:31 +09:00
commit afa83d8b79
7 files changed
+463 -14

No files matched your search

+9
View File
@@ -458,3 +458,12 @@ docs를 6개로 합칠 때 옛 내용을 그대로 옮겼다. 아래는 코드
| [ ] | `feat/halloween` main 병합 → 킹서버 배포(백엔드 `TalkTopic` 6~9 포함). 10/31 00시 전에 올라가야 할로윈이 켜짐 | 10/30 킹서버 작업 중이라 배포 보류 | `deploy.sh` |
| [ ] | 할로윈 타로·코디 카드 (`/daily-tarot 할로윈`, `/daily-ootd`) — 킹서버 게시라 보류 | 10/30 킹서버 작업 중 | |
| [ ] | 2028년부터 추석 날짜 추가 (음력이라 해마다 `ranges` 에 한 줄) | 2027-09-14~16만 들어 있음 | `frontend/src/b/holiday.ts` |
## 검색 클릭률 (10/30)
| 상태 | 할 일 | 이유 | 관련 파일 |
|---|---|---|---|
| [ ] | `/today`·`/tomorrow` 검색 결과 새 문구(내일 제목 '○○ 내일 날씨 · 내일 1위는 ○○각', 날짜·지역 먼저인 설명)를 지역 절반에만 배포하고, 배포 2주 뒤 Search Console에서 두 그룹 클릭률 비교 + GA `search_landing` 의 `copy` 별 유입. 기준(10/7~27 클릭률): 내일 새 그룹 0.044%·예전 그룹 0.047%, 오늘 새 그룹 0.044%·예전 그룹 0.026% | 10/30 사용자: 색인 늘리기보다 클릭률. 구현 끝, 배포 전 | `backend/services/seo_service.py`, `backend/services/seo_copy_test.json` |
| [ ] | (보류) `/foliage`·`/sky`·`/week` 서버 HTML에 실제 내용 넣기 — 새 URL 없이, 단풍 상태는 화면과 같은 4단계(단풍 전·첫 단풍·절정·절정 지남), 앱이 뜬 뒤에도 화면 아래에 글 남김. 지역 단풍·지역 주말 페이지는 안 만듦 | 10/30 사용자: 클릭률 먼저 | `frontend/vite.config.ts`, `frontend/nginx.conf`, `backend/services/seo_service.py` |
| [ ] | 주말 순위가 Redis 13시간 보관이라 06:40·18:40 갱신이 두 번 연속 실패하면 비어 보임 — 마지막 정상값 따로 보관 | 10/30 조사 중 발견 | `backend/services/weekend_rank.py`, `backend/worker_main.py` |
| [ ] | 오늘 페이지 설명에 "강수확률 60%, 비" 와 "낮은 한강각"이 같이 나옴(10/30 성남) — 하루 중 한 시간이라도 비면 "비"로 적는 요약과 시간대별 1위 각이 어긋나 보임. 계산이 맞는지 확인 | 10/30 클릭률 조사 중 발견 | `backend/services/seo_service.py` |
+275
View File
@@ -0,0 +1,275 @@
{
"about": "검색 결과 제목·설명 새 문구를 쓰는 지역 페이지. 나머지는 예전 문구로 두고 클릭률을 비교한다. Search Console 페이지 노출(2026-10-07~27) 많은 순으로 오늘·내일 따로 줄 세워 ABBA 로 나눔",
"new": [
"today/busan/busanjin",
"today/busan/dong",
"today/busan/geumjeong",
"today/busan/gijang",
"today/busan/nam",
"today/busan/saha",
"today/busan/suyeong",
"today/busan/yeonje",
"today/chungbuk/boeun",
"today/chungbuk/eumseong",
"today/chungbuk/jeungpyeong",
"today/chungbuk/okcheon",
"today/chungnam/boryeong",
"today/chungnam/buyeo",
"today/chungnam/cheonan/dongnam",
"today/chungnam/cheongyang",
"today/chungnam/geumsan",
"today/chungnam/gongju",
"today/chungnam/seocheon",
"today/chungnam/seosan",
"today/daegu/buk",
"today/daegu/dalseo",
"today/daegu/gunwi",
"today/daegu/jung",
"today/daegu/suseong",
"today/daejeon/daedeok",
"today/daejeon/dong",
"today/daejeon/yuseong",
"today/gangwon/cheorwon",
"today/gangwon/donghae",
"today/gangwon/goseong",
"today/gangwon/hongcheon",
"today/gangwon/hwacheon",
"today/gangwon/pyeongchang",
"today/gangwon/samcheok",
"today/gangwon/wonju",
"today/gangwon/yanggu",
"today/gwangju/buk",
"today/gwangju/dong",
"today/gwangju/nam",
"today/gyeongbuk/andong",
"today/gyeongbuk/bonghwa",
"today/gyeongbuk/cheongdo",
"today/gyeongbuk/gimcheon",
"today/gyeongbuk/goryeong",
"today/gyeongbuk/gyeongsan",
"today/gyeongbuk/mungyeong",
"today/gyeongbuk/pohang",
"today/gyeongbuk/pohang/buk",
"today/gyeongbuk/uiseong",
"today/gyeongbuk/uljin",
"today/gyeongbuk/yeongdeok",
"today/gyeongbuk/yeongju",
"today/gyeonggi/anseong",
"today/gyeonggi/anyang",
"today/gyeonggi/anyang/dongan",
"today/gyeonggi/anyang/manan",
"today/gyeonggi/bucheon/sosa",
"today/gyeonggi/bucheon/wonmi",
"today/gyeonggi/gapyeong",
"today/gyeonggi/gimpo",
"today/gyeonggi/goyang/deogyang",
"today/gyeonggi/guri",
"today/gyeonggi/gwacheon",
"today/gyeonggi/hanam",
"today/gyeonggi/hwaseong/hyohaeng",
"today/gyeonggi/namyangju",
"today/gyeonggi/pocheon",
"today/gyeonggi/pyeongtaek",
"today/gyeonggi/seongnam",
"today/gyeonggi/seongnam/bundang",
"today/gyeonggi/seongnam/jungwon",
"today/gyeonggi/suwon/gwonseon",
"today/gyeonggi/suwon/jangan",
"today/gyeonggi/suwon/paldal",
"today/gyeonggi/suwon/yeongtong",
"today/gyeonggi/uiwang",
"today/gyeonggi/yangju",
"today/gyeonggi/yeoncheon",
"today/gyeonggi/yongin",
"today/gyeonggi/yongin/suji",
"today/gyeongnam/changnyeong",
"today/gyeongnam/changwon/jinhae",
"today/gyeongnam/changwon/masanhoewon",
"today/gyeongnam/geoje",
"today/gyeongnam/goseong",
"today/gyeongnam/hadong",
"today/gyeongnam/miryang",
"today/gyeongnam/namhae",
"today/gyeongnam/tongyeong",
"today/gyeongnam/uiryeong",
"today/incheon/ganghwa",
"today/incheon/geomdan",
"today/incheon/gyeyang",
"today/incheon/namdong",
"today/incheon/ongjin",
"today/incheon/seohae",
"today/jeju/jeju",
"today/jeju/seogwipo",
"today/jeonbuk/buan",
"today/jeonbuk/imsil",
"today/jeonbuk/jangsu",
"today/jeonbuk/jeongeup",
"today/jeonbuk/namwon",
"today/jeonbuk/sunchang",
"today/jeonbuk/wanju",
"today/jeonnam/gangjin",
"today/jeonnam/goheung",
"today/jeonnam/gurye",
"today/jeonnam/haenam",
"today/jeonnam/hampyeong",
"today/jeonnam/hwasun",
"today/jeonnam/jindo",
"today/jeonnam/mokpo",
"today/jeonnam/suncheon",
"today/jeonnam/wando",
"today/jeonnam/yeongam",
"today/sejong/sejong",
"today/seoul/dobong",
"today/seoul/dongdaemun",
"today/seoul/gangbuk",
"today/seoul/gangdong",
"today/seoul/geumcheon",
"today/seoul/guro",
"today/seoul/jongno",
"today/seoul/jung",
"today/seoul/jungnang",
"today/seoul/seocho",
"today/seoul/seodaemun",
"today/seoul/seongdong",
"today/seoul/yeongdeungpo",
"today/seoul/yongsan",
"today/ulsan/jung",
"today/ulsan/nam",
"today/ulsan/ulju",
"tomorrow/busan/gangseo",
"tomorrow/busan/geumjeong",
"tomorrow/busan/gijang",
"tomorrow/busan/jung",
"tomorrow/busan/sasang",
"tomorrow/busan/seo",
"tomorrow/busan/yeonje",
"tomorrow/chungbuk/cheongju",
"tomorrow/chungbuk/cheongju/heungdeok",
"tomorrow/chungbuk/danyang",
"tomorrow/chungbuk/goesan",
"tomorrow/chungbuk/jecheon",
"tomorrow/chungbuk/jincheon",
"tomorrow/chungbuk/yeongdong",
"tomorrow/chungnam/asan",
"tomorrow/chungnam/boryeong",
"tomorrow/chungnam/cheonan",
"tomorrow/chungnam/cheonan/dongnam",
"tomorrow/chungnam/cheonan/seobuk",
"tomorrow/chungnam/dangjin",
"tomorrow/chungnam/geumsan",
"tomorrow/chungnam/hongseong",
"tomorrow/chungnam/seocheon",
"tomorrow/chungnam/seosan",
"tomorrow/chungnam/taean",
"tomorrow/daegu/dong",
"tomorrow/daegu/gunwi",
"tomorrow/daegu/nam",
"tomorrow/daegu/suseong",
"tomorrow/daejeon/daedeok",
"tomorrow/daejeon/seo",
"tomorrow/gangwon/chuncheon",
"tomorrow/gangwon/hoengseong",
"tomorrow/gangwon/inje",
"tomorrow/gangwon/jeongseon",
"tomorrow/gangwon/samcheok",
"tomorrow/gangwon/sokcho",
"tomorrow/gangwon/taebaek",
"tomorrow/gangwon/wonju",
"tomorrow/gangwon/yeongwol",
"tomorrow/gwangju/buk",
"tomorrow/gwangju/gwangsan",
"tomorrow/gyeongbuk/cheongdo",
"tomorrow/gyeongbuk/cheongsong",
"tomorrow/gyeongbuk/goryeong",
"tomorrow/gyeongbuk/gumi",
"tomorrow/gyeongbuk/gyeongsan",
"tomorrow/gyeongbuk/sangju",
"tomorrow/gyeongbuk/seongju",
"tomorrow/gyeongbuk/ulleung",
"tomorrow/gyeongbuk/yeongju",
"tomorrow/gyeonggi/ansan",
"tomorrow/gyeonggi/ansan/sangnok",
"tomorrow/gyeonggi/anyang",
"tomorrow/gyeonggi/anyang/dongan",
"tomorrow/gyeonggi/bucheon/ojeong",
"tomorrow/gyeonggi/gimpo",
"tomorrow/gyeonggi/goyang",
"tomorrow/gyeonggi/gunpo",
"tomorrow/gyeonggi/guri",
"tomorrow/gyeonggi/gwangmyeong",
"tomorrow/gyeonggi/hanam",
"tomorrow/gyeonggi/hwaseong/hyohaeng",
"tomorrow/gyeonggi/namyangju",
"tomorrow/gyeonggi/paju",
"tomorrow/gyeonggi/pocheon",
"tomorrow/gyeonggi/seongnam/jungwon",
"tomorrow/gyeonggi/siheung",
"tomorrow/gyeonggi/suwon",
"tomorrow/gyeonggi/suwon/gwonseon",
"tomorrow/gyeonggi/suwon/yeongtong",
"tomorrow/gyeonggi/uijeongbu",
"tomorrow/gyeonggi/yangju",
"tomorrow/gyeonggi/yangpyeong",
"tomorrow/gyeonggi/yeoncheon",
"tomorrow/gyeonggi/yongin/cheoin",
"tomorrow/gyeonggi/yongin/suji",
"tomorrow/gyeongnam/changnyeong",
"tomorrow/gyeongnam/changwon/jinhae",
"tomorrow/gyeongnam/changwon/uichang",
"tomorrow/gyeongnam/geochang",
"tomorrow/gyeongnam/goseong",
"tomorrow/gyeongnam/haman",
"tomorrow/gyeongnam/hamyang",
"tomorrow/gyeongnam/hapcheon",
"tomorrow/gyeongnam/jinju",
"tomorrow/gyeongnam/namhae",
"tomorrow/gyeongnam/sacheon",
"tomorrow/gyeongnam/uiryeong",
"tomorrow/gyeongnam/yangsan",
"tomorrow/incheon/ganghwa",
"tomorrow/incheon/jemulpo",
"tomorrow/incheon/michuhol",
"tomorrow/incheon/seohae",
"tomorrow/jeju/jeju",
"tomorrow/jeonbuk/buan",
"tomorrow/jeonbuk/gimje",
"tomorrow/jeonbuk/gochang",
"tomorrow/jeonbuk/gunsan",
"tomorrow/jeonbuk/jangsu",
"tomorrow/jeonbuk/jeonju",
"tomorrow/jeonbuk/muju",
"tomorrow/jeonbuk/wanju",
"tomorrow/jeonnam/boseong",
"tomorrow/jeonnam/damyang",
"tomorrow/jeonnam/gangjin",
"tomorrow/jeonnam/gurye",
"tomorrow/jeonnam/haenam",
"tomorrow/jeonnam/jangseong",
"tomorrow/jeonnam/jindo",
"tomorrow/jeonnam/muan",
"tomorrow/jeonnam/naju",
"tomorrow/jeonnam/suncheon",
"tomorrow/jeonnam/yeongam",
"tomorrow/jeonnam/yeosu",
"tomorrow/seoul/dongjak",
"tomorrow/seoul/eunpyeong",
"tomorrow/seoul/gangnam",
"tomorrow/seoul/geumcheon",
"tomorrow/seoul/guro",
"tomorrow/seoul/gwanak",
"tomorrow/seoul/gwangjin",
"tomorrow/seoul/jongno",
"tomorrow/seoul/jung",
"tomorrow/seoul/jungnang",
"tomorrow/seoul/nowon",
"tomorrow/seoul/seocho",
"tomorrow/seoul/seongdong",
"tomorrow/seoul/songpa",
"tomorrow/seoul/yangcheon",
"tomorrow/seoul/yongsan",
"tomorrow/ulsan/buk",
"tomorrow/ulsan/dong",
"tomorrow/ulsan/jung",
"tomorrow/ulsan/nam"
]
}
+94 -12
View File
@@ -1,6 +1,8 @@
import json
import re
from datetime import datetime, timedelta
from datetime import date, datetime, timedelta
from html import escape
from pathlib import Path
from typing import Optional
import httpx
@@ -23,6 +25,11 @@ _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>)")
_TITLE = re.compile(r"<title>[^<]*</title>")
_TITLE_META = re.compile(r'(<meta (?:property|name)="(?:og:title|twitter:title)" content=")[^"]*"')
_WEEKDAY = "월화수목금토일"
# 검색 결과 새 문구를 쓰는 페이지(나머지 반은 예전 문구로 두고 클릭률을 견준다)
NEW_COPY = frozenset(json.loads(Path(__file__).with_name("seo_copy_test.json").read_text(encoding="utf-8"))["new"])
def _clock(at: datetime) -> str:
@@ -31,19 +38,35 @@ def _clock(at: datetime) -> str:
return f"{'오전' if at.hour < 12 else '오후'} {h}시" + (f" {at.minute}분" if at.minute else "")
def _date(day: date) -> str:
return f"{day.month}월 {day.day}일({_WEEKDAY[day.weekday()]})"
def _final(word: str) -> bool:
"""마지막 글자에 받침이 있는지 (한글이 아니면 없다고 본다)."""
c = ord(word[-1]) - 0xAC00
return 0 <= c < 11172 and c % 28 != 0
_SKY_WORD = {Sky.CLEAR: "맑음", Sky.PARTLY: "구름 많음", Sky.CLOUDY: "흐림"}
_RAIN_WORD = {RainType.RAIN: "비", RainType.SLEET: "비나 눈", RainType.SNOW: "눈", RainType.SHOWER: "소나기"}
def _day(rows: list[WeatherHourly]) -> tuple[int, int, int, str]:
"""하루 예보: 최저, 최고, 강수확률, 하늘 (비·눈이 있으면 그것)."""
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 round(min(temps)), round(max(temps)), max(r.rain_prob for r in rows), sky
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}."
lo, hi, prob, sky = _day(rows)
return f"최저 {lo}°·최고 {hi}°, 강수확률 {prob}%, {sky}."
def today_line(feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
@@ -69,6 +92,53 @@ def tomorrow_line(rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> s
return " ".join(parts)
def today_copy(day: date, place: str, feed: Res_Feed, rows: list[WeatherHourly], sunset_at: Optional[datetime]) -> str:
"""새 문구의 오늘 설명: 날짜·지역, 하루 예보, 아침·낮 1위 각, 미세먼지·불쾌지수·자외선, 해 지는 시각."""
weather = ""
if rows:
lo, hi, prob, _ = _day(rows)
weather = f": 최저 {lo}°·최고 {hi}°, 비 올 확률 {prob}%"
parts = [f"{_date(day)} {place} 오늘 날씨{weather}."]
# 아침·낮 1위가 같으면 한 번만: 아침·낮엔 캠핑각
firsts: dict[str, list[str]] = {}
for slot, label in SLOT_LABEL.items():
for s in feed.stories:
if slot in ("morning", "day") and s.slot_ranks.get(slot) == 1:
firsts.setdefault(s.name, []).append(label)
if firsts:
said = ", ".join("·".join(labels) + f"엔 {name}" for name, labels in firsts.items())
parts.append(f"{said}{'이' if _final(list(firsts)[-1]) else '가'} 1위예요.")
status = {s.label: s.value for s in feed.hero.status} if feed.hero else {}
tail = [f"{label} {status[label]}" for label in ("미세먼지", "불쾌지수", "자외선") if label in status]
if sunset_at:
tail.append(f"해 지는 시각 {_clock(sunset_at)}")
if tail:
parts.append(", ".join(tail) + ".")
return " ".join(parts)
def tomorrow_copy(day: date, place: str, rows: list[WeatherHourly], top1: Optional[str], sunset_at: Optional[datetime]) -> str:
"""새 문구의 내일 설명: 날짜·지역, 내일 하루 예보, 내일 1위 각, 해 지는 시각."""
if not rows:
return ""
lo, hi, prob, sky = _day(rows)
line = f"{_date(day)} {place} 내일 날씨: 최저 {lo}°·최고 {hi}°, {sky}, 비 올 확률 {prob}%."
tail = ([f"내일 하기 좋은 일 1위는 {top1}"] if top1 else []) + ([f"해 지는 시각은 {_clock(sunset_at)}"] if sunset_at else [])
if not tail:
return line
return f"{line} {', '.join(tail)}{'이에요' if _final(tail[-1]) else '예요'}."
def _retitle(html: str, title: str) -> str:
html = _TITLE.sub(lambda _: f"<title>{escape(title)}</title>", html, count=1)
return _TITLE_META.sub(lambda m: f'{m.group(1)}{escape(title, quote=True)}"', html)
def _mark(html: str, copy: str) -> str:
"""앱이 검색 유입 GA 에 어느 문구로 들어왔는지 실어 보내게 표시한다."""
return html.replace("</head>", f'<meta name="seo-copy" content="{copy}" />\n </head>', 1)
def _put(template: str, line: str, extra: str = "") -> str:
"""설명 메타와 본문 h1 바로 아래에 한 줄을 넣는다."""
if not line:
@@ -77,11 +147,14 @@ def _put(template: str, line: str, extra: str = "") -> str:
return _H1.sub(lambda m: f"{m.group(1)}<p>{escape(line)}</p>{extra}", html, count=1)
def _ranks(feed: Res_Feed, name: str) -> str:
top = feed.bands.top5 if feed.bands else []
return f"<h2>오늘 {escape(name)} 각 순위</h2><ol>{''.join(f'<li>{escape(t.name)} {t.score}점</li>' for t in top)}</ol>" if top else ""
def fill(template: str, feed: Res_Feed, rows: list[WeatherHourly], name: str, sunset_at: Optional[datetime]) -> str:
"""정적 지역 페이지에 오늘 값을 채운다: 설명 메타와 본문 첫 단락, 오늘 각 순위."""
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 ""
return _put(template, today_line(feed, rows, sunset_at), ranks)
return _put(template, today_line(feed, rows, sunset_at), _ranks(feed, name))
class SeoService:
@@ -115,7 +188,16 @@ class SeoService:
sunset_at = sun_times(day, float(region.lat), float(region.lon)).sunset_at if region else None
start = kst_midnight(day)
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.weather.hourly_between(s, code, start, start + timedelta(days=1)))
found = _NAME.search(template)
name = found.group(1) if found else (feed.region_name or "")
if path not in NEW_COPY:
html = _put(template, tomorrow_line(rows or [], sunset_at)) if ahead else fill(template, feed, rows or [], name, sunset_at)
return ErrorType.SUCCESS, _mark(html, "old")
place = name.split(" ")[-1]
if ahead:
return ErrorType.SUCCESS, _put(template, tomorrow_line(rows or [], sunset_at))
name = _NAME.search(template)
return ErrorType.SUCCESS, fill(template, feed, rows or [], name.group(1) if name else (feed.region_name or ""), sunset_at)
top1 = feed.hero.tomorrow.top1.name if feed.hero and feed.hero.tomorrow and feed.hero.tomorrow.top1 else None
html = _put(template, tomorrow_copy(day, place, rows or [], top1, sunset_at))
if top1:
html = _retitle(html, f"{place} 내일 날씨 · 내일 1위는 {top1} | 날씨각")
return ErrorType.SUCCESS, _mark(html, "new")
return ErrorType.SUCCESS, _mark(_put(template, today_copy(day, place, feed, rows or [], sunset_at), _ranks(feed, name)), "new")
+70 -2
View File
@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import date, datetime
import pytest
from httpx import ASGITransport, AsyncClient
@@ -7,7 +7,8 @@ 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, tomorrow_line
from services import seo_service
from services.seo_service import SeoService, day_summary, fill, today_copy, today_line, tomorrow_copy, tomorrow_line
REGION = "1114000000"
TEMPLATE = (
@@ -55,6 +56,7 @@ def test_fill_keeps_template_when_no_weather():
@pytest.mark.anyio
async def test_today_page_fills_real_feed(offline, monkeypatch):
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset())
async def template(self, path):
return TEMPLATE if path == "today/seoul/jung" else None
@@ -69,6 +71,7 @@ async def test_today_page_fills_real_feed(offline, monkeypatch):
@pytest.mark.anyio
async def test_gu_page_of_city_has_its_own_address(offline, monkeypatch):
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset())
async def template(self, path):
return TEMPLATE if path == "today/gyeonggi/seongnam/bundang" else None
@@ -86,6 +89,7 @@ def test_tomorrow_line_has_day_and_sunset():
@pytest.mark.anyio
async def test_tomorrow_page_fills_tomorrow_forecast(offline, monkeypatch):
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset())
tmpl = TEMPLATE.replace("오늘 날씨", "내일 날씨")
async def template(self, path):
@@ -98,3 +102,67 @@ async def test_tomorrow_page_fills_tomorrow_forecast(offline, monkeypatch):
assert page.status_code == 200 and "<h1>서울 중구 내일 날씨, 뭐 할까?</h1><p>최저 " in page.text
assert "지금 " not in page.text and "<ol>" not in page.text
assert missing.status_code == 404
def test_today_copy_has_date_place_morning_day_firsts_and_status():
line = today_copy(date(2026, 10, 14), "중구", _feed(), [_hour(12, 19.5, prob=10)], datetime(2026, 10, 14, 17, 52, tzinfo=KST))
assert line == "10월 14일(수) 중구 오늘 날씨: 최저 20°·최고 20°, 비 올 확률 10%. 아침엔 러닝각, 낮엔 빨래각이 1위예요. 미세먼지 좋음, 해 지는 시각 오후 5시 52분."
same = _feed()
same.stories = [_top("캠핑각", 90, {"morning": 1, "day": 1})]
assert "아침·낮엔 캠핑각이 1위예요." in today_copy(date(2026, 10, 14), "중구", same, [], None)
def test_today_copy_lists_dust_discomfort_uv_in_order():
feed = _feed()
feed.hero.status = [HeroStat(icon="m", label=label, value=value, tone="normal") for label, value in (("습도", "보통"), ("불쾌지수", "쾌적"), ("자외선", "보통"), ("미세먼지", "보통"))]
line = today_copy(date(2026, 10, 30), "성남시", feed, [_hour(12, 18, rain=2, prob=60)], None)
assert line.endswith("미세먼지 보통, 불쾌지수 쾌적, 자외선 보통.")
assert "습도" not in line
def test_tomorrow_copy_has_date_place_top1_and_sunset():
sunset = datetime(2026, 10, 31, 17, 36, tzinfo=KST)
line = tomorrow_copy(date(2026, 10, 31), "평택시", [_hour(12, 15, prob=30)], "빨래각", sunset)
assert line == "10월 31일(토) 평택시 내일 날씨: 최저 15°·최고 15°, 맑음, 비 올 확률 30%. 내일 하기 좋은 일 1위는 빨래각, 해 지는 시각은 오후 5시 36분이에요."
on_hour = tomorrow_copy(date(2026, 10, 31), "평택시", [_hour(12, 15)], None, datetime(2026, 10, 31, 18, 0, tzinfo=KST))
assert on_hour.endswith("해 지는 시각은 오후 6시예요.")
assert tomorrow_copy(date(2026, 10, 31), "평택시", [], "빨래각", sunset) == ""
@pytest.mark.anyio
async def test_new_copy_pages_get_new_title_and_description(offline, monkeypatch):
tomorrow = TEMPLATE.replace("오늘 날씨", "내일 날씨").replace("</head>", "<title>중구 내일 날씨, 뭐 할까? · 서울 | 날씨각</title></head>")
async def template(self, path):
return {"today/seoul/jung": TEMPLATE, "tomorrow/seoul/jung": tomorrow}.get(path)
monkeypatch.setattr(SeoService, "template", template)
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset({"today/seoul/jung", "tomorrow/seoul/jung"}))
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
today = await client.get("/v1/seo/today/seoul/jung")
ahead = await client.get("/v1/seo/tomorrow/seoul/jung")
assert today.status_code == 200 and ahead.status_code == 200
assert '<meta name="description" content="10월 ' in today.text and " 중구 오늘 날씨: 최저 " in today.text
assert "<ol><li>" in today.text and '<meta name="seo-copy" content="new" />' in today.text
assert " 중구 내일 날씨: 최저 " in ahead.text and "해 지는 시각은 오후" in ahead.text
assert "<title>중구 내일 날씨 · 내일 1위는 " in ahead.text and 'property="og:description" content="10월 ' in ahead.text
assert '<meta name="seo-copy" content="new" />' in ahead.text
@pytest.mark.anyio
async def test_old_copy_pages_keep_old_text_and_are_marked(offline, monkeypatch):
async def template(self, path):
return TEMPLATE if path == "today/seoul/jung" else None
monkeypatch.setattr(SeoService, "template", template)
monkeypatch.setattr(seo_service, "NEW_COPY", frozenset())
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
page = await client.get("/v1/seo/today/seoul/jung")
assert "<h1>서울 중구 오늘 날씨, 뭐 할까?</h1><p>최저 " in page.text
assert '<meta name="seo-copy" content="old" />' in page.text
def test_copy_test_groups_split_region_pages_in_half():
assert seo_service.NEW_COPY and all(p.startswith(("today/", "tomorrow/")) for p in seo_service.NEW_COPY)
today = sum(p.startswith("today/") for p in seo_service.NEW_COPY)
assert today == len(seo_service.NEW_COPY) - today
+1
View File
@@ -48,6 +48,7 @@ GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화
| `피드_항목_노출` (코드 `feed_item_view`) | 오늘 피드에 섞인 사람 글·행사 포스트가 처음 반쯤 보임 (한 장에 한 번) | `item_type: 'talk' \| 'event'`, `position`(피드에서 그 종류의 몇 번째) | `TodayPage.tsx` `Seen` |
| `오늘내일_전환` (코드 `hero_day_switch`) | 히어로 오늘/내일 스위치를 바꿈 | `day: 'today' \| 'tomorrow'` | `TodayPage.tsx` |
| `내일에서_오늘로` (코드 `tomorrow_to_today`) | 내일 날씨 페이지(`/tomorrow/...`) 맨 아래 '오늘 ○○ 소식 보기'를 누름 | `region_name` | `TomorrowFeed.tsx` |
| `검색_유입` (코드 `search_landing`) | 구글·네이버 검색 결과에서 지역 오늘·내일 페이지(/today·/tomorrow)로 들어옴 (페이지 열 때 한 번). 검색 결과 제목·설명 새 문구와 예전 문구의 유입을 견주려고 | `page: 'today' \| 'tomorrow'`, `engine: 'google' \| 'naver'`, `copy: 'new' \| 'old' \| 'none'`(서버가 넣은 `seo-copy` 표시, 서버가 못 채운 정적 페이지면 none. 새 문구 페이지 목록은 `backend/services/seo_copy_test.json`) | `regionContext.ts` |
| `쇼츠_열기` (코드 `shorts_open`) | 쇼츠 페이지(/shorts/영상ID)로 들어옴 (오늘 화면 쇼츠 줄·공유 링크) | `video_id` | `Shorts.tsx` `ShortsPage` |
| `쇼츠_보기` (코드 `shorts_view`) | 쇼츠를 넘겨 다른 영상으로 감 | `video_id`, `index`(목록 순서) | `Shorts.tsx` `ShortsPage` |
| `쇼츠_소리` (코드 `shorts_sound`) | 쇼츠 소리 켜기·끄기 | `on` | `Shorts.tsx` `toggleSound` |
+12
View File
@@ -2,6 +2,7 @@ import { createContext, use } from 'react'
import { useLocation } from 'react-router'
import type { RegionData } from '@nalssigak/shared/api/client/types.gen'
import regionPages from '../../seo/region.json'
import { track } from '../lib/analytics'
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
@@ -21,6 +22,17 @@ export function pageOf(pathname: string) {
/** 지역 페이지로 들어오면 서버가 채운 소개 글(#root 안)을 앱이 덮기 전에 잡아 둔다. 구글은 JS 실행 뒤 화면으로 색인한다 */
const landingAbout = pageOf(location.pathname) ? { path: location.pathname, html: document.querySelector('#root > main')?.innerHTML ?? '' } : null
// 구글·네이버 검색으로 지역 페이지에 들어옴: 검색 결과 문구(새·예전, 서버가 못 채웠으면 none)별 유입을 견준다
const searchEngine = document.referrer ? new URL(document.referrer).hostname.match(/(?:^|\.)(google|naver)\./)?.[1] : undefined
if (landingAbout && (searchEngine === 'google' || searchEngine === 'naver')) {
const copy = document.querySelector<HTMLMetaElement>('meta[name="seo-copy"]')?.content
track('search_landing', {
page: location.pathname.startsWith('/tomorrow/') ? 'tomorrow' : 'today',
engine: searchEngine,
copy: copy === 'new' || copy === 'old' ? copy : 'none',
})
}
/** 들어온 지역 페이지에 그대로 있을 때만 그 소개 글 */
export function useLandingAbout(): string | null {
const { pathname } = useLocation()
+2
View File
@@ -28,6 +28,7 @@ type Events = {
feed_item_view: { item_type: 'talk' | 'event'; position: number }
hero_day_switch: { day: 'today' | 'tomorrow' }
tomorrow_to_today: { region_name: string }
search_landing: { page: 'today' | 'tomorrow'; engine: 'google' | 'naver'; copy: 'new' | 'old' | 'none' }
shorts_open: { video_id: string }
shorts_view: { video_id: string; index: number }
shorts_sound: { on: boolean }
@@ -79,6 +80,7 @@ const GA_NAME: Record<keyof Events, string> = {
feed_item_view: '피드_항목_노출',
hero_day_switch: '오늘내일_전환',
tomorrow_to_today: '내일에서_오늘로',
search_landing: '검색_유입',
shorts_open: '쇼츠_열기',
shorts_view: '쇼츠_보기',
shorts_sound: '쇼츠_소리',