[feat] solution,postgres-init,docs: 생성 진행 상태 · 새로 만들기 존중 · 발행본 색인·파비콘

작업트리에 커밋되지 않은 채 쌓여 있던 것과, 오늘 찾은 문제 셋을 함께 담는다.

## 1. 콘텐츠 생성 진행 상태 (작업트리에 있던 것)

COPY 잡의 실제 단계를 DB에 기록하고 응답으로 내보낸다. 폴링 횟수로 진행률을 흉내 내던
것을 걷어냈다. 새로고침·재접속해도 jobId 로 이어서 본다.

- services/copy_steps.py · services/job_progress.py · common/job_errors.py (신규)
- postgres-init/migrations/0013_job_progress.sql + init.sql
- 프론트: useGenerationJob · generationLabels (신규), Step5Generating·pollJob 배선,
  orval 모델 갱신(jobProgress · jobStep · jobStepStatus · jobStepReason)
- docs/GENERATION_FLOW.md (신규)

## 2. 발행된 사이트만 색인한다

실측(2026-09-15): 디스크의 발행본 33곳 중 **15곳이 draft 인데 `index, follow`** 였고
사이트맵에도 올라가 있었다. 사장님이 발행 버튼을 누른 적 없는 사이트가 짓다 만 상태로
구글에 실려 있었다는 뜻이다.

head.ts 가 robots 를 하드코딩하고 payload 의 `site.status` 를 보지 않았다.
"색인을 막을 이유가 없다"는 주석은 굽는 것이 곧 발행이던 시절의 말인데, 지금은 빌더
미리보기만 눌러도 draft 로 구워진다.

- seo/head.ts: PUBLISHED 일 때만 index, 아니면 `noindex, follow`
- 사이트맵·`/s` 목록·llms.txt 에서도 함께 빠진다 — 그쪽은 구운 HTML 의 robots 를 읽어
  거른다(seo/directory.ts readBakedNoindex). 규칙을 두 자리에 두지 않으려고 한 곳에 뒀다

## 3. [새로 크롤링하고 사이트 생성하기] 를 뒤집지 않는다

ba90a19 의 중복 합치기가 **일부러 다시 만들려는 경우까지** 기존 사업장으로 끌고 갔다 —
새로 만들기를 눌렀는데 기존 에디터가 열린다(사장님 보고 2026-09-15).

- Req_VerifyPlaceByUrl.reuse_existing (기본 True — 다른 호출자의 동작은 그대로)
- place_service.verify_place_by_url: 끄면 이어붙이지 않는다. 다만 **비어 있는 중복 행은
  계속 치운다** — 원래 막으려던 누적이 그것이고 빈 행은 잃을 것이 없다
- ensureServerPlace: 위저드는 새로 만들기 경로에서만 오므로 False 로 보낸다

## 4. 발행본 파비콘

발행본에 파비콘 링크가 아예 없어 브라우저 탭에 기본 아이콘이 떴다. 파일은 오리진 루트의
공용 자산이라 사이트마다 복사하지 않고 루트 절대경로로 가리킨다.

검증: site vitest 84건 통과 · tsc(site·frontend) · eslint 통과.
백엔드 pytest 는 로컬 DB 비밀번호가 맞지 않아 돌리지 못했다(a5b8701 과 같은 자리).
발행본 반영에는 전체 재굽기가 필요하다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
minaChoiandClaude Opus 5 committed 2026-09-15 17:29:27 +09:00
1 parent 4cd756108d
commit 079c93a62a
60 files changed
+1465 -596

No files matched your search

+2 -1
View File
@@ -42,6 +42,7 @@ from services import (
from services.local_content_service import LocalContentService
from services.site_payload import emit_payload
from services.snapshot import build_snapshot
from common.job_errors import PermanentJobError
_site_crud = SiteCRUD()
_place_crud = PlaceCRUD()
@@ -52,7 +53,7 @@ _place_crud = PlaceCRUD()
RENDER_TIMEOUT_SEC = float(os.environ.get("RENDER_TIMEOUT_SEC") or 180)
class BuildAborted(RuntimeError):
class BuildAborted(PermanentJobError):
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남는다."""
+2 -1
View File
@@ -19,12 +19,13 @@ from services.collector import yanolja_adapter
from services.external import naver_place_lookup, perplexity, tour_lookup
from services.fact_service import FactService
from router.v1.fact.protocol import Req_UpsertFact
from common.job_errors import PermanentJobError
_place_crud = PlaceCRUD()
_fact_crud = FactCRUD()
class CollectAborted(RuntimeError):
class CollectAborted(PermanentJobError):
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남아 운영자가 본다."""
@@ -1,5 +1,31 @@
"""정적 HTML 어댑터 — **사장님이 확정한 자기 홈페이지** 전용.
★ 왜 이 어댑터가 지금 등록되는가 (docs/DATA_SOURCE_RESEARCH.md, 2026-08-28)
docs/DECISIONS.md 1-1 이 "약관·robots.txt 기준 허용 범위" 결론 전까지 등록을 보류했던
그 어댑터다. 실측 결론은 이렇다.
야놀자·여기어때 HTTP 403 + Cloudflare 챌린지. 기술적으로 막혔고, 같은 행위에
민사 10억 배상 선례가 있다(야놀자 v 여기어때, 서울중앙지법 2021-08).
네이버·카카오 robots.txt 가 `Disallow: /`. 명시적 불허.
사장님 자체 홈페이지 사장님이 URL 을 확정해 주고, 그 사실의 주인도 사장님이다. **가능.**
즉 이 어댑터의 정당성은 전부 "사장님이 확정한 URL 만 본다" 에서 나온다.
그 전제가 깨지면(플랫폼 URL 이 흘러들어오면) 정당성도 같이 깨지므로,
아래 _DENY_HOSTS 로 **구조적으로** 막는다. 운영자가 실수로 넣어도 안 긁힌다.
★ NOL(nol.yanolja.com) 은 이 어댑터가 아니라 전용 어댑터가 받는다(2026-09-14).
범용 HTML 수집을 OTA 로 넓힌 것이 아니다 — 레지스트리가 yanolja 를 이 어댑터보다
**앞에** 등록하므로 그 한 패턴만 전용 경로로 가고, 나머지 야놀자·여기어때 주소는
여기 _DENY_HOSTS 에서 그대로 막힌다.
★ 실측(2026-09-15): 이 deny 목록에서 두 호스트가 빠져 있던 동안 범용 HTML 수집이
`www.yanolja.com` · `goodchoice.kr` 을 받았다. 전용 어댑터를 들이는 것과
범용 수집기를 그 플랫폼에 푸는 것은 다른 일이다.
**금지 (docs/DECISIONS.md 1-1, 결론과 무관하게 영구)**
캡차 우회 · 봇 탐지 우회 · IP 회전. 여기에 하나 더 —
**robots.txt 를 확인하고 그대로 따른다.** 사장님 홈페이지라도 예외 없다.
막히면 실패로 돌려주고 폴백 3단계로 간다(공식 API → 사장님 붙여넣기 → 최소 정보 생성).
★ 표본 근거 — 왜 이 어댑터가 숙박에서 특히 값이 큰가
네이버 지역검색 `link` 필드 충전율(업종별 25건 표본): 숙박 96% 중 자체 도메인 19건,
음식점 64%, 카페 92% 중 인스타 17건. 숙박은 자체 홈페이지 보유율이 3업종 중 가장 높다.
@@ -42,9 +68,15 @@ HEADERS = {
"Accept-Language": "ko-KR,ko;q=0.9",
}
# ★ 이 호스트들은 이 어댑터가 절대 건드리지 않는다.
# - 전용 어댑터가 따로 있거나(naver_place · yanolja)
# - 실측·판례로 수집 불가 결론이 난 곳이거나(야놀자·여기어때·카카오맵)
# - 공식 OAuth 로만 가져와야 하는 곳(인스타그램)이다.
# can_handle 에서 걸러 AdapterNotFound 로 떨어뜨린다.
_DENY_HOSTS = (
"naver.com", "naver.me", # 플레이스·지도·블로그·예약 — robots Disallow: /
"kakao.com", "daum.net", # 카카오맵 — robots Disallow, 내부 API 406
"yanolja.com", "goodchoice.kr", # OTA — 403 + 민사 10억 선례. NOL 은 전용 어댑터가 먼저 받는다
"dailyhotel.com", "catchtable.co.kr",
"airbnb.co.kr", "airbnb.com",
"booking.com", "agoda.com", "expedia.co.kr",
+28 -314
View File
@@ -1,325 +1,39 @@
"""소개문·FAQ 생성 — COPY 잡이 하는 일.
★ LLM 은 사실을 만들지 않는다. 문장만 쓴다.
- 입력은 **확보된 fact(노출 가능한 것)만**. 미검증 값으로 문장을 쓰면 그 문장도 미검증이다.
- 생성물은 `ground_check` 를 통과한 것만 저장한다(클라이언트가 이미 걸러 보내지만 근거를 다시 요구한다).
- 소개문·FAQ 는 **바로 노출값**이다(VERIFIED). 승인 단계를 두지 않는다 — 2026-09-10 결정.
게이트는 앞에 있다: 입력이 확인된 fact 뿐이고, 근거 없는 FAQ 는 저장조차 하지 않는다.
확인된 사실로 쓴 문장을 한 번 더 승인받게 하면 같은 사실을 두 번 승인하는 셈이고,
실제로는 그 화면이 닫힌 뒤에 문장이 도착해 발행본이 영영 빈칸이었다
(근거·실측: services/fact_service.upsert_fact · docs/DECISIONS.md 7절).
- 사장님이 고친 문장(CORRECTED)은 재생성이 덮지 않는다. 그 잠금은 그대로다.
- FAQ 가 목표 수(20)에 모자라면 업종 카탈로그에서 겹치지 않는 공통 질문을 **문의 안내** 답으로 채운다
(services/faq_fill · common/faq_catalog). 답에 값·가능 여부를 적지 않으므로 사실을 만들지 않는다.
★ fact 가 0건이어도(또는 API 키가 없어도) 채운다 — 그때는 LLM 을 부르지 않고 채우기만 한다.
"""
import uuid
from common.category_schema import CategorySchemaError, get_schema
from common.database.db_session_manager import DB_SESSION_MNG
from common.faq_catalog import FaqCatalog, find_catalog
from common.database.model.models import place_facts, place_faqs, place_channels, places, place_units
from common.enums import (
PUBLISHABLE_FACT_STATUSES,
DBWRType,
ErrorType,
FactStatus,
PlaceCategory,
SourceType,
)
from common.logger import LOG
from common.models.gmodel import UserInfo
from common.utils.gtime import GTime
from config.server_configs import external_api_config
from crud.fact_crud import FactCRUD
from crud.faq_crud import FaqCRUD
from crud.place_crud import PlaceCRUD
from router.v1.fact.protocol import Req_UpsertFact
from services import faq_fill, place_research
"""COPY 흐름. 단계 구현: copy_steps / 프롬프트: prompts/copy / 호출·검증: external/gemini_text."""
from services.copy_steps import CopyAborted, prepare_copy, generate_copy, save_copy, fill_faqs
from services.external import gemini_text
from services.fact_service import FactService
from services.job_progress import JobProgress
_fact_crud = FactCRUD()
_faq_crud = FaqCRUD()
_place_crud = PlaceCRUD()
class CopyAborted(RuntimeError):
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남는다."""
COPY_STEPS = ("prepare", "generate", "save", "faq_fill")
async def run_copy(job: dict) -> dict:
"""COPY 잡 핸들러. payload: {place_id, owner_user_id, requested_by?}"""
progress = JobProgress(job, COPY_STEPS)
payload = job["payload"]
place_id = payload["place_id"]
owner_user_id = payload["owner_user_id"]
async with progress.step("prepare"):
inputs = await prepare_copy(payload["place_id"], payload["owner_user_id"])
err, place = await DB_SESSION_MNG.execute_lambda(
places.DBType(),
DBWRType.DB_READ.value,
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
)
if err != ErrorType.SUCCESS or place is None:
raise CopyAborted(f"사업장을 찾을 수 없다: {place_id}")
copy = None
note = None
if inputs.ungrounded or not gemini_text.is_configured():
note = "근거로 쓸 확인된 fact 가 없다" if inputs.ungrounded else "GEMINI_API_KEY 미설정"
await progress.skip("generate", "no_facts" if inputs.ungrounded else "not_configured")
if inputs.catalog is None and not inputs.ungrounded:
raise CopyAborted(note)
else:
async with progress.step("generate"):
copy = await generate_copy(inputs)
try:
schema = get_schema(PlaceCategory(place.category))
except (CategorySchemaError, ValueError) as ex:
raise CopyAborted(f"지원하지 않는 업종: {place.category}") from ex
async with progress.step("save"):
result = await save_copy(inputs, copy)
# ★ 노출 가능한 fact 만 근거로 준다. 미검증 값으로 쓴 문장은 그 자체가 미검증이다.
pid = uuid.UUID(place_id)
f_err, fact_rows = await DB_SESSION_MNG.execute_lambda(
place_facts.DBType(),
DBWRType.DB_READ.value,
lambda s: _fact_crud.list_facts(s, pid, None, None, True, True),
)
if f_err != ErrorType.SUCCESS:
raise CopyAborted(f"fact 조회 실패: {f_err.name}")
grounded = [
gemini_text.FactInput(
key=r.key,
label=(schema.get(r.key).label if schema.get(r.key) else r.key),
value=r.value,
unit=r.unit,
)
for r in fact_rows
if r.unit_id is None and (r.value or "").strip()
]
# ★ 수집 원문도 근거로 넘긴다 — fact 가 아니라 place_channels.raw 에 박제된 글이다.
#
# 왜 필요한가: 소개 원문(TourAPI overview·네이버 description)에만 있는 정보가 있다.
# '전면 통창 실내 온수풀', '판교역에서 3분' 같은 것들인데, 이게 근거에 없으면
# ground_check 가 그 문장을 전부 반려해 소개문·FAQ 가 앙상해진다.
#
# 왜 fact 로 넣지 않는가: `intro` 는 allow_llm=True 라 LLM 의 출력 칸이다.
# 원문을 그 칸에 넣었더니 457자 원문이 발행본의 '숙소 소개' 를 차지했다(2026-08-31).
# 근거로만 쓰고 저장은 하지 않는다 — 원문은 화면에 나가지 않는다.
# ★ 확정 링크만 읽던 것을 **조사 근거까지** 읽게 넓혔다(2026-09-10).
# 업소 조사(`place_research`)는 남이 쓴 글이라 확정하지 않는다 — 공식 채널이 아니므로
# 발행본의 sameAs·푸터에 나가면 안 된다. 그런데 그것 때문에 여기서도 안 읽혀서,
# 조사해 온 재료가 소개문에 한 글자도 닿지 않았다. 확정 여부는 "화면에 채널로
# 내보낼 것인가" 의 판단이지 "근거로 읽을 것인가" 의 판단이 아니다.
# ★ 다만 아무 미확정 링크나 읽지는 않는다 — raw.kind 가 research 인 것만이다.
# 미확정 채널 URL 은 동명 업소일 수 있고(그게 확정 절차의 이유다), 조사 근거는
# 상호 대조를 통과한 것만 적재된다(`grounding/place_research.parse_items`).
records: list[str] = []
l_err, link_rows = await DB_SESSION_MNG.execute_lambda(
place_channels.DBType(),
DBWRType.DB_READ.value,
lambda s: _place_crud.list_links(s, pid, False),
)
if l_err == ErrorType.SUCCESS:
for link in (link_rows or []):
raw = link.raw if isinstance(link.raw, dict) else {}
if link.confirmed_at is None and raw.get("kind") != place_research.RAW_KIND:
continue
text = (raw.get("text") or "").strip()
if text:
# ★ fact 목록이 아니라 records 로 넘긴다. fact 자리에 넣으면 모델이 값 하나로
# 읽고 거의 쓰지 않는다(prompts/copy.build_prompt 머리주석의 실측).
records.append(text[:4000])
# ground_check 는 여전히 이 글을 근거로 인정해야 한다 — 근거 목록에도 남긴다.
grounded.append(gemini_text.FactInput(
key=f"source:{link.link_id}", label="수집 원문", value=text[:4000],
))
# 객실·메뉴 요약도 근거로 넘긴다 — "최대 4명" 같은 수치가 통과하려면 근거에 있어야 한다.
#
# ★ 근거 없음 판정보다 **먼저** 읽는다.
# 예전에는 사업장 fact 가 0건이면 여기까지 오지 못하고 되돌아갔다. 그런데 네이버에
# 요금표만 올라온 모텔은 사업장 fact 가 0건이고 객실 fact 만 있다 — 쓸 근거가 있는데도
# "근거 없음"으로 끝나 소개문·FAQ 가 영구히 생기지 않았다.
u_err, unit_rows = await DB_SESSION_MNG.execute_lambda(
place_units.DBType(),
DBWRType.DB_READ.value,
lambda s: _place_crud.list_units(s, pid),
)
unit_summaries = []
if u_err == ErrorType.SUCCESS:
by_unit: dict = {}
for r in fact_rows:
if r.unit_id and (r.value or "").strip():
by_unit.setdefault(str(r.unit_id), {})[r.key] = r.value
unit_summaries = [
{
"name": u.name,
"facts": by_unit.get(str(u.unit_id), {}),
# 스키마 라벨·단위를 같이 넘긴다 — 이게 없으면 프롬프트에 'weekday_price' 라는
# 날 key 가 그대로 실려 모델이 그 낱말로 문장을 쓴다.
"labels": {
key: {
"label": schema.get(key).label if schema.get(key) else key,
"unit": schema.get(key).unit if schema.get(key) else None,
}
for key in by_unit.get(str(u.unit_id), {})
},
}
for u in unit_rows
if by_unit.get(str(u.unit_id))
]
# FAQ 채우기에 쓸 업종 카탈로그. 없으면(카페·음식점·호텔) 채우지 않는다.
catalog = find_catalog(place.category, place.external_category)
# 사업장·객실 fact 를 가리지 않는다 — "기준 인원" 은 객실 fact 로 답한다.
known_fact_keys = {r.key for r in fact_rows if (r.value or "").strip()}
# ── LLM 을 부르지 않는 경우 ── 근거가 없거나(환각·유료 호출 방지) 키가 없을 때.
# ★ 그래도 카탈로그가 있으면 FAQ 는 문의 안내로 20개를 채운다 — fact 가 0건이어도 20개(DECISIONS 8절).
ungrounded = not grounded and not unit_summaries
if ungrounded or not gemini_text.is_configured():
note = "근거로 쓸 확인된 fact 가 없다" if ungrounded else "GEMINI_API_KEY 미설정"
if catalog is None:
if not ungrounded:
raise CopyAborted(f"{note} — 소개문·FAQ 를 생성할 수 없다")
return {"place_id": place_id, "intro": False, "faqs": 0, "faq_fill": 0, "note": note}
if ungrounded:
# 근거가 사라졌으니 예전 생성분도 근거가 없다 — 내리고 새로 채운다.
# 키만 없는 경우는 내리지 않는다: 멀쩡한 생성 FAQ 가 키 설정 하나 때문에 사라지면 안 된다.
await DB_SESSION_MNG.execute_lambda_claim(
place_faqs.DBType(),
lambda s: _faq_crud.expire_generated(s, pid, GTime.UTC()),
if inputs.catalog is not None:
async with progress.step("faq_fill"):
result["faq_fill"] = await fill_faqs(
inputs.place.place_id, inputs.catalog, inputs.known_fact_keys, inputs.place.phone,
)
filled = await _fill_faqs(pid, catalog, known_fact_keys, place.phone)
LOG.i(f"[copy] place={place_id} LLM 호출 없음({note}) · 문의 안내 채움 {filled}건")
return {
"place_id": place_id, "grounded_facts": len(grounded), "intro": False, "meta": False,
"faqs": 0, "faq_fill": filled, "rejected": [], "note": note,
}
else:
await progress.skip("faq_fill", "no_catalog")
try:
copy = await gemini_text.generate_copy(
place.name,
PlaceCategory(place.category),
grounded,
unit_summaries=unit_summaries or None,
records=records or None,
suggested_questions=faq_fill.suggested_questions(catalog, known_fact_keys) if catalog else None,
max_faqs=faq_fill.FAQ_TARGET,
model=external_api_config.gemini_text_model,
)
except gemini_text.GeminiNotConfigured as ex:
raise CopyAborted(str(ex)) from ex
now = GTime.UTC()
stat = {
"place_id": place_id,
"grounded_facts": len(grounded),
"intro": False,
"meta": False,
"faqs": 0,
"faq_fill": 0, # 목표 수를 채운 문의 안내 문항 수
# ★ 반려된 문장을 그대로 남긴다 — 소개문이 왜 안 나왔는지 운영자가 알아야 한다.
"rejected": [list(r) for r in (copy.rejected or [])][:20],
}
actor = UserInfo(
# ★ 잡이 쓰는 신원. user_id 는 **사업장 주인**이어야 한다 — FactService 가 이 값으로
# 사업장을 스코프하고(fact_service._load_place) verified_by 에도 그대로 박는다.
# 회사를 걷어내기 전에는 스코프가 company_id 였고 여기엔 요청자·검증자·랜덤 uuid 가
# 순서대로 들어갔다. 그 랜덤 uuid 가 이제는 "남의 사업장" 이 되어 조회가 0건이 된다.
user_id=owner_user_id,
id="generator",
role=1,
)
service = FactService(_fact_crud, _place_crud)
# 소개문·메타는 fact 로 들어간다 — FactService 가 allow_llm 을 다시 확인하고(뒷문 없음),
# LLM 출처라 후보가 아니라 노출값으로 앉힌다(upsert_fact 의 LLM 분기).
for key, text_value in (("intro", copy.intro), ("meta_description", copy.meta_description)):
if not (text_value or "").strip():
continue
if not (schema.get(key) and schema.get(key).allow_llm):
# 이 업종 스키마가 LLM 작성을 허용하지 않는 필드다. 조용히 건너뛴다.
continue
res = await service.upsert_fact(
actor, place_id,
Req_UpsertFact(
key=key, value=text_value.strip(),
source_type=SourceType.LLM, source_url=f"gemini:{external_api_config.gemini_text_model}",
),
)
if res.result.success:
stat["intro" if key == "intro" else "meta"] = True
else:
stat["rejected"].append([key, res.result.desc])
# 확인 안 된 기존 생성 FAQ 는 내리고 새로 넣는다. 사람이 확인한 FAQ 는 건드리지 않는다.
await DB_SESSION_MNG.execute_lambda_claim(
place_faqs.DBType(),
lambda s: _faq_crud.expire_generated(s, pid, now),
)
for order, faq in enumerate(copy.faqs or []):
if not faq.fact_keys:
# ★ 근거 없는 FAQ 는 저장하지 않는다.
stat["rejected"].append([faq.question, "근거 fact 없음"])
continue
row = place_faqs(
place_id=pid,
question=faq.question,
answer=faq.answer,
source_fact_ids=list(faq.fact_keys),
generated_by=SourceType.LLM.value,
# ★ 바로 노출한다 (2026-09-10 결정 — fact_service.upsert_fact 주석이 근거).
# 근거 fact 가 없으면 위에서 이미 버렸으므로, 여기 남은 것은 전부 확인된 사실로 쓴 문장이다.
status=FactStatus.VERIFIED.value,
sort_order=order,
)
run_err = await DB_SESSION_MNG.execute_lambda_run(
[place_faqs.DBType()],
[lambda s, r=row: _faq_crud.add_faq(s, r)],
)
if run_err == ErrorType.SUCCESS:
stat["faqs"] += 1
# ── 목표 수 채우기 ── 생성분이 모자라면 카탈로그의 겹치지 않는 공통 질문을 문의 안내로 채운다.
if catalog is not None:
stat["faq_fill"] = await _fill_faqs(pid, catalog, known_fact_keys, place.phone)
LOG.i(f"[copy] place={place_id} 소개문 {'O' if stat['intro'] else 'X'} · FAQ {stat['faqs']}건 · "
f"문의 안내 채움 {stat['faq_fill']}건 · 반려 {len(stat['rejected'])}건 (근거 fact {len(grounded)}개)")
return stat
async def _fill_faqs(pid: uuid.UUID, catalog: FaqCatalog, known_fact_keys: set[str], phone: str | None) -> int:
"""노출 중인 FAQ 가 목표 수에 모자란 만큼 문의 안내 문항을 넣는다. 넣은 건수를 돌려준다.
★ 기존 FAQ 는 **노출 중인 것 전부**로 센다 — 방금 넣은 생성분만이 아니라 재생성이 남긴
사장님 입력·정정분까지. 그래야 사장님이 이미 답한 주제에 문의 안내가 겹쳐 붙지 않는다.
★ 바로 노출값(VERIFIED)으로 넣는다. 답이 주장을 하지 않아 확인할 대상이 없다 —
대신 JSON-LD · llms.txt · 고유 콘텐츠 계수에서는 빠진다(shared selectAnsweredFaqs)."""
l_err, rows = await DB_SESSION_MNG.execute_lambda(
place_faqs.DBType(),
DBWRType.DB_READ.value,
lambda s: _faq_crud.list_faqs(s, pid, True),
)
if l_err != ErrorType.SUCCESS:
LOG.e_no_callstack(f"[copy] FAQ 채우기 건너뜀 — 목록 조회 실패 place={pid} {l_err.name}")
return 0
picks = faq_fill.pick_fill_faqs(
catalog,
[faq_fill.ExistingFaq(r.question, r.source_fact_ids) for r in rows],
known_fact_keys,
phone,
)
next_order = max((r.sort_order for r in rows), default=-1) + 1
added = 0
for offset, pick in enumerate(picks):
row = place_faqs(
place_id=pid,
question=pick.question,
answer=pick.answer,
source_fact_ids=None,
generated_by=SourceType.TEMPLATE.value,
status=FactStatus.VERIFIED.value,
sort_order=next_order + offset,
)
run_err = await DB_SESSION_MNG.execute_lambda_run(
[place_faqs.DBType()],
[lambda s, r=row: _faq_crud.add_faq(s, r)],
)
if run_err == ErrorType.SUCCESS:
added += 1
return added
if note:
result["note"] = note
return result
+327
View File
@@ -0,0 +1,327 @@
"""소개문·FAQ 생성 — COPY 잡이 하는 일.
★ LLM 은 사실을 만들지 않는다. 문장만 쓴다.
- 입력은 **확보된 fact(노출 가능한 것)만**. 미검증 값으로 문장을 쓰면 그 문장도 미검증이다.
- 생성물은 `ground_check` 를 통과한 것만 저장한다(클라이언트가 이미 걸러 보내지만 근거를 다시 요구한다).
- 소개문·FAQ 는 **바로 노출값**이다(VERIFIED). 승인 단계를 두지 않는다 — 2026-09-10 결정.
게이트는 앞에 있다: 입력이 확인된 fact 뿐이고, 근거 없는 FAQ 는 저장조차 하지 않는다.
확인된 사실로 쓴 문장을 한 번 더 승인받게 하면 같은 사실을 두 번 승인하는 셈이고,
실제로는 그 화면이 닫힌 뒤에 문장이 도착해 발행본이 영영 빈칸이었다
(근거·실측: services/fact_service.upsert_fact · docs/DECISIONS.md 7절).
- 사장님이 고친 문장(CORRECTED)은 재생성이 덮지 않는다. 그 잠금은 그대로다.
- FAQ 가 목표 수(20)에 모자라면 업종 카탈로그에서 겹치지 않는 공통 질문을 **문의 안내** 답으로 채운다
(services/faq_fill · common/faq_catalog). 답에 값·가능 여부를 적지 않으므로 사실을 만들지 않는다.
★ fact 가 0건이어도(또는 API 키가 없어도) 채운다 — 그때는 LLM 을 부르지 않고 채우기만 한다.
"""
import uuid
from dataclasses import dataclass
from common.category_schema import CategorySchema, CategorySchemaError, get_schema
from common.database.db_session_manager import DB_SESSION_MNG
from common.faq_catalog import FaqCatalog, find_catalog
from common.database.model.models import place_facts, place_faqs, place_channels, places, place_units
from common.enums import (
DBWRType,
ErrorType,
FactStatus,
PlaceCategory,
SourceType,
)
from common.logger import LOG
from common.models.gmodel import UserInfo
from common.utils.gtime import GTime
from config.server_configs import external_api_config
from crud.fact_crud import FactCRUD
from crud.faq_crud import FaqCRUD
from crud.place_crud import PlaceCRUD
from router.v1.fact.protocol import Req_UpsertFact
from services import faq_fill, place_research
from services.external import gemini_text
from services.fact_service import FactService
from common.job_errors import PermanentJobError
_fact_crud = FactCRUD()
_faq_crud = FaqCRUD()
_place_crud = PlaceCRUD()
class CopyAborted(PermanentJobError):
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남는다."""
@dataclass
class CopyInputs:
place: places
schema: CategorySchema
grounded: list[gemini_text.FactInput]
records: list[str]
unit_summaries: list[dict]
catalog: FaqCatalog | None
known_fact_keys: set[str]
@property
def ungrounded(self) -> bool:
return not self.grounded and not self.unit_summaries
async def prepare_copy(place_id: str, owner_user_id: str) -> CopyInputs:
err, place = await DB_SESSION_MNG.execute_lambda(
places.DBType(),
DBWRType.DB_READ.value,
lambda s: _place_crud.get_place(s, uuid.UUID(owner_user_id), uuid.UUID(place_id)),
)
if err != ErrorType.SUCCESS or place is None:
raise CopyAborted(f"사업장을 찾을 수 없다: {place_id}")
try:
schema = get_schema(PlaceCategory(place.category))
except (CategorySchemaError, ValueError) as ex:
raise CopyAborted(f"지원하지 않는 업종: {place.category}") from ex
# ★ 노출 가능한 fact 만 근거로 준다. 미검증 값으로 쓴 문장은 그 자체가 미검증이다.
pid = uuid.UUID(place_id)
f_err, fact_rows = await DB_SESSION_MNG.execute_lambda(
place_facts.DBType(),
DBWRType.DB_READ.value,
lambda s: _fact_crud.list_facts(s, pid, None, None, True, True),
)
if f_err != ErrorType.SUCCESS:
raise CopyAborted(f"fact 조회 실패: {f_err.name}")
grounded = [
gemini_text.FactInput(
key=r.key,
label=(schema.get(r.key).label if schema.get(r.key) else r.key),
value=r.value,
unit=r.unit,
)
for r in fact_rows
if r.unit_id is None and (r.value or "").strip()
]
# ★ 수집 원문도 근거로 넘긴다 — fact 가 아니라 place_channels.raw 에 박제된 글이다.
#
# 왜 필요한가: 소개 원문(TourAPI overview·네이버 description)에만 있는 정보가 있다.
# '전면 통창 실내 온수풀', '판교역에서 3분' 같은 것들인데, 이게 근거에 없으면
# ground_check 가 그 문장을 전부 반려해 소개문·FAQ 가 앙상해진다.
#
# 왜 fact 로 넣지 않는가: `intro` 는 allow_llm=True 라 LLM 의 출력 칸이다.
# 원문을 그 칸에 넣었더니 457자 원문이 발행본의 '숙소 소개' 를 차지했다(2026-08-31).
# 근거로만 쓰고 저장은 하지 않는다 — 원문은 화면에 나가지 않는다.
# ★ 확정 링크만 읽던 것을 **조사 근거까지** 읽게 넓혔다(2026-09-10).
# 업소 조사(`place_research`)는 남이 쓴 글이라 확정하지 않는다 — 공식 채널이 아니므로
# 발행본의 sameAs·푸터에 나가면 안 된다. 그런데 그것 때문에 여기서도 안 읽혀서,
# 조사해 온 재료가 소개문에 한 글자도 닿지 않았다. 확정 여부는 "화면에 채널로
# 내보낼 것인가" 의 판단이지 "근거로 읽을 것인가" 의 판단이 아니다.
# ★ 다만 아무 미확정 링크나 읽지는 않는다 — raw.kind 가 research 인 것만이다.
# 미확정 채널 URL 은 동명 업소일 수 있고(그게 확정 절차의 이유다), 조사 근거는
# 상호 대조를 통과한 것만 적재된다(`grounding/place_research.parse_items`).
records: list[str] = []
l_err, link_rows = await DB_SESSION_MNG.execute_lambda(
place_channels.DBType(),
DBWRType.DB_READ.value,
lambda s: _place_crud.list_links(s, pid, False),
)
if l_err == ErrorType.SUCCESS:
for link in (link_rows or []):
raw = link.raw if isinstance(link.raw, dict) else {}
if link.confirmed_at is None and raw.get("kind") != place_research.RAW_KIND:
continue
text = (raw.get("text") or "").strip()
if text:
# ★ fact 목록이 아니라 records 로 넘긴다. fact 자리에 넣으면 모델이 값 하나로
# 읽고 거의 쓰지 않는다(prompts/copy.build_prompt 머리주석의 실측).
records.append(text[:4000])
# ground_check 는 여전히 이 글을 근거로 인정해야 한다 — 근거 목록에도 남긴다.
grounded.append(gemini_text.FactInput(
key=f"source:{link.link_id}", label="수집 원문", value=text[:4000],
))
# 객실·메뉴 요약도 근거로 넘긴다 — "최대 4명" 같은 수치가 통과하려면 근거에 있어야 한다.
#
# ★ 근거 없음 판정보다 **먼저** 읽는다.
# 예전에는 사업장 fact 가 0건이면 여기까지 오지 못하고 되돌아갔다. 그런데 네이버에
# 요금표만 올라온 모텔은 사업장 fact 가 0건이고 객실 fact 만 있다 — 쓸 근거가 있는데도
# "근거 없음"으로 끝나 소개문·FAQ 가 영구히 생기지 않았다.
u_err, unit_rows = await DB_SESSION_MNG.execute_lambda(
place_units.DBType(),
DBWRType.DB_READ.value,
lambda s: _place_crud.list_units(s, pid),
)
unit_summaries = []
if u_err == ErrorType.SUCCESS:
by_unit: dict = {}
for r in fact_rows:
if r.unit_id and (r.value or "").strip():
by_unit.setdefault(str(r.unit_id), {})[r.key] = r.value
unit_summaries = [
{
"name": u.name,
"facts": by_unit.get(str(u.unit_id), {}),
# 스키마 라벨·단위를 같이 넘긴다 — 이게 없으면 프롬프트에 'weekday_price' 라는
# 날 key 가 그대로 실려 모델이 그 낱말로 문장을 쓴다.
"labels": {
key: {
"label": schema.get(key).label if schema.get(key) else key,
"unit": schema.get(key).unit if schema.get(key) else None,
}
for key in by_unit.get(str(u.unit_id), {})
},
}
for u in unit_rows
if by_unit.get(str(u.unit_id))
]
# FAQ 채우기에 쓸 업종 카탈로그. 없으면(카페·음식점·호텔) 채우지 않는다.
catalog = find_catalog(place.category, place.external_category)
# 사업장·객실 fact 를 가리지 않는다 — "기준 인원" 은 객실 fact 로 답한다.
known_fact_keys = {r.key for r in fact_rows if (r.value or "").strip()}
return CopyInputs(place, schema, grounded, records, unit_summaries, catalog, known_fact_keys)
async def generate_copy(inputs: CopyInputs) -> gemini_text.GeneratedCopy:
try:
return await gemini_text.generate_copy(
inputs.place.name,
PlaceCategory(inputs.place.category),
inputs.grounded,
unit_summaries=inputs.unit_summaries or None,
records=inputs.records or None,
suggested_questions=faq_fill.suggested_questions(inputs.catalog, inputs.known_fact_keys) if inputs.catalog else None,
max_faqs=faq_fill.FAQ_TARGET,
model=external_api_config.gemini_text_model,
)
except gemini_text.GeminiNotConfigured as ex:
raise CopyAborted(str(ex)) from ex
async def save_copy(inputs: CopyInputs, copy: gemini_text.GeneratedCopy | None) -> dict:
pid = inputs.place.place_id
place_id = str(pid)
schema = inputs.schema
now = GTime.UTC()
stat = {
"place_id": place_id,
"grounded_facts": len(inputs.grounded),
"intro": False,
"meta": False,
"faqs": 0,
"faq_fill": 0, # 목표 수를 채운 문의 안내 문항 수
# ★ 반려된 문장을 그대로 남긴다 — 소개문이 왜 안 나왔는지 운영자가 알아야 한다.
"rejected": [list(r) for r in (copy.rejected or [])][:20] if copy else [],
}
if copy is None:
# 키만 없는 경우에는 기존 생성물을 보존한다.
if inputs.ungrounded and inputs.catalog is not None:
await DB_SESSION_MNG.execute_lambda_claim(
place_faqs.DBType(), lambda s: _faq_crud.expire_generated(s, pid, now),
)
return stat
actor = UserInfo(
# ★ 잡이 쓰는 신원. user_id 는 **사업장 주인**이어야 한다 — FactService 가 이 값으로
# 사업장을 스코프하고(fact_service._load_place) verified_by 에도 그대로 박는다.
# 회사를 걷어내기 전에는 스코프가 company_id 였고 여기엔 요청자·검증자·랜덤 uuid 가
# 순서대로 들어갔다. 그 랜덤 uuid 가 이제는 "남의 사업장" 이 되어 조회가 0건이 된다.
user_id=str(inputs.place.owner_user_id),
id="generator",
role=1,
)
service = FactService(_fact_crud, _place_crud)
# 소개문·메타는 fact 로 들어간다 — FactService 가 allow_llm 을 다시 확인하고(뒷문 없음),
# LLM 출처라 후보가 아니라 노출값으로 앉힌다(upsert_fact 의 LLM 분기).
for key, text_value in (("intro", copy.intro), ("meta_description", copy.meta_description)):
if not (text_value or "").strip():
continue
if not (schema.get(key) and schema.get(key).allow_llm):
# 이 업종 스키마가 LLM 작성을 허용하지 않는 필드다. 조용히 건너뛴다.
continue
res = await service.upsert_fact(
actor, place_id,
Req_UpsertFact(
key=key, value=text_value.strip(),
source_type=SourceType.LLM, source_url=f"gemini:{external_api_config.gemini_text_model}",
),
)
if res.result.success:
stat["intro" if key == "intro" else "meta"] = True
else:
stat["rejected"].append([key, res.result.desc])
# 확인 안 된 기존 생성 FAQ 는 내리고 새로 넣는다. 사람이 확인한 FAQ 는 건드리지 않는다.
await DB_SESSION_MNG.execute_lambda_claim(
place_faqs.DBType(),
lambda s: _faq_crud.expire_generated(s, pid, now),
)
for order, faq in enumerate(copy.faqs or []):
if not faq.fact_keys:
# ★ 근거 없는 FAQ 는 저장하지 않는다.
stat["rejected"].append([faq.question, "근거 fact 없음"])
continue
row = place_faqs(
place_id=pid,
question=faq.question,
answer=faq.answer,
source_fact_ids=list(faq.fact_keys),
generated_by=SourceType.LLM.value,
# ★ 바로 노출한다 (2026-09-10 결정 — fact_service.upsert_fact 주석이 근거).
# 근거 fact 가 없으면 위에서 이미 버렸으므로, 여기 남은 것은 전부 확인된 사실로 쓴 문장이다.
status=FactStatus.VERIFIED.value,
sort_order=order,
)
run_err = await DB_SESSION_MNG.execute_lambda_run(
[place_faqs.DBType()],
[lambda s, r=row: _faq_crud.add_faq(s, r)],
)
if run_err == ErrorType.SUCCESS:
stat["faqs"] += 1
LOG.i(f"[copy] place={place_id} 소개문 {'O' if stat['intro'] else 'X'} · FAQ {stat['faqs']}건 · "
f"반려 {len(stat['rejected'])}건 (근거 fact {len(inputs.grounded)}개)")
return stat
async def fill_faqs(pid: uuid.UUID, catalog: FaqCatalog, known_fact_keys: set[str], phone: str | None) -> int:
"""노출 중인 FAQ 가 목표 수에 모자란 만큼 문의 안내 문항을 넣는다. 넣은 건수를 돌려준다.
★ 기존 FAQ 는 **노출 중인 것 전부**로 센다 — 방금 넣은 생성분만이 아니라 재생성이 남긴
사장님 입력·정정분까지. 그래야 사장님이 이미 답한 주제에 문의 안내가 겹쳐 붙지 않는다.
★ 바로 노출값(VERIFIED)으로 넣는다. 답이 주장을 하지 않아 확인할 대상이 없다 —
대신 JSON-LD · llms.txt · 고유 콘텐츠 계수에서는 빠진다(shared selectAnsweredFaqs)."""
l_err, rows = await DB_SESSION_MNG.execute_lambda(
place_faqs.DBType(),
DBWRType.DB_READ.value,
lambda s: _faq_crud.list_faqs(s, pid, True),
)
if l_err != ErrorType.SUCCESS:
LOG.e_no_callstack(f"[copy] FAQ 채우기 건너뜀 — 목록 조회 실패 place={pid} {l_err.name}")
return 0
picks = faq_fill.pick_fill_faqs(
catalog,
[faq_fill.ExistingFaq(r.question, r.source_fact_ids) for r in rows],
known_fact_keys,
phone,
)
next_order = max((r.sort_order for r in rows), default=-1) + 1
added = 0
for offset, pick in enumerate(picks):
row = place_faqs(
place_id=pid,
question=pick.question,
answer=pick.answer,
source_fact_ids=None,
generated_by=SourceType.TEMPLATE.value,
status=FactStatus.VERIFIED.value,
sort_order=next_order + offset,
)
run_err = await DB_SESSION_MNG.execute_lambda_run(
[place_faqs.DBType()],
[lambda s, r=row: _faq_crud.add_faq(s, r)],
)
if run_err == ErrorType.SUCCESS:
added += 1
return added
+34
View File
@@ -0,0 +1,34 @@
"""작업 단계 기록. 실행 순서는 도메인 서비스, 화면 문구는 프론트가 소유한다."""
from contextlib import asynccontextmanager
from crud.job_crud import JobQueue
class JobProgress:
def __init__(self, job: dict, steps: tuple[str, ...]):
self.job = job
self.queue = JobQueue()
self.state = {
"attempt": job["attempts"],
"steps": [{"id": step, "status": "pending"} for step in steps],
}
async def _set(self, step_id: str, status: str, reason: str | None = None):
step = next(step for step in self.state["steps"] if step["id"] == step_id)
step.update(status=status, reason=reason)
if not await self.queue.set_progress(self.job, self.state):
raise RuntimeError("작업 소유권이 만료되어 진행 기록을 중단합니다")
@asynccontextmanager
async def step(self, step_id: str):
await self._set(step_id, "running")
try:
yield
except BaseException:
await self._set(step_id, "failed")
raise
else:
await self._set(step_id, "done")
async def skip(self, step_id: str, reason: str):
await self._set(step_id, "skipped", reason)
+25 -3
View File
@@ -1,6 +1,7 @@
from fastapi import Depends
from common.enums import ErrorType, JobType
from common.enums import ErrorType, JobType, UserRole
from common.models.gmodel import UserInfo
from common.logger import LOG
from crud.job_crud import JobQueue
from router.v1.job.protocol import JobData, Res_Job, Res_JobOps
@@ -15,13 +16,34 @@ class JobService:
def __init__(self, queue: JobQueue = Depends(JobQueue)):
self.queue = queue
async def get_job(self, job_id: str) -> Res_Job:
async def get_job(self, job_id: str, user_info: UserInfo | None = None) -> Res_Job:
"""잡 단건. ★ 주인이 아니면 **없는 것으로** 답한다(JOB_NOT_FOUND).
★ 잡 id 하나만 알면 남의 작업 결과가 열렸다(실측 2026-09-15). BUILD 결과에는
site_id · 게이트 상세(비어 있는 필수 항목 목록) · payload 경로가 들어 있다.
예전에는 COPY 만 주인을 봤는데, 가려야 할 것은 잡 종류가 아니라 **남의 사업장**이다.
★ 주인을 알 수 없는 잡(내부 동기화·노래 등 payload 에 owner_user_id 가 없는 것)은
사장님에게 열지 않는다 — '주인이 없으니 아무나' 가 아니라 '확인할 수 없으니 닫는다' 다.
★ user_info 가 None 인 호출은 내부 경로다(운영자 전용 requeue) — 그쪽은 이미
RequireDeveloper 가 막는다.
"""
res = Res_Job()
row = await self.queue.get(job_id)
if row is None:
res.result.SetResult(ErrorType.JOB_NOT_FOUND)
return res
res.job = JobData(**{k: v for k, v in row.items() if k in JobData.model_fields})
payload = row.get("payload") or {}
if user_info is not None and (user_info.role or 0) < UserRole.DEVELOPER.value:
owner = payload.get("owner_user_id")
if owner is None or str(owner) != str(user_info.user_id):
res.result.SetResult(ErrorType.JOB_NOT_FOUND)
return res
fields = {k: v for k, v in row.items() if k in JobData.model_fields}
# 어느 사업장의 작업인지는 종류를 가리지 않고 싣는다 — 화면이 "이 화면의 작업이 맞나" 를
# 이 값으로 판단한다(useGenerationJob 의 wrongJob).
if payload.get("place_id") is not None:
fields["place_id"] = payload.get("place_id")
res.job = JobData(**fields)
return res
async def ops(self) -> Res_JobOps:
+53 -17
View File
@@ -295,28 +295,55 @@ class PlaceService:
sess, uuid.UUID(user_info.user_id), ExternalPlaceSource.NAVER.value, str(naver_id),
),
)
canonical_id = place_id
#
# ★ **사장님이 새로 만들겠다고 누른 것은 뒤집지 않는다** (2026-09-15)
# 위 합치기는 "위저드를 다시 시작하면 빈 행이 쌓인다" 를 막으려던 것인데,
# [새로 크롤링하고 사이트 생성하기] 와 구분이 없어서 **일부러 다시 만들려는 경우도
# 기존 사업장으로 끌고 갔다** — 새로 만들기를 눌렀는데 기존 에디터가 열린다.
# 그래서 이어붙이기는 `reuse_existing` 이 켜져 있을 때만 한다.
#
# 끄더라도 **비어 있는 중복 행은 치운다.** 원래 막으려던 누적이 그것이고,
# 빈 행은 잃을 것이 없다. 지금 행은 앞으로 채워질 것이므로 대상이 아니다.
others = []
if err_dup == ErrorType.SUCCESS:
existing = next((r for r in (dup_rows or []) if str(r.place_id) != str(place_id)), None)
if existing is not None:
canonical_id = str(existing.place_id)
if await self._is_empty(place_id):
others = [r for r in (dup_rows or []) if str(r.place_id) != str(place_id)]
if others and not req.reuse_existing:
for row in others:
if await self._is_empty(str(row.place_id)):
await DB_SESSION_MNG.execute_lambda_claim(
places.DBType(),
lambda sess: self.crud.delete_place(
sess, uuid.UUID(user_info.user_id), uuid.UUID(place_id),
lambda sess, rid=row.place_id: self.crud.delete_place(
sess, uuid.UUID(user_info.user_id), rid,
),
)
LOG.i(f"[verify_by_url] 같은 업소가 이미 있다 — 빈 행 {place_id} 를 접고 "
f"{canonical_id} 로 잇는다 (naver {naver_id})")
else:
LOG.w(f"[verify_by_url] 같은 업소가 둘이다 — {place_id} 에 쌓인 것이 있어 "
f"지우지 않는다. 정본 {canonical_id} 를 돌려준다 (naver {naver_id})")
place_id = canonical_id
err_type, place = await self._load(user_info, place_id)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
LOG.i(f"[verify_by_url] 새로 만들기 — 빈 중복 행 {row.place_id} 를 치운다 "
f"(naver {naver_id})")
LOG.i(f"[verify_by_url] 새로 만들기 — 같은 업소가 {len(others)}개 있지만 "
f"{place_id} 로 새로 간다 (naver {naver_id})")
others = []
canonical_id = place_id
if others:
existing = others[0]
canonical_id = str(existing.place_id)
if await self._is_empty(place_id):
await DB_SESSION_MNG.execute_lambda_claim(
places.DBType(),
lambda sess: self.crud.delete_place(
sess, uuid.UUID(user_info.user_id), uuid.UUID(place_id),
),
)
LOG.i(f"[verify_by_url] 같은 업소가 이미 있다 — 빈 행 {place_id} 를 접고 "
f"{canonical_id} 로 잇는다 (naver {naver_id})")
else:
LOG.w(f"[verify_by_url] 같은 업소가 둘이다 — {place_id} 에 쌓인 것이 있어 "
f"지우지 않는다. 정본 {canonical_id} 를 돌려준다 (naver {naver_id})")
place_id = canonical_id
err_type, place = await self._load(user_info, place_id)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
coord = base.get("coordinate") or {}
verify_req = Req_VerifyPlace(
@@ -919,6 +946,15 @@ class PlaceService:
res.result.SetResult(err_type)
return res
# URL 에 잡 ID 를 쓰기 전에 응답이 끊겨도 완료된 작업을 다시 만들지 않는다.
if req.resume:
existing = await self.queue.find_latest(f"copy:{place_id}")
if existing:
res.job_id = uuid.UUID(existing["job_id"])
res.status = JobStatus(existing["status"])
res.created = False
return res
crud = FactCRUD()
f_err, rows = await DB_SESSION_MNG.execute_lambda(
facts_model.DBType(),
+40 -3
View File
@@ -217,10 +217,15 @@ class SiteService:
return reason, None
value = (slug or "").strip()
# ★ 주인 확인이 예약어보다 먼저다. 예약어 목록은 나중에 늘어나는데(목업 슬러그를 막는
# 것처럼), 늘린 이름을 이미 쓰고 있던 사장님이 자기 편집 화면을 여는 순간
# "이 주소는 못 씁니다" 가 뜬다 — 바꿀 수도 없는 주소다(발행 뒤 SITE_SLUG_LOCKED).
owner = await self._domain_owner(value)
if owner is not None and owner == str(uuid.UUID(place_id)):
return None, None
if reason is None:
owner = await self._domain_owner(value)
# ★ 이미 자기 주소면 쓸 수 있다 — 저장해 둔 화면을 다시 열었을 때 '중복'이라고 하면 안 된다.
if owner is None or owner == str(uuid.UUID(place_id)):
if owner is None:
return None, None
reason = site_slug.REASON_TAKEN
return reason, await self._suggest(value)
@@ -228,13 +233,25 @@ class SiteService:
async def check_slug(self, user_info: UserInfo, place_id: str, slug: str) -> Res_SlugCheck:
"""주소를 쓸 수 있는지 미리 본다.
★ 서버가 상호명으로 자동 확정하지 않는다 — 사람이 고르고, 겹치면 고르기 전에 알려 준다."""
★ 서버가 상호명으로 자동 확정하지 않는다 — 사람이 고르고, 겹치면 고르기 전에 알려 준다.
★ 확인과 저장은 같은 판정을 해야 한다. 발행 잠금(SITE_SLUG_LOCKED)을 여기서 안 보면
"쓸 수 있습니다" 라고 답해 놓고 저장에서 1707 로 튕긴다 — 지금은 발행 모달이
입력칸을 잠가 가려져 있을 뿐이고, API 를 직접 쓰는 쪽에는 그대로 드러난다."""
res = Res_SlugCheck()
err_type, _place = await self._load_place(user_info, place_id)
if err_type != ErrorType.SUCCESS:
res.result.SetResult(err_type)
return res
site = await self._get_site(place_id)
if site is not None and (site.published_at is not None or site.status == SiteStatus.PUBLISHED.value):
if (site.domain or "") != (slug or "").strip():
res.available = False
res.reason = site_slug.REASON_LOCKED
return res
res.available = True
return res
reason, suggestion = await self._judge_slug(place_id, slug)
res.available = reason is None
res.reason = reason
@@ -560,6 +577,26 @@ class SiteService:
res.result.SetResult(ErrorType.PLACE_NOT_VERIFIED)
return res
# ★ publish=False 는 **이미 나가 있는 사이트를 다시 굽는** 경로다. 한 번도 발행한 적
# 없는 사업장에는 쓸 수 없다.
# 왜 막나 — 빌드는 게이트를 판정하려고 payload 를 디스크에 쓰고, 프리렌더는 거기
# 생긴 것을 곧바로 공개 페이지로 굽는다(sitemap · llms.txt · /s 목록 포함).
# 그래서 publish=False 인데도 페이지가 공개됐고, DB 는 DRAFT·published_at=NULL 이라
# 빌더 화면은 "발행 전" 으로 보였다. 2차 게이트(고유 콘텐츠 · JSON-LD)는 구운 결과를
# 봐야 판정하므로 **거부돼도 페이지는 이미 나가 있었다**(실측 2026-09-15).
# 발행 전에 보고 싶은 것은 `GET /site/preview` 가 준다 — 그쪽은 디스크를 건드리지 않는다.
site = await self._get_site(place_id)
if not req.publish:
if site is None or site.published_at is None:
res.result.SetResult(ErrorType.SITE_VERSION_NOT_FOUND)
return res
# ★ 주소를 안 골랐어도 막지 않는다. 그때 쓰는 임시 슬러그(`slugify(상호명)-place_id[:8]`)에
# 한글이 남는 것은 실수가 아니라 결정이다 — 음차하면 같은 가게가 두 주소를 갖는다
# (`site_payload.slugify` 주석). 사람이 고르는 주소만 영문으로 제한한다.
# 발행 모달은 주소를 먼저 받게 되어 있고(PublishModal), API 로 건너뛰면 임시 주소로
# 나간 뒤 SITE_SLUG_LOCKED 로 잠긴다는 점은 그대로다.
job_id, created = await enqueue_job(
self.queue, JobType.BUILD,
{
+8
View File
@@ -48,6 +48,14 @@ RESERVED_SLUGS = frozenset({
"search", "index", "home", "main", "new", "edit", "delete", "create", "update",
# 값이 비었을 때 프론트가 문자열로 흘려보내는 것들 — 주소로 들어오면 버그의 흔적이다
"null", "undefined", "none", "nan", "true", "false",
# ★ 손으로 만든 목업이 쓰는 주소(solution/site/out/s, mockup/README).
# payload 가 없어 프리렌더가 굽지 않는 자리인데, 사장님이 이 주소로 발행하면
# **payload 가 생기는 순간** 덮여서 유일본이 영영 사라진다(AGENTS.md ★★ 항목).
# 실측(2026-09-15): `stay` 는 주인이 있어 우연히 TAKEN 이었을 뿐이고
# `stay2` · `stay3` 는 주인도 예약도 없어 "쓸 수 있다" 로 나갔다.
# ★ 굽기 쪽 보호(prerender PROTECTED_SLUGS)와 겹쳐 두는 것이지 대신하는 게 아니다 —
# 저쪽은 이미 나간 발행을 막고, 여기는 애초에 고르지 못하게 한다.
"stay", "stay2", "stay3",
})
+2 -1
View File
@@ -54,6 +54,7 @@ from crud.song_crud import SongCRUD
from services import place_research, site_payload
from services.external import gemini_text, suno
from services.llm.gemini import GeminiError, GeminiInvalidOutput, GeminiNotConfigured
from common.job_errors import PermanentJobError
_fact_crud = FactCRUD()
_place_crud = PlaceCRUD()
@@ -65,7 +66,7 @@ _song_crud = SongCRUD()
SONGS_DIRNAME = "songs"
class SongAborted(RuntimeError):
class SongAborted(PermanentJobError):
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남아 운영자가 본다."""
+2 -1
View File
@@ -18,12 +18,13 @@ from config.server_configs import external_api_config
from crud.media_crud import MediaCRUD
from crud.place_crud import PlaceCRUD
from services.external import gemini
from common.job_errors import PermanentJobError
_media_crud = MediaCRUD()
_place_crud = PlaceCRUD()
class VisionAborted(RuntimeError):
class VisionAborted(PermanentJobError):
"""재시도해도 소용없는 중단 — 잡의 last_error 로 남는다."""