Merge remote-tracking branch 'origin/main' into fix/mobile-arrows

This commit is contained in:
minaChoi committed 2026-10-08 13:37:37 +09:00
commit 5734b57758
12 files changed
+267 -43

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@
DATA_GO_KR_SERVICE_KEY= DATA_GO_KR_SERVICE_KEY=
# 행사 수집(7일마다) 완료 알림 — Microsoft Teams Workflows 수신 webhook. 비우면 보내지 않는다. # 행사 수집(7일마다) 완료 알림 — Microsoft Teams Workflows 수신 webhook. 비우면 보내지 않는다.
TEAMS_WEBHOOK_URL= TEAMS_WEBHOOK_URL=
IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr IMAGE_PROXY_HOSTS=tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr
# ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다) # ── 백엔드: DB·Redis (네이티브 실행 기준. compose 안에서는 compose.yaml 이 host·port 를 덮어쓴다)
DB_HOST=localhost DB_HOST=localhost
+1 -1
View File
@@ -29,7 +29,7 @@ class Settings(BaseSettings):
data_go_kr_service_key: str = "" data_go_kr_service_key: str = ""
teams_webhook_url: str = "" teams_webhook_url: str = ""
# 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분) # 공유 이미지용 사진 대신 받기를 허용할 호스트 (쉼표로 구분)
image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr" image_proxy_hosts: str = "tong.visitkorea.or.kr,www.culture.go.kr,culture.seoul.go.kr"
jwt_access_secret: str = "" jwt_access_secret: str = ""
jwt_refresh_secret: str = "" jwt_refresh_secret: str = ""
+4 -3
View File
@@ -21,10 +21,10 @@ from services.external.culture_api import SIDO_NAME
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather from services.external.open_meteo import OpenMeteoRequestFailed, fetch_weather, parse_weather
from services.feed_service import build_feed_day, clear_feed_cache from services.feed_service import build_feed_day, clear_feed_cache
from services.week_service import collect_events from services.week_service import collect_events, drop_known
from services.weekend_rank import WeekendRank from services.weekend_rank import WeekendRank
_POPGA_SEEN = "popga:lastmod" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다 _POPGA_SEEN = "popga:lastmod:v2" # {팝업 id: 마지막으로 읽은 lastmod}, 바뀐 페이지만 다시 읽는다. 받는 분류가 바뀌면 이름을 바꿔 처음부터 읽는다
_POPGA_BATCH = 100 _POPGA_BATCH = 100
EVENTS_DONE = "events:collected" # 행사 수집을 마친 표시. 7일 유지, 없으면 worker 가 켜질 때 한 번 돈다 EVENTS_DONE = "events:collected" # 행사 수집을 마친 표시. 7일 유지, 없으면 worker 가 켜질 때 한 번 돈다
_EVENTS_TTL_SEC = 7 * 86400 _EVENTS_TTL_SEC = 7 * 86400
@@ -105,6 +105,7 @@ async def build_today_feed() -> ErrorType:
async def _save_popups(rows: list[dict], seen: dict[str, str]) -> ErrorType: async def _save_popups(rows: list[dict], seen: dict[str, str]) -> ErrorType:
rows = await drop_known(rows)
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)]) err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)])
if err is ErrorType.SUCCESS and seen: if err is ErrorType.SUCCESS and seen:
await REDIS.conn.hset(_POPGA_SEEN, mapping=seen) await REDIS.conn.hset(_POPGA_SEEN, mapping=seen)
@@ -147,7 +148,7 @@ async def refresh_popups() -> ErrorType:
async def _popup_count() -> int: async def _popup_count() -> int:
q = text("SELECT count(*) FROM public.event WHERE source_id LIKE 'popga:%' AND end_date >= (now() AT TIME ZONE 'Asia/Seoul')::date") q = text("SELECT count(*) FROM public.event WHERE source_id LIKE 'popga:%' AND kind = 4 AND end_date >= (now() AT TIME ZONE 'Asia/Seoul')::date")
err, n = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(q)) err, n = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(q))
return n if err is ErrorType.SUCCESS and n is not None else 0 return n if err is ErrorType.SUCCESS and n is not None else 0
+21 -7
View File
@@ -13,9 +13,19 @@ from common.enums import EVENT_ICON, EventKind
SITEMAP_URL = "https://popga.co.kr/sitemap.xml" SITEMAP_URL = "https://popga.co.kr/sitemap.xml"
POPUP_URL = "https://popga.co.kr/popup/{id}" POPUP_URL = "https://popga.co.kr/popup/{id}"
SOURCE_PREFIX = "popga:" SOURCE_PREFIX = "popga:"
STORE = "STORE" # 팝가 분류: STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제 # 팝가 분류(STORE=팝업스토어, PERFORMANCE=공연, FESTIVAL=축제) 중 받는 것. 공연은 문화정보원에서 따로 받는다
_KINDS = {"STORE": EventKind.POPUP, "FESTIVAL": EventKind.FESTIVAL}
REQUEST_GAP_SEC = 0.3 REQUEST_GAP_SEC = 0.3
# 팝가 '축제' 중 연극제·음악제의 공연 한 편. 극장·홀에서 하거나 이름이 공연이면 공연으로 넣는다
_SHOW_PLACE = ("극장", "홀", "아트센터", "예술의전당", "씨어터", "시어터", "문화회관", "공연장")
_SHOW_NAME = ("연극", "뮤지컬", "오페라", "독주회", "리사이틀", "콘서트")
def is_show(name: str, place: str) -> bool:
return any(w in place for w in _SHOW_PLACE) or any(w in name for w in _SHOW_NAME)
_LOC = re.compile(r"<loc>\s*([^<\s]+)\s*</loc>") _LOC = re.compile(r"<loc>\s*([^<\s]+)\s*</loc>")
_URL = re.compile(r"<url>(.*?)</url>", re.S) _URL = re.compile(r"<url>(.*?)</url>", re.S)
_LASTMOD = re.compile(r"<lastmod>\s*([^<\s]+)\s*</lastmod>") _LASTMOD = re.compile(r"<lastmod>\s*([^<\s]+)\s*</lastmod>")
@@ -86,10 +96,11 @@ def _coord(v) -> Optional[float]:
def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]: def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
"""팝업스토어이고 since 이후에 끝나면 event 행, 아니면 None.""" """팝업스토어·축제이고 since 이후에 끝나면 event 행, 아니면 None."""
kind = re.search(rf'\\?"id\\?":{popup_id},\\?"type\\?":\\?"([A-Z_]+)', page) found = re.search(rf'\\?"id\\?":{popup_id},\\?"type\\?":\\?"([A-Z_]+)', page)
kind = _KINDS.get(found.group(1)) if found else None
ld = _event_ld(page) ld = _event_ld(page)
if kind is None or kind.group(1) != STORE or ld is None: if kind is None or ld is None:
return None return None
start, end = _date(ld.get("startDate")), _date(ld.get("endDate")) start, end = _date(ld.get("startDate")), _date(ld.get("endDate"))
if start is None or end is None or end < since: if start is None or end is None or end < since:
@@ -99,9 +110,12 @@ def parse_popup(page: str, popup_id: int, since: date) -> Optional[dict]:
if sido is None: if sido is None:
return None return None
geo = loc.get("geo") or {} geo = loc.get("geo") or {}
name, place = html.unescape(ld.get("name") or ""), html.unescape(loc.get("name") or "")
if kind is EventKind.FESTIVAL and is_show(name, place):
kind = EventKind.CONCERT
return { return {
"source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": html.unescape(ld.get("name") or "")[:60], "source_id": f"{SOURCE_PREFIX}{popup_id}", "sido_code": sido, "name": name[:60],
"place_name": html.unescape(loc.get("name") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True, "place_name": place[:60], "start_date": start, "end_date": end, "is_confirmed": True,
"source_url": POPUP_URL.format(id=popup_id), "image_url": None, "source_url": POPUP_URL.format(id=popup_id), "image_url": None,
"lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": EventKind.POPUP, "icon": EVENT_ICON[EventKind.POPUP], "lat": _coord(geo.get("latitude")), "lon": _coord(geo.get("longitude")), "kind": kind, "icon": EVENT_ICON[kind],
} }
+68
View File
@@ -0,0 +1,68 @@
import asyncio
import html
import re
from datetime import date, timedelta
from typing import Optional
import httpx
from common.enums import EVENT_ICON, EventKind
# 서울문화포털 문화행사 중 축제. 공개 API 는 키가 따로 있어 robots.txt 가 허용하는 /culture/culture/ 목록을 읽는다.
LIST_URL = "https://culture.seoul.go.kr/culture/culture/cultureEvent/jsonList.json"
VIEW_URL = "https://culture.seoul.go.kr/culture/culture/cultureEvent/view.do?cultcode={code}&menuNo=200010"
IMAGE_URL = "https://culture.seoul.go.kr/cmmn/file/getImage.do?atchFileId={id}&thumb=Y"
IMAGE_CREDIT = "ⓒ서울문화포털"
SOURCE_PREFIX = "seoul:"
SEOUL = "11"
REQUEST_GAP_SEC = 0.3
_MAX_PAGES = 30
# 이름 앞 주최 기관 "[서울시청] ", "[마포문화재단] " 은 카드 제목에서 뗀다
_HOST_PREFIX = re.compile(r"^(\s*\[[^\]]*\]\s*)+")
async def fetch_seoul_festivals(client: httpx.AsyncClient, since: date, days: int) -> list[dict]:
"""since 부터 days 일 안에 열리는 서울 축제. 한 쪽에 10개씩, 빈 쪽이 나올 때까지."""
form = {"menuNo": "200010", "searchCate": "FESTIVAL", "sdate": since.isoformat(), "edate": (since + timedelta(days=days)).isoformat()}
items: list[dict] = []
for page in range(1, _MAX_PAGES + 1):
res = await client.post(LIST_URL, data={**form, "pageIndex": str(page)})
res.raise_for_status()
chunk = res.json().get("resultList") or []
if not chunk:
break
items.extend(chunk)
await asyncio.sleep(REQUEST_GAP_SEC)
return items
def _date(v) -> Optional[date]:
try:
return date.fromisoformat(str(v)[:10])
except ValueError:
return None
def _coord(v) -> Optional[float]:
try:
return round(float(v), 5) if v not in (None, "") else None
except (TypeError, ValueError):
return None
def parse_seoul_festivals(items: list[dict]) -> list[dict]:
rows = []
for it in items:
start, end = _date(it.get("strtdate")), _date(it.get("endDate"))
name = _HOST_PREFIX.sub("", html.unescape(it.get("title") or "")).strip()
if start is None or end is None or not name or it.get("cultcode") is None:
continue
rows.append({
"source_id": f"{SOURCE_PREFIX}{it['cultcode']}", "sido_code": SEOUL, "name": name[:60],
"place_name": html.unescape(it.get("facName") or it.get("addr") or "")[:60], "start_date": start, "end_date": end, "is_confirmed": True,
"source_url": VIEW_URL.format(code=it["cultcode"]),
"image_url": IMAGE_URL.format(id=it["atchFileId"]) if it.get("atchFileId") else None,
# 이 목록은 xCoord 가 위도, yCoord 가 경도다
"lat": _coord(it.get("xCoord")), "lon": _coord(it.get("yCoord")), "kind": EventKind.FESTIVAL, "icon": EVENT_ICON[EventKind.FESTIVAL],
})
return rows
+50 -1
View File
@@ -1,5 +1,6 @@
import asyncio import asyncio
import math import math
import re
from dataclasses import dataclass from dataclasses import dataclass
from datetime import date, timedelta from datetime import date, timedelta
from typing import Optional from typing import Optional
@@ -27,6 +28,10 @@ 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
from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed from services.external.data_go_kr import DataGoKrNotConfigured, DataGoKrRequestFailed
from services.external.kasi import fetch_holidays from services.external.kasi import fetch_holidays
from services.external.seoul_culture import IMAGE_CREDIT as SEOUL_CREDIT
from services.external.seoul_culture import SEOUL
from services.external.seoul_culture import SOURCE_PREFIX as SEOUL_PREFIX
from services.external.seoul_culture import fetch_seoul_festivals, parse_seoul_festivals
from services.external.tour_api import IMAGE_CREDIT as TOUR_CREDIT from services.external.tour_api import IMAGE_CREDIT as TOUR_CREDIT
from services.external.tour_api import fetch_festivals, parse_festivals from services.external.tour_api import fetch_festivals, parse_festivals
from services.index_service import IndexService from services.index_service import IndexService
@@ -104,6 +109,8 @@ def image_credit(e: Event) -> Optional[str]:
"""사진 출처 표기. 직접 넣은 행사(source_id 없음)는 출처를 모르니 None.""" """사진 출처 표기. 직접 넣은 행사(source_id 없음)는 출처를 모르니 None."""
if not e.image_url or e.source_id is None: if not e.image_url or e.source_id is None:
return None return None
if e.source_id.startswith(SEOUL_PREFIX):
return SEOUL_CREDIT
return CULTURE_CREDIT if e.source_id.startswith(CULTURE_PREFIX) else TOUR_CREDIT return CULTURE_CREDIT if e.source_id.startswith(CULTURE_PREFIX) else TOUR_CREDIT
@@ -178,17 +185,59 @@ async def _culture(client: httpx.AsyncClient, sido: str, today: date, realm: str
return [] return []
# 같은 축제를 두 출처가 다르게 적는다: "[성동문화재단] 2026 크리에이티브X성수" ↔ "2026 크리에이티브X성수"
_NAME_NOISE = re.compile(r"\[[^\]]*\]|\([^)]*\)|20\d\d|제\s*\d+\s*회|[^\w]")
def _name_key(name: str) -> str:
return _NAME_NOISE.sub("", name).lower()
async def drop_known(rows: list[dict]) -> list[dict]:
"""다른 출처로 이미 들어 있는 행사(같은 시도, 이름이 같고 기간이 겹침)는 뺀다. 먼저 넣은 출처를 남긴다."""
if not rows:
return rows
since, until = min(r["start_date"] for r in rows), max(r["end_date"] for r in rows)
err, existing = await DB_SESSION_MNG.execute_lambda(lambda s: WeekCRUD().events(s, sorted({r["sido_code"] for r in rows}), since, until))
if err is not ErrorType.SUCCESS:
return rows
known: dict[tuple[str, str], list[Event]] = {}
for e in existing or []:
known.setdefault((e.sido_code, _name_key(e.name)), []).append(e)
def dup(r: dict) -> bool:
key = _name_key(r["name"])
return bool(key) and any(e.source_id != r["source_id"] and e.start_date <= r["end_date"] and r["start_date"] <= e.end_date
for e in known.get((r["sido_code"], key), []))
return [r for r in rows if not dup(r)]
async def _seoul(client: httpx.AsyncClient, sido: str, today: date, known: list[dict]) -> list[dict]:
"""서울문화포털 축제(동네·구청·공원 행사). TourAPI 에 이미 있는 축제는 뺀다. 실패해도 다른 출처는 그대로 넣는다."""
if sido != SEOUL:
return []
try:
rows = parse_seoul_festivals(await fetch_seoul_festivals(client, today, EVENT_DAYS))
except (httpx.HTTPError, ValueError) as e:
LOG.error(f"[week] seoul festivals: {type(e).__name__} {e}")
return []
names = {_name_key(r["name"]) for r in known}
return [r for r in rows if _name_key(r["name"]) not in names]
async def collect_events(sido: str, today: date) -> tuple[ErrorType, dict[str, int]]: async def collect_events(sido: str, today: date) -> tuple[ErrorType, dict[str, int]]:
"""시도 하나의 축제·전시·콘서트를 받아 event 에 넣는다. 종류별 건수를 돌려준다.""" """시도 하나의 축제·전시·콘서트를 받아 event 에 넣는다. 종류별 건수를 돌려준다."""
try: try:
async with httpx.AsyncClient(timeout=30) as client: async with httpx.AsyncClient(timeout=30) as client:
festivals = parse_festivals(await fetch_festivals(client, sido, today), sido) festivals = parse_festivals(await fetch_festivals(client, sido, today), sido)
festivals += await _seoul(client, sido, today, festivals)
exhibitions = await _culture(client, sido, today, EXHIBITION) exhibitions = await _culture(client, sido, today, EXHIBITION)
concerts = await _culture(client, sido, today, CONCERT) concerts = await _culture(client, sido, today, CONCERT)
except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e: except (DataGoKrNotConfigured, DataGoKrRequestFailed) as e:
LOG.error(f"[week] events {sido}: {e}") LOG.error(f"[week] events {sido}: {e}")
return ErrorType.EXTERNAL_API_ERROR, {} return ErrorType.EXTERNAL_API_ERROR, {}
rows = list({r["source_id"]: r for r in festivals + exhibitions + concerts}.values()) rows = await drop_known(list({r["source_id"]: r for r in festivals + exhibitions + concerts}.values()))
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)]) err = await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, rows)])
LOG.info(f"[week] events {sido} {len(rows)}: {err.name}") LOG.info(f"[week] events {sido} {len(rows)}: {err.name}")
return err, {"festival": len(festivals), "exhibition": len(exhibitions), "concert": len(concerts)} return err, {"festival": len(festivals), "exhibition": len(exhibitions), "concert": len(concerts)}
+8
View File
@@ -65,6 +65,14 @@ async def _async(v):
return v return v
@pytest.fixture(autouse=True)
def _no_seoul_crawl(monkeypatch):
"""서울문화포털은 키 없이 바로 긁어 오므로, 테스트가 실제 사이트를 부르지 않게 기본으로 막는다."""
import services.week_service as week_service
monkeypatch.setattr(week_service, "fetch_seoul_festivals", lambda *a: _async([]))
@pytest.fixture @pytest.fixture
def offline(monkeypatch): def offline(monkeypatch):
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다.""" """외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
+10
View File
@@ -28,6 +28,16 @@ def test_parse_popup_maps_store():
} }
def test_parse_popup_maps_festival():
row = parse_popup(_page(504, "FESTIVAL", "2026-10-02", "2026-10-11", "경기 수원시 팔달구 테스트로 1"), 504, date(2026, 10, 1))
assert (row["kind"], row["icon"], row["sido_code"]) == (EventKind.FESTIVAL, "fireworks", "41")
def test_parse_popup_moves_festival_shows_in_theaters_to_concert():
page = _page(505, "FESTIVAL", "2026-10-02", "2026-10-11").replace("테스트 빌딩 1F", "대학로예술극장 소극장")
assert parse_popup(page, 505, date(2026, 10, 1))["kind"] is EventKind.CONCERT
@pytest.mark.parametrize("kind,end,address", [ @pytest.mark.parametrize("kind,end,address", [
("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"), ("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"),
("STORE", "2026-09-30", "서울 성동구 테스트로 1"), ("STORE", "2026-09-30", "서울 성동구 테스트로 1"),
+83
View File
@@ -0,0 +1,83 @@
from datetime import date
import httpx
import pytest
import services.week_service as week_service
from services.external.seoul_culture import LIST_URL, fetch_seoul_festivals, parse_seoul_festivals
from services.week_service import _seoul
ITEM = {
"cultcode": 159216, "title": "[중랑문화재단] 2026 중랑용마폭포축제", "strtdate": "2026-10-10", "endDate": "2026-10-10",
"atchFileId": "abc", "xCoord": "37.5118239", "yCoord": "127.0591590", "facName": "용마폭포공원", "addr": "서울특별시 중랑구",
}
def test_parse_reads_lat_from_x_and_builds_image_and_link():
[row] = parse_seoul_festivals([ITEM, {**ITEM, "cultcode": None}, {**ITEM, "cultcode": 2, "strtdate": ""}])
assert row["source_id"] == "seoul:159216" and row["sido_code"] == "11"
assert (row["lat"], row["lon"]) == (37.51182, 127.05916)
assert row["name"] == "2026 중랑용마폭포축제"
assert row["place_name"] == "용마폭포공원" and row["start_date"] == date(2026, 10, 10)
assert row["image_url"].endswith("atchFileId=abc&thumb=Y") and "cultcode=159216" in row["source_url"]
@pytest.mark.anyio
async def test_fetch_pages_until_empty(monkeypatch):
monkeypatch.setattr("services.external.seoul_culture.REQUEST_GAP_SEC", 0)
pages = []
def handler(req: httpx.Request) -> httpx.Response:
assert str(req.url) == LIST_URL
page = int(dict(x.split("=") for x in req.content.decode().split("&"))["pageIndex"])
pages.append(page)
return httpx.Response(200, json={"resultList": [ITEM] * 10 if page < 3 else []})
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
items = await fetch_seoul_festivals(client, date(2026, 10, 8), 30)
assert len(items) == 20 and pages == [1, 2, 3]
@pytest.mark.anyio
async def test_seoul_skips_festivals_tour_api_already_has_and_other_sidos(monkeypatch):
other = {**ITEM, "cultcode": 2, "title": "2026 서울어텀페스타"}
async def fake(client, since, days):
return [ITEM, other]
monkeypatch.setattr(week_service, "fetch_seoul_festivals", fake)
known = [{"name": "제3회 중랑용마폭포축제"}]
rows = await _seoul(None, "11", date(2026, 10, 8), known)
assert [r["name"] for r in rows] == ["2026 서울어텀페스타"]
assert await _seoul(None, "41", date(2026, 10, 8), known) == []
@pytest.mark.anyio
async def test_seoul_failure_keeps_other_sources(monkeypatch):
async def broken(client, since, days):
raise httpx.ConnectError("down")
monkeypatch.setattr(week_service, "fetch_seoul_festivals", broken)
assert await _seoul(None, "11", date(2026, 10, 8), []) == []
def _row(source_id, name, start, end, sido="11"):
return {"source_id": source_id, "sido_code": sido, "name": name, "place_name": "", "start_date": start, "end_date": end,
"is_confirmed": True, "source_url": None, "image_url": None, "lat": None, "lon": None, "kind": 1, "icon": "fireworks"}
@pytest.mark.anyio
async def test_drop_known_skips_same_festival_from_another_source():
from common.database.db_session_manager import DB_SESSION_MNG
from crud.week_crud import WeekCRUD
from services.week_service import drop_known
tour = _row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 24))
await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, [tour])])
rows = [
_row("popga:1", "2026 경복궁 별빛야행", date(2026, 10, 8), date(2026, 10, 10)),
_row("popga:2", "경복궁 별빛야행", date(2026, 11, 1), date(2026, 11, 2)),
_row("popga:3", "경복궁 별빛야행", date(2026, 10, 8), date(2026, 10, 10), sido="41"),
_row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 25)),
]
assert [r["source_id"] for r in await drop_known(rows)] == ["popga:2", "popga:3", "9001"]
+9 -15
View File
@@ -1,22 +1,22 @@
# 이벤트 추적 (GTM · GA4) # 이벤트 추적 (GA4)
기준: `frontend/index.html`, `frontend/src/lib/analytics.ts`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/region.tsx` (2026-10-08) 기준: `frontend/index.html`, `frontend/src/lib/analytics.ts`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/region.tsx` (2026-10-08)
## 한 줄 요약 ## 한 줄 요약
GTM 컨테이너 `GTM-PKQMKPFC`를 `index.html`에 심고, 화면에서는 `track(이벤트, 값)`으로 `dataLayer`에 이벤트를 넣는다. GTM이 그 이벤트를 받아 GA4로 보낸다. GA4 태그(`gtag.js`, 측정 ID `G-D378J4X373`)를 `index.html`에 심고, 화면에서는 `track(이벤트, 값)`으로 GA4에 이벤트를 바로 보낸다. GTM은 쓰지 않는다.
``` ```
[화면] track('share', {...}) [화면] track('share', {...})
└─ window.dataLayer.push({ event: 'share', ... }) └─ window.gtag('event', 'share', {...}) → GA4
└─ [GTM] 맞춤 이벤트 트리거 → GA4 이벤트 태그 → GA4
``` ```
- 개발 서버(`npm run dev`)에서는 보내지 않는다. 개발 트래픽이 집계에 섞이지 않게. - 왜 GTM이 아니라 GA4 직접인가: 이벤트를 코드(`analytics.ts`)에서 정하므로, GTM을 쓰면 이벤트마다 트리거·태그를 한 번 더 만들어야 한다. 광고 픽셀도, 마케터가 직접 손볼 일도 아직 없다.
- 개발 서버(`npm run dev`)에서는 `track()`이 이벤트를 보내지 않는다. 단 `index.html`의 페이지 조회(`page_view`)는 개발 서버에서도 나가므로 GA4에서 `localhost`를 걸러 본다.
- 이벤트 이름은 영어 snake_case. GA4 추천 이벤트(`share`, `login`, `sign_up`, `select_content`)는 이름을 그대로 써야 GA4 기본 보고서에 잡힌다. - 이벤트 이름은 영어 snake_case. GA4 추천 이벤트(`share`, `login`, `sign_up`, `select_content`)는 이름을 그대로 써야 GA4 기본 보고서에 잡힌다.
- 값은 사람이 읽을 수 있게 한글 그대로 둔다 (예: `gak_name: '야장각'`). - 값은 사람이 읽을 수 있게 한글 그대로 둔다 (예: `gak_name: '야장각'`).
- 개인정보(아이디, 닉네임 등)는 값에 넣지 않는다. - 개인정보(아이디, 닉네임 등)는 값에 넣지 않는다.
- 페이지 이동은 코드로 보내지 않는다. GTM의 "기록 변경(History Change)" 트리거로 잡는다. 모든 이벤트에는 GA4가 `page_location`을 자동으로 붙이므로 어느 탭에서 일어났는지는 따로 보내지 않는다. - 페이지 이동은 코드로 보내지 않는다. GA4 향상된 측정의 "브라우저 기록 이벤트 기반 페이지 변경"이 잡는다(기본 켜짐). 모든 이벤트에 GA4가 `page_location`을 붙이므로 어느 탭에서 일어났는지는 따로 보내지 않는다.
## 이벤트 목록 ## 이벤트 목록
@@ -33,13 +33,7 @@ GTM 컨테이너 `GTM-PKQMKPFC`를 `index.html`에 심고, 화면에서는 `trac
- `region_change`의 `location`은 처음 온 사람의 자동 위치 맞춤도 포함한다. - `region_change`의 `location`은 처음 온 사람의 자동 위치 맞춤도 포함한다.
- 새 이벤트는 `analytics.ts`의 `Events` 타입에 먼저 더한다. 타입에 없는 이름은 빌드에서 걸린다. - 새 이벤트는 `analytics.ts`의 `Events` 타입에 먼저 더한다. 타입에 없는 이름은 빌드에서 걸린다.
## GTM 설정 ## GA4 설정
이벤트마다 아래 두 개를 만든다. - 맞춤 값(`gak_name`, `ratio`, `region_name` 등)으로 보고서를 나눠 보려면 GA4 관리 → 맞춤 정의에서 이벤트 범위 측정기준으로 등록한다. 등록 전 값은 보고서에 소급되지 않는다.
- 확인은 GA4 보고서 → 실시간, 또는 관리 → DebugView에서 한다. 운영 빌드(`docker compose up --build frontend`, http://localhost:8080)나 운영 사이트에서 눌러 본다.
1. **트리거**: 유형 "맞춤 이벤트", 이벤트 이름은 위 표의 이름 (예: `view_gak`).
2. **태그**: 유형 "Google 애널리틱스: GA4 이벤트", 이벤트 이름은 같은 이름. 이벤트 매개변수에 위 표의 값을 하나씩 더하고, 값은 "데이터 영역 변수"(이름은 값 키 그대로, 예: `gak_name`)로 넣는다.
GA4 보고서에서 맞춤 값(`gak_name`, `ratio`, `region_name` 등)으로 나눠 보려면 GA4 관리 → 맞춤 정의에서 이벤트 범위 측정기준으로 등록한다.
확인은 GTM 미리보기 모드에서 운영 빌드(`docker compose up --build frontend`, http://localhost:8080)를 열어 한다.
+9 -11
View File
@@ -1,13 +1,15 @@
<!doctype html> <!doctype html>
<html lang="ko"> <html lang="ko">
<head> <head>
<!-- Google Tag Manager --> <!-- Google tag (gtag.js) -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': <script async src="https://www.googletagmanager.com/gtag/js?id=G-D378J4X373"></script>
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], <script>
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= window.dataLayer = window.dataLayer || [];
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); function gtag(){dataLayer.push(arguments);}
})(window,document,'script','dataLayer','GTM-PKQMKPFC');</script> gtag('js', new Date());
<!-- End Google Tag Manager -->
gtag('config', 'G-D378J4X373');
</script>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" /> <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
@@ -38,10 +40,6 @@
/> />
</head> </head>
<body> <body>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-PKQMKPFC"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<div id="root"></div> <div id="root"></div>
<script type="module" src="/src/main.tsx"></script> <script type="module" src="/src/main.tsx"></script>
</body> </body>
+3 -4
View File
@@ -1,4 +1,4 @@
/** GTM으로 보내는 이벤트와 값. 목록과 GTM 설정은 docs/이벤트_추적.md */ /** GA4로 보내는 이벤트와 값. 목록은 docs/이벤트_추적.md */
type Events = { type Events = {
view_gak: { index_id: number; gak_name: string; score: number; rank: number } view_gak: { index_id: number; gak_name: string; score: number; rank: number }
select_content: { content_type: 'article'; item_id: number; category: string } select_content: { content_type: 'article'; item_id: number; category: string }
@@ -10,12 +10,11 @@ type Events = {
declare global { declare global {
interface Window { interface Window {
dataLayer?: Record<string, unknown>[] gtag?: (command: 'event', name: string, params: Record<string, unknown>) => void
} }
} }
export function track<E extends keyof Events>(event: E, params: Events[E]) { export function track<E extends keyof Events>(event: E, params: Events[E]) {
if (import.meta.env.DEV) return if (import.meta.env.DEV) return
window.dataLayer ??= [] window.gtag?.('event', event, params)
window.dataLayer.push({ event, ...params })
} }