[feat] solution,postgres-init: FAQ 를 20개까지 채운다 — 펜션 공통 질문 30개 + 문의 안내

COPY 잡은 확인된 fact 로만 FAQ 를 써서 4~8개에서 끝났다(실측 로컬: 스테이머뭄 fact 8건,
산하연 풀빌라 fact 4건 · FAQ 4건). fact 가 0건이면 start_copy 가 FAQ_UNGROUNDED 로 잡을 만들지 않아 0개였다.
생성 상한을 20으로 올리고, 모자라면 펜션 카탈로그에서 겹치지 않는 질문을 **문의 안내** 답으로 채운다.
공통 답에 값·가능 여부를 적으면 업종 시드 FAQ 가 가공의 가격을 사이트에 내보낸 사고와 같다 —
답은 "…은 전화(…)로 문의해 주시면 안내해 드립니다" 뿐이고, 그래서 화면에만 나간다.

- common/faq_catalog(신규): 로더 + resources/pension.json 30문항. fact_keys 가 업종 스키마에 없으면 로드 시 예외
- services/faq_fill.py(신규): 고르기 규칙 — fact 로 답할 수 있는 질문 · 기존 FAQ 와 근거 key 또는 질문 키워드가
  겹치는 질문은 건너뛴다(LLM 은 "주차 및 와이파이" 처럼 묶어 쓰고, 사장님 입력은 근거 key 가 없다)
- copy_service: max_faqs=20, 생성 뒤 _fill_faqs. 근거가 없거나 키가 없으면 LLM 없이 채우기만
- place_service.start_copy: 카탈로그가 있으면 fact 0건이어도 잡 생성(FAQ_UNGROUNDED 는 카탈로그 없는 업종만)
- SourceType.TEMPLATE=5(백엔드·shared·orval 모델). fact_service 규칙 4 로 fact 에는 못 쓴다
- faq_crud.expire_generated: TEMPLATE 도 재생성 때 내린다 — 새 fact 로 답이 생긴 주제에 옛 문의 안내가 남지 않게
- prompts/copy: fact 로 답할 수 있는 카탈로그 질문을 싣고 "한 문항 한 주제" 규칙(생성 FAQ 4건 중 3건이 묶여 있었다)
- shared selectAnsweredFaqs · jsonld · llms · prerender(↔ conftest) · seo_audit: 문의 안내는 FAQPage JSON-LD ·
  llms.txt · 고유 콘텐츠 계수 · FAQ 점수에서 뺀다 — 모든 펜션에 같은 문구라 세면 빈 사이트가 게이트를 통과한다
- site FaqSection: 문의 안내가 섞이면 "모두 사업자가 확인한 내용" 문구를 달지 않는다
- frontend FaqPanel "노출 N건 (문의 안내 M)" · notifyCopy 가 faq_fill 을 본다
- postgres-init: 컬럼 변경 없음(CHECK 없는 SMALLINT). 0012 + init.sql 에 generated_by·source_fact_ids COMMENT ON,
  0012 는 컬럼이 있을 때만(DO $$ IF EXISTS). init.sql 의 "비면 발행 게이트가 반려" 주석은 사실이 아니어서 고쳤다
- docs/DECISIONS.md 8절 · DATA_MODEL.md · DEVLOG.md

백엔드 664 passed(신규 test_faq_fill 10건 · test_copy_api 3건). 실패 2건은 이 변경 전 HEAD 에서도 같다:
test_rate_limit_closes_the_tap · test_사이트_디렉터리_밖의_thumbs_에_올린다
site·frontend·admin tsc 통과 · site vitest 63 passed · FaqPanel·collectNotify eslint 통과
로컬 실사업장(하늘물빛정원, fact 4건): 생성 4건 + 문의 안내 16건 = 20건, 질문 중복 0
0012: 새 DB(init.sql → migrate 규칙)와 로컬 DB 사본 양쪽에서 두 번씩 적용 통과

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011yLDuinzgyCxmqAutE1tse
This commit is contained in:
민헌andClaude Opus 5 committed 2026-09-14 17:05:43 +09:00
1 parent b2c8bb033e
commit 8a09af6599
29 files changed
+804 -62

No files matched your search

+103 -14
View File
@@ -52,7 +52,8 @@ async def _place_with_facts(client, h, n_verified=5):
async def _faq_rows(db_engine, pid):
async with db_engine.begin() as c:
return (await c.execute(
text("SELECT question, answer, source_fact_ids, status FROM place_faqs WHERE place_id = :p ORDER BY sort_order"),
text("SELECT question, answer, source_fact_ids, status, generated_by FROM place_faqs "
"WHERE place_id = :p ORDER BY sort_order"),
{"p": uuid.UUID(pid)},
)).all()
@@ -86,22 +87,29 @@ async def test_copy_generates_intro_and_faq_as_published(auth_headers, client, d
assert intro[0]["source_type"] == SourceType.LLM.value
async def test_copy_refuses_without_verified_facts(auth_headers, client, monkeypatch):
"""검증: 확인된 fact 가 하나도 없는 사업장에서 생성을 시도한다.
기대결과: FAQ_UNGROUNDED — ★ 잡을 만들지 않는다. 근거 없이 쓰면 환각이고 유료 호출만 낭비다."""
async def _must_not_call_llm(*args, **kwargs):
raise AssertionError("★ 근거 없이 LLM 을 불렀다")
async def test_copy_refuses_without_facts_when_no_catalog(auth_headers, client, monkeypatch):
"""검증: 확인된 fact 가 하나도 없는 **호텔**(펜션 카탈로그 제외 대상)에서 생성을 시도한다.
기대결과: FAQ_UNGROUNDED — ★ 잡을 만들지 않는다. 쓸 근거도, 채울 공통 질문도 없다."""
monkeypatch.setattr(gemini_text, "is_configured", lambda: True)
h = await auth_headers("u1")
pid = (await client.post("/v1/place", headers=h, json={"name": "빈펜션", "category": 1})).json()["place"]["place_id"]
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "빈주소"})
pid = (await client.post("/v1/place", headers=h, json={"name": "빈호텔", "category": 1})).json()["place"]["place_id"]
await client.post(f"/v1/place/{pid}/verify", headers=h,
json={"source": 2, "road_address": "빈호텔주소", "category_name": "호텔"})
r = await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
assert r.json()["result"]["code"] == ErrorType.FAQ_UNGROUNDED.value
async def test_unverified_facts_are_not_used_as_grounding(auth_headers, client, monkeypatch):
"""검증: 크롤링으로 들어온 미검증 fact 만 있는 사업장.
기대결과: 근거로 안 쳐서 FAQ_UNGROUNDED — 미검증 값으로 쓴 문장도 미검증이다."""
async def test_unverified_facts_are_not_used_as_grounding(auth_headers, client, db_engine, monkeypatch):
"""검증: 크롤링으로 들어온 미검증 fact 만 있는 펜션.
기대결과: ★ 근거 0건으로 친다 — LLM 을 부르지 않는다(미검증 값으로 쓴 문장도 미검증이다).
FAQ 는 문의 안내로 20개를 채우고, 미검증인 체크인도 '답이 있는 주제' 로 치지 않는다."""
monkeypatch.setattr(gemini_text, "is_configured", lambda: True)
monkeypatch.setattr(gemini_text, "generate_copy", _must_not_call_llm)
h = await auth_headers("u1")
pid = (await client.post("/v1/place", headers=h, json={"name": "미검증펜션", "category": 1})).json()["place"]["place_id"]
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "미검증주소"})
@@ -109,8 +117,36 @@ async def test_unverified_facts_are_not_used_as_grounding(auth_headers, client,
"key": "check_in_time", "value": "15:00",
"source_type": SourceType.CRAWL.value, "source_url": "https://ota.test/1"})
r = await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
assert r.json()["result"]["code"] == ErrorType.FAQ_UNGROUNDED.value
body = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()
assert body["result"]["success"] is True and body["grounded_facts"] == 0
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
job = (await client.get(f"/v1/job/{body['job_id']}", headers=h)).json()["job"]
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
assert job["result"]["faqs"] == 0 and job["result"]["faq_fill"] == 20
live = [r for r in await _faq_rows(db_engine, pid) if r[3] in _PUBLISHABLE]
assert len(live) == 20 and all(r[4] == SourceType.TEMPLATE.value for r in live)
assert any("체크인" in r[0] for r in live)
async def test_zero_facts_still_fill_twenty_without_api_key(auth_headers, client, db_engine, monkeypatch):
"""검증: fact 0건 · GEMINI 키 없음인 펜션(분류 없음 — 스테이머뭄처럼).
기대결과: ★ 잡이 만들어지고 FAQ 가 정확히 20건 — 채우기는 LLM 을 안 쓰므로 키가 필요 없다."""
monkeypatch.setattr(gemini_text, "is_configured", lambda: False)
monkeypatch.setattr(gemini_text, "generate_copy", _must_not_call_llm)
h = await auth_headers("u1")
pid = (await client.post("/v1/place", headers=h, json={"name": "무근거펜션", "category": 1})).json()["place"]["place_id"]
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "무근거주소"})
body = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()
assert body["result"]["success"] is True, body["result"]
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
job = (await client.get(f"/v1/job/{body['job_id']}", headers=h)).json()["job"]
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
assert job["result"]["faq_fill"] == 20
live = [r for r in await _faq_rows(db_engine, pid) if r[3] in _PUBLISHABLE]
assert len(live) == 20 and len({r[0] for r in live}) == 20
async def test_faq_without_grounding_is_dropped(auth_headers, client, db_engine, monkeypatch):
@@ -128,7 +164,10 @@ async def test_faq_without_grounding_is_dropped(auth_headers, client, db_engine,
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
assert job["result"]["faqs"] == 1
assert any("수영장" in str(r) for r in job["result"]["rejected"])
assert len(await _faq_rows(db_engine, pid)) == 1
rows = await _faq_rows(db_engine, pid)
assert len([r for r in rows if r[4] == SourceType.LLM.value]) == 1
# 채우기가 넣은 문의 안내에도 '수영장 있나요?' 의 거짓 답("네 있습니다")은 없다.
assert not any("있습니다" in r[1] for r in rows if r[4] == SourceType.TEMPLATE.value)
async def test_rejected_sentences_are_reported(auth_headers, client, monkeypatch):
@@ -161,9 +200,10 @@ async def test_regeneration_keeps_faq_the_owner_corrected(auth_headers, client,
# 사장님이 문구를 고쳐 승인 — 잠긴 상태(CORRECTED)가 되고 책임 주체가 사람으로 넘어온다.
async with db_engine.begin() as c:
await c.execute(
text("UPDATE place_faqs SET status = :s, generated_by = :g, question = :q WHERE place_id = :p"),
text("UPDATE place_faqs SET status = :s, generated_by = :g, question = :q "
"WHERE place_id = :p AND generated_by = :llm"),
{"s": FactStatus.CORRECTED.value, "g": SourceType.OWNER.value,
"q": "체크인 시간이 어떻게 되나요?", "p": uuid.UUID(pid)},
"q": "체크인 시간이 어떻게 되나요?", "p": uuid.UUID(pid), "llm": SourceType.LLM.value},
)
_patch(monkeypatch, _copy(faqs=[gemini_text.GeneratedFaq("새 질문?", "새 답변", ["check_in_time"])]))
@@ -177,6 +217,55 @@ async def test_regeneration_keeps_faq_the_owner_corrected(auth_headers, client,
assert any(r[0] == "새 질문?" and r[3] == FactStatus.VERIFIED.value for r in rows)
_PUBLISHABLE = (FactStatus.VERIFIED.value, FactStatus.CORRECTED.value)
async def test_copy_fills_faqs_to_target_without_duplicates(auth_headers, client, db_engine, monkeypatch):
"""검증: 생성된 FAQ 가 1건뿐이고, 사장님이 직접 쓴 FAQ 가 1건 있다.
기대결과: 노출 중 FAQ 가 정확히 20건 —
· 모자란 만큼은 문의 안내(TEMPLATE)로 채운다
· fact 로 답할 수 있는 주제(체크인·체크아웃·취소·취사·반려동물)에는 문의 안내를 붙이지 않는다
· 사장님이 이미 쓴 주제(보증금)도 다시 넣지 않는다"""
_patch(monkeypatch, _copy())
h = await auth_headers("u1")
pid = await _place_with_facts(client, h)
owner = await client.post(f"/v1/place/{pid}/faq", headers=h, json={"question": "보증금이 있나요?", "answer": "없습니다."})
assert owner.json()["result"]["success"] is True
job_id = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json()["job_id"]
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]
assert job["status"] == JobStatus.DONE.value, job.get("last_error")
assert job["result"]["faqs"] == 1
assert job["result"]["faq_fill"] == 18
live = [r for r in await _faq_rows(db_engine, pid) if r[3] in _PUBLISHABLE]
assert len(live) == 20
assert len({r[0] for r in live}) == 20, "같은 질문이 두 번 들어갔다"
fills = [r for r in live if r[4] == SourceType.TEMPLATE.value]
assert len(fills) == 18
fill_text = " ".join(r[0] for r in fills)
for topic in ("체크인", "체크아웃", "취소", "요리", "반려동물", "보증금"):
assert topic not in fill_text, f"★ 이미 답이 있는 주제 '{topic}' 에 문의 안내가 붙었다"
assert all("문의" in r[1] or "확인" in r[1] for r in fills), "문의 안내가 아닌 답이 섞였다"
async def test_regeneration_replaces_fill_faqs(auth_headers, client, db_engine, monkeypatch):
"""검증: 생성을 두 번 돌린다.
기대결과: 노출 중 FAQ 는 여전히 20건 — 옛 문의 안내는 내려가고 다시 고른다(쌓이지 않는다)."""
_patch(monkeypatch, _copy())
h = await auth_headers("u1")
pid = await _place_with_facts(client, h)
for _ in range(2):
await client.post(f"/v1/place/{pid}/copy", headers=h, json={})
await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).drain()
live = [r for r in await _faq_rows(db_engine, pid) if r[3] in _PUBLISHABLE]
assert len(live) == 20
assert len({r[0] for r in live}) == 20
async def test_copy_requires_api_key(auth_headers, client, monkeypatch):
"""검증: GEMINI_API_KEY 없이 생성을 시도한다.
기대결과: GENERATOR_NOT_CONFIGURED — 잡을 만들지 않는다."""
+104
View File
@@ -0,0 +1,104 @@
"""FAQ 목표 수 채우기 — ★ 공통 답은 문의 안내뿐이고, 이미 다룬 주제는 다시 넣지 않는다.
이 기능이 절대 하면 안 되는 것:
- 공통 답에 값·가능 여부를 적는 것 (가게마다 다르다 — 틀리면 예약 클레임)
- fact 로 답할 수 있는 질문에 "문의 부탁드립니다" 를 붙이는 것 (아는 것을 숨긴다)
- 기존 FAQ 와 같은 주제를 다시 넣는 것
"""
import re
from common.enums import ErrorType, PlaceCategory
from common.faq_catalog import find_catalog
from services import faq_fill
from services.faq_fill import ExistingFaq
def _pension():
catalog = find_catalog(PlaceCategory.LODGING.value, "펜션")
assert catalog is not None
return catalog
def _ids(picks):
return {p.catalog_id for p in picks}
def test_pension_catalog_has_thirty_questions():
"""검증: 카탈로그 로드. fact_keys 가 업종 스키마에 없으면 로더가 예외를 던진다."""
catalog = _pension()
assert len(catalog.items) == 30
assert len({item.id for item in catalog.items}) == 30
def test_catalog_scope():
"""검증: 호텔·카페에는 펜션 질문을 붙이지 않는다. 분류가 비어 있는 숙박업(스테이머뭄)에는 붙인다."""
assert find_catalog(PlaceCategory.LODGING.value, "호텔") is None
assert find_catalog(PlaceCategory.CAFE.value, None) is None
assert find_catalog(PlaceCategory.LODGING.value, None) is not None
def test_fills_only_the_shortfall():
"""검증: 기존 FAQ 5건(카탈로그와 무관한 질문). 기대결과: 15건만 고른다. 20건이면 0건."""
catalog = _pension()
picks = faq_fill.pick_fill_faqs(catalog, [ExistingFaq(f"기타 질문 {i}") for i in range(5)], set())
assert len(picks) == 15 and len(_ids(picks)) == 15
assert faq_fill.pick_fill_faqs(catalog, [ExistingFaq(f"질문 {i}") for i in range(20)], set()) == []
def test_skips_topics_answerable_by_facts():
"""검증: 체크인·반려동물 fact 가 있다(객실 fact 는 'A동:max_capacity' 로 적힌다).
기대결과: 그 질문들은 문의 안내로 채우지 않는다 — LLM 이 fact 로 답할 자리다."""
picks = faq_fill.pick_fill_faqs(_pension(), [], {"check_in_time", "pet_allowed", "A동:max_capacity"}, target=30)
assert not _ids(picks) & {"check_in", "pet", "capacity"}
def test_skips_topics_already_asked_by_keyword():
"""검증: 사장님이 근거 key 없이 쓴 FAQ 가 있다. 기대결과: 질문 낱말로 같은 주제를 알아본다."""
existing = [ExistingFaq("반려견 데려가도 되나요?"), ExistingFaq("주차 되나요?")]
picks = faq_fill.pick_fill_faqs(_pension(), existing, set(), target=30)
assert not _ids(picks) & {"pet", "parking"}
def test_skips_topics_covered_by_source_fact_keys():
"""검증: LLM FAQ 의 질문에는 키워드가 없지만 근거 key 가 [wifi, A동:max_capacity] 다.
기대결과: 와이파이·인원 질문을 넣지 않는다 — LLM 은 두 주제를 한 문항에 묶기도 한다."""
existing = [ExistingFaq("편의 안내가 궁금해요", ["wifi", "A동:max_capacity"])]
picks = faq_fill.pick_fill_faqs(_pension(), existing, set(), target=30)
assert not _ids(picks) & {"wifi", "capacity"}
def test_answers_are_inquiry_only():
"""검증: 공통 답 문구.
기대결과: ★ 연락처가 없으면 숫자가 하나도 없다(가격·시각을 지어내지 않는다). 연락처가 있으면 그 번호만 들어간다."""
catalog = _pension()
for pick in faq_fill.pick_fill_faqs(catalog, [], set(), target=30):
assert not re.search(r"\d", pick.answer), pick.answer
assert "숙소" in pick.answer
for pick in faq_fill.pick_fill_faqs(catalog, [], set(), phone="010-1234-5678", target=30):
assert "전화(010-1234-5678)로" in pick.answer
assert not re.search(r"\d", pick.answer.replace("010-1234-5678", "")), pick.answer
def test_answer_particle_and_rotation():
"""검증: 주제 뒤 조사(은/는)와 문구 돌려쓰기."""
catalog = _pension()
assert faq_fill.fallback_answer(catalog, 0, "보증금 여부", None).startswith("보증금 여부는 ")
assert faq_fill.fallback_answer(catalog, 0, "주변 편의시설", None).startswith("주변 편의시설은 ")
assert len({faq_fill.fallback_answer(catalog, i, "주제", None) for i in range(3)}) == 3
def test_suggested_questions_are_the_answerable_ones():
"""검증: 프롬프트에 실을 질문 = fact 로 답할 수 있는 카탈로그 질문."""
questions = faq_fill.suggested_questions(_pension(), {"parking", "check_out_time"})
assert questions == ["체크아웃은 몇 시까지인가요?", "주차할 수 있나요? 몇 대까지 가능한가요?"]
async def test_template_source_cannot_write_fact(auth_headers, client):
"""검증: fact 를 TEMPLATE 출처로 쓴다.
기대결과: INVALID_REQUEST_DATA — 막지 않으면 사람 입력처럼 바로 노출값이 된다(fact_service 규칙 4)."""
h = await auth_headers("u1")
pid = (await client.post("/v1/place", headers=h, json={"name": "틀펜션", "category": 1})).json()["place"]["place_id"]
await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "road_address": "틀주소"})
r = await client.post(f"/v1/place/{pid}/fact", headers=h, json={
"key": "check_in_time", "value": "15:00", "source_type": 5, "source_url": "template:test"})
assert r.json()["result"]["code"] == ErrorType.INVALID_REQUEST_DATA.value