최상단을 프로젝트 단위로 평평하게 둔다 — o2o-negosium 과 같은 규약이고, 이 레포만
다르게 갈 이유가 없다. negodata/{backend,front} 가 프로젝트 안에서 f/b 를 가르는 선례,
lps-admin/ 이 백엔드 없이 프론트만 가진 최상단 폴더의 선례다.
backend/ frontend/{admin,site,shared} → solution/{backend,front,site,shared} + admin/
## 왜
내부 라우트(/local-content, /places/:id/seo)의 이름과 화면 코드가 사장님 번들에
그대로 실려 나가고 있었다. UserRole.DEVELOPER 주석의 "고객사에 존재를 노출하지 않는다"를
번들이 깨고 있었다 — 라우트 가드는 화면을 가리지 번들은 못 가린다.
번들을 갈라 확인했다: 사장님 dist 에서 local-content · /places · SeoAudit 이 전부 0건이다.
그 과정에서 두 곳이 더 새고 있었다.
- AppShell 의 NAV 배열이 내부 메뉴를 하드코딩하고 있었다. 앱을 가른 뒤에도 dist 에
local-content 가 남아서 찾았다. 메뉴는 이제 앱이 prop 으로 들고 온다.
- EditorHeader·BuilderPage·LoginPage 가 /places 로 링크하고 있었다. 그 화면이 admin 으로
나갔으니 사장님 앱에서는 404 다. 링크를 걷어내고 LoginPage 기본 도착지는 '/' 로 바꿨다
(앱마다 홈이 다르고 각 라우터의 '/' 가 이미 그걸 안다).
## admin 에 백엔드를 두지 않았다
내부 화면이 부르는 훅이 전부 router/v1/{place,fact,local,validator} 에 이미 있다.
자체 백엔드를 두면 place·fact·link 를 같은 DB 에 대고 두 번 구현하게 된다.
대가는 solution/backend 가 죽으면 admin 도 멈추는 것 — 내부 도구라 감수한다.
## admin 의 `@` 는 solution/front/src 를 가리킨다
내부 화면이 쓰는 API 클라이언트·UI·수집 배선이 solution 에 한 벌만 있고 그 파일들끼리도
`@/...` 로 서로를 부른다. admin 에서 `@` 를 자기 src 로 잡으면 그 참조가 전부 깨진다
(실측 TS2307 14건). 복제하는 길도 있지만 RecollectPanel 주석이 금지한다 —
"수집 경로를 두 벌 만들면 확정 게이트"가 갈라진다.
admin 자기 파일만 `@admin` 이고, 의존 방향은 admin → solution 한 쪽뿐이다.
admin 이 여는 빌더는 다른 오리진이라 절대 URL + 새 탭이다(admin/src/lib/solutionUrl.ts).
react-router Link 로 두면 admin 안에서 라우트를 찾다 404 다.
## 그 밖
- npm 워크스페이스 루트를 레포 루트로 올렸다(admin 이 solution 밖이라).
- docker-compose 를 255→174줄로 줄이고 admin(:3002) 서비스를 넣었다. ADMIN_BIND 기본값은
127.0.0.1 — 0.0.0.0 으로 열면 앱을 가른 의미가 없다.
- 발행 호스트를 프론트 .env 에 따로 적지 않는다. compose 가 루트의 SITE_PUBLIC_HOST 를
VITE_PUBLISH_HOST 로 흘려보낸다 — 두 곳에 적으면 canonical 과 화면 주소가 조용히 갈라진다.
- nginx/site.conf 를 git 에서 빼고 .example 만 남겼다(.env·*.toml 과 같은 규약).
compose 가 bind mount 하므로 클론 직후 복사해야 한다 — 없으면 Docker 가 그 자리에
디렉토리를 만들어 nginx 가 설정 없이 뜬다.
- config.test.toml.example 을 추가했다. 없으면 클론한 사람이 pytest 를 아예 못 돌린다
(conftest import 단계에서 죽는다). 외부 API 키는 전부 빈값이다 —
APP_ENV=test 가 .env 를 안 읽는 이유를 여기서 우회하면 안 된다.
- 경로가 한 칸 깊어져 test_schema_ddl(parents[2]→[3]) 과 test_site_theme 을 고쳤다.
검증: front·admin·site 전부 lint 0 / build 0. 백엔드 514 passed.
남은 4건(test_build_publish 3 · test_snapshot 1)은 이 변경 전부터 실패하던 것으로,
손대지 않은 메인 체크아웃에서 같은 4건이 같게 실패하는 것을 확인했다.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019uYhHQdssRubirPirrdJJC
298 lines
16 KiB
Python
298 lines
16 KiB
Python
"""디자인(색·서체·섹션) 저장과 발행 payload 반영.
|
|
|
|
이 경로가 절대 하면 안 되는 것:
|
|
- 고른 디자인을 브라우저에만 두는 것 — 발행 잡이 읽을 곳이 없어 업종 기본 모양으로 굽는다.
|
|
사장님이 섹션을 끄고 순서를 바꿔도 발행본이 안 바뀌던 것이 이 API 가 생긴 이유다.
|
|
- ★ 잠긴 섹션(SEO·필수 마크업)을 끈 채로 내보내는 것 — 끄기로도, 목록에서 빼기로도 막아야 한다.
|
|
한쪽만 막으면 "끄는 대신 빼면 그만"이라 잠금이 무의미해진다.
|
|
- 저장값을 서버가 해석하는 것 — 섹션 목록·배리에이션 키는 프론트가 소유한다.
|
|
화이트리스트를 두면 프론트에 항목 하나 늘 때마다 백엔드를 같이 고쳐야 한다.
|
|
- templateId 를 theme 안에 같이 보관하는 것 — sites.template_id 와 갈린다.
|
|
"""
|
|
import uuid
|
|
|
|
import pytest
|
|
|
|
import pathlib
|
|
import re
|
|
|
|
from sqlalchemy import text
|
|
|
|
from common.enums import ErrorType, PlaceCategory, SiteStatus
|
|
from services.site_payload import _DEFAULT_THEME, to_site_payload
|
|
|
|
# 계약 그대로의 최소 테마. 배열 순서가 곧 섹션 순서다(별도 order 필드가 없다).
|
|
_THEME = {
|
|
"colors": {"accent": "#c2410c"},
|
|
"fontStyle": "Warm Serif",
|
|
"colorPaletteId": "warm-sand",
|
|
"sections": [
|
|
{"id": "faq", "name": "자주 묻는 질문", "enabled": True, "locked": False, "variantId": "faq.two-column"},
|
|
{"id": "hero", "name": "우리 히어로", "enabled": True, "locked": True},
|
|
{"id": "rooms", "name": "객실 안내", "enabled": False, "locked": False},
|
|
],
|
|
}
|
|
|
|
|
|
async def _place(client, headers, name="테마펜션"):
|
|
r = await client.post("/v1/place", headers=headers, json={"name": name, "category": 1})
|
|
return r.json()["place"]["place_id"]
|
|
|
|
|
|
async def _set_theme(client, headers, pid, theme):
|
|
return (await client.post(f"/v1/place/{pid}/site/theme", headers=headers, json={"theme": theme})).json()
|
|
|
|
|
|
async def _get_site(client, headers, pid):
|
|
return (await client.get(f"/v1/place/{pid}/site", headers=headers)).json()
|
|
|
|
|
|
async def test_set_theme_creates_site_row_and_round_trips(auth_headers, client):
|
|
"""검증: 사이트 행이 없어도 디자인을 먼저 고를 수 있고, 저장한 모양 그대로 다시 읽힌다.
|
|
기대결과: SUCCESS + 조회 응답의 site.theme 가 보낸 것과 같다.
|
|
★ 다시 읽히지 않으면 저장은 됐는데 에디터는 기본값으로 돌아간다."""
|
|
h = await auth_headers("thm1")
|
|
pid = await _place(client, h)
|
|
|
|
saved = await _set_theme(client, h, pid, _THEME)
|
|
assert saved["result"]["code"] == ErrorType.SUCCESS.value
|
|
assert saved["site"]["theme"] == _THEME
|
|
|
|
assert (await _get_site(client, h, pid))["site"]["theme"] == _THEME
|
|
|
|
|
|
async def test_unknown_sections_and_variants_are_accepted(auth_headers, client):
|
|
"""검증: ★ 서버는 값을 해석하지 않는다 — 섹션 목록·배리에이션 키는 프론트가 소유한다.
|
|
기대결과: 백엔드가 처음 보는 섹션 id 와 배리에이션 키도 그대로 저장된다."""
|
|
h = await auth_headers("thm2")
|
|
pid = await _place(client, h)
|
|
|
|
theme = {"sections": [{"id": "brand-new-section", "name": "신규", "enabled": True,
|
|
"locked": False, "variantId": "nobody.knows"}]}
|
|
saved = await _set_theme(client, h, pid, theme)
|
|
assert saved["result"]["code"] == ErrorType.SUCCESS.value
|
|
assert saved["site"]["theme"]["sections"][0]["variantId"] == "nobody.knows"
|
|
|
|
|
|
async def test_oversized_theme_is_refused(auth_headers, client):
|
|
"""검증: 해석하지 않는 값이라 크기만은 막는다 — 안 막으면 jsonb 하나가 DB 와 스냅샷을 부풀린다.
|
|
기대결과: INVALID_REQUEST_DATA."""
|
|
h = await auth_headers("thm3")
|
|
pid = await _place(client, h)
|
|
|
|
refused = await _set_theme(client, h, pid, {"fontStyle": "x" * 70_000})
|
|
assert refused["result"]["code"] == ErrorType.INVALID_REQUEST_DATA.value
|
|
assert "site" not in refused
|
|
|
|
|
|
async def test_template_id_is_not_stored_inside_theme(auth_headers, client):
|
|
"""검증: templateId 는 sites.template_id 컬럼이 소유한다.
|
|
기대결과: theme 안에 실려 와도 저장되지 않는다 — 두 곳에 두면 어느 쪽이 진짜인지 갈린다."""
|
|
h = await auth_headers("thm4")
|
|
pid = await _place(client, h)
|
|
|
|
saved = await _set_theme(client, h, pid, {"templateId": "sneaky", "fontStyle": "폰트"})
|
|
assert saved["result"]["code"] == ErrorType.SUCCESS.value
|
|
assert "templateId" not in saved["site"]["theme"]
|
|
assert saved["site"]["theme"]["fontStyle"] == "폰트"
|
|
|
|
|
|
async def test_empty_theme_clears_to_default(auth_headers, client):
|
|
"""검증: 빈 값은 '고르지 않음'이다 — NULL 로 되돌아가 업종 기본으로 떨어진다.
|
|
기대결과: 저장 후 {} 를 보내면 theme 가 응답에서 사라진다(None)."""
|
|
h = await auth_headers("thm5")
|
|
pid = await _place(client, h)
|
|
await _set_theme(client, h, pid, _THEME)
|
|
|
|
cleared = await _set_theme(client, h, pid, {})
|
|
assert cleared["result"]["code"] == ErrorType.SUCCESS.value
|
|
# RemoveNoneResponse 가 None 필드를 지운다 — 키가 없으면 NULL 이다.
|
|
assert "theme" not in cleared["site"]
|
|
|
|
|
|
async def test_published_site_theme_is_not_locked(auth_headers, client, db_engine):
|
|
"""검증: ★ 발행된 사이트도 디자인은 바꿀 수 있다(주소와 다르다 — URL 이 그대로라 색인이 안 깨진다).
|
|
기대결과: SUCCESS + 재빌드 필요 표시(needs_rebuild)."""
|
|
h = await auth_headers("thm6")
|
|
pid = await _place(client, h)
|
|
await _set_theme(client, h, pid, _THEME)
|
|
|
|
async with db_engine.begin() as conn:
|
|
await conn.execute(
|
|
text("UPDATE sites SET status = :st, published_at = now() WHERE place_id = :p"),
|
|
{"st": SiteStatus.PUBLISHED.value, "p": uuid.UUID(pid)},
|
|
)
|
|
|
|
changed = await _set_theme(client, h, pid, {**_THEME, "fontStyle": "다른서체"})
|
|
assert changed["result"]["code"] == ErrorType.SUCCESS.value
|
|
# 나가 있는 페이지와 달라졌으므로 이 사업장만 다시 빌드하면 된다는 표시가 서야 한다.
|
|
assert changed["needs_rebuild"] is True
|
|
|
|
|
|
async def test_other_company_place_is_blocked(auth_headers, client, other_company_id):
|
|
"""검증: 남의 회사 사업장의 디자인은 바꿀 수 없다.
|
|
기대결과: PLACE_NOT_FOUND(존재 여부조차 알려주지 않는다)."""
|
|
h = await auth_headers("thm7")
|
|
intruder = await auth_headers("thm8", other_company_id)
|
|
pid = await _place(client, h)
|
|
|
|
assert (await _set_theme(client, intruder, pid, _THEME))["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value
|
|
|
|
|
|
# ── payload 반영(순수 변환) ───────────────────────────────────────────────
|
|
_PLACE = {"place_id": uuid.uuid4(), "category": PlaceCategory.LODGING.value, "name": "테마펜션"}
|
|
_SNAPSHOT = {"place": {"name": "테마펜션", "category": PlaceCategory.LODGING.value}}
|
|
_VERSION = {"version": 1}
|
|
|
|
|
|
def _payload_theme(theme):
|
|
return to_site_payload(_PLACE, _SNAPSHOT, {"template_id": None, "theme": theme}, _VERSION, [])["theme"]
|
|
|
|
|
|
def test_payload_without_saved_theme_falls_back_to_category_default():
|
|
"""검증: 저장된 디자인이 없을 때.
|
|
기대결과: 업종 기본 색·서체·섹션 그대로 — 고르지 않은 값을 고른 것처럼 굽지 않는다."""
|
|
spec = _DEFAULT_THEME[PlaceCategory.LODGING.value]
|
|
theme = _payload_theme(None)
|
|
|
|
assert theme["fontStyle"] == spec["fontStyle"]
|
|
assert theme["colors"] == spec["colors"]
|
|
assert [s["id"] for s in theme["sections"]] == [sid for sid, _, _ in spec["sections"]]
|
|
assert all(s["enabled"] for s in theme["sections"])
|
|
|
|
|
|
def test_payload_follows_saved_order_and_toggles():
|
|
"""검증: 저장된 배열 순서와 on/off 가 발행본에 그대로 간다.
|
|
기대결과: 저장 순서대로 앞자리를 채우고, 끈 섹션은 꺼진 채로 나간다.
|
|
★ 예전엔 enabled 가 True 로 박혀 있어 끈 섹션이 그대로 발행됐다."""
|
|
theme = _payload_theme(_THEME)
|
|
assert [s["id"] for s in theme["sections"]][:3] == ["faq", "hero", "rooms"]
|
|
assert next(s for s in theme["sections"] if s["id"] == "rooms")["enabled"] is False
|
|
|
|
|
|
def test_payload_carries_variant_id_only_when_chosen():
|
|
"""검증: 배리에이션은 그대로 싣되, 고르지 않았으면 키 자체를 붙이지 않는다.
|
|
기대결과: 고른 섹션엔 variantId, 안 고른 섹션엔 키 없음
|
|
(null 을 실으면 렌더러 타입과 안 맞고, 비면 렌더러가 기본 레이아웃으로 떨어진다)."""
|
|
theme = _payload_theme(_THEME)
|
|
assert next(s for s in theme["sections"] if s["id"] == "faq")["variantId"] == "faq.two-column"
|
|
assert "variantId" not in next(s for s in theme["sections"] if s["id"] == "hero")
|
|
|
|
|
|
def test_locked_section_cannot_be_published_disabled():
|
|
"""검증: ★ 잠긴 섹션을 껐다고 저장한 경우.
|
|
기대결과: 켜서 내보낸다 — SEO·필수 마크업 때문에 잠긴 것이라 꺼진 채로 나갈 수 없다.
|
|
★ 저장값의 locked:false 도 믿지 않는다. 믿으면 클라이언트가 locked 를 내려 보내는 것만으로
|
|
필수 섹션을 끌 수 있어 잠금 자체가 무의미해진다."""
|
|
theme = _payload_theme({"sections": [{"id": "hero", "name": "히어로", "enabled": False, "locked": False}]})
|
|
hero = next(s for s in theme["sections"] if s["id"] == "hero")
|
|
assert hero["enabled"] is True and hero["locked"] is True
|
|
|
|
|
|
def test_locked_section_omitted_from_saved_list_comes_back_enabled():
|
|
"""검증: ★ 잠긴 섹션을 아예 목록에서 뺀 경우.
|
|
기대결과: 끝에 켜서 덧붙는다 — 끄기만 막고 빼기를 통과시키면
|
|
"끄는 대신 빼면 그만"이라 위 규칙이 그대로 뚫린다."""
|
|
theme = _payload_theme({"sections": [{"id": "faq", "name": "FAQ", "enabled": True, "locked": False}]})
|
|
for sid in ("hero", "info", "map"):
|
|
entry = next(s for s in theme["sections"] if s["id"] == sid)
|
|
assert entry["locked"] is True and entry["enabled"] is True, sid
|
|
|
|
|
|
def test_section_missing_from_saved_list_comes_back_enabled():
|
|
"""검증: 저장값에 없는 기본 섹션(= 나중에 추가한 섹션).
|
|
기대결과: ★ 끝에 **켜서** 덧붙는다.
|
|
|
|
에디터에는 섹션을 빼는 기능이 없다(toggleSection·reorderSection 뿐).
|
|
그래서 저장값에 없다는 건 "사장님이 뺐다"가 아니라 "저장할 당시 그 섹션이 없었다"는 뜻이다.
|
|
꺼서 붙이면 새로 만든 섹션이 기존 사업장에 영원히 안 나온다 — 에디터에는 보이는데
|
|
발행본에는 없는 상태가 된다(실측: 날씨 섹션이 그렇게 빠져 있었다)."""
|
|
theme = _payload_theme({"sections": [{"id": "faq", "name": "FAQ", "enabled": True, "locked": False}]})
|
|
photos = next(s for s in theme["sections"] if s["id"] == "photos")
|
|
assert photos["enabled"] is True
|
|
# 저장값에 있던 섹션이 앞, 새로 붙은 섹션이 뒤 — 순서는 사장님이 정한 것이 이긴다.
|
|
ids = [s["id"] for s in theme["sections"]]
|
|
assert ids[0] == "faq"
|
|
|
|
|
|
def test_owner_disabled_section_stays_disabled():
|
|
"""검증: 사장님이 **끈** 섹션(목록에는 있고 enabled=False).
|
|
기대결과: 꺼진 채로 나간다 — 위 규칙이 "끈 것"까지 켜버리면 안 된다."""
|
|
theme = _payload_theme({"sections": [{"id": "photos", "name": "사진", "enabled": False, "locked": False}]})
|
|
assert next(s for s in theme["sections"] if s["id"] == "photos")["enabled"] is False
|
|
|
|
|
|
def test_partial_colors_are_filled_from_category_default():
|
|
"""검증: 저장된 색이 일부 키만 담고 있을 때.
|
|
기대결과: 빠진 자리는 업종 기본이 메운다 — 렌더러 타입이 6개를 모두 요구하므로
|
|
일부만 실으면 나머지 색이 undefined 로 나가 화면이 깨진다."""
|
|
spec = _DEFAULT_THEME[PlaceCategory.LODGING.value]
|
|
colors = _payload_theme({"colors": {"accent": "#c2410c"}})["colors"]
|
|
assert colors["accent"] == "#c2410c"
|
|
assert colors["bg"] == spec["colors"]["bg"]
|
|
assert set(colors) == set(spec["colors"])
|
|
|
|
|
|
def test_color_palette_id_never_reaches_the_payload():
|
|
"""검증: colorPaletteId 는 에디터 복원 전용이다.
|
|
기대결과: 저장·반환은 되지만 발행 payload 의 theme 에는 없다 —
|
|
발행 계약(SitePayload.SiteTheme)에 없는 필드를 흘리지 않는다."""
|
|
assert "colorPaletteId" not in _payload_theme(_THEME)
|
|
|
|
|
|
def test_saved_theme_does_not_override_chosen_template():
|
|
"""검증: templateId 의 출처.
|
|
기대결과: 언제나 sites.template_id 다 — theme 는 색·서체·섹션만 담당한다."""
|
|
payload = to_site_payload(
|
|
_PLACE, _SNAPSHOT, {"template_id": "stay-quiet-margin", "theme": _THEME}, _VERSION, []
|
|
)
|
|
assert payload["theme"]["templateId"] == "stay-quiet-margin"
|
|
|
|
|
|
# ── 에디터 기본 섹션표와의 1:1 대조 ────────────────────────────────────────
|
|
# ★ 이 두 표가 어긋나면 발행본에서 섹션이 통째로 사라진다. 저장된 테마가 없는 사업장
|
|
# (위저드만 돌고 [디자인] 탭을 건드리지 않은 대부분)은 _DEFAULT_THEME 이 곧 발행본이라,
|
|
# 여기에 없는 섹션은 사장님이 에디터에서 아무리 봐도 사이트에 나오지 않는다.
|
|
# 실측으로 날씨·실시간 예약·대관 문의·관람 안내가 그렇게 빠져 있었다.
|
|
_ADMIN_SECTIONS_TS = (
|
|
pathlib.Path(__file__).resolve().parents[2] / "front/src/data/industryData.ts" # parents[2] = solution/
|
|
)
|
|
|
|
# 에디터 업종 키 → PlaceCategory. 이름이 다른 건 두 층의 어휘가 달라서다(tour vs TOUR_ACTIVITY).
|
|
_INDUSTRY_TO_CATEGORY = {
|
|
"stay": PlaceCategory.LODGING.value,
|
|
"cafe": PlaceCategory.CAFE.value,
|
|
"restaurant": PlaceCategory.RESTAURANT.value,
|
|
"tour": PlaceCategory.TOUR_ACTIVITY.value,
|
|
}
|
|
|
|
|
|
def _editor_sections() -> dict[str, list[tuple[str, str, bool]]]:
|
|
"""industryData.ts 의 업종별 sections 를 (id, name, locked) 목록으로 읽는다.
|
|
|
|
★ TS 를 정규식으로 읽는 건 곱지 않지만, 이 표를 백엔드로 복사해 오면 복사본이 또 어긋난다.
|
|
원본을 그대로 읽어 비교하는 것이 이 테스트의 요점이다."""
|
|
src = _ADMIN_SECTIONS_TS.read_text(encoding="utf-8")
|
|
out: dict[str, list[tuple[str, str, bool]]] = {}
|
|
for block in re.finditer(r"^ (\w+): \{$(.*?)^ \},$", src, re.S | re.M):
|
|
industry = block.group(1)
|
|
body = block.group(2)
|
|
arr = re.search(r"^ sections: \[$(.*?)^ \],$", body, re.S | re.M)
|
|
if not arr:
|
|
continue
|
|
items = re.findall(
|
|
r"id: '([\w]+)', type: '[\w]+', name: '([^']*)', isLocked: (true|false)", arr.group(1)
|
|
)
|
|
out[industry] = [(sid, name, locked == "true") for sid, name, locked in items]
|
|
return out
|
|
|
|
|
|
@pytest.mark.parametrize("industry", sorted(_INDUSTRY_TO_CATEGORY))
|
|
def test_default_sections_match_the_editor(industry):
|
|
"""검증: 업종 기본 섹션표가 에디터(industryData.ts)와 id·순서·이름·잠금까지 같은가.
|
|
기대결과: 완전히 같다 — 여기가 어긋나면 에디터에는 보이는 섹션이 발행본에 없다."""
|
|
editor = _editor_sections()
|
|
assert industry in editor, f"industryData.ts 에서 {industry} 의 sections 를 읽지 못했다"
|
|
server = _DEFAULT_THEME[_INDUSTRY_TO_CATEGORY[industry]]["sections"]
|
|
assert [tuple(s) for s in server] == editor[industry]
|