"""디자인(색·서체·섹션) 저장과 발행 payload 반영.""" import uuid import pytest from sqlalchemy import text from common.enums import ErrorType, PlaceCategory, SiteStatus from common.template_catalog import INDUSTRIES, TEMPLATES, UnknownTemplate from services.site_payload import to_site_payload # 계약 그대로의 최소 테마. _THEME = { "colors": {"accent": "#c2410c"}, "colorPaletteId": "warm-sand", "sections": [ {"id": "faq", "name": "자주 묻는 질문", "enabled": True, "locked": False}, {"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): """검증: 사이트 행이 없어도 디자인을 먼저 고를 수 있고, 저장한 모양 그대로 다시 읽힌다.""" 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_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}]} saved = await _set_theme(client, h, pid, theme) assert saved["result"]["code"] == ErrorType.SUCCESS.value assert saved["site"]["theme"]["sections"][0]["id"] == "brand-new-section" async def test_oversized_theme_is_refused(auth_headers, client): """검증: 해석하지 않는 값이라 크기만은 막는다 — 안 막으면 jsonb 하나가 DB 와 스냅샷을 부풀린다.""" h = await auth_headers("thm3") pid = await _place(client, h) refused = await _set_theme(client, h, pid, {"colors": {"accent": "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 컬럼이 소유한다.""" h = await auth_headers("thm4") pid = await _place(client, h) saved = await _set_theme(client, h, pid, {"templateId": "sneaky", "colors": {"accent": "#000000"}}) assert saved["result"]["code"] == ErrorType.SUCCESS.value assert "templateId" not in saved["site"]["theme"] assert saved["site"]["theme"]["colors"] == {"accent": "#000000"} async def test_empty_theme_clears_to_default(auth_headers, client): """검증: 빈 값은 '고르지 않음'이다 — NULL 로 되돌아가 업종 기본으로 떨어진다.""" 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 이 그대로라 색인이 안 깨진다).""" 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, "colors": {"accent": "#111111"}}) assert changed["result"]["code"] == ErrorType.SUCCESS.value # 나가 있는 페이지와 달라졌으므로 이 사업장만 다시 빌드하면 된다는 표시가 서야 한다. assert changed["needs_rebuild"] is True async def test_other_owners_place_is_blocked(auth_headers, client): """검증: 남의 사업장의 디자인은 바꿀 수 없다.""" h = await auth_headers("thm7") intruder = await auth_headers("thm8") 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_uses_industry_default(): """검증: 저장된 디자인이 없으면 업종 기본 템플릿(숙박=retro)과 업종 섹션 목록 그대로 나간다.""" theme = _payload_theme(None) stay = INDUSTRIES["stay"] assert theme["templateId"] == "retro" assert theme["colors"] == TEMPLATES["retro"]["colors"] assert theme["look"] == TEMPLATES["retro"]["look"] assert [s["id"] for s in theme["sections"]] == [s["id"] for s in stay["sections"]] assert [s["enabled"] for s in theme["sections"]] == [s["enabled"] for s in stay["sections"]] def test_payload_follows_saved_order_and_toggles(): """검증: 저장된 배열 순서와 on/off 가 발행본에 그대로 간다.""" 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_drops_variant_id(): """검증: 배치 고르기를 뺐으므로 저장값에 variantId가 남아 있어도 payload에 싣지 않는다.""" theme = _payload_theme({"sections": [{"id": "faq", "name": "FAQ", "enabled": True, "locked": False, "variantId": "faq.two-column"}]}) assert "variantId" not in next(s for s in theme["sections"] if s["id"] == "faq") def test_payload_ignores_saved_look(): """검증: 모양(look)은 템플릿 정의가 정한다.""" theme = _payload_theme({"look": {"fontHeading": "Comic Sans"}}) assert theme["look"] == TEMPLATES["retro"]["look"] def test_locked_section_cannot_be_published_disabled(): """검증: ★ 잠긴 섹션을 껐다고 저장한 경우.""" 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(): """검증: 저장값에 없는 기본 섹션(= 나중에 추가한 섹션).""" 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_owner_written_section_body_reaches_publish_payload(): """검증: 에디터에서 직접 쓴 소개 본문.""" theme = _payload_theme({"sections": [{ "id": "intro", "name": "소개", "enabled": True, "locked": False, "body": "바다를 보며 조용히 쉬어가는 작은 숙소입니다.", }]}) assert next(s for s in theme["sections"] if s["id"] == "intro")["body"] == ( "바다를 보며 조용히 쉬어가는 작은 숙소입니다." ) def test_partial_colors_are_filled_from_category_default(): """검증: 저장된 색이 일부 키만 담고 있을 때.""" colors = _payload_theme({"colors": {"accent": "#c2410c"}})["colors"] assert colors["accent"] == "#c2410c" assert colors["bg"] == TEMPLATES["retro"]["colors"]["bg"] assert set(colors) == set(TEMPLATES["retro"]["colors"]) def test_color_palette_id_never_reaches_the_payload(): """검증: colorPaletteId 는 에디터 복원 전용이다.""" assert "colorPaletteId" not in _payload_theme(_THEME) def test_saved_theme_does_not_override_chosen_template(): """검증: templateId와 모양은 언제나 sites.template_id가 가리키는 템플릿에서 온다.""" payload = to_site_payload(_PLACE, _SNAPSHOT, {"template_id": "paper", "theme": _THEME}, _VERSION, []) assert payload["theme"]["templateId"] == "paper" assert payload["theme"]["look"] == TEMPLATES["paper"]["look"] def test_unknown_template_stops_the_payload(): """검증: 등록되지 않은 id, 업종 허용 목록에 없는 id는 payload를 만들지 않는다.""" with pytest.raises(UnknownTemplate): to_site_payload(_PLACE, _SNAPSHOT, {"template_id": "stay-retro"}, _VERSION, []) clinic = {**_PLACE, "category": PlaceCategory.CLINIC.value} clinic_snapshot = {"place": {"name": "테마의원", "category": PlaceCategory.CLINIC.value}} with pytest.raises(UnknownTemplate): to_site_payload(clinic, clinic_snapshot, {"template_id": "retro"}, _VERSION, [])