[refactor] postgres-init,solution: DB 구조 재편 — 스키마 해체 · 공용 콘텐츠 한 벌 · 마이그레이션 체계

도메인별 스키마(company·place·fact·local·site·job)를 걷어내고 public 한 벌로 폈다.
스키마 한정자가 붙은 순간부터 ORM·raw SQL·테스트 픽스처가 각자 그 이름을 들고 다녀야 했다.

- 공용 콘텐츠를 한 테이블로 되돌린다. spots·region_stories 를 따로 파 놓고 보니
  같은 성격이 세 곳으로 갈라져 있었다 — `area_contents` 가 처음부터 content_type 으로
  종류를 가르는 설계였고 그걸 쓰면 됐다. 관계(거리·숨김)만 `place_area_refs` 로 남긴다.
- migrations/ + scripts/migrate.py: `init.sql` 은 **DB 를 처음 만들 때만** 돈다. 파일에
  컬럼을 더해도 이미 데이터가 든 DB 에는 반영되지 않는다 — 실제로 TourAPI 가 주변 정보를
  받아 와도 저장할 곳이 없어 축제·맛집이 0건이었고, 화면에는 "그냥 안 나오는 것" 으로만 보였다.
  DECISIONS.md 가 예고한 그대로다("운영 DB 가 생기는 순간 다시 필요해진다").
  Alembic 을 쓰지 않는 이유는 스키마 정의가 이미 두 곳(ORM·init.sql)이라 세 번째를
  더하면 어긋날 자리가 하나 더 생기기 때문이다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
minaChoiandClaude Opus 5 committed 2026-09-09 17:08:02 +09:00
1 parent 7bbeb068a8
commit 64ce467f21
189 files changed
+13374 -5023

No files matched your search

+113 -14
View File
@@ -31,6 +31,7 @@ from common.enums import (
SourceType,
)
from common.logger import LOG
from services.itinerary import build_itineraries
# 렌더러가 확인하는 스키마 버전. 모양이 바뀌면 여기와 site-payload.ts 를 같이 올린다.
SCHEMA_VERSION = 1
@@ -65,6 +66,26 @@ _CHANNEL_TITLE = {
LinkChannel.ETC.value: "기타 채널",
}
# 저장된 look 이 없을 때 쓰는 기본 생김새 — 에디터의 '심플' 템플릿
# (`solution/frontend/src/data/industryData.ts` 의 LOOK.simple)과 같은 값이다.
# ★ 왜 필요한가 (실측 2026-09-08, `/s/stay-mumum-gunsan`)
# 이 키가 없으면 `<head>` 에 --tpl-font-heading·--tpl-radius·--tpl-texture 가 아예
# 안 실리고, 발행본은 렌더러 CSS 의 폴백으로 떨어진다. 그 폴백의 제목 서체는
# `--font-serif`(명조)다 — 그래서 위저드를 안 돈 사업장의 발행본만 제목이 명조로,
# 모서리는 렌더러 기본값으로 나가 에디터 미리보기(고딕)와 눈에 띄게 갈렸다.
# 색은 업종 기본이 있는데 생김새만 없어서 생긴 구멍이라, 고르지 않았을 때의 모습도 정해 둔다.
_DEFAULT_LOOK = {
"fontHeading": "'Pretendard Variable', 'Noto Sans KR', system-ui, sans-serif",
"fontBody": "'Pretendard Variable', 'Noto Sans KR', system-ui, sans-serif",
"radius": "0.75rem",
"borderWidth": "1px",
"shadow": "0 1px 2px rgb(0 0 0 / 0.06)",
"headingTracking": "-0.02em",
"headingWeight": "700",
"sectionSpace": "4rem",
}
# 업종별 **기본 디자인**. 사장님이 아직 아무것도 고르지 않았을 때 쓰는 폴백이다.
# ★ 이제 여섯 가지가 모두 저장되는 자리를 갖는다:
# templateId ← sites.template_id (POST /v1/place/{id}/site/template)
@@ -84,11 +105,22 @@ _DEFAULT_THEME = {
"fontStyle": "Modern Editorial",
"colors": {"primary": "#18181b", "secondary": "#52525b", "bg": "#ffffff",
"card": "#fafafa", "text": "#09090b", "accent": "#2563eb"},
# ★ 순서·구성이 시안(/s/stay)과 같다. 여기가 시안보다 적으면 새로 만든 사업장은
# 수집이 다 됐어도 그 섹션이 아예 안 나온다 — 저장값이 없는 사업장에는 이 표가 곧 발행본이다.
# ★ "이용 규정"은 뺐다 (2026-09-09) — 발행본에 그 섹션이 없다. 체크인·취소·취사·
# 반려동물 줄은 기본 정보 안에서 규정 덩이로 묶여 나간다(EssentialInfoSection).
# ★ 가요·인물·연표·엽서·퀴즈는 여기 넣지 않는다. 이 표의 항목은 전부 켜서 나가는데
# (`_sections`), 그것들은 '지역 이야기'(story) 탭 **안에서** 그려지는 것이라
# 켜면 탭 밖에 한 번 더 선다. story 하나만 두면 데이터가 있는 것만 탭이 된다.
"sections": [
("hero", "히어로", True), ("intro", "소개", False), ("rooms", "객실 안내", False),
("info", "기본 정보", True), ("rules", "이용 규정", False), ("booking", "예약 안내", False),
("photos", "사진 갤러리", False), ("map", "오시는 길", True), ("weather", "날씨", False),
("local", "지역 정보", False), ("faq", "자주 묻는 질문", False),
("event", "소식", False),
("info", "기본 정보", True), ("booking", "예약 안내", False),
("video", "영상", False),
("photos", "사진 갤러리", False), ("map", "오시는 길", True),
("festival", "계절별 축제", False), ("local", "지역 정보", False),
("itinerary", "추천 일정", False), ("story", "지역 이야기", False),
("faq", "자주 묻는 질문", False), ("weather", "날씨", False),
],
},
PlaceCategory.CAFE.value: {
@@ -313,9 +345,15 @@ def _theme(site, theme_spec: dict) -> dict:
# ★ 템플릿의 생김새(서체·모서리·테두리·그림자·여백). 색과 달리 업종 기본이 없다 —
# 프론트가 소유하는 값이라 서버가 지어낼 수 없고, 없으면 렌더러가 자기 기본 서체로 떨어진다.
# 이걸 안 실으면 발행본은 색만 템플릿을 따르고 서체는 늘 같은 것으로 나간다.
# 저장된 look 이 있으면 그게 이긴다. 다만 **덮어쓰기가 아니라 덧칠이다** — 프론트가
# 일부 키만 보낸 옛 저장값에 빈칸이 생기면 그 칸만 명조·렌더러 기본값으로 떨어진다.
look = saved.get("look")
if isinstance(look, dict) and look:
out["look"] = {k: v for k, v in look.items() if isinstance(v, str) and v.strip()}
cleaned = (
{k: v for k, v in look.items() if isinstance(v, str) and v.strip()}
if isinstance(look, dict)
else {}
)
out["look"] = {**_DEFAULT_LOOK, **cleaned}
return out
@@ -477,32 +515,77 @@ def _festival(row: dict):
# 공식 홈페이지는 출처가 준 값일 때만 싣는다. 형식이 URL 이 아니면 링크로 걸지 않는다.
if homepage.startswith("http://") or homepage.startswith("https://"):
entry["officialUrl"] = homepage
# 업장 반경 캐시(place_contents)에서 온 축제는 거리·사진도 있다 — 카드 캐러셀이 맛집·명소와
# 같은 모양으로 그리려면 필요하다(2026-09-07, 도보 시간 필터 형식 결정).
_put_distance(entry, body)
image = _text(body.get("firstimage"))
if image:
entry["imageUrl"] = image
return entry
def _local_place(row: dict, category: str):
"""LocalPlace(주변 명소·맛집).
★ title 컬럼만 믿는다. 이 두 종류(ATTRACTION·RESTAURANT)를 채우는 수집기가 아직 없어서
body 의 모양이 정해지지 않았다 — 있지도 않은 키를 가정해 파싱하면 수집기가 붙는 날
조용히 빈 값이 나간다. 지금은 테이블 스키마가 보장하는 것(title)만 쓰고,
설명·거리는 실제 수집기가 붙을 때 그 모양을 보고 채운다."""
body 는 TourAPI 수집기가 채운다(services/external/tour_api._normalize) —
주소(addr1)가 있으면 위치로 싣는다. 없는 값은 만들지 않는다."""
name = _text(row.get("title"))
if not name:
return None
return {"name": name, "category": category, "searchQuery": name}
body = row.get("body") or {}
entry = {"name": name, "category": category, "searchQuery": name}
location = _text(body.get("addr1"))
if location:
entry["location"] = location
# 거리는 수집 시점에 업장 좌표로 잰 값(place_contents.distance_m). 지역 캐시 항목엔 없다.
# ★ 숫자(distanceMeters)도 함께 싣는다 — 화면이 도보 시간 필터(분속 80m 환산)를 계산하려면
# "1.2km" 같은 문자열을 다시 파싱하는 것보다 원값이 안전하다.
_put_distance(entry, body)
image = _text(body.get("firstimage"))
if image:
entry["imageUrl"] = image
return entry
def _local(snapshot_local: dict) -> tuple[dict, str | None]:
def _put_distance(entry: dict, body: dict) -> None:
"""distance_m → distanceText("850m") + distanceMeters(850). 값이 없거나 음수면 둘 다 넣지 않는다."""
distance = _distance_text(body.get("distance_m"))
if not distance:
return
entry["distanceText"] = distance
entry["distanceMeters"] = int(body.get("distance_m"))
def _distance_text(meters) -> str:
"""850 → "850m", 1234 → "1.2km". 없으면 빈 문자열."""
try:
m = int(meters)
except (TypeError, ValueError):
return ""
if m < 0:
return ""
if m < 1000:
return f"{m}m"
# 반올림은 '5 는 올림'으로 — f"{1.45:.1f}" 는 부동소수 탓에 1.4 가 나온다.
return f"{(m + 50) // 100 / 10:.1f}km"
def _local(snapshot_local: dict, base_lat: float | None, base_lng: float | None) -> tuple[dict, str | None]:
"""스냅샷의 지역 정보 → LocalContents.
★ 스냅샷이 이미 걸렀다(PUBLISHED + 노출 기간 안). 여기서 더 거르지 않고 모양만 바꾼다 —
fact·사진과 같은 분업이다.
★ 예전에는 이 자리가 무조건 빈 배열이었다. local_contents 에 검수·발행된 지역 정보가 있어도
payload 경계에서 통째로 버려져, 모든 발행 사이트의 지역 정보 섹션이 영구히 안 나왔다."""
payload 경계에서 통째로 버려져, 모든 발행 사이트의 지역 정보 섹션이 영구히 안 나왔다.
★ itineraries(1박2일·2박3일 일정)는 저장하지 않고 여기서 즉석 계산한다 —
재료가 갱신되면 다음 빌드에서 일정도 저절로 최신이 된다(services/itinerary.py).
렌더러에 아직 이 필드의 자리가 없다 — 모르는 필드는 무시되므로 화면은 변하지 않는다."""
contents = (snapshot_local or {}).get("contents") or []
local = {"attractions": [], "restaurants": [], "festivals": []}
# courses(여행코스)는 백엔드만 채운다 — 렌더러 타입에 아직 자리가 없어 화면은 무시한다(2026-09-07).
local = {"attractions": [], "restaurants": [], "festivals": [], "courses": []}
synced_at = None
# 일정 계산용 원본 행(좌표가 body 에 있다). payload 항목은 좌표를 싣지 않으므로 따로 모은다.
raw = {"attractions": [], "restaurants": [], "festivals": []}
for row in contents:
if not isinstance(row, dict):
@@ -523,16 +606,29 @@ def _local(snapshot_local: dict) -> tuple[dict, str | None]:
entry = _festival(row)
if entry:
local["festivals"].append(entry)
raw["festivals"].append(row)
elif content_type == LocalContentType.ATTRACTION.value:
entry = _local_place(row, "관광지")
if entry:
local["attractions"].append(entry)
raw["attractions"].append(row)
elif content_type == LocalContentType.RESTAURANT.value:
entry = _local_place(row, "맛집")
if entry:
local["restaurants"].append(entry)
raw["restaurants"].append(row)
elif content_type == LocalContentType.COURSE.value:
entry = _local_place(row, "여행코스")
if entry:
local["courses"].append(entry)
# 그 밖의 content_type 은 버린다 — 렌더러 타입에 담을 자리가 없다.
itineraries = build_itineraries(
base_lat, base_lng, raw["attractions"], raw["restaurants"], raw["festivals"]
)
if itineraries:
local["itineraries"] = itineraries
return local, synced_at
@@ -708,7 +804,10 @@ def to_site_payload(place, snapshot: dict, site, version, links) -> dict:
# ★ 스냅샷에서 읽는다 — 여기서 DB 를 다시 읽으면 '스냅샷과 다른 페이지'가 나온다(파일 상단 원칙).
# 지역 정보를 스냅샷에 담는 필터링은 services/snapshot._local_contents 가 한다.
# 옛 스냅샷에는 "local" 키가 없다. 그때는 빈 채로 나가고, 다음 빌드에서 채워진다.
local, local_synced_at = _local(snapshot.get("local") or {})
local, local_synced_at = _local(
snapshot.get("local") or {},
_as_float(snap_place.get("latitude")), _as_float(snap_place.get("longitude")),
)
if local_synced_at:
local["syncedAt"] = local_synced_at