commit 6784e59ca5c2c4d1df77ef2ec97a1f0f7b266b13 Author: Mina Choi Date: Mon Aug 31 13:57:59 2026 +0900 최초 커밋 — 기존 코드 전체 + 문서 체계 신설 git 저장소가 없어 히스토리·협업 기반이 아예 없던 상태를 연다. 함께 문서를 재편했다. 그동안 문서가 있어도 "이 제품이 뭘 푸는가"와 "어떻게 도는가"를 담은 문서가 없어서, 목표 문장이 backend/frontend README 두 곳에 복붙돼 있었다 — 상위 문서가 없어 아래로 샌 것이다. 신설 README.md 레포 진입점 + 문서 지도 + 문서 규칙 4가지 AGENTS.md 에이전트·신규 합류자용 함정 목록과 규약 (CLAUDE.md 는 여기로 걸린 심볼릭 링크) docs/PRODUCT.md 제품 정의 — 문제·사용자·원칙·**non-goals**·성공 기준 docs/ARCHITECTURE.md payload 경계·발행 파이프라인·서빙 결정·앱 분리 설계 이동 backend/docs/DECISIONS.md → docs/DECISIONS.md 백엔드만의 결정이 아니다. 게다가 코드 주석 ~25곳이 이미 `docs/DECISIONS.md` 로 적고 있어 레포 루트 기준으로는 그게 맞다. 갱신 docs/DEPLOY.md 서빙 결정 반영 — nginx 정적 서빙이 지금 경로(3절), Azure 는 나중에 켤 때(4절)로 분리 docs/ARCHITECTURE.md 사이트 = 한 장(2026-08-31) 구조 반영 docs/COLLECTION_SEO_AEO_FLOW.md robots.txt·sitemap.xml 은 오리진 루트에만 굽는다는 점 명시 frontend/site/scripts/prerender.ts 헤더 주석의 렌더 보고서 경로가 실제(422줄)와 달라 수정 .gitignore ★ CLAUDE.md 를 더 이상 무시하지 않는다. 에이전트 지침은 팀과 모든 에이전트가 공유하는 규약이라 커밋해야 한다 — 무시하면 클론한 사람이 "배포 후 republish_all.py 필수" 같은 함정을 전달받지 못한다. 개인용 오버라이드는 ~/.claude/CLAUDE.md 에 둔다. diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..4db4484 --- /dev/null +++ b/.env.example @@ -0,0 +1,83 @@ +# o2o-web4ai 환경변수 템플릿. +# cp .env.example .env 후 값을 채운다. .env 는 커밋되지 않는다(.gitignore). +# +# 우선순위: 실제 환경변수(docker-compose 등) > .env > config/config.{APP_ENV}.toml +# DB 접속·JWT 는 config.local.toml 이 기본값이다. 여기 값을 채우면 그쪽을 덮어쓴다. +# 외부 API 키는 toml 을 비워두고 여기서만 관리하는 것을 권장한다. + +# ── 실행 ───────────────────────────────────────────────── +APP_ENV=local +# RELOAD=1 # uvicorn --reload (개발 컨테이너) +# SCHEDULER_ENABLED=1 # 배치 스케줄러 기동. 다중 워커면 1개 프로세스에서만 1 + +# ── DB (비우면 config.local.toml 의 [MainDBConfig] 사용) ── +# DB_HOST=127.0.0.1 +# DB_PORT=5432 +# DB_USER=postgres +# DB_PASSWORD= +# DB_NAME=o2o_site_db + +# ── JWT 서명 키 ─────────────────────────────────────────── +# ★ 도커 이미지는 시크릿을 굽지 않으므로(config.local.toml 이 플레이스홀더 사본) +# 컨테이너로 띄울 땐 반드시 여기서 주입해야 한다. 비우면 공개된 플레이스홀더가 서명 키가 된다. +# 생성: python -c "import secrets; print(secrets.token_urlsafe(48))" +JWT_ACCESS_SECRET= +JWT_REFRESH_SECRET= + +# ── 외부 API 키 ─────────────────────────────────────────── +# 비어 있으면 해당 어댑터만 비활성된다. 서버는 그대로 뜬다. + +# 채널 URL 발견 (api.perplexity.ai, 모델 sonar / sonar-pro) +# ★ 지금은 **기본으로 꺼져 있다**(COLLECT_USE_PERPLEXITY=0). 키가 있어도 호출하지 않는다. +# 실측(2026-08-27 도플로·버터브루·힐튼 가든 인 서울 강남): 야놀자만 물어오고 네이버 +# 플레이스는 0건, 필터를 넓히면 네이버 도움말 페이지를 채널로 등록했다. 게다가 +# 검색 호출 요금이 토큰 요금과 별도로 붙는다(생성 1건당 15회). +# ★ 답변을 사실로 쓰지 않는다. URL 발견 전용 — 동명 업소가 섞이고 환각이 있다. +PERPLEXITY_API_KEY= + +# Perplexity 채널 URL 발견 스위치. 0=끔(기본) / 1=켬. +# 코드는 지우지 않고 여기서만 끈다 — 야놀자·여기어때 어댑터가 붙으면 배포 없이 되켠다. +# 끈 상태에서도 상호 → 네이버 place id 직접 해석은 계속 돈다(유일한 자동 발견 경로). +COLLECT_USE_PERPLEXITY=0 + +# 동일 업소 검증 · 주변 정보 (dapi.kakao.com) +# https://developers.kakao.com > 내 애플리케이션 > 앱 키 > REST API 키 +# ★ 무료 쿼터는 개발자 계정의 "첫 번째 활성 앱" 에만 붙는다. +# dev/stage/prod 앱을 따로 파면 하나만 무료다 — 앱을 나누기 전에 확인할 것. +# 초과 단가: 키워드/카테고리 검색 2원, 좌표 변환 0.5원 (키워드가 4배 비싸다) +# 동일 업소 검증 — 네이버 지역검색 (카카오 키 미발급이라 이쪽을 쓴다) +# https://developers.naver.com/apps 검색 API +# ★ 제약: display 최대 5건 · telephone 이 빈 값으로 온다 · 행정구역 코드 없음 +# → 카카오보다 동일 업소 판정 근거가 약하다(AMBIGUOUS 가 늘어난다) +NAVER_CLIENT_ID= +NAVER_CLIENT_SECRET= + +KAKAO_REST_API_KEY= + +# 사진 분류 + 카피 작성 (Google AI Studio) +# https://aistudio.google.com/apikey +GEMINI_API_KEY= + +# 축제 · 관광지 (한국관광공사 TourAPI, data.go.kr) +# ★ TourAPI 는 자체 areaCode/sigunguCode 체계를 쓴다 — 카카오 행정구역 코드와 다르므로 매핑이 필요하다. +# 디코딩된 서비스키를 넣는다(인코딩 키를 넣으면 %2B 등이 이중 인코딩된다). +TOUR_API_KEY= + +# Open-Meteo(날씨)는 API 키가 필요 없다. 좌표만 있으면 된다. +# ── 발행 호스트 ── +# 커스텀 도메인이 없는 사이트의 공개 주소(`https://<이 값>/s/`). +# canonical·og:url·sitemap·IndexNow 가 전부 이 값을 쓴다. 비우면 w4ai.o2o.kr. +# ★ 프론트(admin)의 VITE_PUBLISH_HOST 와 **같은 값**이어야 화면과 발행본이 갈리지 않는다. +SITE_PUBLIC_HOST=w4ai.o2o.kr + +# Azure Blob 정적 사이트 발행. 비우면 기존 로컬 out/ 발행만 사용한다. +AZURE_STORAGE_CONNECTION_STRING= +AZURE_STORAGE_CONTAINER=$web +AZURE_STORAGE_PREFIX=ai-for-web + +# ── 색인 통보(IndexNow) ── +# 발행 즉시 네이버·Bing·Yandex 에 URL 을 알린다. 비우면 통보를 건너뛴다(발행은 정상). +# 구글은 IndexNow 를 지원하지 않는다 — 구글 쪽은 Search Console 사이트맵 제출이 별도 경로다. +# 값은 8~128자의 영문·숫자·하이픈 아무 문자열이면 된다(비밀이 아니다. 공개되어야 작동한다): +# python3 -c "import uuid; print(uuid.uuid4().hex)" +INDEXNOW_KEY= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..58dc088 --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +# 환경변수: 실제 값(.env)은 커밋하지 않는다. 템플릿(.env.example)만 커밋한다. +.env +.env.* +!.env.example + +# 설정: 시크릿 포함이라 커밋하지 않는다. *.example 만 커밋한다. +*.toml +!*.toml.example + +# Python 바이트코드/캐시 — 절대 커밋하지 않는다. +__pycache__/ +*.py[cod] +*$py.class +.pytest_cache/ + +# 가상환경 +.venv/ +venv/ + +# 생성물(FastAPI OpenAPI 스펙). 필요 시 재생성한다. +backend/openapi.json + +# 발행 payload 는 frontend/site/payloads/.gitignore 가 단일 출처다 — 여기에 겹쳐 쓰지 않는다. + +# 정적 산출물 — 운영에서는 Docker named volume(site-out)에 있고, 로컬에서 직접 구우면 +# 여기 생긴다. 어느 쪽이든 payload 로 다시 굽는 재생성물이라 git 이 관리할 대상이 아니다. +frontend/site/out/ +frontend/site/dist/ +frontend/admin/dist/ + +# OS +.DS_Store + +# ── 에이전트 지침은 커밋한다 ────────────────────────────────────────────── +# AGENTS.md / CLAUDE.md 는 팀과 모든 에이전트가 공유하는 규약이라 반드시 커밋한다. +# 개인용 오버라이드는 레포가 아니라 ~/.claude/CLAUDE.md 나 .claude/settings.local.json 에 둔다. +.claude/settings.local.json diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..d128964 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,77 @@ +# AGENTS.md — 이 레포에서 작업하기 전에 + +에이전트와 신규 합류자가 **먼저 읽는 파일**이다. 여기에는 *밟기 쉬운 함정*과 *규약*만 둔다. +설명은 각 문서가 단일 출처다 — 여기로 복사하지 말고 링크한다. + +| 궁금한 것 | 문서 | +|---|---| +| 이 제품이 뭘 푸나 · **안 하기로 한 것** | [docs/PRODUCT.md](docs/PRODUCT.md) | +| 어떻게 도나 · 앱 경계 | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | +| **다음에 뭘 만드나** (우선순위 P0~P4) | [docs/DEVELOPMENT_DIRECTION.md](docs/DEVELOPMENT_DIRECTION.md) | +| 미결 사항 · 코드가 그걸 어떻게 격리했나 | [docs/DECISIONS.md](docs/DECISIONS.md) | +| 서버에 올릴 때 | [docs/DEPLOY.md](docs/DEPLOY.md) | + +--- + +## 이 레포의 한 가지 규칙 + +**백엔드는 HTML 을 만들지 않는다.** payload JSON 을 파일로 떨어뜨리고, Node 프리렌더가 그걸 읽어 +정적 사이트를 굽는다. 두 쪽은 서로를 모르고 **디렉토리 하나로만 만난다.** +이 경계를 넘는 변경은 하기 전에 [ARCHITECTURE.md 1절](docs/ARCHITECTURE.md)을 읽는다. + +## 반드시 알아야 할 함정 + +밟으면 **조용히 틀린다** — 빌드는 성공하고 화면도 뜨는데 결과가 잘못된 종류다. + +- **번들 파일명은 콘텐츠 해시다.** HTML 은 `/assets/index-DvNTmLhy.css` 를 **루트 절대경로**로 + 가리킨다. 경로는 프리렌더가 `dist/client/.vite/manifest.json` 에서 읽어 박는다 + (`prerender.ts:160`). 렌더러 CSS 를 고치면 이름이 바뀐다. +- **로컬 `out/assets` 는 빌드마다 통째로 갈린다** (`prerender.ts:573` `rmSync`). 옛 해시 파일이 + 사라지므로 새 번들로 일부 사이트만 구우면 나머지는 CSS 가 404 다. + → 프리렌더 기동 시 전체 재굽기가 이 구멍을 메운다. +- **★ 프론트(`frontend/site`)를 배포하면 반드시 전체 재굽기 + 전체 재업로드.** + `azure_static.publish(slug)` 는 공용 자산 + `s/` 만 올린다 — + **렌더러를 고쳐도 다른 사이트에는 반영되지 않는다.** + → `docker compose restart web` 후 `python scripts/republish_all.py` +- **발행 호스트는 두 곳에 있고 같아야 한다.** 백엔드 `SITE_PUBLIC_HOST`(기본 `w4ai.o2o.kr`, + `site_payload.py`) ↔ 프론트 `VITE_PUBLISH_HOST`. canonical·og:url·sitemap·IndexNow 가 전부 + 이 값을 쓴다. 그리고 **`origin` 은 payload JSON 에 구워진다** — 호스트를 바꾸면 프리렌더 + 재실행만으로는 안 되고 **백엔드에서 재발행**해 payload 를 다시 만들어야 한다. +- **`AZURE_STORAGE_PREFIX` 와 루트 절대경로는 충돌한다.** HTML 이 `/assets/…` 를 가리키는데 + 블롭은 `ai-for-web/assets/…` 에 놓인다. 접두사를 쓰려면 오리진 경로를 `/ai-for-web` 로 잡는 + CDN 을 앞에 세워야 한다. 아니면 비워라. + (프리렌더는 서브패스 마운트를 지원한다 — `basePath` 가 `/sites/s/joy` 면 자산은 `/sites/assets`.) +- **`AZURE_STORAGE_CONTAINER=$web`** — 셸에서 export 할 땐 반드시 작은따옴표(`'$web'`). +- **슬러그 규칙은 두 곳에 있고 같아야 한다**: `site_payload.publish_slug()` ↔ + `frontend/shared/src/lib/slug.ts publishUrl`. 어긋나면 발행은 성공하고 주소만 404 다. +- **디렉토리 요청 → `index.html`.** `/s/` 가 **끝 슬래시 없이** 열려야 한다. + 정적 서버를 바꾸든 nginx 설정을 만지든 이 규칙부터 확인한다. + +## 코드 규약 + +- **미결 사항은 코드로 풀지 않는다.** [DECISIONS.md](docs/DECISIONS.md) 1절이 보류한 것은 + 플래그·어댑터로 격리해 두고, 결론이 나면 **날짜와 함께 결론을 적고 격리를 제거한다.** +- **수집 어댑터를 추가하기 전에** [DECISIONS.md](docs/DECISIONS.md) 1-1 과 + [DATA_SOURCE_RESEARCH.md](docs/DATA_SOURCE_RESEARCH.md)를 읽는다. + 봇 탐지 우회는 **결론과 무관하게 영구 금지**다. +- **주석은 "왜"를 적는다.** 이 레포의 기존 주석이 그 톤이다 — 실측값, 밟았던 함정, 안 한 이유. + 코드를 읽으면 알 수 있는 "무엇"은 쓰지 않는다. +- 문서는 코드와 **같은 커밋**에서 고친다. 동작을 바꿨는데 문서를 안 고쳤으면 미완이다. + +## 실행 + +```bash +docker compose up -d # API :9800 · 워커 · web :3000 · nginx :80 +docker compose logs -f worker +``` + +- 발행 사이트: `http://localhost:3000/s/` (admin Vite 가 :3001 정적서버로 프록시) +- DB 는 compose 밖이다 (호스트 PostgreSQL, `host.docker.internal`). `.env` 없으면 `cp .env.example .env` +- 백엔드 스크립트는 `backend/` 에서 `.venv/bin/python scripts/.py` +- 테스트: `backend/` 에서 `.venv/bin/pytest`. **`APP_ENV=test` 면 `.env` 를 읽지 않는다** — + 실키가 테스트로 새어 외부 API 요금이 나가는 경로를 막아 뒀다 + +## 커밋 + +- 한 커밋 = 한 가지 변경. 문서와 그 문서가 설명하는 코드는 같은 커밋에 둔다. +- 커밋 메시지는 한국어로, **무엇을 왜 바꿨는지**. 파일 목록은 `git` 이 이미 안다. diff --git a/README.md b/README.md new file mode 100644 index 0000000..bb65e5f --- /dev/null +++ b/README.md @@ -0,0 +1,63 @@ +# o2o-web4ai + +**상호명 하나로 소상공인 홈페이지를 만들어 발행하는 서비스.** + +목표는 예쁜 사이트가 아니다 — **AI 검색과 검색엔진이 이 가게를 "공식 홈페이지 기준"으로 +설명하게 만드는 것**이다. 그래서 산출물은 SPA 가 아니라 **크롤러가 그대로 읽는 정적 HTML** 이고, +발행 게이트가 통과시키지 않은 값은 사이트에 나가지 않는다. + +- 무엇을 · 누구를 위해 · 무엇을 안 하는가 → **[docs/PRODUCT.md](docs/PRODUCT.md)** +- 어떻게 도는가 (파이프라인·앱 경계) → **[docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)** +- 에이전트·신규 합류자가 먼저 읽을 규약 → **[AGENTS.md](AGENTS.md)** + +## 실행 + +```bash +cp .env.example .env # DB_*, JWT_*, 외부 API 키 +docker compose up -d # API :9800 · 워커 · web :3000 +docker compose logs -f worker +``` + +| | 주소 | +|---|---| +| 빌더/운영 화면 | http://localhost:3000 | +| 발행된 사이트 | http://localhost:3000/s/`` | +| API 문서 | http://localhost:9800/docs | + +DB 는 compose 밖이다 (호스트 PostgreSQL, `host.docker.internal`). +백엔드 스크립트는 `backend/` 에서 `.venv/bin/python scripts/.py`. + +## 레포 구조 + +``` +backend/ FastAPI + 워커. HTML 을 만들지 않는다 — payload JSON 만 떨어뜨린다 +frontend/ + admin/ 빌더(사장님) + 내부 운영 화면 — ★ 분리 예정, ARCHITECTURE.md 4절 + site/ 발행 사이트. SSR 엔트리 + 프리렌더 + 정적 서버 + shared/ 두 앱과 백엔드 계약이 만나는 타입·규칙 (SitePayload, slug) +docs/ 아래 표 +postgres-init/ 스키마 DDL +``` + +## 문서 지도 + +| 문서 | 언제 읽나 | +|---|---| +| [docs/PRODUCT.md](docs/PRODUCT.md) | 이 제품이 뭘 푸는지 · **안 하기로 한 것**이 뭔지 | +| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | 발행 파이프라인 전체 · 앱을 어떻게 나눌지 | +| [docs/DEVELOPMENT_DIRECTION.md](docs/DEVELOPMENT_DIRECTION.md) | v19 설계서 대비 격차 · **개발 우선순위(P0~P4)** | +| [docs/DECISIONS.md](docs/DECISIONS.md) | 미결 사항과, 코드가 그걸 어떻게 격리해 뒀는지 | +| [docs/DEPLOY.md](docs/DEPLOY.md) | 서버에 올릴 때 · 배포 후 재발행 절차 | +| [docs/DATA_SOURCE_RESEARCH.md](docs/DATA_SOURCE_RESEARCH.md) | 어디서 콘텐츠를 가져올 수 있나 (실측 근거) | +| [docs/COLLECTION_SEO_AEO_FLOW.md](docs/COLLECTION_SEO_AEO_FLOW.md) | 수집→LLM→SEO/AEO 현재 구현 | +| [docs/API_USAGE.md](docs/API_USAGE.md) | API 비용 — 제품 원가와 개발비 구분 | +| [docs/DEVELOPMENT_DIRECTION.md](docs/DEVELOPMENT_DIRECTION.md) | Web4AI v19 설계서와 현재 구현의 차이 · 추가 개발 우선순위 | + +## 문서 규칙 + +1. **한 사실은 한 곳에.** 중복된 문서는 썩고, 썩은 문서는 사람과 에이전트를 적극적으로 오도한다. + 다른 문서의 내용은 복사하지 말고 링크한다. +2. **코드가 말해주는 건 쓰지 않는다.** 문서에 적을 값어치가 있는 건 *왜 이렇게 했는지*, + *왜 저건 안 했는지*, 그리고 **실측값**(날짜와 함께)이다. +3. **결론이 나면 `DECISIONS.md` 에 날짜와 함께 적고, 격리해 둔 플래그를 제거한다.** +4. 문서는 코드와 같은 커밋·같은 리뷰에서 고친다. 동작을 바꾸는 PR 이 문서를 안 고쳤으면 미완이다. diff --git a/backend/.dockerignore b/backend/.dockerignore new file mode 100644 index 0000000..0c8c6a0 --- /dev/null +++ b/backend/.dockerignore @@ -0,0 +1,23 @@ +__pycache__/ +# `__pycache__/` 는 최상위만 매칭한다 — 하위 디렉터리(config/, common/ …)까지 빼려면 ** 가 필요하다. +# (원본 보일러플레이트엔 이 줄이 없어 config/__pycache__ 가 이미지에 들어가 있었다.) +**/__pycache__/ +*.pyc +.pytest_cache/ +.git/ +tests/ +loadtest/ +*.md + +# 가상환경 — 호스트 전용(수백 MB). 컨테이너는 requirements.txt 로 새로 설치한다. +.venv/ +venv/ + +# 시크릿 — 이미지에 굽지 않는다. Dockerfile 이 example 을 복사해 넣고, +# 실값은 compose env 로 주입한다(server_configs 의 env override). +config/config.local.toml +# 테스트 설정 — 컨테이너에서 pytest 를 돌리지 않는다(테스트는 호스트 venv 에서). +config/config.test.toml +# 레포 최상위 .env 는 빌드 컨텍스트(./backend) 밖이라 애초에 안 들어오지만, 방어적으로 막아둔다. +.env +.env.* diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..7f87406 --- /dev/null +++ b/backend/.env.example @@ -0,0 +1,31 @@ + +# ── 수집 어댑터 ──────────────────────────────────────────── +# 켤 어댑터 id(쉼표 구분). 배포 없이 채널 하나를 내릴 수 있게 코드가 아니라 env 로 둔다. +COLLECT_ADAPTERS=mock,naver_place + +# 네이버 플레이스 GraphQL 은 익명 요청을 429 로 막는다. +# 정상 보유한 세션 쿠키가 있으면 여기에 둔다. ★ IP 회전·핑거프린트 위조는 하지 않는다. +NAVER_COOKIES= + +# ── 채널 URL 발견 ────────────────────────────────────────── +# Perplexity 로 채널 URL 을 찾을지. **기본 0(끔)** — 코드는 남아 있고 env 로만 켠다. +# +# ★ 왜 껐나 (실측 2026-08-27) +# · '도플로'·'버터브루'·'힐튼 가든 인 서울 강남' 세 곳 전부 야놀자만 물어왔다. +# 네이버 플레이스는 **0건**. 도메인 필터를 map.naver.com 까지 넓혔더니 이번엔 +# pages.map.naver.com/useful-tips(네이버 도움말 페이지)를 이 가게 채널로 등록했다. +# · 검색 호출 요금이 토큰 요금과 별도로 붙는다. 생성 1건마다 15회씩 나갔다. +# · 대신 네이버 플레이스는 **URL 만 있으면 100%** 된다(fact 5~7건 + 사진 10장). +# 그래서 1순위는 "사장님이 네이버 지도 주소를 붙여넣는다", 2순위는 상호로 place id +# 직접 해석(services/external/naver_place_lookup.py)이다. +# +# 1 로 켜는 시점: 야놀자·여기어때 어댑터가 붙어서, 그 채널 URL 을 찾는 값이 생겼을 때. +COLLECT_USE_PERPLEXITY=0 + +# ── 발행 산출물 ──────────────────────────────────────────── +# BUILD 잡이 발행 payload JSON 을 떨어뜨릴 디렉토리. 없으면 만든다. +# 이 JSON 하나가 정적 렌더러(frontend/site)의 유일한 입력이다 — +# npm run prerender -- --payload=<이 디렉토리 또는 그 안의 파일> → out//index.html +# 컨테이너 밖(볼륨·오브젝트 스토리지)으로 빼기 쉬우라고 코드가 아니라 env 로 둔다. +# ★ 쓰기에 실패해도 발행은 진행된다(경고 로그만). 발행 기록은 DB 가 진실이다. +SITE_PAYLOAD_DIR=/app/out/payloads diff --git a/backend/Dockerfile b/backend/Dockerfile new file mode 100644 index 0000000..ce1e824 --- /dev/null +++ b/backend/Dockerfile @@ -0,0 +1,36 @@ +# o2o-web4ai 백엔드 이미지 — API 와 워커가 **같은 이미지**를 공유하고 command 로만 갈린다. +# API : python web_main.py (요청 접수/조회, :9800) +# 워커 : python worker_main.py (수집·비전분석·빌드 잡 처리, 포트 없음) +# +# Phase 1 은 collector 가 MockAdapter 만 등록하므로 브라우저가 필요 없다 → 이 lean 이미지 하나면 된다. +# 크롤링 법무 검토가 끝나 HeadlessAdapter 를 붙이면, 그때 Chrome+Xvfb 를 담은 별도 워커 이미지 +# (Dockerfile.worker)를 만들어 갈라낸다 — 선례: o2o-negosium/lps/Dockerfile.worker +# +# 시크릿은 이미지에 굽지 않는다 — config 는 example(플레이스홀더)로 대체되고, +# 실제 값은 compose 의 env(DB_USER/DB_PASSWORD, *_API_KEY 등)로 주입된다(server_configs override). +FROM python:3.12-slim + +WORKDIR /app + +# 의존성 먼저 설치 (레이어 캐시 활용) +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +# 시크릿 든 config.local.toml 은 .dockerignore 로 제외됨 → example(플레이스홀더)로 대체. +# 실값은 env 주입: DB_HOST/DB_PORT/DB_USER/DB_PASSWORD/DB_NAME, +# PERPLEXITY_API_KEY/KAKAO_REST_API_KEY/GEMINI_API_KEY/TOUR_API_KEY +RUN cp config/config.local.toml.example config/config.local.toml + +# 항상 APP_ENV=local 로 실행 → config.local.toml(=example 사본) + env override. +ENV APP_ENV=local + +EXPOSE 9800 + +# API 컨테이너용. 워커는 command 를 갈아끼우고 이 헬스체크를 쓰지 않는다 +# (워커는 포트가 없다 — 하트비트 파일 기반 체크는 필요해질 때 추가한다). +HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \ + CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:9800/healthz', timeout=4).status==200 else 1)" + +CMD ["python", "web_main.py"] diff --git a/backend/README.md b/backend/README.md new file mode 100644 index 0000000..e452535 --- /dev/null +++ b/backend/README.md @@ -0,0 +1,257 @@ +# o2o-web4ai Backend + +상호명 하나로 소상공인 홈페이지를 만들어 주는 서비스의 API 서버. +목표는 예쁜 사이트가 아니라 **AI 검색이 이 가게를 공식 홈페이지 기준으로 설명하게 만드는 것**. + +`o2o-negosium/negodata/backend` 보일러플레이트를 이식했다 — 레이어 구조·설정 로딩·DB 세션·프로토콜 규약은 원본과 동일하다. + +## 현재 상태 + +**수집 → 생성 → 빌드 → 발행 파이프라인이 API 로 다 열렸다.** 프론트(`frontend/admin`)가 이 API 를 붙여 쓴다. + +| 모듈 | 상태 | 역할 | +|---|---|---| +| `places` | 완료 | 사업장 등록·조회, 동일 업소 검증, 하위 단위, 채널 URL 확정 | +| `facts` | 완료 | fact CRUD, 검증 상태 전이, 업종 스키마 조회 | +| `faqs` | 완료 | FAQ 목록·승인(검증 상태 전이)·직접 추가 — ★ 승인된 것만 FAQPage JSON-LD 로 나간다 | +| `collector` | 완료 | 수집 파이프라인 (어댑터 패턴 — Phase 1 은 MockAdapter 만) | +| `generator` | 완료 | Gemini 호출 — 사진 분류(vision), 소개문·FAQ 작성(copy) | +| `local` | 스키마 완료 / API 미착수 | 지역 정보 (날씨·축제·관광지·맛집) + 행정구역 코드 단위 캐싱 | +| `sites` | 완료 | 사이트 상태, 정적 빌드, 발행 검수 게이트, 발행 상태 전이 | +| `media` | 스키마 완료 / 조회 API 미착수 | 사진·alt. 수집·비전이 채우지만 아직 읽을 창구가 없다 | +| `reports` | 미착수 | 노출 리포트, 유입 통계 | + +> OpenAPI 스펙은 `python scripts/export_openapi.py` 로 서버 없이 뽑을 수 있다 +> (프론트의 orval 이 이 파일을 읽는다). + +### 업종 스키마 + +업종마다 필드가 완전히 다르므로(숙박=체크인시간, 카페=브레이크타임) `facts` 는 key-value 로 두고, +**어떤 key 가 존재하는가**는 업종별 JSON 스키마가 정의한다. + +``` +common/category_schema/resources/ +├── lodging.json 숙박 필드 30 (critical 14) +├── cafe.json 카페 필드 23 (critical 12) +├── restaurant.json 음식점 필드 24 (critical 15) +└── tour_activity.json 관광체험 필드 24 (critical 17) +``` + +**업종 추가 = JSON 파일 1개 + `PlaceCategory` 코드 1줄.** 로직은 건드리지 않는다. + +필드 속성 — `critical` 과 `allow_llm` 이 절대규칙과 직결된다. + +| 속성 | 뜻 | +|---|---| +| `scope` | `place`(사업장 단위) / `unit`(객실·메뉴·프로그램 단위) | +| `required` | 발행 검수 게이트의 필수 항목. 빠지면 `PUBLISH_REQUIRED_FACT_MISSING` | +| `critical` | ★ 틀리면 헛걸음·예약 클레임이 나는 항목. 미검증 상태로 절대 노출하지 않는다 | +| `allow_llm` | LLM 이 값을 만들어도 되는가. **기본 False** — True 인 것은 소개문처럼 문장 자체가 산출물인 필드뿐 | + +```python +from common.category_schema import get_schema, is_valid_key +from common.enums import PlaceCategory + +schema = get_schema(PlaceCategory.LODGING) +schema.required_keys("place") # ['check_in_time', 'check_out_time', 'cancel_policy', ...] +schema.critical_keys() # 미검증이면 노출 금지인 key 목록 +is_valid_key(PlaceCategory.CAFE, "check_in_time") # False — 업종에 없는 key 는 거부 +``` + +### fact 검증 상태 + +``` +UNVERIFIED ──┬─> PENDING_OWNER ──┬─> VERIFIED ──┬─> CORRECTED ──> REJECTED + │ │ │ │ ▲ + ├──────────────────>┤ ├───────┘ └── (사장님만 다시 고침) + │ │ │ + └─> REJECTED / EXPIRED ────────────┴──> UNVERIFIED (재수집으로만 부활) +``` + +- **노출 가능**: `VERIFIED` · `CORRECTED` (`PUBLISHABLE_FACT_STATUSES`) +- **잠김**: `CORRECTED` (`LOCKED_FACT_STATUSES`) — 자동 갱신이 사장님 수정본을 덮어쓰지 않는다 +- 허용 전이는 `FACT_STATUS_TRANSITIONS` 한 곳에만 있다. 없는 전이는 `FACT_INVALID_TRANSITION` 으로 거부 +- **활성 fact 는 (사업장, 단위, key) 당 1건** — DB 부분 유니크 인덱스로 강제. + `REJECTED`·`EXPIRED` 는 이력이라 유니크에서 빠진다 + +미결 사항(크롤링 법적 검토 · 이미지 재게시 권리 · 관리자 수정 범위 · 해지 정책)은 [../docs/DECISIONS.md](../docs/DECISIONS.md). + +## 디렉토리 구조 + +``` +o2o-web4ai/ +├── .env.example # 외부 API 키·DB 접속 주입 템플릿 (cp .env.example .env) +├── postgres-init/ +│ ├── init-data/init.sql # 스키마 DDL 전부 (재실행 안전) +│ └── alters/ # 컬럼 추가/타입 변경 누적 (YYYY-MM-DD-<주제>.sql) +└── backend/ + ├── web_main.py # 엔트리포인트 (uvicorn) + ├── config/ # 환경설정 (APP_ENV 별 toml 로드) + ├── conftest.py, tests/ # pytest (test DB 자동 create/drop) — 아래 '테스트' + ├── common/ + │ ├── enums.py # ErrorType / 코드값 enum / EXCEPTION_* / fact 상태 전이표 + │ ├── category_schema/ # ★ 업종별 fact 스키마 (resources/*.json + 로더) + │ ├── models/gmodel.py # 프로토콜 베이스 (WebPacketProtocol 등) + │ └── database/ + │ ├── db_session_manager.py# ★ DB Read/Write + 람다 실행 핵심 + │ └── model/models.py # ORM 모델 (16 테이블) + ├── crud/ # 도메인별 DB 접근 (I*CRUD 인터페이스 + 구현) + ├── services/ # 비즈니스 로직 + ├── scheduler/ # 배치 크론 (현재 등록된 잡 없음) + └── router/ + ├── router.py # FastAPI app (CORS 등) + └── v1/ # 도메인별 라우터 + └── validator/dependencies.py # ★ JWT 발급·검증, 해시(bcrypt), RemoveNoneResponse, RequireOwner +``` + +## 핵심 패턴 +- **MVC**: router(컨트롤러) → service(로직) → crud(쿼리). crud 는 인터페이스/구현 분리. +- **Depends 주입**: service 가 `IUserCRUD = Depends(UserCRUD)`, router 가 `Depends(AuthService)`, 인증은 `Depends(IsValidAccessToken)`. +- **DB Read/Write 분리**: `DBType` × `DBWRType` 조합마다 별도 async 엔진(조회=Read, 변경=Write). +- **람다 DB 실행**: service 는 세션을 직접 열지 않고 람다를 매니저에 넘긴다. 세션/트랜잭션은 매니저가 책임. + ```python + err, user = await DB_SESSION_MNG.execute_lambda( # 단일 조회 + users.DBType(), DBWRType.DB_READ.value, lambda s: crud.get_user_by_login_id(s, id)) + err = await DB_SESSION_MNG.execute_lambda_run( # 여러 변경 = 1 트랜잭션 + [users.DBType()], [lambda s: crud.update_last_accessed(s, uid)]) + ``` +- **비동기**: 전 계층 async/await, SQLAlchemy async + asyncpg, task 단위 scoped session. +- **Protocol 규약**: 모든 패킷 `WebPacketProtocol` 상속, `Req_*`/`Res_*`(응답엔 `result: ErrorInfo`), 라우터별 `protocol.py`. +- **ResponseNone**: 응답의 `None` 필드 재귀 제거(`RemoveNoneResponse`). +- **bcrypt 비차단**: `GetHashedPW`/`VerifyPW` 를 `asyncio.to_thread` 로 오프로드(이벤트 루프 비차단). + +## API 도메인 (`/v1/*`) +전체 스펙은 실행 후 **http://localhost:9800/docs** (Swagger). + +| prefix | 요약 | +|---|---| +| `/healthz` | 헬스체크 — 서버 기동 시각(UTC) 반환 | +| `/v1/auth` | 로그인 · access 토큰 재발급 · 내 정보(`me`) | +| `/v1/place` | 사업장 등록·조회 · **동일 업소 검증** · 하위 단위(객실·메뉴·프로그램) · 채널 URL 등록/**확정** · **수집 시작** | +| `/v1/place/{id}/fact` | 업종 스키마 조회 · fact 기록 · **검증 상태 전이** | +| `/v1/place/{id}/faq` | FAQ 목록 · **승인·정정 전이** · 사장님 직접 추가 | +| `/v1/job` | 잡 상태 폴링 · 큐 운영 스냅샷 · DEAD 잡 재큐 | +| `/v1/place/{id}/site` | 사이트 상태(재빌드 필요 여부) · **사이트 주소 확인/예약** · **정적 빌드/발행** · 버전 목록 · 발행 기록 · 발행 상태 전이 | + +수집처럼 몇 분 걸리는 작업은 **잡을 적재하고 즉시 응답**한다. + +``` +POST /v1/place/{id}/collect → { job_id, status: PENDING } +GET /v1/job/{job_id} → { status: RUNNING → DONE, result } ← 폴링 +``` + +★ **발행 엔드포인트는 따로 없다.** 발행 검수 게이트가 BUILD 잡 안에 있어서 +(`services/build_service` → `services/publish_gate`) 게이트를 우회하는 경로 자체를 만들지 않았다. +그래서 발행은 `POST /v1/place/{id}/site/build {publish: true}` 하나고, +**잡이 DONE 이어도 발행됐다는 뜻이 아니다** — 게이트가 막으면 잡은 정상 종료하고 +`result.gate.passed` 가 false, `build_status` 가 FAILED 로 온다. 호출측이 그걸 읽어야 한다. + +### 사이트 주소(네임스페이스) + +주소는 **사장님이 고른다.** 서버가 상호명으로 자동 확정하지 않는다 — 한 번 정하면 AI 검색이 색인하는 +영구 식별자라 되돌리는 비용이 사장님 몫이 된다. + +``` +GET /v1/place/{id}/site/slug/check?slug=doflo → { available, reason?, suggestion? } +POST /v1/place/{id}/site/slug {slug} → sites.domain 에 저장(사이트 행 없으면 생성) +``` + +- 규칙(정규식·예약어)은 [services/site_slug.py](services/site_slug.py) **한 곳**에 있고 확인과 저장이 같이 쓴다. + 소문자 영문·숫자·하이픈 3~50자만 — 한글 주소는 퍼센트 인코딩(`/s/%EC%8A%A4…`)이라 사람이 불러줄 수 없다. +- 저장 직전에 서버가 같은 규칙으로 다시 본다. **클라이언트 검증을 믿지 않는다.** +- 중복은 `uq_sites_domain` 이 최종 판정한다. 지금 자기가 쓰는 주소면 중복이 아니다. +- ★ **이미 발행된 사이트의 주소는 바꾸지 않는다**(`SITE_SLUG_LOCKED`). 색인된 주소가 바뀌면 + AI 검색이 잡아 둔 페이지가 404 가 되고 그 자리를 다시 OTA 가 가져간다 — '해지는 상태 전이지 삭제가 아니다' 와 같은 이유다. + +### DB 스키마 (16 테이블) + +| schema | 테이블 | +|---|---| +| `company` | `companies` `users` | +| `place` | `places` `place_aliases` `place_links` `units` `media` | +| `fact` | `facts` `faqs` | +| `local` | `local_contents` `routes` `nearby_links` | +| `site` | `sites` `site_versions` `publish_logs` `ai_check_results` | + +핵심 게이트 3개가 컬럼으로 박혀 있다. + +| 게이트 | 컬럼 | 뜻 | +|---|---|---| +| 동일 업소 검증 | `places.verified_at` | NULL 이면 수집·발행 진입 금지 | +| 채널 URL 확정 | `place_links.confirmed_at` | NULL 이면 크롤링 대상 아님 | +| 사실 노출 | `facts.status` | `VERIFIED`·`CORRECTED` 만 사이트로 나간다 | + +> 인증 헤더: `Authorization: Bearer `. + +## 설정 + +| 무엇 | 어디 | 커밋 | +|---|---|---| +| DB 접속 · JWT · 포트 | `backend/config/config.local.toml` | ✗ (`*.toml` ignore) | +| 외부 API 키 | 레포 최상위 `.env` | ✗ | +| 템플릿 | `config/config.local.toml.example` · `.env.example` | ✓ | + +우선순위: **실제 환경변수(docker-compose) > `.env` > `config.{APP_ENV}.toml`** + +`APP_ENV=test` 이면 `.env` 를 읽지 않는다 — 실키가 새어 들어가면 테스트가 실제 외부 API 를 때린다. + +## 실행 + +DB 준비(최초 1회) — 로컬 PostgreSQL 에 스키마를 적용한다. +```bash +psql -h 127.0.0.1 -p 5432 -U postgres -f ../postgres-init/init-data/init.sql +# 호스트에 psql 이 없으면 도커 컨테이너의 psql 로 태운다: +# docker exec -i -e PGPASSWORD=password negosium-db \ +# psql -h 127.0.0.1 -U postgres -d postgres -v ON_ERROR_STOP=1 < ../postgres-init/init-data/init.sql +``` + +서버 실행. +```bash +cd .. +cp .env.example .env # 최초 1회, 외부 API 키 채우기 +cd backend +cp config/config.local.toml.example config/config.local.toml # 최초 1회, DB·JWT 채우기 +python3 -m venv .venv && source .venv/bin/activate +pip install -r requirements.txt +python web_main.py # APP_ENV 기본 local → http://localhost:9800/docs +``` +환경: `config.{local,test}.toml` (`APP_ENV` 로 선택). +`SCHEDULER_ENABLED=1` 인 프로세스에서만 배치 스케줄러가 뜬다(다중 워커 중복 실행 방지). + +## 테스트 + +**테스트는 호스트(venv)에서 돌린다** — DB(PostgreSQL)만 `127.0.0.1:5432` 에 떠 있으면 된다. +test DB(`o2o_site_test_db`)는 알아서 만들어졌다 지워지므로 **수동 세팅이 필요 없다.** + +```bash +cd backend +source .venv/bin/activate +pip install pytest pytest-asyncio # 테스트 도구(requirements 에 없음) + +python -m pytest # 전체 +python -m pytest -v # 테스트별 PASS/FAIL +python -m pytest tests/test_auth.py # 파일 하나만 +``` +venv 를 활성화하지 않으면 `.venv/bin/python -m pytest` 로 직접 지정한다. 정상이면 마지막 줄에 `NN passed`. + +동작 방식 (전부 [conftest.py](conftest.py) 가 자동 처리): +- `APP_ENV` 를 `test` 로 자동 설정 → [config.test.toml](config/config.test.toml) 의 **`o2o_site_test_db`** 사용(dev DB 와 완전 분리). +- **세션 시작 시 test DB 를 새로 만들고(CREATE), 끝나면 내린다(DROP).** 매번 현재 모델로 새로 빌드돼 스키마가 낡을 일이 없다. +- 테이블은 `create_all` 로 자동 생성, 매 테스트 전 `TRUNCATE` 로 비워 격리. +- 안전가드: 이름에 `test` 없는 DB 는 만들지도 지우지도 않는다(실 DB 보호). + +> ⚠ **전체 실행(`python -m pytest`)을 동시에 두 개 돌리지 마라.** 세션마다 같은 test DB 를 +> CREATE/DROP 하므로 서로의 DB 를 지워 엉뚱한 실패가 난다. 병렬로 작업 중이면 +> 각자 파일 단위로 돌리고(`pytest tests/test_kakao.py`), 전체 실행은 한 번에 하나만. + +## 절대 규칙 (도메인 코드를 얹을 때) + +1. **미검증 fact 는 응답에 포함하지 않는다.** `VERIFIED`/`CORRECTED` 만 노출. 특히 체크인·취사·반려동물·취소 규정. +2. **고유 콘텐츠가 1건도 없으면 발행 API 가 거부한다.** +3. **구조화 데이터(JSON-LD) 값 = 화면에 보이는 값.** 불일치 시 빌드 실패. +4. **생성 사이트는 정적 빌드.** DB 는 빌드 시점에만 읽고 방문자와 만나지 않는다. +5. **개별 재빌드 단위로 설계.** 전체 재빌드만 되면 사이트 1,000개에서 못 쓴다. +6. **관리자에서 수정한 값은 잠긴다.** 자동 갱신이 사장님 수정본을 덮어쓰지 않는다. +7. **LLM 은 사실을 만들지 않는다.** 문장만 쓴다. +8. **실시간 혼잡도·대기시간 API 를 만들지 않는다.** 출처가 없다. +9. **외부 API 실패 시 직전 값을 유지한다.** 빈 값을 내보내지 않고 내부 알림만 발생시킨다. diff --git a/backend/common/authz.py b/backend/common/authz.py new file mode 100644 index 0000000..6e7b1a3 --- /dev/null +++ b/backend/common/authz.py @@ -0,0 +1,9 @@ +from common.enums import UserRole + + +def is_owner_or_admin(resource_user_id, user_id, role) -> bool: + """변경 액션 공용 소유권 판정 — 리소스 소유자(user_id 일치) 또는 최고관리자 이상(OWNER/DEVELOPER)이면 True. + + 프론트의 버튼 게이팅과 같은 규칙을 백엔드에서 강제하는 단일 출처. + 소유자 없는 공용 리소스(예: user_id NULL 공용카드)는 이 판정 대상이 아니다(도메인별 별도 처리).""" + return str(resource_user_id) == str(user_id) or (role or 0) >= UserRole.OWNER.value diff --git a/backend/common/category_schema/__init__.py b/backend/common/category_schema/__init__.py new file mode 100644 index 0000000..2f52d55 --- /dev/null +++ b/backend/common/category_schema/__init__.py @@ -0,0 +1,26 @@ +"""업종별 fact 스키마 패키지. + +업종마다 필드가 완전히 다르므로(숙박=체크인시간, 카페=브레이크타임) facts 는 key-value 로 두고, +'어떤 key 가 존재하는가'는 업종별 JSON 스키마가 정의한다. + +**업종 추가 = resources/ 에 JSON 파일 1개 추가 + PlaceCategory 에 코드 1줄.** 로직 수정 없음. +""" +from common.category_schema.loader import ( + CategorySchema, + CategorySchemaError, + FieldSpec, + all_schemas, + get_schema, + is_valid_key, + load_schemas, +) + +__all__ = [ + "CategorySchema", + "CategorySchemaError", + "FieldSpec", + "all_schemas", + "get_schema", + "is_valid_key", + "load_schemas", +] diff --git a/backend/common/category_schema/loader.py b/backend/common/category_schema/loader.py new file mode 100644 index 0000000..97a4317 --- /dev/null +++ b/backend/common/category_schema/loader.py @@ -0,0 +1,171 @@ +"""업종별 fact 스키마 — 업종마다 어떤 key 가 존재하는지의 유일한 소스. + +resources/*.json 을 최초 사용 시 메모리에 로드한다. DB 에 저장하지 않으며 런타임에 수정하지 않는다. +**업종 추가 = resources/ 에 JSON 파일 1개 추가 + PlaceCategory 에 코드 1줄 추가.** 코드 수정은 없다. + +검증 실패 시 예외를 던진다(요청 실패가 아니라 잘못된 리소스 배포를 조기에 드러내기 위함 — +파일은 코드와 함께 배포되므로 정상 배포에선 실패하지 않는다). + +필드 속성 + key : facts.key 에 저장되는 식별자. 업종 안에서 유일해야 한다 + label : 화면·프롬프트에 쓰는 한글 이름 + type : text | number | bool | time + scope : place(사업장 단위) | unit(객실·메뉴·프로그램 단위) + required : 발행 검수 게이트의 필수 항목. 빠지면 PUBLISH_REQUIRED_FACT_MISSING + critical : ★ 틀리면 손님이 헛걸음하거나 예약 클레임이 나는 항목. + 미검증 상태로는 절대 노출하지 않는다(절대규칙 1) + allow_llm : LLM 이 값을 만들어도 되는 필드인가. **False 가 기본** — LLM 은 사실을 만들지 않는다. + True 인 것은 소개문처럼 '문장' 자체가 산출물인 필드뿐이다(절대규칙 7) + unit : 값의 단위(원·명·분…). 없으면 null +""" +import json +from pathlib import Path + +from common.enums import PlaceCategory + +_RESOURCE_DIR = Path(__file__).parent / "resources" + +_ALLOWED_TYPES = ("text", "number", "bool", "time") +_ALLOWED_SCOPES = ("place", "unit") + +_schemas: dict | None = None # category code -> CategorySchema + + +class CategorySchemaError(RuntimeError): + """업종 스키마 로드/검증 실패.""" + + +class FieldSpec: + """업종 스키마의 필드 1개. JSON 한 행에 대응한다.""" + + __slots__ = ("key", "label", "type", "scope", "required", "critical", "allow_llm", "unit") + + def __init__(self, row: dict, source: str): + for name in ("key", "label", "type", "scope"): + if not isinstance(row.get(name), str) or not row[name]: + raise CategorySchemaError(f"{source}: 필드 '{name}' 이 비었거나 문자열이 아님 — {row}") + if row["type"] not in _ALLOWED_TYPES: + raise CategorySchemaError(f"{source}: type 값 오류 key={row['key']} type={row['type']} (허용 {_ALLOWED_TYPES})") + if row["scope"] not in _ALLOWED_SCOPES: + raise CategorySchemaError(f"{source}: scope 값 오류 key={row['key']} scope={row['scope']} (허용 {_ALLOWED_SCOPES})") + for name in ("required", "critical", "allow_llm"): + if not isinstance(row.get(name), bool): + raise CategorySchemaError(f"{source}: '{name}' 은 bool 이어야 함 key={row['key']} value={row.get(name)}") + + self.key = row["key"] + self.label = row["label"] + self.type = row["type"] + self.scope = row["scope"] + self.required = row["required"] + self.critical = row["critical"] + self.allow_llm = row["allow_llm"] + self.unit = row.get("unit") + + def to_dict(self) -> dict: + return {name: getattr(self, name) for name in self.__slots__} + + +class CategorySchema: + """업종 1개의 fact 스키마.""" + + def __init__(self, doc: dict, source: str): + code = doc.get("code") + try: + self.category = PlaceCategory(code) + except ValueError as ex: + raise CategorySchemaError(f"{source}: PlaceCategory 에 없는 code={code}") from ex + self.name = doc.get("category") + self.label = doc.get("label") + if not isinstance(self.name, str) or not isinstance(self.label, str): + raise CategorySchemaError(f"{source}: category/label 이 문자열이 아님") + + rows = doc.get("fields") + if not isinstance(rows, list) or not rows: + raise CategorySchemaError(f"{source}: fields 가 비었음") + + self.fields: dict[str, FieldSpec] = {} + for row in rows: + spec = FieldSpec(row, source) + if spec.key in self.fields: + raise CategorySchemaError(f"{source}: key 중복 — {spec.key}") + self.fields[spec.key] = spec + + @property + def code(self) -> int: + return self.category.value + + def get(self, key: str) -> FieldSpec | None: + return self.fields.get(key) + + def has(self, key: str) -> bool: + return key in self.fields + + def keys_by_scope(self, scope: str) -> list[str]: + return [k for k, f in self.fields.items() if f.scope == scope] + + def required_keys(self, scope: str | None = None) -> list[str]: + """발행 검수 게이트가 존재를 확인하는 필수 key 목록.""" + return [k for k, f in self.fields.items() if f.required and (scope is None or f.scope == scope)] + + def critical_keys(self) -> list[str]: + """★ 미검증 상태로 노출하면 안 되는 key 목록(체크인·취사·반려동물·취소 규정 등).""" + return [k for k, f in self.fields.items() if f.critical] + + def llm_writable_keys(self) -> list[str]: + """LLM 이 값을 만들어도 되는 key 목록. 나머지는 LLM 이 값을 채울 수 없다.""" + return [k for k, f in self.fields.items() if f.allow_llm] + + +def load_schemas() -> None: + """리소스 디렉터리 전체 로드 + 검증. 최초 1회 호출(멱등). + 파일을 하나 추가하면 그대로 새 업종이 된다 — 로더 코드는 건드리지 않는다.""" + global _schemas + if _schemas is not None: + return + + paths = sorted(_RESOURCE_DIR.glob("*.json")) + if not paths: + raise CategorySchemaError(f"업종 스키마 파일이 없습니다: {_RESOURCE_DIR}") + + loaded: dict[int, CategorySchema] = {} + for path in paths: + try: + doc = json.loads(path.read_text(encoding="utf-8")) + except Exception as ex: + raise CategorySchemaError(f"업종 스키마 파일 로드 실패: {path}: {ex}") from ex + schema = CategorySchema(doc, path.name) + if schema.code in loaded: + raise CategorySchemaError(f"업종 code 중복: {schema.code} ({path.name})") + loaded[schema.code] = schema + + missing = [c.name for c in PlaceCategory if c.value not in loaded] + if missing: + raise CategorySchemaError(f"PlaceCategory 에 있으나 스키마 파일이 없는 업종: {missing}") + + _schemas = loaded + + +def get_schema(category) -> CategorySchema: + """업종 코드(int 또는 PlaceCategory) → 스키마. 없는 업종이면 CategorySchemaError.""" + if _schemas is None: + load_schemas() + code = category.value if isinstance(category, PlaceCategory) else category + schema = _schemas.get(code) + if schema is None: + raise CategorySchemaError(f"지원하지 않는 업종 코드: {code}") + return schema + + +def all_schemas() -> dict: + """전 업종 스키마. {code: CategorySchema}""" + if _schemas is None: + load_schemas() + return dict(_schemas) + + +def is_valid_key(category, key: str) -> bool: + """해당 업종에 존재하는 fact key 인지. facts 쓰기 전 검증에 쓴다(FACT_INVALID_KEY).""" + try: + return get_schema(category).has(key) + except CategorySchemaError: + return False diff --git a/backend/common/category_schema/resources/cafe.json b/backend/common/category_schema/resources/cafe.json new file mode 100644 index 0000000..4892f11 --- /dev/null +++ b/backend/common/category_schema/resources/cafe.json @@ -0,0 +1,31 @@ +{ + "category": "cafe", + "code": 2, + "label": "카페", + "fields": [ + { "key": "business_hours", "label": "영업시간", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "closed_days", "label": "휴무일", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "break_time", "label": "브레이크타임", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "last_order", "label": "라스트오더", "type": "time", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "pet_allowed", "label": "반려동물 동반", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "kids_allowed", "label": "아동 입장", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "parking", "label": "주차 가능", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "parking_free_hours", "label": "무료 주차 시간", "type": "number", "scope": "place", "required": false, "critical": true, "allow_llm": false, "unit": "시간" }, + { "key": "seat_count", "label": "좌석 수", "type": "number", "scope": "place", "required": false, "critical": false, "allow_llm": false, "unit": "석" }, + { "key": "wifi", "label": "와이파이", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "power_outlet", "label": "콘센트", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "study_allowed", "label": "장시간 이용", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "terrace", "label": "테라스·야외석", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "takeout", "label": "테이크아웃", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "delivery", "label": "배달", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "signature_menu", "label": "대표 메뉴", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "price_range", "label": "가격대", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "payment_methods", "label": "결제 수단", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "wheelchair_accessible", "label": "휠체어 접근", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "intro", "label": "카페 소개", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": true }, + + { "key": "menu_name", "label": "메뉴명", "type": "text", "scope": "unit", "required": true, "critical": false, "allow_llm": false }, + { "key": "menu_price", "label": "메뉴 가격", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" }, + { "key": "menu_intro", "label": "메뉴 소개", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": true } + ] +} diff --git a/backend/common/category_schema/resources/lodging.json b/backend/common/category_schema/resources/lodging.json new file mode 100644 index 0000000..61991af --- /dev/null +++ b/backend/common/category_schema/resources/lodging.json @@ -0,0 +1,38 @@ +{ + "category": "lodging", + "code": 1, + "label": "숙박", + "fields": [ + { "key": "check_in_time", "label": "체크인 시간", "type": "time", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "check_out_time", "label": "체크아웃 시간", "type": "time", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "cancel_policy", "label": "취소·환불 규정", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "cooking_allowed", "label": "취사 가능", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "pet_allowed", "label": "반려동물 동반", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "smoking", "label": "흡연 가능", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "extra_person_fee", "label": "인원 추가 요금", "type": "number", "scope": "place", "required": false, "critical": true, "allow_llm": false, "unit": "원" }, + { "key": "reception_hours", "label": "프런트 운영시간", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "parking", "label": "주차 가능", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "parking_capacity", "label": "주차 대수", "type": "number", "scope": "place", "required": false, "critical": false, "allow_llm": false, "unit": "대" }, + { "key": "wifi", "label": "와이파이", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "bbq_available", "label": "바비큐 이용", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "bbq_fee", "label": "바비큐 이용료", "type": "number", "scope": "place", "required": false, "critical": true, "allow_llm": false, "unit": "원" }, + { "key": "breakfast", "label": "조식 제공", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "baby_amenities", "label": "유아용품 비치", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "pickup_service", "label": "픽업 서비스", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "intro", "label": "숙소 소개", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": true }, + + { "key": "room_type", "label": "객실 타입", "type": "text", "scope": "unit", "required": true, "critical": false, "allow_llm": false }, + { "key": "standard_capacity", "label": "기준 인원", "type": "number", "scope": "unit", "required": true, "critical": true, "allow_llm": false, "unit": "명" }, + { "key": "max_capacity", "label": "최대 인원", "type": "number", "scope": "unit", "required": true, "critical": true, "allow_llm": false, "unit": "명" }, + { "key": "bed_type", "label": "침대 구성", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": false }, + { "key": "room_size", "label": "객실 면적", "type": "number", "scope": "unit", "required": false, "critical": false, "allow_llm": false, "unit": "㎡" }, + { "key": "bathroom_count", "label": "욕실 수", "type": "number", "scope": "unit", "required": false, "critical": false, "allow_llm": false, "unit": "개" }, + { "key": "has_kitchen", "label": "주방 여부", "type": "bool", "scope": "unit", "required": false, "critical": true, "allow_llm": false }, + { "key": "has_aircon", "label": "에어컨", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false }, + { "key": "view", "label": "전망", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": false }, + { "key": "weekday_price", "label": "주중 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" }, + { "key": "weekend_price", "label": "주말 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" }, + { "key": "peak_price", "label": "성수기 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" }, + { "key": "room_intro", "label": "객실 소개", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": true } + ] +} diff --git a/backend/common/category_schema/resources/restaurant.json b/backend/common/category_schema/resources/restaurant.json new file mode 100644 index 0000000..e4a8672 --- /dev/null +++ b/backend/common/category_schema/resources/restaurant.json @@ -0,0 +1,32 @@ +{ + "category": "restaurant", + "code": 3, + "label": "음식점", + "fields": [ + { "key": "business_hours", "label": "영업시간", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "closed_days", "label": "휴무일", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "break_time", "label": "브레이크타임", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "last_order", "label": "라스트오더", "type": "time", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "reservation_required", "label": "예약 필수", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "reservation_channel", "label": "예약 방법", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "pet_allowed", "label": "반려동물 동반", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "kids_allowed", "label": "아동 입장", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "corkage", "label": "콜키지", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "room_available", "label": "룸·별실", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "group_seat_max", "label": "단체석 최대 인원", "type": "number", "scope": "place", "required": false, "critical": true, "allow_llm": false, "unit": "명" }, + { "key": "parking", "label": "주차 가능", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "parking_capacity", "label": "주차 대수", "type": "number", "scope": "place", "required": false, "critical": false, "allow_llm": false, "unit": "대" }, + { "key": "takeout", "label": "포장", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "delivery", "label": "배달", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "payment_methods", "label": "결제 수단", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "signature_menu", "label": "대표 메뉴", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "price_range", "label": "가격대", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "wheelchair_accessible", "label": "휠체어 접근", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "intro", "label": "가게 소개", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": true }, + + { "key": "menu_name", "label": "메뉴명", "type": "text", "scope": "unit", "required": true, "critical": false, "allow_llm": false }, + { "key": "menu_price", "label": "메뉴 가격", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" }, + { "key": "menu_min_order", "label": "최소 주문 인분", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "인분" }, + { "key": "menu_intro", "label": "메뉴 소개", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": true } + ] +} diff --git a/backend/common/category_schema/resources/tour_activity.json b/backend/common/category_schema/resources/tour_activity.json new file mode 100644 index 0000000..74b7623 --- /dev/null +++ b/backend/common/category_schema/resources/tour_activity.json @@ -0,0 +1,32 @@ +{ + "category": "tour_activity", + "code": 4, + "label": "관광체험", + "fields": [ + { "key": "operating_hours", "label": "운영시간", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "closed_days", "label": "휴무일", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "reservation_required", "label": "예약 필수", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "reservation_channel", "label": "예약 방법", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "cancel_policy", "label": "취소·환불 규정", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "age_limit", "label": "연령 제한", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "safety_notice", "label": "안전 유의사항", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "weather_dependent", "label": "우천 시 운영", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false }, + { "key": "what_to_bring", "label": "준비물", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "session_times", "label": "회차 시간", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "guide_language", "label": "안내 언어", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "parking", "label": "주차 가능", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "wheelchair_accessible", "label": "휠체어 접근", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false }, + { "key": "locker_available", "label": "물품보관함", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "shower_available", "label": "샤워시설", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false }, + { "key": "intro", "label": "체험 소개", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": true }, + + { "key": "program_name", "label": "프로그램명", "type": "text", "scope": "unit", "required": true, "critical": false, "allow_llm": false }, + { "key": "program_duration", "label": "소요 시간", "type": "number", "scope": "unit", "required": true, "critical": true, "allow_llm": false, "unit": "분" }, + { "key": "program_capacity", "label": "회차당 정원", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "명" }, + { "key": "program_min_people", "label": "최소 출발 인원", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "명" }, + { "key": "price_adult", "label": "성인 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" }, + { "key": "price_child", "label": "소인 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" }, + { "key": "program_level", "label": "난이도", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": false }, + { "key": "program_intro", "label": "프로그램 소개", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": true } + ] +} diff --git a/backend/common/cost.py b/backend/common/cost.py new file mode 100644 index 0000000..8a1a52f --- /dev/null +++ b/backend/common/cost.py @@ -0,0 +1,198 @@ +"""사이트 1건 생성 원가 미터 — **$1 예산을 코드로 강제한다.** + +★ 제품 제약: **업소 1곳의 사이트를 만드는 데 드는 외부 API 비용은 $1(1,400원)을 넘으면 안 된다.** + 이 모듈은 그 예산을 "문서에 적힌 목표" 가 아니라 **호출을 막는 가드**로 만든다. + + 쓰는 법 — 사이트 1건 = 미터 1개: + + meter = CostMeter(place_id=42) + meter.guard(Provider.PERPLEXITY, calls=1, tokens=3000) # 호출 "전" 에 물어본다 + ...실제 호출... + meter.charge(Provider.PERPLEXITY, calls=1, tokens=3100) # 호출 "후" 에 실측을 적는다 + + `guard()` 가 BudgetExceeded 를 던지면 **그 호출은 하지 않는다.** 이미 쓴 돈은 못 돌려받지만 + 다음 호출을 막아 손실이 선형으로 늘어나는 것을 끊는다. + +비용 리스크 순서(큰 것부터): Gemini(사진 장수에 비례) > Perplexity(토큰+요청 요금) > Kakao(건당 2원). +""" + +from dataclasses import dataclass, field +from enum import Enum + +from common.logger import LOG + +# ── 예산 ──────────────────────────────────────────────────────── +USD_KRW = 1400.0 # 환산 환율. 실제 청구 환율과 다를 수 있다. +SITE_BUDGET_KRW = 1400.0 # ★ 사이트 1건당 상한 = $1 +# 예산의 몇 %까지 차면 경고를 남길지. 넘겨도 막지는 않는다 — 막는 건 100% 지점이다. +WARN_RATIO = 0.7 + + +class Provider(Enum): + PERPLEXITY = "perplexity" + KAKAO = "kakao" + GEMINI = "gemini" + TOUR_API = "tour_api" + OPEN_METEO = "open_meteo" + + +@dataclass(frozen=True) +class Rate: + """공급자별 단가(원 기준). + + confirmed=False 는 **아직 공식 단가표로 확인하지 않은 추정치**라는 뜻이다. + 추정치로 예산을 계산하면 "예산 안" 이라는 결론 자체가 추정이 된다 — + 실제 배치를 돌리기 전에 `assert_rates_confirmed()` 로 막는다. + """ + + per_call_krw: float = 0.0 # 호출 1건당 고정비 + per_search_krw: float = 0.0 # 검색 1회당 (Perplexity 는 토큰과 별도 과금) + per_1k_token_krw: float = 0.0 # 토큰 1,000개당 + per_image_krw: float = 0.0 # 이미지 1장당 + confirmed: bool = False + source: str = "" + + +# ── 단가표 ────────────────────────────────────────────────────── +# ★ 확정된 것만 confirmed=True 다. 나머지는 자리만 잡아둔 추정치이므로 +# 공식 단가표를 확인해서 교체하기 전에는 실배치를 돌리면 안 된다. +RATES: dict[Provider, Rate] = { + # 레포에 확정값이 있다(.env.example): 키워드/카테고리 검색 2원, 좌표 변환 0.5원. + # 좌표 변환은 per_call 로 따로 세지 않고 호출측이 kakao_coord 로 구분해 넘긴다. + Provider.KAKAO: Rate( + per_call_krw=2.0, + confirmed=True, + source=".env.example — 키워드/카테고리 검색 2원 (무료 쿼터 초과분)", + ), + # Sonar 기본 search_context_size=low: 요청 $5/1K + 입력/출력 각각 $1/1M. + # 2026-08-28 환산(USD_KRW=1,400)이다. 내부 검색 횟수에는 별도 요금이 없다. + Provider.PERPLEXITY: Rate( + per_call_krw=7.0, + per_1k_token_krw=1.4, + confirmed=True, + source="https://docs.perplexity.ai/docs/getting-started/pricing — Sonar low context", + ), + # ★ 미확인 — Google AI Studio 단가표 확인 후 교체할 것. + Provider.GEMINI: Rate( + per_image_krw=1.0, + per_1k_token_krw=0.5, + confirmed=False, + source="추정치", + ), + # 공공데이터·무료. + Provider.TOUR_API: Rate(confirmed=True, source="공공데이터포털 무료(일 트래픽 제한)"), + Provider.OPEN_METEO: Rate(confirmed=True, source="무료, 키 불필요"), +} + +# 카카오 좌표 변환은 키워드 검색보다 4배 싸다 — 같은 공급자지만 단가가 다르다. +KAKAO_COORD_KRW = 0.5 + + +class BudgetExceeded(Exception): + """사이트 1건 예산을 넘겼다. 호출측은 **더 호출하지 말고** 작업을 중단한다.""" + + def __init__(self, place_id: int | None, spent_krw: float, would_add_krw: float): + self.place_id = place_id + self.spent_krw = spent_krw + self.would_add_krw = would_add_krw + super().__init__( + f"사이트 원가 예산 초과 (place_id={place_id}): " + f"이미 {spent_krw:.1f}원 + 이번 {would_add_krw:.1f}원 > 상한 {SITE_BUDGET_KRW:.0f}원" + ) + + +class UnconfirmedRate(Exception): + """추정 단가로 실배치를 돌리려 했다.""" + + +def assert_rates_confirmed(*providers: Provider) -> None: + """실배치 직전에 호출한다. 추정 단가가 섞여 있으면 막는다. + + ★ 이걸 건너뛰면 "예산 안에 들어온다" 는 결론이 추정 위에 서게 된다. + """ + bad = [p for p in (providers or tuple(RATES)) if not RATES[p].confirmed] + if bad: + names = ", ".join(p.value for p in bad) + raise UnconfirmedRate( + f"단가 미확인: {names} — 공식 단가표로 RATES 를 교체한 뒤에 배치를 돌려라" + ) + + +def estimate_krw( + provider: Provider, + *, + calls: int = 0, + searches: int = 0, + tokens: int = 0, + images: int = 0, + kakao_coord_calls: int = 0, +) -> float: + """이번 호출의 원가(원)를 계산한다. 실측이든 예상이든 같은 식을 쓴다.""" + rate = RATES[provider] + krw = ( + rate.per_call_krw * calls + + rate.per_search_krw * searches + + rate.per_1k_token_krw * (tokens / 1000.0) + + rate.per_image_krw * images + ) + if provider is Provider.KAKAO: + krw += KAKAO_COORD_KRW * kakao_coord_calls + return krw + + +@dataclass +class CostMeter: + """사이트 1건(업소 1곳)의 원가 누적기. **미터 1개 = 사이트 1건**이다.""" + + place_id: int | None = None + budget_krw: float = SITE_BUDGET_KRW + spent_krw: float = 0.0 + by_provider: dict[str, float] = field(default_factory=dict) + calls: int = 0 + _warned: bool = False + + @property + def remaining_krw(self) -> float: + return max(0.0, self.budget_krw - self.spent_krw) + + @property + def spent_usd(self) -> float: + return self.spent_krw / USD_KRW + + def guard(self, provider: Provider, **units) -> float: + """호출 **전** 에 예산을 확인한다. 넘으면 BudgetExceeded — 호출하지 마라. + + 돌려주는 값은 이번 호출의 예상 원가(원)다. + """ + krw = estimate_krw(provider, **units) + if self.spent_krw + krw > self.budget_krw: + raise BudgetExceeded(self.place_id, self.spent_krw, krw) + return krw + + def charge(self, provider: Provider, **units) -> float: + """호출 **후** 에 실측 사용량을 적는다. 적고 나서 예산을 넘었으면 예외를 던진다. + + ★ 이미 나간 호출은 되돌릴 수 없다 — 예외의 목적은 **다음 호출을 막는 것**이다. + """ + krw = estimate_krw(provider, **units) + self.spent_krw += krw + self.calls += 1 + self.by_provider[provider.value] = self.by_provider.get(provider.value, 0.0) + krw + + if not self._warned and self.spent_krw >= self.budget_krw * WARN_RATIO: + self._warned = True + LOG.w( + f"[cost] place_id={self.place_id} 예산 {WARN_RATIO:.0%} 소진 — " + f"{self.spent_krw:.1f}/{self.budget_krw:.0f}원" + ) + if self.spent_krw > self.budget_krw: + LOG.w(f"[cost] place_id={self.place_id} 예산 초과 — {self.summary()}") + raise BudgetExceeded(self.place_id, self.spent_krw - krw, krw) + return krw + + def summary(self) -> str: + parts = " ".join(f"{k}={v:.1f}원" for k, v in sorted(self.by_provider.items())) + return ( + f"place_id={self.place_id} 합계={self.spent_krw:.1f}원(${self.spent_usd:.3f}) " + f"호출={self.calls}건 상한={self.budget_krw:.0f}원 [{parts}]" + ) diff --git a/backend/common/database/db_session_manager.py b/backend/common/database/db_session_manager.py new file mode 100644 index 0000000..c164142 --- /dev/null +++ b/backend/common/database/db_session_manager.py @@ -0,0 +1,263 @@ +from asyncio import current_task + +from sqlalchemy.orm import sessionmaker +from sqlalchemy.exc import IntegrityError +from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_scoped_session +from sqlalchemy.util._collections import immutabledict + +from common.database.model.models import MAIN_BASE +from common.enums import DBType, DBWRType, ErrorType +from common.logger import LOG +from common.singleton import Singleton +from config.server_configs import main_db_config + + +class DBSessionManager(Singleton): + """DB 세션/엔진 관리자 (싱글톤). + + 핵심 패턴 + - DBType(논리 DB) x DBWRType(Read/Write) 조합마다 별도 async 엔진을 둔다. + => 조회는 Read 복제본, 변경은 Write 주 DB 로 자연스럽게 분리된다. + - 비즈니스 로직(service)은 직접 세션을 열지 않고 "람다"를 넘긴다. + execute_lambda : 단일 쿼리 (주로 조회) + execute_lambda_run : 동일 DB 의 여러 변경 쿼리를 한 트랜잭션으로 commit + 세션 open/close 와 commit/rollback 은 매니저가 책임진다. + """ + + def __init__(self): + if DBSessionManager.is_init(): + LOG.e_no_callstack("already init DBSessionManager") + return + DBSessionManager.set_init() + + self.__DB_URL_MAP = {"postgresql": "postgresql+asyncpg"} + # 종료 시 dispose 하기 위해 생성한 엔진을 모아둔다. + self.__engines = [] + # 논리 DB -> config. DB 가 늘어나면 여기에 추가만 하면 된다. + self.__db_type_map = { + DBType.MAIN.value: main_db_config, + } + + # Write 엔진 맵 + self.__write_session = { + DBType.MAIN.value: self.create_engine(DBType.MAIN.value, DBWRType.DB_WRITE.value), + } + # Read 엔진 맵 + self.__read_session = { + DBType.MAIN.value: self.create_engine(DBType.MAIN.value, DBWRType.DB_READ.value), + } + + def create_engine(self, db_type: int, db_wr_type: int): + db_config = self.__db_type_map.get(db_type) + if not db_config: + raise ValueError("Invalid database type") + + if db_wr_type == DBWRType.DB_READ.value: + pw = (":" + db_config.read_pw) if len(db_config.read_pw) > 0 else "" + db_url = f"{self.__DB_URL_MAP[db_config.db_type]}://{db_config.read_id}{pw}@{db_config.read_host}:{db_config.read_port}/{db_config.name}" + LOG.i(f"Read DB create engine url : {db_url}") + else: + pw = (":" + db_config.write_pw) if len(db_config.write_pw) > 0 else "" + db_url = f"{self.__DB_URL_MAP[db_config.db_type]}://{db_config.write_id}{pw}@{db_config.write_host}:{db_config.write_port}/{db_config.name}" + LOG.i(f"Write DB create engine url : {db_url}") + + # SSL/TLS: 관리형 DB(RDS/Aurora/Azure)는 보통 TLS 필수. sslmode 가 설정되면 asyncpg 에 전달. + connect_args = {} + sslmode = (getattr(db_config, "sslmode", "") or "").lower() + if sslmode and sslmode != "disable": + connect_args["ssl"] = sslmode + + engine = create_async_engine( + db_url, + echo=db_config.show_log, + pool_size=db_config.pool_size, + max_overflow=db_config.max_overflow, + pool_pre_ping=True, + pool_recycle=600, + connect_args=connect_args, + ) + self.__engines.append(engine) + scoped_session = async_scoped_session( + sessionmaker(engine, class_=AsyncSession, expire_on_commit=False, autocommit=False, autoflush=False), + scopefunc=current_task, + ) + return scoped_session + + def is_registered(self, db_type: int) -> bool: + """해당 논리 DB 가 등록돼 있는지 — 선택 연동(부속 DB)의 배치가 실행 전 확인하는 용도.""" + return db_type in self.__db_type_map + + async def dispose_all(self): + """모든 엔진의 커넥션 풀을 정리한다. 앱 종료/테스트 종료 시 호출한다. + 호출하지 않으면 풀 커넥션이 이벤트 루프 종료 후 GC 되며 경고를 남긴다. + """ + for engine in self.__engines: + await engine.dispose() + + # ---- 세션 lifecycle ------------------------------------------------- + async def start_session(self, db_type: int, db_wr_type: int) -> AsyncSession: + if db_wr_type == DBWRType.DB_WRITE.value: + return self.__write_session[db_type]() + return self.__read_session[db_type]() + + async def end_session(self, db_type: int, db_wr_type: int): + if db_wr_type == DBWRType.DB_WRITE.value: + await self.__write_session[db_type].remove() + else: + await self.__read_session[db_type].remove() + + # ---- 저수준 DB 연산 (crud 에서 호출) -------------------------------- + async def run(self, db: AsyncSession, err_msg="DB Run Failed", raise_error=True) -> ErrorType: + try: + await db.commit() + return ErrorType.SUCCESS + except IntegrityError as ex: + await db.rollback() + LOG.e_no_callstack(f"duplicated. {ex}") + return ErrorType.DB_ALREADY_SAME_KEY + except Exception as ex: + await db.rollback() + err_type = ErrorType.DB_RUN_FAILED + LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}") + if raise_error: + raise RuntimeError(err_type.name, err_msg) + return err_type + + async def insert(self, db: AsyncSession, obj, err_msg="DB Failed", raise_error=True) -> ErrorType: + try: + if isinstance(obj, MAIN_BASE): + db.add(obj) + elif isinstance(obj, list): + db.add_all(obj) + else: + raise RuntimeError("DO NOT USE QUERY IN DBJOB") + return ErrorType.SUCCESS + except Exception as ex: + await db.rollback() + err_type = ErrorType.DB_RUN_FAILED + LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}") + if raise_error: + raise RuntimeError(err_type.name, err_msg) + return err_type + + async def add(self, db: AsyncSession, query, err_msg="DB Operation Failed", raise_error=True) -> ErrorType: + """update/delete 등 비-select 쿼리 실행.""" + try: + if hasattr(query, "column_descriptions"): + raise RuntimeError("DO NOT USE SELECT QUERY IN DBJOB") + await db.execute(query, execution_options=immutabledict({"synchronize_session": "fetch"})) + return ErrorType.SUCCESS + except IntegrityError as ex: + await db.rollback() + err_type = ErrorType.DB_ALREADY_SAME_KEY + LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}") + return err_type + except Exception as ex: + await db.rollback() + err_type = ErrorType.DB_RUN_FAILED + LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}") + if raise_error: + raise RuntimeError(err_type.name, err_msg) + return err_type + + async def add_with_rowcount(self, db: AsyncSession, query, err_msg="DB Operation Failed") -> tuple[ErrorType, int]: + """update/delete 등 비-select 쿼리 실행 후 (ErrorType, 영향행수) 반환. + 조건부 갱신(WHERE 로 상태를 거른 UPDATE)이 실제로 적용됐는지 판별하는 동시처리 가드용.""" + try: + if hasattr(query, "column_descriptions"): + raise RuntimeError("DO NOT USE SELECT QUERY IN DBJOB") + res = await db.execute(query, execution_options=immutabledict({"synchronize_session": "fetch"})) + return ErrorType.SUCCESS, res.rowcount + except IntegrityError as ex: + await db.rollback() + err_type = ErrorType.DB_ALREADY_SAME_KEY + LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}") + return err_type, 0 + except Exception as ex: + await db.rollback() + err_type = ErrorType.DB_RUN_FAILED + LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}") + return err_type, 0 + + async def execute(self, db: AsyncSession, query, err_msg="DB Query Execution Failed", raise_error=True) -> tuple[ErrorType, list]: + """select 쿼리 실행 후 결과 리스트 반환.""" + try: + if not hasattr(query, "column_descriptions"): + raise RuntimeError("DO NOT USE NON-SELECT QUERY IN DBJOB") + res = await db.execute(query, execution_options=immutabledict({"synchronize_session": "fetch"})) + return ErrorType.SUCCESS, res.scalars().fetchall() if 1 == len(query.column_descriptions) else res.all() + except Exception as ex: + err_type = ErrorType.DB_RUN_FAILED + LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}") + if raise_error: + raise RuntimeError(err_type.name, err_msg) + return err_type, [] + + # ---- 람다 실행 진입점 (service 에서 호출) --------------------------- + async def execute_lambda(self, db_type: int, db_wr_type: int, func): + """단일 쿼리 호출. func(session) 한 개를 실행하고 결과를 그대로 반환.""" + s = await self.start_session(db_type, db_wr_type) + try: + return await func(s) + finally: + await self.end_session(db_type, db_wr_type) + + async def execute_lambda_run(self, db_type_list: list[int], func_list: list): + """동일 DB 의 변경 쿼리 여러 개를 한 트랜잭션으로 실행 후 commit. + 하나라도 SUCCESS 가 아니면 즉시 중단(rollback)된다. + """ + temp_list = list(set(db_type_list)) + if len(temp_list) != 1: + return ErrorType.DB_INVALID_TYPE + + db_type = temp_list[0] + s = await self.start_session(db_type, DBWRType.DB_WRITE.value) + try: + for func in func_list: + err_type = await func(s) + if err_type != ErrorType.SUCCESS: + return err_type + return await self.run(s) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + finally: + await self.end_session(db_type, DBWRType.DB_WRITE.value) + + async def execute_lambda_write(self, db_type: int, func): + """Write 세션에서 func(session) 을 실행하고 commit 한 뒤 **func 의 반환값을 그대로** 돌려준다. + + execute_lambda_run 은 ErrorType 만, execute_lambda_claim 은 (ErrorType, 적용행수) 만 돌려준다. + 작업 큐처럼 "변경하면서 값을 받아와야" 하는 경우(RETURNING 절)를 위한 진입점이다 — + 원자적 claim(FOR UPDATE SKIP LOCKED + UPDATE + RETURNING)은 조회/변경을 나눌 수 없다. + 예외는 rollback 후 그대로 전파한다(호출측이 잡 실패로 처리).""" + s = await self.start_session(db_type, DBWRType.DB_WRITE.value) + try: + result = await func(s) + await s.commit() + return result + except Exception: + await s.rollback() + raise + finally: + await self.end_session(db_type, DBWRType.DB_WRITE.value) + + async def execute_lambda_claim(self, db_type: int, func) -> tuple[ErrorType, int]: + """조건부 변경 쿼리 1건을 한 트랜잭션으로 실행/commit 하고 (ErrorType, 적용행수) 반환. + 동시처리 가드용 — func(session) -> (ErrorType, rowcount). 적용행수 0 이면 다른 호출자가 이미 처리한 것. + (Postgres READ COMMITTED 에서 같은 행 UPDATE 는 행 잠금으로 직렬화되어, 진 호출자는 0 을 받는다.)""" + s = await self.start_session(db_type, DBWRType.DB_WRITE.value) + try: + err_type, rowcount = await func(s) + if err_type != ErrorType.SUCCESS: + return err_type, 0 + commit_err = await self.run(s) + return commit_err, rowcount + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + finally: + await self.end_session(db_type, DBWRType.DB_WRITE.value) + + +DB_SESSION_MNG = DBSessionManager() diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py new file mode 100644 index 0000000..fdb2c8c --- /dev/null +++ b/backend/common/database/model/models.py @@ -0,0 +1,507 @@ +import uuid + +from sqlalchemy.orm import declarative_base +from sqlalchemy import Column, Index, Integer, SmallInteger, Numeric, String, Text, Boolean, DateTime +from sqlalchemy.dialects.postgresql import UUID, JSONB +from sqlalchemy.sql import text + +from common.enums import ( + DBType, + UserStatus, + UserRole, + CompanyStatus, + PlaceStatus, + FactStatus, + MediaStatus, + SiteStatus, + BuildStatus, + JobStatus, +) + +# 모든 ORM 모델의 베이스. insert 시 isinstance 체크에도 사용된다. +MAIN_BASE = declarative_base() + + +# 공통 mixin +# DB 계약(_DBTypeMixin)과 ERD 공통 컬럼(MainTableMixin)을 분리해 둔다. +def _utc_now_sql(): + return text("(now() AT TIME ZONE 'utc')") + + +class _DBTypeMixin: + """모델이 자신이 속한 논리 DB 를 알려준다 (람다 실행 시 DBType 으로 세션 선택).""" + + @staticmethod + def DBType(): + return DBType.MAIN.value + + +# ERD 공통 컬럼 +class MainTableMixin(_DBTypeMixin): + created_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql()) + updated_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql(), onupdate=_utc_now_sql()) + deleted = Column(Boolean, nullable=False, server_default=text("false"), default=False) + + +# ERD 도메인 모델 +class companies(MainTableMixin, MAIN_BASE): + __tablename__ = "companies" + __table_args__ = {"schema": "company"} + + company_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + name = Column(String(100), nullable=False) + business_number = Column(String(30), nullable=True) + code = Column(Integer, nullable=True) # 내부 인덱스용 + representative_name = Column(String(50), nullable=True) + email = Column(String(255), nullable=True) + contact_number = Column(String(20), nullable=True) + website_url = Column(String(255), nullable=True) + industry = Column(SmallInteger, nullable=True) # 업종 코드 (스키마 SMALLINT) + status = Column(SmallInteger, nullable=False, default=CompanyStatus.ACTIVE.value) # CompanyStatus + # 회사별 커스터마이징 설정. branding(CI)/labels(용어)/features(동작) + settings = Column(JSONB, nullable=True) + + +class users(MainTableMixin, MAIN_BASE): + __tablename__ = "users" + __table_args__ = {"schema": "company"} + + user_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + company_id = Column(UUID(as_uuid=True), nullable=False, index=True) + id = Column(String(20), nullable=False, unique=True, index=True) # 로그인 아이디 + password = Column(String(255), nullable=False) # bcrypt 해시 (ERD VARCHAR(30)→255 확장) + name = Column(String(50), nullable=True) + email = Column(String(255), nullable=True) + contact_number = Column(String(20), nullable=True) + last_accessed_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql()) + status = Column(SmallInteger, nullable=False, default=UserStatus.ACTIVE.value) + role = Column(SmallInteger, nullable=False, default=UserRole.USER.value) + + +# ============================================================ +# place : 사업장 / 별칭 / 채널 링크 / 객실·메뉴·프로그램 / 사진 +# ============================================================ +class places(MainTableMixin, MAIN_BASE): + """사업장. 상호명 하나로 시작해서, 카카오 로컬 검증을 통과해야 수집이 열린다. + + ★ verified_at 이 NULL 이면 collector 진입 금지 — 검증 없이 수집하면 남의 가게가 섞인다.""" + + __tablename__ = "places" + __table_args__ = ( + Index("idx_places_region_code", "region_code", postgresql_where=text("deleted = false")), + {"schema": "place"}, + ) + + place_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + company_id = Column(UUID(as_uuid=True), nullable=False, index=True) # 테넌트 스코프(company.companies) + owner_user_id = Column(UUID(as_uuid=True), nullable=True, index=True) # 사장님 계정(company.users) + name = Column(String(200), nullable=False) # 상호명(입력값) + category = Column(SmallInteger, nullable=False) # PlaceCategory — 업종 스키마 선택 키 + status = Column(SmallInteger, nullable=False, server_default=text("1"), default=PlaceStatus.DRAFT.value) + + # ---- 카카오 로컬 검증 산출물 (동일 업소 판정) ---- + # 동일 업소 판정 키. 소스에 따라 있을 수도 없을 수도 있다 — + # 카카오는 고유 id 를 주지만 네이버는 안 준다(그 경우 상호명+도로명주소가 대체 키). + external_source = Column(SmallInteger, nullable=True) # ExternalPlaceSource + external_place_id = Column(String(64), nullable=True) + road_address = Column(String(255), nullable=True) + address = Column(String(255), nullable=True) # 지번 + phone = Column(String(30), nullable=True) + latitude = Column(Numeric(10, 7), nullable=True) + longitude = Column(Numeric(10, 7), nullable=True) + region_code = Column(String(10), nullable=True) # 행정구역 코드 — ★ 지역정보 캐시 키(사이트 50개여도 조회 1회) + verified_at = Column(DateTime(timezone=True), nullable=True) # ★ NULL = 미검증 → 수집·발행 금지 + verified_by = Column(UUID(as_uuid=True), nullable=True) + # ★ 노출값(VERIFIED/CORRECTED fact)이 마지막으로 바뀐 시각. 개별 재빌드 대상 판별용 — + # site_versions.built_at < content_updated_at 인 사이트만 다시 빌드한다. + content_updated_at = Column(DateTime(timezone=True), nullable=True) + + +class place_aliases(MainTableMixin, MAIN_BASE): + """상호 별칭. 동명 업소 구분과 재검색에 쓴다(옛 상호, '본관/별관' 표기 등).""" + + __tablename__ = "place_aliases" + __table_args__ = {"schema": "place"} + + alias_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + place_id = Column(UUID(as_uuid=True), nullable=False, index=True) + alias = Column(String(200), nullable=False) + source_type = Column(SmallInteger, nullable=False) # SourceType + + +class place_links(MainTableMixin, MAIN_BASE): + """Perplexity 가 발견한 채널 URL. + + ★ confirmed_at 이 NULL 이면 크롤링 대상이 아니다 — 카카오 로컬로 동일 업소임을 확인한 URL만 넘긴다. + raw 에 Perplexity 응답(본문 + search_results)을 통째로 남긴다. 환각 추적용이며 사실 근거로 쓰지 않는다.""" + + __tablename__ = "place_links" + __table_args__ = ( + Index( + "uq_place_links_place_url", + "place_id", + "url", + unique=True, + postgresql_where=text("deleted = false"), + ), + {"schema": "place"}, + ) + + link_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + place_id = Column(UUID(as_uuid=True), nullable=False, index=True) + channel = Column(SmallInteger, nullable=False) # LinkChannel + url = Column(String(1000), nullable=False) + title = Column(String(300), nullable=True) # 발견 시 제목/스니펫 + discovered_by = Column(SmallInteger, nullable=False) # SourceType (API=Perplexity, OWNER=직접 입력) + discovered_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql()) + confirmed_at = Column(DateTime(timezone=True), nullable=True) # ★ NULL = 미확정, 크롤링 금지 + confirmed_by = Column(UUID(as_uuid=True), nullable=True) + raw = Column(JSONB, nullable=True) # Perplexity 응답 원문(본문 + search_results) + + +class units(MainTableMixin, MAIN_BASE): + """업종별 하위 단위 — 숙박=객실, 카페·음식점=메뉴, 관광체험=프로그램. + 가변 필드는 facts(scope=unit)로 들어가고, 여기에는 목록 렌더에 필요한 뼈대만 둔다.""" + + __tablename__ = "units" + __table_args__ = {"schema": "place"} + + unit_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + place_id = Column(UUID(as_uuid=True), nullable=False, index=True) + name = Column(String(200), nullable=False) + sort_order = Column(Integer, nullable=False, server_default=text("0"), default=0) + + +class media(MainTableMixin, MAIN_BASE): + """사진. Gemini Vision 이 분류 라벨과 alt 를 만든다. + + ★ source_type 을 반드시 남긴다 — 크롤링 이미지의 재게시 권리가 미결이라(docs/DECISIONS.md 1-2), + 결론에 따라 발행 시 source_type 으로 걸러낼 수 있어야 한다. + ★ vision_confidence 가 낮으면 자동 반영하지 않고 PENDING_REVIEW 로 사람 확인 큐에 둔다.""" + + __tablename__ = "media" + __table_args__ = {"schema": "place"} + + media_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + place_id = Column(UUID(as_uuid=True), nullable=False, index=True) + unit_id = Column(UUID(as_uuid=True), nullable=True, index=True) # 객실·메뉴 사진이면 연결 + url = Column(String(1000), nullable=False) # 우리가 보관하는 접근 URL + origin_url = Column(String(1000), nullable=True) # 수집 원본 이미지 URL + source_type = Column(SmallInteger, nullable=False) # SourceType — OWNER 업로드 / CRAWL 수집 + source_url = Column(String(1000), nullable=True) # 수집한 페이지 URL + label = Column(String(200), nullable=True) # Vision 분류 라벨 (예: "A동 침실") + alt_text = Column(String(500), nullable=True) # Vision 생성 alt + vision_confidence = Column(Numeric(4, 3), nullable=True) # 0.000~1.000 + status = Column(SmallInteger, nullable=False, server_default=text("1"), default=MediaStatus.PENDING_REVIEW.value) + width = Column(Integer, nullable=True) + height = Column(Integer, nullable=True) + sort_order = Column(Integer, nullable=False, server_default=text("0"), default=0) + + +# ============================================================ +# fact : 사실 / FAQ +# ============================================================ +class facts(MainTableMixin, MAIN_BASE): + """★ 가장 중요한 테이블. 모든 사실은 값과 함께 출처·수집시각·검증상태를 갖는다. + + - key 는 업종 스키마(common/category_schema)에 정의된 것만 허용한다. + - unit_id 가 NULL 이면 사업장 단위 fact, 있으면 객실·메뉴·프로그램 단위 fact. + - ★ VERIFIED / CORRECTED 만 사이트에 노출한다(PUBLISHABLE_FACT_STATUSES). + - ★ CORRECTED(사장님 수정본)는 잠긴다 — 자동 갱신이 덮어쓰지 않는다. + + 활성 유니크: 같은 (place, unit, key) 로 살아있는 fact 는 1건. REJECTED/EXPIRED 는 이력으로 남기므로 제외한다.""" + + __tablename__ = "facts" + __table_args__ = ( + # unit_id 가 NULL 인 행끼리는 유니크가 안 걸리므로 place 단위 / unit 단위를 나눠 건다. + # 노출값은 (사업장, 단위, key) 당 1건. 후보(1,2)·이력(5,6)은 제외 — 재수집이 쌓일 수 있게. + Index( + "uq_facts_published_place_key", + "place_id", + "key", + unique=True, + postgresql_where=text("deleted = false AND unit_id IS NULL AND status IN (3, 4)"), + ), + Index( + "uq_facts_published_unit_key", + "place_id", + "unit_id", + "key", + unique=True, + postgresql_where=text("deleted = false AND unit_id IS NOT NULL AND status IN (3, 4)"), + ), + # 후보 조회 경로(사람 확인 큐) — 재수집이 올려놓은 대기 항목. + Index( + "idx_facts_candidate", + "place_id", + "key", + "source_type", + postgresql_where=text("deleted = false AND status IN (1, 2)"), + ), + # 발행 게이트가 "노출 가능한 fact" 만 훑는 경로. + Index( + "idx_facts_publishable", + "place_id", + "status", + postgresql_where=text("deleted = false AND status IN (3, 4)"), + ), + {"schema": "fact"}, + ) + + fact_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + place_id = Column(UUID(as_uuid=True), nullable=False, index=True) + unit_id = Column(UUID(as_uuid=True), nullable=True, index=True) + key = Column(String(100), nullable=False) # 업종 스키마의 필드 key + value = Column(Text, nullable=True) + unit = Column(String(30), nullable=True) # 값의 단위(원·명·분…) + source_type = Column(SmallInteger, nullable=False) # SourceType — owner | api | crawl | llm + source_url = Column(String(1000), nullable=True) + collected_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql()) + verified_by = Column(UUID(as_uuid=True), nullable=True) # company.users.user_id + verified_at = Column(DateTime(timezone=True), nullable=True) + status = Column(SmallInteger, nullable=False, server_default=text("1"), default=FactStatus.UNVERIFIED.value) + expires_at = Column(DateTime(timezone=True), nullable=True) # 지나면 EXPIRED 전이 대상 + + +class faqs(MainTableMixin, MAIN_BASE): + """FAQ. ★ 확보된 fact 만 근거로 쓴다 — source_fact_ids 가 비면 발행 게이트가 반려한다.""" + + __tablename__ = "faqs" + __table_args__ = {"schema": "fact"} + + faq_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + place_id = Column(UUID(as_uuid=True), nullable=False, index=True) + question = Column(String(500), nullable=False) + answer = Column(Text, nullable=False) + source_fact_ids = Column(JSONB, nullable=True) # ★ 근거 fact_id 배열. 비면 반려 + generated_by = Column(SmallInteger, nullable=False) # SourceType — LLM | OWNER + status = Column(SmallInteger, nullable=False, server_default=text("1"), default=FactStatus.UNVERIFIED.value) + sort_order = Column(Integer, nullable=False, server_default=text("0"), default=0) + + +# ============================================================ +# local : 지역 정보(행정구역 코드 단위 캐시) / 가는 길 / 주변 +# ============================================================ +class local_contents(MainTableMixin, MAIN_BASE): + """지역 정보 캐시. ★ 키는 place_id 가 아니라 region_code 다 — + 같은 지역에 사이트 50개가 생겨도 외부 조회는 1회여야 한다. + + ★ 외부 API 실패 시 이 행을 지우거나 비우지 않는다 — 직전 값을 그대로 유지하고 내부 알림만 낸다.""" + + __tablename__ = "local_contents" + __table_args__ = ( + # external_id 가 있는 항목(축제·관광지·맛집)은 출처 고유 ID 로 중복을 막는다. + Index( + "uq_local_contents_keyed", + "region_code", + "content_type", + "external_id", + unique=True, + postgresql_where=text("deleted = false AND external_id IS NOT NULL"), + ), + # external_id 가 없는 항목(날씨)은 지역 × 종류당 1행. + Index( + "uq_local_contents_single", + "region_code", + "content_type", + unique=True, + postgresql_where=text("deleted = false AND external_id IS NULL"), + ), + {"schema": "local"}, + ) + + local_content_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + region_code = Column(String(10), nullable=False, index=True) # 카카오 행정구역 코드 = 캐시 키 + content_type = Column(SmallInteger, nullable=False) # LocalContentType + source = Column(SmallInteger, nullable=False) # LocalSource + external_id = Column(String(100), nullable=True) # TourAPI contentid 등 출처 고유 ID + title = Column(String(300), nullable=True) + body = Column(JSONB, nullable=False) # 원문 페이로드 + status = Column(SmallInteger, nullable=False, server_default=text("1")) # LocalContentStatus + published_at = Column(DateTime(timezone=True), nullable=True) + published_by = Column(UUID(as_uuid=True), nullable=True) + display_start_at = Column(DateTime(timezone=True), nullable=True) + display_end_at = Column(DateTime(timezone=True), nullable=True) + collected_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql()) + expires_at = Column(DateTime(timezone=True), nullable=True) # TTL — 지나면 갱신 대상(값은 유지) + + +class routes(MainTableMixin, MAIN_BASE): + """가는 길. 검증 상태(FactStatus)를 그대로 쓴다 — 틀린 경로 안내도 헛걸음을 만든다.""" + + __tablename__ = "routes" + __table_args__ = {"schema": "local"} + + route_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + place_id = Column(UUID(as_uuid=True), nullable=False, index=True) + origin_name = Column(String(200), nullable=False) # 출발지 (예: "서울역") + transport = Column(SmallInteger, nullable=False) # TransportType + duration_min = Column(Integer, nullable=True) + distance_m = Column(Integer, nullable=True) + description = Column(Text, nullable=True) + source_type = Column(SmallInteger, nullable=False) # SourceType + status = Column(SmallInteger, nullable=False, server_default=text("1"), default=FactStatus.UNVERIFIED.value) + sort_order = Column(Integer, nullable=False, server_default=text("0"), default=0) + + +class nearby_links(MainTableMixin, MAIN_BASE): + """주변 맛집·시설. 카카오 카테고리 검색 결과를 사업장에 붙인 것. + 카테고리 검색은 좌표 변환보다 4배 비싸므로 region_code 단위 캐시(local_contents)에서 파생시킨다.""" + + __tablename__ = "nearby_links" + __table_args__ = {"schema": "local"} + + nearby_link_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + place_id = Column(UUID(as_uuid=True), nullable=False, index=True) + region_code = Column(String(10), nullable=True) # 어느 지역 캐시에서 왔는지 + name = Column(String(200), nullable=False) + category_name = Column(String(100), nullable=True) # 카카오 category_name + kakao_place_id = Column(String(32), nullable=True) + distance_m = Column(Integer, nullable=True) + url = Column(String(1000), nullable=True) + latitude = Column(Numeric(10, 7), nullable=True) + longitude = Column(Numeric(10, 7), nullable=True) + sort_order = Column(Integer, nullable=False, server_default=text("0"), default=0) + + +# ============================================================ +# site : 사이트 / 버전 / 발행 로그 / AI 노출 점검 +# ============================================================ +class sites(MainTableMixin, MAIN_BASE): + """발행 대상 사이트. 사업장당 1개. + ★ 해지는 물리 삭제가 아니라 status 전이로만 처리한다 — 색인된 페이지를 갑자기 404 로 만들지 않는다.""" + + __tablename__ = "sites" + __table_args__ = ( + Index("uq_sites_place", "place_id", unique=True, postgresql_where=text("deleted = false")), + Index("uq_sites_domain", "domain", unique=True, postgresql_where=text("deleted = false AND domain IS NOT NULL")), + {"schema": "site"}, + ) + + site_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + place_id = Column(UUID(as_uuid=True), nullable=False) + domain = Column(String(255), nullable=True) + path_prefix = Column(String(100), nullable=True) + # 사장님이 고른 템플릿 키(프론트 배리에이션 레지스트리의 id). 서버는 해석하지 않고 보관·반환만 한다 — + # 템플릿 목록은 프론트가 소유하므로, 서버가 값을 검증하면 템플릿을 늘릴 때마다 백엔드를 고쳐야 한다. + # NULL 이면 발행 잡이 업종 기본 템플릿으로 굽는다(services/site_payload). + template_id = Column(String(100), nullable=True) + # 에디터가 정한 색·서체·섹션(순서·on/off·배리에이션). template_id 와 같은 이유로 서버에 저장한다 — + # 브라우저에만 두면 발행 잡이 읽을 곳이 없어 업종 기본 모양으로 굽고, 고른 디자인과 발행본이 갈린다. + # ★ 컬럼으로 펼치지 않고 jsonb 로 통째로 담는 이유: 섹션 목록·배리에이션 키·색 토큰 이름은 + # 프론트가 소유한다. 펼치면 프론트가 항목 하나 늘릴 때마다 마이그레이션이 따라와야 한다. + # ★ templateId 는 여기 넣지 않는다 — 위 template_id 컬럼이 소유한다. 두 곳에 두면 어느 쪽이 진짜인지 갈린다. + # NULL 이면 발행 잡이 업종 기본 색·서체·섹션으로 굽는다(services/site_payload). + theme = Column(JSONB, nullable=True) + status = Column(SmallInteger, nullable=False, server_default=text("1"), default=SiteStatus.DRAFT.value) + current_version_id = Column(UUID(as_uuid=True), nullable=True) # site.site_versions.site_version_id + published_at = Column(DateTime(timezone=True), nullable=True) + + +class site_versions(MainTableMixin, MAIN_BASE): + """빌드 버전. ★ 정적 빌드 — snapshot 에 빌드 시점 데이터를 박제하고, 방문자는 DB 와 만나지 않는다. + ★ 개별 재빌드 단위다. 사이트 1,000개에서 전체 재빌드는 못 쓴다. + ★ jsonld 값은 화면에 보이는 값과 같아야 한다 — 불일치면 빌드 실패(PUBLISH_JSONLD_MISMATCH). + ★ unique_content_count 가 0 이면 발행 API 가 거부한다(스팸 판정 대상).""" + + __tablename__ = "site_versions" + __table_args__ = ( + Index("uq_site_versions_no", "site_id", "version", unique=True, postgresql_where=text("deleted = false")), + {"schema": "site"}, + ) + + site_version_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + site_id = Column(UUID(as_uuid=True), nullable=False, index=True) + version = Column(Integer, nullable=False) # 1부터 + build_status = Column(SmallInteger, nullable=False, server_default=text("1"), default=BuildStatus.PENDING.value) + snapshot = Column(JSONB, nullable=True) # 빌드 시점 데이터 박제 + jsonld = Column(JSONB, nullable=True) # 구조화 데이터 + unique_content_count = Column(Integer, nullable=False, server_default=text("0"), default=0) # ★ 0 이면 발행 거부 + build_error = Column(Text, nullable=True) + built_at = Column(DateTime(timezone=True), nullable=True) + + +class publish_logs(MainTableMixin, MAIN_BASE): + """발행 시도 기록. 검수 게이트가 막았으면 result=REJECTED + reject_reason 을 남긴다.""" + + __tablename__ = "publish_logs" + __table_args__ = {"schema": "site"} + + publish_log_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + site_id = Column(UUID(as_uuid=True), nullable=False, index=True) + site_version_id = Column(UUID(as_uuid=True), nullable=True) + action = Column(SmallInteger, nullable=False) # PublishAction + result = Column(SmallInteger, nullable=False) # PublishResult + reject_reason = Column(SmallInteger, nullable=True) # PublishRejectReason + detail = Column(JSONB, nullable=True) # 막힌 항목 목록(미검증 fact key 등) + actor_user_id = Column(UUID(as_uuid=True), nullable=True) + + +class ai_check_results(MainTableMixin, MAIN_BASE): + """AI 검색 노출 점검. 이 서비스의 목표 지표 — + AI 가 이 가게를 **우리 사이트를 근거로** 설명하는가, 아니면 여전히 OTA 를 인용하는가.""" + + __tablename__ = "ai_check_results" + __table_args__ = {"schema": "site"} + + ai_check_result_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + place_id = Column(UUID(as_uuid=True), nullable=False, index=True) + engine = Column(SmallInteger, nullable=False) # AiEngine + query = Column(String(500), nullable=False) # 던진 질의 + answer = Column(Text, nullable=True) + cited_urls = Column(JSONB, nullable=True) # 인용된 URL 목록 + is_own_site_cited = Column(Boolean, nullable=False, server_default=text("false"), default=False) # ★ 핵심 지표 + ota_cited = Column(Boolean, nullable=False, server_default=text("false"), default=False) # OTA 가 대신 인용됐는지 + checked_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql()) + + +# ============================================================ +# job : 작업 큐 (PostgreSQL 을 큐로 — LPS 의 job 큐 구조 이식) +# ============================================================ +class jobs(MainTableMixin, MAIN_BASE): + """작업 큐. 수집·비전분석·빌드는 몇 분 걸려 동기 요청으로 처리할 수 없다. + + - 할당은 **단일 문장 원자 claim**: FOR UPDATE SKIP LOCKED 서브쿼리 + 같은 UPDATE + RETURNING. + 워커 컨테이너가 몇 개든 같은 잡 이중 할당이 불가능하다. + - 복구는 타임아웃 추측이 아니라 **lease 만료 소유권** — 워커가 죽어도 reaper 가 회수한다. + (도커에서 컨테이너를 재시작해도 진행 중이던 잡이 증발하지 않는다.) + - 재시도·백오프·dead-letter 를 큐에 내장한다. + - dedupe_key 로 활성 중복(PENDING/RUNNING)을 막는다 — 같은 사업장 수집이 두 번 돌지 않게. + + ※ 이 테이블만 MainTableMixin 의 deleted 를 쓰지 않는다(잡은 이력이지 소프트 삭제 대상이 아니다). + 그래도 컬럼은 남겨 공통 규약을 깨지 않는다. + """ + + __tablename__ = "jobs" + __table_args__ = ( + # claim 경로: status=PENDING & run_after<=now() 을 priority·created_at 순으로 훑는다. + Index("ix_jobs_claim", "status", "run_after", "priority", "created_at"), + # reaper 경로: 만료된 lease 회수. + Index("ix_jobs_lease", "status", "lease_until"), + # 활성 중복 방지 — 같은 dedupe_key 는 PENDING(1)/RUNNING(2) 중 하나만. + Index( + "uq_jobs_dedupe_active", + "dedupe_key", + unique=True, + postgresql_where=text("status IN (1, 2) AND dedupe_key IS NOT NULL"), + ), + {"schema": "job"}, + ) + + # ★ 이 테이블만 PK 에 server_default 가 필요하다 — 큐 전이는 raw SQL(RETURNING) 이라 + # ORM 의 Python 쪽 default(uuid.uuid4)가 적용되지 않는다. init.sql 의 DEFAULT gen_random_uuid() 와 맞춘다. + # (다른 테이블은 ORM 으로만 INSERT 하므로 원본 보일러플레이트대로 Python default 만 둔다.) + job_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), default=uuid.uuid4) + job_type = Column(SmallInteger, nullable=False) # JobType + status = Column(SmallInteger, nullable=False, server_default=text("1"), default=JobStatus.PENDING.value) + priority = Column(SmallInteger, nullable=False, server_default=text("100"), default=100) # 낮을수록 우선 + payload = Column(JSONB, nullable=False, server_default=text("'{}'::jsonb")) # 잡 입력 + result = Column(JSONB, nullable=True) # 잡 출력(완료 시) + dedupe_key = Column(String(200), nullable=True) # 활성 중복 방지 키(부분 유니크) + attempts = Column(SmallInteger, nullable=False, server_default=text("0"), default=0) # claim 시 +1 + max_attempts = Column(SmallInteger, nullable=False, server_default=text("3"), default=3) + run_after = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql()) # 백오프 + lease_until = Column(DateTime(timezone=True), nullable=True) # 소유권 임대 만료(reaper 회수 기준) + worker_id = Column(String(80), nullable=True) # 현재 점유 워커 + run_started_at = Column(DateTime(timezone=True), nullable=True) # RUNNING 진입 시각 + last_error = Column(Text, nullable=True) diff --git a/backend/common/enums.py b/backend/common/enums.py new file mode 100644 index 0000000..6da569e --- /dev/null +++ b/backend/common/enums.py @@ -0,0 +1,392 @@ +from enum import Enum, auto + +from fastapi import HTTPException + + +class CodeEnum(Enum): + """OpenAPI 스키마에 x-enum-varnames(멤버 이름)을 실어 orval 이 이름 있는 enum 을 생성하게 하는 베이스.""" + + @classmethod + def __get_pydantic_json_schema__(cls, core_schema, handler): + json_schema = handler(core_schema) + json_schema = handler.resolve_ref_schema(json_schema) + json_schema["x-enum-varnames"] = [m.name for m in cls] + return json_schema + + +class ErrorType(Enum): + """서버 전역 결과 코드. Res_WebPacketProtocol.result 에 담겨 클라이언트로 전달된다. + HTTP status 와 겹치지 않도록 구간을 분리해서 관리한다. + + 도메인 코드는 모듈이 붙을 때 구간을 새로 열어 추가한다 + (places 1200 / facts 1300 / collector 1400 / generator 1500 / local 1600 / sites 1700 / reports 1800 예약). + """ + + SUCCESS = 0 + FAIL = 1 + + # DB / Redis 에러 + DB_RUN_FAILED = 10 + DB_ALREADY_SAME_KEY = auto() + DB_INVALID_KEY = auto() + DB_EMPTY_DATA = auto() + DB_INVALID_TYPE = auto() + + # 요청/직렬화 에러 + JSON_PARSE_ERROR = 100 + INVALID_REQUEST_DATA = auto() + INTERNAL_EXCEPTION = auto() + + # http 에러 코드와 겹치지 않게 설정 - router 전용 예외 발생 옵션 + HTTP_FORBIDDEN = 403 + HTTP_INVALID_CLIENT_REQUEST = 419 + HTTP_TO_MANY_REQUEST = 429 + HTTP_INVALID_CLIENT_ACCESS = 433 + HTTP_ACCESS_TOKEN_EXPIRED = 434 + HTTP_REFRESH_TOKEN_EXPIRED = 435 + HTTP_INVALID_TOKEN_ACCESS = 436 + + # 계정 관련 에러 + ACCOUNT_INVALID_INFO = 1100 + ACCOUNT_ALREADY_EXIST = auto() + ACCOUNT_BLOCKED_USER = auto() + ACCOUNT_NOT_FOUND = auto() + ACCOUNT_FORBIDDEN = auto() # 최고관리자 외 접근 / 다른 회사·최고관리자 대상 변경 시도 + + # 사업장(places) 관련 에러 + PLACE_NOT_FOUND = 1200 + PLACE_ALREADY_EXIST = auto() # 같은 회사 안에 같은 카카오 장소 ID — 중복 등록 + PLACE_NOT_VERIFIED = auto() # ★ 동일 업소 검증 전 — 수집·발행 진입 금지 + PLACE_VERIFY_NO_CANDIDATE = auto() # 카카오 로컬에서 후보를 못 찾음 + PLACE_VERIFY_AMBIGUOUS = auto() # 동명 업소 다수 — 사람이 골라야 함 + PLACE_INVALID_CATEGORY = auto() # 지원하지 않는 업종 코드 + UNIT_NOT_FOUND = auto() + LINK_NOT_FOUND = auto() + LINK_NOT_CONFIRMED = auto() # ★ 확정 안 된 URL — 크롤링 대상 아님 + MEDIA_NOT_FOUND = auto() + + # fact 관련 에러 + FACT_NOT_FOUND = 1300 + FACT_INVALID_KEY = auto() # 업종 스키마에 없는 key + FACT_INVALID_TRANSITION = auto() # 허용되지 않은 검증 상태 전이 + FACT_LOCKED = auto() # ★ CORRECTED(사장님 수정본) — 자동 갱신이 덮어쓸 수 없다 + FACT_SOURCE_REQUIRED = auto() # source_type 이 owner 가 아닌데 source_url 이 없음 + FAQ_NOT_FOUND = auto() + FAQ_UNGROUNDED = auto() # ★ 확보된 fact 로 뒷받침되지 않는 문장 — 반려 + + # 수집(collector) 관련 에러 + COLLECT_ADAPTER_NOT_FOUND = 1400 # 해당 URL 을 처리할 어댑터 없음 + COLLECT_ADAPTER_DISABLED = auto() # 법무 검토 전이라 미등록된 어댑터(HeadlessAdapter 등) + COLLECT_FETCH_FAILED = auto() + COLLECT_ALREADY_RUNNING = auto() + + # 생성(generator) 관련 에러 + GENERATOR_NOT_CONFIGURED = 1500 # GEMINI_API_KEY 미설정 + GENERATOR_CALL_FAILED = auto() + GENERATOR_INVALID_OUTPUT = auto() # 구조화 출력 파싱 실패 + GENERATOR_LOW_CONFIDENCE = auto() # 신뢰도 낮음 — 자동 반영 금지, 사람 확인 큐로 + + # 지역 정보(local) 관련 에러 + LOCAL_NOT_CONFIGURED = 1600 # KAKAO_REST_API_KEY / TOUR_API_KEY 미설정 + LOCAL_REGION_UNKNOWN = auto() # 좌표 → 행정구역 코드 변환 실패 + LOCAL_FETCH_FAILED = auto() # ★ 실패해도 직전 값을 유지한다 — 빈 값을 내보내지 않는다 + + # 사이트(sites) 관련 에러 + SITE_NOT_FOUND = 1700 + SITE_VERSION_NOT_FOUND = auto() + SITE_BUILD_FAILED = auto() + PUBLISH_UNVERIFIED_FACT = auto() # ★ 미검증 fact 포함 — 발행 거부 + PUBLISH_NO_UNIQUE_CONTENT = auto() # ★ 고유 콘텐츠 0건 — 발행 거부(스팸 판정 대상) + PUBLISH_JSONLD_MISMATCH = auto() # ★ 구조화 데이터 값 != 화면 값 — 빌드 실패 + PUBLISH_REQUIRED_FACT_MISSING = auto() # 업종 스키마의 required 필드 누락 + SITE_SLUG_LOCKED = auto() # ★ 이미 발행된 사이트의 주소 변경 — 색인된 페이지가 404 가 된다 + + # 리포트(reports) 관련 에러 + REPORT_NOT_FOUND = 1800 + + # 작업 큐(job) 관련 에러 + JOB_NOT_FOUND = 1900 + JOB_ALREADY_QUEUED = auto() # 같은 dedupe_key 의 활성 잡이 이미 있다 + JOB_NOT_DEAD = auto() # DEAD 가 아닌 잡을 재큐하려 함 + + +# ErrorType 의 HTTP_* 값과 status_code 를 맞춰 router 단에서 raise 한다. +EXCEPTION_FORBIDDEN = HTTPException(status_code=ErrorType.HTTP_FORBIDDEN.value, detail=ErrorType.HTTP_FORBIDDEN.name) +EXCEPTION_INVALID_CLIENT_REQUEST = HTTPException(status_code=ErrorType.HTTP_INVALID_CLIENT_REQUEST.value, detail=ErrorType.HTTP_INVALID_CLIENT_REQUEST.name) +EXCEPTION_TO_MANY_REQUEST = HTTPException(status_code=ErrorType.HTTP_TO_MANY_REQUEST.value, detail=ErrorType.HTTP_TO_MANY_REQUEST.name) +EXCEPTION_INVALID_CLIENT_ACCESS = HTTPException(status_code=ErrorType.HTTP_INVALID_CLIENT_ACCESS.value, detail=ErrorType.HTTP_INVALID_CLIENT_ACCESS.name) +EXCEPTION_ACCESS_TOKEN_EXPIRED = HTTPException(status_code=ErrorType.HTTP_ACCESS_TOKEN_EXPIRED.value, detail=ErrorType.HTTP_ACCESS_TOKEN_EXPIRED.name) +EXCEPTION_REFRESH_TOKEN_EXPIRED = HTTPException(status_code=ErrorType.HTTP_REFRESH_TOKEN_EXPIRED.value, detail=ErrorType.HTTP_REFRESH_TOKEN_EXPIRED.name) +EXCEPTION_HTTP_INVALID_TOKEN_ACCESS = HTTPException(status_code=ErrorType.HTTP_INVALID_TOKEN_ACCESS.value, detail=ErrorType.HTTP_INVALID_TOKEN_ACCESS.name) + + +class DBType(Enum): + """논리 DB 구분. 모델마다 DBType() 으로 자신이 속한 DB 를 반환한다. + DB 가 늘어나면 여기에 추가하고 db_session_manager 의 맵에 등록만 하면 된다. + """ + + MAIN = 1 + + +class DBWRType(Enum): + """Read / Write 접속 구분. 조회는 DB_READ, 변경은 DB_WRITE 엔진을 사용한다.""" + + DB_READ = 1 + DB_WRITE = 2 + + +# 도메인 코드값 +class UserStatus(CodeEnum): + """users.status 코드값.""" + + ACTIVE = 1 + INACTIVE = 2 + + +class UserRole(CodeEnum): + """users.role 코드값. + 1=일반, 2=최고관리자(고객사 최상위), 3=개발자(우리 내부 운영 계정). + 개발자 계정은 고객사에 존재를 노출하지 않는다 — 회원 목록에서 빼고 총계에도 넣지 않는다.""" + + USER = 1 + OWNER = 2 # 최고관리자: 자기 회사 계정 관리 + 회사 설정 + DEVELOPER = 3 # 개발자(내부 운영): 최고관리자 권한 전부 + 고객사에 보이지 않음 + + +class CompanyStatus(CodeEnum): + """companies.status 코드값.""" + + ACTIVE = 1 + INACTIVE = 2 + + +class PlaceCategory(CodeEnum): + """places.category 코드값. 업종 — 스키마 파일(common/category_schema/resources/*.json)과 1:1. + 업종 추가 = 여기에 코드 추가 + 스키마 파일 1개 추가.""" + + LODGING = 1 # 숙박 + CAFE = 2 # 카페 + RESTAURANT = 3 # 음식점 + TOUR_ACTIVITY = 4 # 관광체험 + + +class ExternalPlaceSource(CodeEnum): + """places.external_source 코드값. 동일 업소 검증에 쓴 외부 장소 DB. + + 카카오는 안정적인 고유 place id 를 준다 → 그걸로 중복 등록을 막는다. + 네이버는 고유 id 가 없다(응답의 link 는 업체 홈페이지다) → 상호명+도로명주소로 막는다.""" + + KAKAO = 1 # dapi.kakao.com — 고유 place id O · 전화번호 O · 행정구역 코드 O + NAVER = 2 # openapi.naver.com 지역검색 — 고유 id X · 전화번호 X · 5건 제한 + + +class PlaceStatus(CodeEnum): + """places.status 코드값. 사업장 생애주기. + 해지는 삭제가 아니라 SUSPENDED 로의 상태 전이다(색인된 페이지를 갑자기 404 로 만들지 않는다).""" + + DRAFT = 1 # 등록만 됨 — 동일 업소 검증 전 + COLLECTING = 2 # 수집 진행 중 + REVIEW = 3 # 검수 대기(사람 확인 큐) + PUBLISHED = 4 # 발행됨 + SUSPENDED = 5 # 해지·중지 — 사이트 상태 전이로 처리 + + +class SourceType(CodeEnum): + """facts.source_type / media.source_type / place_aliases.source_type 공용 코드값. + 값이 어디서 왔는지 — 모든 사실은 출처를 갖는다.""" + + OWNER = 1 # 사장님이 직접 입력·업로드 + API = 2 # 공식 API (카카오 로컬 · TourAPI · Open-Meteo · Perplexity) + CRAWL = 3 # 크롤링 + LLM = 4 # LLM 생성 — ★ 사실이 아니라 문장에만 쓴다 + + +class FactStatus(CodeEnum): + """facts.status / faqs.status / routes.status 공용 검증 상태. + ★ VERIFIED 와 CORRECTED 만 사이트에 노출한다(PUBLISHABLE_FACT_STATUSES).""" + + UNVERIFIED = 1 # 수집됐으나 아무도 확인 안 함 + PENDING_OWNER = 2 # 사장님 확인 대기 + VERIFIED = 3 # 확인됨 — 노출 가능 + CORRECTED = 4 # 사장님이 고침 — 노출 가능 + ★ 잠김(자동 갱신이 덮어쓸 수 없다) + REJECTED = 5 # 틀린 값으로 판정 — 노출 안 함 + EXPIRED = 6 # 유효기간 지남 — 노출 안 함, 재수집 대상 + + +# ★ 절대규칙 1: 이 두 상태만 사이트에 노출한다. 발행 게이트가 이 집합으로 필터링한다. +PUBLISHABLE_FACT_STATUSES = {FactStatus.VERIFIED, FactStatus.CORRECTED} + +# 후보 — 재수집이 올려놓은 확인 대기 항목. 노출값과 달리 (place, unit, key) 당 여러 건 공존한다. +CANDIDATE_FACT_STATUSES = {FactStatus.UNVERIFIED, FactStatus.PENDING_OWNER} + +# ★ 절대규칙 6: 자동 수집(api/crawl/llm)이 덮어쓸 수 없는 상태. 사장님 수정본은 후보로만 도전받는다. +LOCKED_FACT_STATUSES = {FactStatus.CORRECTED} + + +class FactWriteOutcome(CodeEnum): + """fact 기록 결과. 재수집(업데이트)이 무엇을 했는지 호출측이 알아야 한다 — + 특히 사이트 재빌드가 필요한 경우(PUBLISHED_REPLACED)를 구분해야 한다.""" + + PUBLISHED_CREATED = 1 # 노출값이 없던 자리에 사람이 직접 넣어 바로 노출됐다 + PUBLISHED_REPLACED = 2 # ★ 노출값이 교체됐다 — 사이트 재빌드 대상 + REFRESHED = 3 # 재수집했는데 값이 그대로 — 검증 유지, 확인 시각만 갱신 + CANDIDATE_CREATED = 4 # 노출값과 다른 값이 들어와 후보로 쌓였다(사람 확인 대기) + CANDIDATE_UPDATED = 5 # 같은 출처의 기존 후보를 새 수집값으로 갱신했다 + +# 검증 상태 전이 허용표. 여기에 없는 전이는 FACT_INVALID_TRANSITION 으로 거부한다. +FACT_STATUS_TRANSITIONS = { + FactStatus.UNVERIFIED: {FactStatus.PENDING_OWNER, FactStatus.VERIFIED, FactStatus.REJECTED, FactStatus.EXPIRED}, + FactStatus.PENDING_OWNER: {FactStatus.VERIFIED, FactStatus.CORRECTED, FactStatus.REJECTED, FactStatus.EXPIRED}, + FactStatus.VERIFIED: {FactStatus.CORRECTED, FactStatus.REJECTED, FactStatus.EXPIRED}, + FactStatus.CORRECTED: {FactStatus.CORRECTED, FactStatus.REJECTED}, # 사장님만 다시 고칠 수 있다 + FactStatus.REJECTED: {FactStatus.UNVERIFIED}, # 재수집으로만 되살아난다 + FactStatus.EXPIRED: {FactStatus.UNVERIFIED}, +} + + +class LinkChannel(CodeEnum): + """place_links.channel 코드값. Perplexity 가 발견하는 채널 종류.""" + + YANOLJA = 1 # 야놀자 + GOODCHOICE = 2 # 여기어때 + NAVER_PLACE = 3 # 네이버 플레이스 + INSTAGRAM = 4 + OFFICIAL_SITE = 5 # 사장님 자체 홈페이지 + BLOG = 6 + ETC = 99 + + +class MediaStatus(CodeEnum): + """media.status 코드값. 비전 결과 신뢰도가 낮으면 자동 반영하지 않고 PENDING_REVIEW 로 둔다.""" + + PENDING_REVIEW = 1 # 사람 확인 큐 — Vision 분석 전이거나 신뢰도가 낮다 + APPROVED = 2 # 사람이 확인함(또는 Vision 신뢰도가 충분히 높음) + REJECTED = 3 + + +# ★ Vision 결과를 자동 반영해도 되는 신뢰도 하한. 이 아래는 사람 확인 큐(PENDING_REVIEW)로 남긴다. +# "신뢰도 낮은 항목은 자동 반영하지 말고 사람 확인 큐로 보낸다" 를 한 곳에서만 판단한다. +VISION_AUTO_APPROVE_CONFIDENCE = 0.7 + + +class LocalContentType(CodeEnum): + """local_contents.content_type 코드값. 행정구역 코드 단위로 캐싱되는 지역 정보 종류.""" + + WEATHER = 1 # 날씨 (Open-Meteo) + FESTIVAL = 2 # 축제 (TourAPI 행사정보, 주 1회) + ATTRACTION = 3 # 관광지 (TourAPI 지역기반, 월 1회) + RESTAURANT = 4 # 주변 맛집 (카카오 카테고리 검색) + + +class LocalSource(CodeEnum): + """local_contents.source 코드값. 어느 외부 API 에서 왔는지.""" + + OPEN_METEO = 1 # 날씨. API 키 불필요 + TOUR_API = 2 # 한국관광공사. ★ 자체 areaCode 체계 — 카카오 행정구역 코드와 다르다 + KAKAO_LOCAL = 3 + OFFICIAL_WEB = 4 # 지자체·행사 공식 홈페이지에서 운영자가 검수해 등록 + + +class LocalContentStatus(CodeEnum): + """운영 관리자가 검수하는 지역 콘텐츠 발행 상태.""" + + REVIEW = 1 + PUBLISHED = 2 + ENDED = 3 + + +class TransportType(CodeEnum): + """routes.transport 코드값. 가는 길 수단.""" + + CAR = 1 + PUBLIC = 2 + WALK = 3 + + +class SiteStatus(CodeEnum): + """sites.status 코드값. ★ 해지는 물리 삭제가 아니라 상태 전이로만 처리한다.""" + + DRAFT = 1 + REVIEW = 2 # 검수 게이트 대기 + PUBLISHED = 3 + SUSPENDED = 4 # 해지 유예 — 페이지는 살아있음 + UNPUBLISHED = 5 # 내림 + + +class BuildStatus(CodeEnum): + """site_versions.build_status 코드값. 정적 빌드는 개별 재빌드 단위로 돈다.""" + + PENDING = 1 + BUILDING = 2 + BUILT = 3 + FAILED = 4 + + +class PublishAction(CodeEnum): + """publish_logs.action 코드값.""" + + PUBLISH = 1 + UNPUBLISH = 2 + REBUILD = 3 + SUSPEND = 4 + RESUME = 5 + + +class PublishResult(CodeEnum): + """publish_logs.result 코드값.""" + + SUCCESS = 1 + REJECTED = 2 # 검수 게이트가 막음 — reject_reason 참고 + FAILED = 3 # 빌드/배포 자체가 실패 + + +class PublishRejectReason(CodeEnum): + """publish_logs.reject_reason 코드값. 검수 게이트가 발행을 막은 이유(절대규칙 1~3).""" + + UNVERIFIED_FACT = 1 # 미검증 fact 포함 + NO_UNIQUE_CONTENT = 2 # 고유 콘텐츠 0건 + JSONLD_MISMATCH = 3 # 구조화 데이터 값 != 화면 값 + REQUIRED_FACT_MISSING = 4 # 업종 스키마 required 필드 누락 + + +class AiEngine(CodeEnum): + """ai_check_results.engine 코드값. AI 검색이 우리 사이트를 근거로 답하는지 측정할 대상.""" + + CHATGPT = 1 + PERPLEXITY = 2 + GEMINI = 3 + CLAUDE = 4 + ETC = 99 + + +# ============================================================ +# 작업 큐 (LPS 의 job 큐 구조를 이식 — PostgreSQL 을 큐로 쓴다) +# ============================================================ +class JobType(CodeEnum): + """jobs.job_type 코드값. 수집·비전·빌드는 몇 분씩 걸려 동기 요청으로 처리할 수 없다. + + 무거운 잡(브라우저 필요)과 가벼운 잡(HTTP API 만)을 코드로 갈라 둔다 — + 크롤링 법무 결론이 나면 무거운 잡만 별도 워커 이미지로 분리한다.""" + + COLLECT = 1 # 수집 파이프라인: Perplexity 채널 발견 → 카카오 검증 → 크롤링 + VISION = 2 # 사진 분류 + alt 생성 (Gemini Vision, 20~50장 배치) + COPY = 3 # 소개문·FAQ 작성 (Gemini 텍스트) — 확보된 fact 만 근거로 + BUILD = 4 # 사이트 정적 빌드 — ★ 개별 재빌드 단위 + LOCAL_SYNC = 5 # 지역 정보 갱신 — 행정구역 코드 단위(같은 지역 사이트 50개여도 1회) + AI_CHECK = 6 # AI 검색 노출 점검 + + +class JobStatus(CodeEnum): + """jobs.status 코드값. 작업 큐 상태. + + 전이는 전부 조건부 원자 UPDATE(CAS)로만 한다. 실패는 재시도 가능하면 + PENDING(run_after=백오프)으로 되돌리고, 소진되면 DEAD(dead-letter).""" + + PENDING = 1 # 대기(claim 가능). run_after <= now() 일 때만 실제 claim 대상 + RUNNING = 2 # 워커가 점유 중(lease_until 까지 소유). 만료 시 reaper 가 회수 + DONE = 3 # 완료 + DEAD = 4 # dead-letter — max_attempts 소진(수동 개입/알림 대상) + + +# claim 대상이 되는 활성 상태. dedupe 부분 유니크 인덱스의 조건과 같아야 한다. +ACTIVE_JOB_STATUSES = {JobStatus.PENDING, JobStatus.RUNNING} diff --git a/backend/common/logger.py b/backend/common/logger.py new file mode 100644 index 0000000..802f664 --- /dev/null +++ b/backend/common/logger.py @@ -0,0 +1,43 @@ +import sys +import traceback +from datetime import datetime, timezone + + +class _Logger: + """원본 DerbyServer LOG 인터페이스를 간소화한 버전. + LOG.i / LOG.d / LOG.w / LOG.e_no_callstack / LOG.SetPrefix 를 제공한다. + """ + + def __init__(self): + self._prefix = "" + + def SetPrefix(self, prefix: str): + self._prefix = prefix + + def _now(self) -> str: + return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") + + def _write(self, level: str, msg): + head = f"{self._now()} [{level}]" + if self._prefix: + head += f"[{self._prefix}]" + print(f"{head} {msg}", file=sys.stderr if level in ("WARN", "ERROR") else sys.stdout) + + def d(self, msg): + self._write("DEBUG", msg) + + def i(self, msg): + self._write("INFO", msg) + + def w(self, msg): + self._write("WARN", msg) + + def e(self, msg): + self._write("ERROR", msg) + traceback.print_stack() + + def e_no_callstack(self, msg): + self._write("ERROR", msg) + + +LOG = _Logger() diff --git a/backend/common/models/gmodel.py b/backend/common/models/gmodel.py new file mode 100644 index 0000000..bb956fe --- /dev/null +++ b/backend/common/models/gmodel.py @@ -0,0 +1,86 @@ +import json +from typing import Optional + +from fastapi import Query +from pydantic import BaseModel, Field + +from common.enums import ErrorType, UserRole + + +class StructModel: + """프로토콜/구조체 식별용 마커 클래스.""" + + pass + + +class ErrorInfo(BaseModel, StructModel): + """모든 응답에 공통으로 실리는 결과 정보. result.success / code / desc 로 내려간다.""" + + success: Optional[bool] = True + code: Optional[int] = ErrorType.SUCCESS.value + desc: Optional[str] = ErrorType.SUCCESS.name + + def SetResult(self, enum: ErrorType): + if enum is not None: + self.success = ErrorType.SUCCESS.value == enum.value + self.code = enum.value + self.desc = enum.name + + +# ---- Protocol 규약 ------------------------------------------------------- +# 모든 통신 패킷은 WebPacketProtocol 을 상속한다. +# 요청 : Req_xxx (WebPacketProtocol) +# 응답 : Res_xxx (Res_WebPacketProtocol) - 항상 result 필드를 가진다. +# 각 라우터 폴더의 protocol.py 에 Req_/Res_ 를 정의한다. +class WebPacketProtocol(BaseModel, StructModel): + pass + + +class Req_WebPacketProtocol(WebPacketProtocol): + pass + + +class Res_WebPacketProtocol(WebPacketProtocol): + # default_factory 로 인스턴스마다 새 ErrorInfo 를 생성한다 (mutable default 공유 방지). + result: ErrorInfo = Field(default_factory=ErrorInfo) + msg: Optional[str] = None + + +class Res_PageProtocol(Res_WebPacketProtocol): + # 목록 응답 공용 페이지 메타. + total: int = 0 + page: int = 0 + size: int = 0 + + +class PageParams: + # 목록 엔드포인트 공용 쿼리 파라미터. 라우터에서 Depends() 로 주입한다. + def __init__(self, page: int = Query(1, ge=1), size: int = Query(20, ge=1, le=100)): + self.page = page + self.size = size + + @property + def skip(self) -> int: + return (self.page - 1) * self.size + + +class UserInfo(StructModel): + """JWT subject 로 인코딩되는 유저 식별 정보.""" + + user_id: str # users.user_id (uuid) — 데이터 스코프 키 + id: str # users.id (로그인 아이디) — get_me 재조회 키 + company_id: str # users.company_id (uuid) — 멀티테넌트 스코프 키 + role: int # users.role (UserRole) — 권한 게이트(최고관리자 등) 판단 키 + + def __init__(self, *args, **kwargs) -> None: + super().__init__() + # 구버전 토큰(role 미포함) 도 디코딩되도록 기본값을 먼저 깔고 kwargs 로 덮어쓴다. + self.role = UserRole.USER.value + for dictionary in args: + for key in dictionary: + setattr(self, key, dictionary[key]) + for key in kwargs: + setattr(self, key, kwargs[key]) + + def to_json(self) -> str: + return json.dumps(self.__dict__) diff --git a/backend/common/singleton.py b/backend/common/singleton.py new file mode 100644 index 0000000..47d87e6 --- /dev/null +++ b/backend/common/singleton.py @@ -0,0 +1,16 @@ +class Singleton: + _init = False + + def __new__(cls, *args, **kwargs): + if not hasattr(cls, "instance"): + cls.instance = super(Singleton, cls).__new__(cls) + + return cls.instance + + @classmethod + def is_init(cls): + return cls._init + + @classmethod + def set_init(cls): + cls._init = True diff --git a/backend/common/utils/gtime.py b/backend/common/utils/gtime.py new file mode 100644 index 0000000..937513b --- /dev/null +++ b/backend/common/utils/gtime.py @@ -0,0 +1,21 @@ +from datetime import datetime, timezone, timedelta + + +class GTime: + """서버 전역에서 UTC 기준 시간을 사용하기 위한 유틸. (원본 DerbyServer 패턴 축약)""" + + @staticmethod + def UTC() -> datetime: + return datetime.now(timezone.utc).replace(tzinfo=None) + + @staticmethod + def UTCStr(fmt: str = "%Y-%m-%d %H:%M:%S") -> str: + return GTime.UTC().strftime(fmt) + + @staticmethod + def AddMinutes(minutes: int) -> datetime: + return GTime.UTC() + timedelta(minutes=minutes) + + @staticmethod + def AddDays(days: int) -> datetime: + return GTime.UTC() + timedelta(days=days) diff --git a/backend/config/config.local.toml.example b/backend/config/config.local.toml.example new file mode 100644 index 0000000..fc60752 --- /dev/null +++ b/backend/config/config.local.toml.example @@ -0,0 +1,52 @@ +# 복사해서 사용: cp config.local.toml.example config.local.toml +# 실제 config.local.toml 은 시크릿 포함이라 커밋하지 않는다(.gitignore: *.toml). +# 모든 서버는 APP_ENV=local 로 띄우며 이 파일을 읽는다. +[WebServerConfig] +server_name = "O2oSiteServer" +port = 9800 +process_count = 1 +is_ssl = false +is_test = true +# 관리자 프론트 오리진 — CORS 허용. 쉼표로 여러 개. +# vite 는 3000 이 쓰이고 있으면 3001, 3002… 로 옮겨 뜨므로 개발 포트 대역을 함께 적어 둔다. +# 운영에서는 실제 도메인 하나만 남긴다. +client_url = "http://localhost:3000,http://localhost:3001,http://localhost:3002,http://localhost:3003,http://localhost:3004,http://localhost:3005" +landing_url = "" # 랜딩(마케팅 사이트). 없으면 빈값 + +[LogConfig] +print_console = true +log_level = "debug" + +# DB Read/Write 분리. 도커 실행 시 host 는 docker-compose 의 DB_HOST 로 override. +# 관리형 DB(RDS/Aurora/Azure)는 host 에 엔드포인트, sslmode="require". +[MainDBConfig] +db_type = "postgresql" +name = "o2o_site_db" +write_host = "127.0.0.1" +write_port = 5432 +write_id = "" +write_pw = "" +read_host = "127.0.0.1" +read_port = 5432 +read_id = "" +read_pw = "" +show_log = false +pool_size = 10 +max_overflow = 20 +sslmode = "" # 로컬: "" / 관리형 DB: "require"|"verify-ca"|"verify-full" + +[JwtToken] +access_key = "" +refresh_key = "" +access_expire_min = 30 +refresh_expire_day = 7 + +# 수집 파이프라인 외부 API 키. 빈값이면 해당 어댑터 비활성(서버는 그대로 뜬다). +# 배포에서 환경변수로만 주입하려면 여기는 비우고 PERPLEXITY_API_KEY 등을 env 로 넘긴다. +[ExternalApiConfig] +perplexity_api_key = "" # 채널 URL 발견 +kakao_rest_api_key = "" # 동일 업소 검증(미발급) +naver_client_id = "" # 동일 업소 검증 — 네이버 지역검색 +naver_client_secret = "" +gemini_api_key = "" # 사진 분류 · 카피 작성 +tour_api_key = "" # 공공데이터포털 전국문화축제표준데이터 일반 인증키 diff --git a/backend/config/config_loader.py b/backend/config/config_loader.py new file mode 100644 index 0000000..8e1f7a0 --- /dev/null +++ b/backend/config/config_loader.py @@ -0,0 +1,37 @@ +import tomllib +from typing import Optional, Type, Dict, TypeVar +from pydantic import BaseModel + + +class ConfigModel(BaseModel): + pass + + +# APP_ENV +# local : 로컬 환경(개인 pc) +# dev : 개발환경 (사내 pc) +# prod : 서비스 환경 (클라우드 서버) +# +# 실행시 환경변수 설정 +# linux : export APP_ENV=dev +# window : set APP_ENV=dev +class Configs: + ConfigType = TypeVar("ConfigType", bound=ConfigModel) + + def __init__(self, file_path: str): + self._settings: Dict[Type["Configs.ConfigType"], "Configs.ConfigType"] = self._load_settings_from_toml(file_path) + + def _load_settings_from_toml(self, file_path: str) -> Dict[Type[ConfigType], ConfigType]: + with open(file_path, "rb") as f: + toml_content = tomllib.load(f) + + config_subclasses = ConfigModel.__subclasses__() + configs = { + config_class: config_class.model_validate(toml_content[config_class.__name__]) + for config_class in config_subclasses + if config_class.__name__ in toml_content + } + return configs + + def get(self, config_class: Type[ConfigType]) -> Optional[ConfigType]: + return self._settings.get(config_class) diff --git a/backend/config/config_models.py b/backend/config/config_models.py new file mode 100644 index 0000000..bf5bf37 --- /dev/null +++ b/backend/config/config_models.py @@ -0,0 +1,66 @@ +from config.config_loader import ConfigModel + + +class WebServerConfig(ConfigModel): + server_name: str = "" + port: int = 0 + process_count: int = 1 + is_ssl: bool = False + is_test: bool = False + client_url: str = "" # 관리자 프론트 오리진. CORS 허용 대상 + landing_url: str = "" # 랜딩(마케팅 사이트) 오리진. 빈값=미허용 + + +class LogConfig(ConfigModel): + print_console: bool = True + log_level: str = "debug" + + +# DB Read/Write 분리 설정. +# 하나의 논리 DB 에 대해 write(주) / read(복제) 접속 정보를 각각 가진다. +class MainDBConfig(ConfigModel): + db_type: str = "postgresql" + name: str = "" + write_host: str = "" + write_port: int = 5432 + write_id: str = "" + write_pw: str = "" + read_host: str = "" + read_port: int = 5432 + read_id: str = "" + read_pw: str = "" + show_log: bool = False + # 커넥션 풀 사이징. 실제 동시 커넥션 상한 = (pool_size + max_overflow) x 엔진수(R/W=2) x 워커수. + # PostgreSQL max_connections 를 넘지 않도록 설정해야 한다. (예: 10+20=30 x 2 x 5워커 = 300) + pool_size: int = 10 + max_overflow: int = 20 + # SSL/TLS 모드: ""/"disable"=미사용(로컬), "require"/"verify-ca"/"verify-full"=관리형 DB(RDS/Aurora/Azure). + sslmode: str = "" + + +class JwtToken(ConfigModel): + access_key: str = "" + refresh_key: str = "" + access_expire_min: int = 30 + refresh_expire_day: int = 7 + + +# 외부 API 키. 수집 파이프라인(Perplexity → 카카오 로컬 → 크롤링 → Gemini)이 쓴다. +# 키가 비면 해당 어댑터는 비활성 — 서버는 그대로 뜬다(부팅이 외부 계약에 묶이면 안 된다). +class ExternalApiConfig(ConfigModel): + perplexity_api_key: str = "" # 채널 URL 발견 (api.perplexity.ai) + # 동일 업소 검증 — 두 소스 중 설정된 쪽을 쓴다(둘 다 있으면 카카오 우선). + # 카카오: 15건 · 전화번호 O · 고유 place id O · 행정구역 코드 O → 판정 근거가 강하다 + # 네이버: 5건 · 전화번호 X · 고유 id 불확실 · 행정구역 코드 X → 그만큼 AMBIGUOUS 가 늘어난다 + kakao_rest_api_key: str = "" # dapi.kakao.com (미발급) + naver_client_id: str = "" # openapi.naver.com 지역검색 + naver_client_secret: str = "" + gemini_api_key: str = "" # 사진 분류 + 카피 작성 (Google AI Studio) + # 비전 모델. 사진 1장 ≈ 1,200 토큰이라 사업장 1건(50장)에 3.7-flash $0.045 / 2.5-flash $0.018. + # 기본을 3.7 로 두는 이유: 라벨이 틀리면 사람 확인 큐 비용이 모델 값 차이보다 크다. + gemini_vision_model: str = "gemini-3.7-flash" + # 소개문·FAQ 생성 모델. 비전과 따로 둔다 — 텍스트는 토큰이 적어 상위 모델을 써도 싸다. + gemini_text_model: str = "gemini-3.7-flash" + # ★ 이 값 미만이면 자동 반영하지 않고 사람 확인 큐(PENDING_REVIEW)에 남긴다. 운영하며 조정한다. + vision_confidence_threshold: float = 0.7 + tour_api_key: str = "" # 공공데이터포털 일반 인증키(전국문화축제표준데이터) diff --git a/backend/config/server_configs.py b/backend/config/server_configs.py new file mode 100644 index 0000000..cc4a821 --- /dev/null +++ b/backend/config/server_configs.py @@ -0,0 +1,107 @@ +import os + +from dotenv import load_dotenv + +from config.config_loader import Configs +from config.config_models import WebServerConfig, LogConfig, MainDBConfig, JwtToken, ExternalApiConfig + +# 레포 최상위 .env 를 환경변수로 올린다 (외부 API 키·DB 접속의 배포용 주입 경로). +# override=False: 이미 설정된 실제 환경변수(docker-compose 등)가 항상 이긴다. +# 우선순위 = 실제 환경변수 > .env > config.{APP_ENV}.toml +# +# ★ APP_ENV=test 면 .env 를 읽지 않는다. 실키가 테스트 환경에 새어 들어가면 +# 테스트가 실제 외부 API(Perplexity·Gemini·카카오)를 때리고 요금이 나간다. +# 테스트의 외부 연동은 config.test.toml(전 키 빈 값) + MockAdapter 로만 검증한다. +_DOTENV_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), ".env") +if os.environ.get("APP_ENV") != "test": + load_dotenv(_DOTENV_PATH, override=False) + +# 실행 환경 결정 (기본 local). 환경변수 APP_ENV 로 변경. +APP_ENV = os.environ.get("APP_ENV", "local") + +_config_dir = os.path.dirname(__file__) +_config_file = os.path.join(_config_dir, f"config.{APP_ENV}.toml") + +# 운영 전제: 항상 APP_ENV=local 로 띄운다 → config.local.toml 사용 (test/docker 도 local 로 실행). +if not os.path.exists(_config_file): + raise FileNotFoundError(f"설정 파일이 없습니다: {_config_file} (APP_ENV={APP_ENV}). APP_ENV=local 로 실행하세요.") + +configs = Configs(_config_file) + +web_server_config: WebServerConfig = configs.get(WebServerConfig) +log_config: LogConfig = configs.get(LogConfig) +main_db_config: MainDBConfig = configs.get(MainDBConfig) +jwt_token_config: JwtToken = configs.get(JwtToken) +# [ExternalApiConfig] 섹션이 없는 toml 에서도 죽지 않게 기본값 폴백(전 키 빈 값 → 해당 어댑터 비활성). +external_api_config: ExternalApiConfig = configs.get(ExternalApiConfig) or ExternalApiConfig() + + +# DB 접속 env override (config.local.toml 유지, 도커에서 host 만 교체). 로컬은 env 미설정 → toml 그대로. +def _apply_db_env_override(cfg: MainDBConfig): + h = os.environ.get("DB_HOST") + if h: + cfg.write_host = cfg.read_host = h + if os.environ.get("DB_PORT"): + cfg.write_port = cfg.read_port = int(os.environ["DB_PORT"]) + if os.environ.get("DB_USER"): + cfg.write_id = cfg.read_id = os.environ["DB_USER"] + if os.environ.get("DB_PASSWORD"): + cfg.write_pw = cfg.read_pw = os.environ["DB_PASSWORD"] + if os.environ.get("DB_NAME"): + cfg.name = os.environ["DB_NAME"] + + +_apply_db_env_override(main_db_config) + + +# 외부 API 키 env override — 키를 toml 에 안 두고 배포 환경변수로만 주입하는 경우. +def _apply_external_api_env_override(cfg: ExternalApiConfig): + if os.environ.get("PERPLEXITY_API_KEY"): + cfg.perplexity_api_key = os.environ["PERPLEXITY_API_KEY"] + if os.environ.get("KAKAO_REST_API_KEY"): + cfg.kakao_rest_api_key = os.environ["KAKAO_REST_API_KEY"] + if os.environ.get("NAVER_CLIENT_ID"): + cfg.naver_client_id = os.environ["NAVER_CLIENT_ID"] + if os.environ.get("NAVER_CLIENT_SECRET"): + cfg.naver_client_secret = os.environ["NAVER_CLIENT_SECRET"] + if os.environ.get("GEMINI_API_KEY"): + cfg.gemini_api_key = os.environ["GEMINI_API_KEY"] + if os.environ.get("GEMINI_VISION_MODEL"): + cfg.gemini_vision_model = os.environ["GEMINI_VISION_MODEL"] + if os.environ.get("GEMINI_TEXT_MODEL"): + cfg.gemini_text_model = os.environ["GEMINI_TEXT_MODEL"] + if os.environ.get("VISION_CONFIDENCE_THRESHOLD"): + cfg.vision_confidence_threshold = float(os.environ["VISION_CONFIDENCE_THRESHOLD"]) + if os.environ.get("TOUR_API_KEY"): + cfg.tour_api_key = os.environ["TOUR_API_KEY"] + + +_apply_external_api_env_override(external_api_config) + + +# JWT 시크릿 env override. +# ★ 도커 이미지는 config.local.toml 을 example 사본(플레이스홀더)으로 굽는다 — 시크릿을 안 굽기 위해서다. +# 그래서 env 로 주입하지 않으면 "" 이라는 공개된 문자열이 서명 키가 된다. +# 운영에서는 반드시 env 로 넣어야 한다. +def _apply_jwt_env_override(cfg: JwtToken): + if os.environ.get("JWT_ACCESS_SECRET"): + cfg.access_key = os.environ["JWT_ACCESS_SECRET"] + if os.environ.get("JWT_REFRESH_SECRET"): + cfg.refresh_key = os.environ["JWT_REFRESH_SECRET"] + if os.environ.get("JWT_ACCESS_EXPIRE_MIN"): + cfg.access_expire_min = int(os.environ["JWT_ACCESS_EXPIRE_MIN"]) + if os.environ.get("JWT_REFRESH_EXPIRE_DAY"): + cfg.refresh_expire_day = int(os.environ["JWT_REFRESH_EXPIRE_DAY"]) + + +_apply_jwt_env_override(jwt_token_config) + +# 플레이스홀더가 그대로 남아 있으면(=env 미주입 도커) 눈에 띄게 경고한다. +# 부팅은 막지 않는다 — 로컬 개발에서 토큰이 안 필요한 작업까지 못 하게 되면 곤란하다. +if jwt_token_config.access_key.startswith("<") or jwt_token_config.refresh_key.startswith("<"): + from common.logger import LOG + + LOG.w( + "[보안] JWT 시크릿이 플레이스홀더입니다 — JWT_ACCESS_SECRET / JWT_REFRESH_SECRET 를 env 로 주입하세요. " + "이 상태로 운영에 띄우면 서명 키가 공개값입니다." + ) diff --git a/backend/conftest.py b/backend/conftest.py new file mode 100644 index 0000000..fe4babd --- /dev/null +++ b/backend/conftest.py @@ -0,0 +1,241 @@ +# 테스트는 APP_ENV=test 로 실행한다 (config.test.toml → o2o_site_test_db, dev DB 와 분리). +# 이 픽스처들은 TRUNCATE 를 하므로 dev DB(o2o_site_db)와 절대 공유하면 안 된다(아래 db_engine 안전가드 참고). +# config.server_configs 가 import 되는 순간 config..toml 을 읽으므로 가장 먼저 설정. +import os + +os.environ.setdefault("APP_ENV", "test") + +import uuid + +import pytest +import pytest_asyncio +from httpx import ASGITransport, AsyncClient +from sqlalchemy import text +from sqlalchemy.ext.asyncio import create_async_engine + +from common.database.model.models import MAIN_BASE +from common.enums import CompanyStatus +from config.server_configs import main_db_config + + +# 모델이 쓰는 스키마. test DB 는 비어 있을 수 있어 create_all 전에 직접 만든다. +# 또 TRUNCATE 가 unqualified 테이블명을 쓰므로 이 스키마들을 search_path 에 얹어 해석시킨다. +# 도메인 모듈(places/facts/sites/local/reports)이 붙을 때마다 스키마를 여기에 추가한다. +_SCHEMAS = ("company", "place", "fact", "local", "site", "job") + + +def _write_url(cfg) -> str: + pw = f":{cfg.write_pw}" if cfg.write_pw else "" + return f"postgresql+asyncpg://{cfg.write_id}{pw}@{cfg.write_host}:{cfg.write_port}/{cfg.name}" + + +def _admin_url(cfg) -> str: + """DB 생성용 관리 접속. CREATE DATABASE 는 대상 DB 안에서 못 하므로 기본 'postgres' DB 로 붙는다.""" + pw = f":{cfg.write_pw}" if cfg.write_pw else "" + return f"postgresql+asyncpg://{cfg.write_id}{pw}@{cfg.write_host}:{cfg.write_port}/postgres" + + +async def _drop_test_db(*, recreate: bool): + """test DB 를 지운다(있으면). recreate=True 면 지운 뒤 새로 만든다. + WITH (FORCE): 남아있는 커넥션을 끊고 drop (PG13+). 관리 접속은 기본 'postgres' DB.""" + engine = create_async_engine(_admin_url(main_db_config), isolation_level="AUTOCOMMIT") + try: + async with engine.connect() as conn: + await conn.execute(text(f'DROP DATABASE IF EXISTS "{main_db_config.name}" WITH (FORCE)')) + if recreate: + await conn.execute(text(f'CREATE DATABASE "{main_db_config.name}"')) + finally: + await engine.dispose() + + +@pytest_asyncio.fixture(scope="session", autouse=True) +async def _test_db_lifecycle(): + """테스트 세션 동안만 test DB 를 만들고, 끝나면 내린다. + + 매 세션 '깨끗한 새 DB'로 시작하므로 스키마 낡음(드리프트)이 원천 차단되고, 끝나면 남는 DB 도 없다. + (테이블 구조는 db_engine 의 create_all 이 현재 모델 기준으로 채운다.) + 안전가드: 이름에 'test' 있는 DB 만 만들고/지운다(dev DB 보호). + """ + assert "test" in main_db_config.name, ( + f"비-test DB('{main_db_config.name}') 는 만들거나 지우지 않는다. APP_ENV=test 로 실행하세요." + ) + await _drop_test_db(recreate=True) # 세션 시작: 깨끗한 새 DB + yield + # 세션 종료: 앱 싱글톤 커넥션부터 정리(활성 커넥션 있으면 FORCE 로 끊김) 후 DB 를 내린다. + from common.database.db_session_manager import DB_SESSION_MNG + + await DB_SESSION_MNG.dispose_all() + await _drop_test_db(recreate=False) + + +@pytest_asyncio.fixture +async def db_engine(_test_db_lifecycle): + """테스트용 스키마를 보장하고, 매 테스트 시작 시 테이블을 비워 격리한다. + + ⚠ 이 픽스처는 TRUNCATE 한다 → dev DB(o2o_site_db)를 가리키면 실데이터가 날아간다. + 그래서 test 전용 DB(이름에 'test')가 아니면 즉시 중단한다(config.test.toml / APP_ENV=test). + 앱(DB_SESSION_MNG)도 APP_ENV=test 면 같은 test DB 에 접속하므로 여기서 만든 스키마를 공유한다. + """ + # 안전가드: dev DB 오염 방지. o2o_site_test_db 이외엔 절대 실행하지 않는다. + assert "test" in main_db_config.name, ( + f"테스트가 비-test DB('{main_db_config.name}')를 가리킵니다. " + "APP_ENV=test(config.test.toml)로 실행하세요. dev DB 보호를 위해 중단합니다." + ) + engine = create_async_engine( + _write_url(main_db_config), + connect_args={"server_settings": {"search_path": ",".join(_SCHEMAS) + ",public"}}, + ) + async with engine.begin() as conn: + for sch in _SCHEMAS: + await conn.execute(text(f"CREATE SCHEMA IF NOT EXISTS {sch}")) + await conn.run_sync(MAIN_BASE.metadata.create_all) # 이미 있으면 skip + # 도메인 테이블 전부 비워 격리 (CASCADE: FK 미설정이라 안전망) + await conn.execute( + text( + "TRUNCATE TABLE users, companies, places, place_aliases, place_links, units, media, " + "facts, faqs, local_contents, routes, nearby_links, " + "sites, site_versions, publish_logs, ai_check_results, jobs RESTART IDENTITY CASCADE" + ) + ) + yield engine + await engine.dispose() + + +@pytest_asyncio.fixture +async def company_id(db_engine) -> str: + """테스트용 소속사 1개를 시드하고 company_id(uuid str)를 돌려준다. + users 는 company_id 를 요구하므로 계정 생성 테스트의 선행 조건이다. + """ + cid = uuid.uuid4() + async with db_engine.begin() as conn: + # status 는 NOT NULL(모델 default 는 ORM 전용이라 raw INSERT 엔 안 먹음) → 명시. + await conn.execute( + text("INSERT INTO companies (company_id, name, status) VALUES (:cid, :name, :status)"), + {"cid": cid, "name": "테스트사", "status": CompanyStatus.ACTIVE.value}, + ) + return str(cid) + + +@pytest_asyncio.fixture +async def other_company_id(db_engine) -> str: + """company_id 와 다른 소속사 1개(회사 스코프/IDOR 격리 테스트용).""" + cid = uuid.uuid4() + async with db_engine.begin() as conn: + await conn.execute( + text("INSERT INTO companies (company_id, name, status) VALUES (:cid, :name, :status)"), + {"cid": cid, "name": "다른회사", "status": CompanyStatus.ACTIVE.value}, + ) + return str(cid) + + +@pytest_asyncio.fixture +async def client(db_engine): + """앱을 실제 네트워크 없이 호출하는 httpx 클라이언트 (ASGITransport).""" + from router.router import app + + transport = ASGITransport(app=app) + async with AsyncClient(transport=transport, base_url="http://test") as ac: + yield ac + + +@pytest_asyncio.fixture +async def auth_headers(db_engine, client, company_id): + """테스트 유저를 시드하고 로그인 헤더(Bearer)를 돌려주는 팩토리. + + 계정 생성 API 가 없으므로 users 행을 직접 INSERT(비번 bcrypt 해시)한 뒤 /v1/auth/login 으로 토큰을 받는다. + company 미지정 시 기본 소속사(company_id 픽스처). role 로 OWNER 계정도 만들 수 있다. + 호출: `h = await auth_headers("user1")` / `await auth_headers("userB", other_company_id)`. + """ + from common.enums import UserRole, UserStatus + from router.v1.validator.dependencies import GetHashedPW + + async def _make(login_id, company=None, *, password="pw1234", role=UserRole.USER.value, name="n"): + cid = company or company_id + hashed = await GetHashedPW(password) + async with db_engine.begin() as conn: + # status·role 은 NOT NULL — ORM default 는 raw INSERT 에 안 먹으므로 명시(companies.status 와 동일). + await conn.execute( + text( + "INSERT INTO users (user_id, company_id, id, password, name, status, role, last_accessed_at) " + "VALUES (:uid, :cid, :id, :pw, :name, :status, :role, now())" + ), + { + "uid": uuid.uuid4(), "cid": uuid.UUID(cid), "id": login_id, "pw": hashed, + "name": name, "status": UserStatus.ACTIVE.value, "role": role, + }, + ) + r = await client.post("/v1/auth/login", json={"id": login_id, "password": password}) + return {"Authorization": f"Bearer {r.json()['access_token']}"} + + return _make + + +# ── 렌더러 스텁 ────────────────────────────────────────────────────────────── +@pytest.fixture(autouse=True) +def fake_renderer(monkeypatch, tmp_path_factory): + """정적 렌더러(frontend/site) 대역. + + ★ 왜 필요한가 + 발행 게이트는 이제 **실제로 나갈 HTML** 을 보고 판정한다. 그 HTML 은 Node 렌더러가 + 굽고, BUILD 잡은 그 결과 보고서를 기다린다(services/render_report.wait_for). + 파이썬 테스트 환경에는 Node 렌더러가 없으므로, payload 를 읽어 보고서를 만들어 주는 + 대역을 끼운다 — 여기서 검사하려는 건 **백엔드가 보고서를 어떻게 처리하는가** 다. + + ★ 구조화 데이터 ↔ 화면 값 대조 자체는 렌더러 쪽 테스트가 본다 + (frontend/site/src/seo/verify.test.ts). 그 규칙을 여기서 다시 구현하지 않는다 — + 두 벌로 두면 어긋나고, 어긋난 걸 아무도 모르는 게 원래 문제였다. + """ + import json + + from services import render_report, site_payload + + payload_dir = tmp_path_factory.mktemp("payloads") + monkeypatch.setattr(site_payload, "payload_dir", lambda: payload_dir) + monkeypatch.setattr(render_report, "payload_dir", lambda: payload_dir) + + # 고유 콘텐츠 계수 규칙은 렌더러(prerender.ts countUniqueContent)와 같아야 한다. + MIN_UNIQUE_TEXT = 8 + + def _count(payload: dict) -> int: + def long(value) -> bool: + return len(str(value or "").strip()) >= MIN_UNIQUE_TEXT + + count = 0 + facts = list(payload.get("facts") or []) + for unit in payload.get("units") or []: + facts.extend(unit.get("facts") or []) + count += sum(1 for f in facts if f.get("type") == "text" and long(f.get("value"))) + count += sum( + 1 for q in payload.get("faqs") or [] + if str(q.get("question") or "").strip() and long(q.get("answer")) + ) + count += sum(1 for m in payload.get("media") or [] if long(m.get("alt"))) + return count + + async def _wait_for(slug, site_version, timeout_sec, poll_sec=1.0): + path = payload_dir / f"{slug}.json" + if not path.is_file(): + return None + payload = json.loads(path.read_text(encoding="utf-8")) + if payload["site"]["version"] != site_version: + return None + place = payload.get("place") or {} + return { + "schemaVersion": 1, + "slug": slug, + "siteId": payload["site"]["siteId"], + "placeId": payload["site"]["placeId"], + "siteVersion": site_version, + "ok": True, + "renderedAt": "2026-01-01T00:00:00.000Z", + "routes": 3, + "bundle": "test.js", + "uniqueContentCount": _count(payload), + "jsonld": [{"@type": "LodgingBusiness", "name": place.get("name"), + "telephone": place.get("phone")}], + "mismatches": [], + "error": None, + } + + monkeypatch.setattr(render_report, "wait_for", _wait_for) + return payload_dir diff --git a/backend/crud/fact_crud.py b/backend/crud/fact_crud.py new file mode 100644 index 0000000..3b5b1dd --- /dev/null +++ b/backend/crud/fact_crud.py @@ -0,0 +1,256 @@ +from abc import ABC, abstractmethod +from typing import Optional, Tuple + +from sqlalchemy import and_, select, update +from sqlalchemy.ext.asyncio import AsyncSession + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import facts +from common.enums import ErrorType, FactStatus +from common.logger import LOG +from common.utils.gtime import GTime + +# ★ 사이트에 나가는 상태. PUBLISHABLE_FACT_STATUSES 와 같은 집합이어야 한다. +# 유니크 인덱스(uq_facts_published_*)의 조건과도 같아야 한다. +_PUBLISHED = (FactStatus.VERIFIED.value, FactStatus.CORRECTED.value) +# 후보 — 재수집이 올려놓은 확인 대기 항목. 여러 건 공존한다. +_CANDIDATE = (FactStatus.UNVERIFIED.value, FactStatus.PENDING_OWNER.value) +# 화면에 보이는 것 전체(이력 제외). +_ACTIVE = _PUBLISHED + _CANDIDATE + + +def _unit_cond(unit_id): + """unit_id 는 NULL 비교라 == 로 걸면 안 된다(사업장 단위 fact 를 못 찾는다).""" + return facts.unit_id.is_(None) if unit_id is None else facts.unit_id == unit_id + + +# fact CRUD. 항상 place_id 로 스코프한다. +class IFactCRUD(ABC): + @abstractmethod + async def add_fact(self, cdb: AsyncSession, fact: facts) -> ErrorType: + pass + + @abstractmethod + async def get_fact(self, cdb: AsyncSession, place_id, fact_id) -> Tuple[ErrorType, facts]: + pass + + @abstractmethod + async def list_facts(self, cdb: AsyncSession, place_id, unit_id, status, publishable_only, active_only) -> Tuple[ErrorType, list]: + pass + + @abstractmethod + async def get_published_fact(self, cdb: AsyncSession, place_id, unit_id, key) -> Tuple[ErrorType, facts]: + pass + + @abstractmethod + async def get_candidate(self, cdb: AsyncSession, place_id, unit_id, key, source_type) -> Tuple[ErrorType, facts]: + pass + + @abstractmethod + async def refresh_collected(self, cdb: AsyncSession, fact_id, source_type, source_url, ts) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def update_candidate(self, cdb: AsyncSession, fact_id, value, source_url, status, ts) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def transition(self, cdb: AsyncSession, fact_id, from_statuses, to_status, data: dict) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def expire_published(self, cdb: AsyncSession, place_id, unit_id, key, ts, except_fact_id=None) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def reject_candidates(self, cdb: AsyncSession, place_id, unit_id, key, ts, except_fact_id=None) -> Tuple[ErrorType, int]: + pass + + +class FactCRUD(IFactCRUD): + async def add_fact(self, cdb: AsyncSession, fact: facts) -> ErrorType: + try: + return await DB_SESSION_MNG.insert(cdb, fact) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def get_fact(self, cdb: AsyncSession, place_id, fact_id) -> Tuple[ErrorType, facts]: + try: + query = ( + select(facts) + .where(facts.fact_id == fact_id, facts.place_id == place_id, facts.deleted == False) # noqa: E712 + .limit(1) + ) + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, None + if len(row_list) != 1: + return ErrorType.DB_INVALID_KEY, None + return ErrorType.SUCCESS, row_list[0] + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def list_facts( + self, cdb: AsyncSession, place_id, unit_id=None, status: Optional[int] = None, + publishable_only: bool = False, active_only: bool = True, + ) -> Tuple[ErrorType, list]: + """fact 목록. + publishable_only=True → ★ VERIFIED·CORRECTED 만 (사이트 렌더·발행 게이트가 쓰는 경로) + active_only=True → REJECTED·EXPIRED 이력 제외 (관리 화면 기본: 노출값 + 후보) + """ + try: + conditions = [facts.place_id == place_id, facts.deleted == False] # noqa: E712 + if unit_id is not None: + conditions.append(facts.unit_id == unit_id) + if publishable_only: + conditions.append(facts.status.in_(_PUBLISHED)) + elif status is not None: + conditions.append(facts.status == status) + elif active_only: + conditions.append(facts.status.in_(_ACTIVE)) + + # 노출값이 먼저, 그 아래 후보. 같은 key 끼리 붙어 보이게 정렬한다. + query = select(facts).where(and_(*conditions)).order_by( + facts.key.asc(), facts.status.desc(), facts.collected_at.desc() + ) + err_type, rows = await DB_SESSION_MNG.execute(cdb, query) + return (err_type, list(rows) if err_type == ErrorType.SUCCESS else []) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, [] + + async def get_published_fact(self, cdb: AsyncSession, place_id, unit_id, key) -> Tuple[ErrorType, facts]: + """★ 지금 사이트에 나가고 있는 값. 없으면 (SUCCESS, None). + 유니크 인덱스가 1건만 허용하므로 결과는 0 또는 1건이다.""" + try: + query = ( + select(facts) + .where(and_( + facts.place_id == place_id, + facts.key == key, + facts.deleted == False, # noqa: E712 + facts.status.in_(_PUBLISHED), + _unit_cond(unit_id), + )) + .limit(1) + ) + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, None + return ErrorType.SUCCESS, (row_list[0] if row_list else None) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def get_candidate(self, cdb: AsyncSession, place_id, unit_id, key, source_type) -> Tuple[ErrorType, facts]: + """같은 출처가 이미 올려둔 후보. 재수집이 같은 후보를 계속 쌓지 않도록 갱신 대상을 찾는다.""" + try: + query = ( + select(facts) + .where(and_( + facts.place_id == place_id, + facts.key == key, + facts.source_type == source_type, + facts.deleted == False, # noqa: E712 + facts.status.in_(_CANDIDATE), + _unit_cond(unit_id), + )) + .order_by(facts.collected_at.desc()) + .limit(1) + ) + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, None + return ErrorType.SUCCESS, (row_list[0] if row_list else None) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def refresh_collected(self, cdb: AsyncSession, fact_id, source_type, source_url, ts) -> Tuple[ErrorType, int]: + """★ 재수집했는데 값이 그대로일 때 — 검증 상태를 건드리지 않고 '언제 다시 확인했는지'만 갱신한다. + + 이게 없으면 값이 안 바뀌었는데도 재수집마다 검증이 초기화돼 사이트에서 사실이 사라진다.""" + try: + values = {"collected_at": ts, "updated_at": ts} + if source_url: + values["source_url"] = source_url + query = update(facts).where(facts.fact_id == fact_id, facts.deleted == False).values(**values) # noqa: E712 + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def update_candidate(self, cdb: AsyncSession, fact_id, value, source_url, status: int, ts) -> Tuple[ErrorType, int]: + """기존 후보를 새 수집값으로 갱신. 같은 출처의 후보가 계속 쌓이는 것을 막는다.""" + try: + query = ( + update(facts) + .where(facts.fact_id == fact_id, facts.status.in_(_CANDIDATE), facts.deleted == False) # noqa: E712 + .values(value=value, source_url=source_url, status=status, collected_at=ts, updated_at=ts) + ) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def transition(self, cdb: AsyncSession, fact_id, from_statuses, to_status: int, data: dict) -> Tuple[ErrorType, int]: + """검증 상태 전이 — **출발 상태를 WHERE 에 걸어** 조건부로만 바꾼다. + + 적용행수 0 = 그 사이 다른 사람이 이미 상태를 바꿨다는 뜻(동시 처리 가드). + 허용 전이 판정 자체는 service 가 FACT_STATUS_TRANSITIONS 로 먼저 한다.""" + try: + query = ( + update(facts) + .where( + facts.fact_id == fact_id, + facts.status.in_(tuple(from_statuses)), + facts.deleted == False, # noqa: E712 + ) + .values(status=to_status, updated_at=GTime.UTC(), **data) + ) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def expire_published(self, cdb: AsyncSession, place_id, unit_id, key, ts, except_fact_id=None) -> Tuple[ErrorType, int]: + """현재 노출값을 EXPIRED 로 내려 자리를 비운다(후보 승격·직접 교체 직전에 호출). + + 지우지 않고 이력으로 남긴다 — 예전에 뭐가 나갔는지 추적할 수 있어야 한다.""" + try: + conditions = [ + facts.place_id == place_id, + facts.key == key, + facts.deleted == False, # noqa: E712 + facts.status.in_(_PUBLISHED), + _unit_cond(unit_id), + ] + if except_fact_id is not None: + conditions.append(facts.fact_id != except_fact_id) + query = update(facts).where(and_(*conditions)).values(status=FactStatus.EXPIRED.value, updated_at=ts) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def reject_candidates(self, cdb: AsyncSession, place_id, unit_id, key, ts, except_fact_id=None) -> Tuple[ErrorType, int]: + """남은 후보를 REJECTED 로 정리한다(하나를 승격시켰으니 나머지는 판정된 셈). + + 후보를 그대로 두면 사람 확인 큐에 이미 처리된 항목이 계속 남는다.""" + try: + conditions = [ + facts.place_id == place_id, + facts.key == key, + facts.deleted == False, # noqa: E712 + facts.status.in_(_CANDIDATE), + _unit_cond(unit_id), + ] + if except_fact_id is not None: + conditions.append(facts.fact_id != except_fact_id) + query = update(facts).where(and_(*conditions)).values(status=FactStatus.REJECTED.value, updated_at=ts) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 diff --git a/backend/crud/faq_crud.py b/backend/crud/faq_crud.py new file mode 100644 index 0000000..831fae0 --- /dev/null +++ b/backend/crud/faq_crud.py @@ -0,0 +1,104 @@ +from abc import ABC, abstractmethod +from typing import Tuple + +from sqlalchemy import and_, select, update +from sqlalchemy.ext.asyncio import AsyncSession + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import faqs +from common.enums import ErrorType, FactStatus +from common.logger import LOG +from common.utils.gtime import GTime + +_PUBLISHABLE = (FactStatus.VERIFIED.value, FactStatus.CORRECTED.value) +_ACTIVE = (FactStatus.UNVERIFIED.value, FactStatus.PENDING_OWNER.value) + _PUBLISHABLE + + +# FAQ CRUD. fact 와 같은 검증 상태 흐름을 탄다 — 생성된 문장도 사람이 확인해야 나간다. +class IFaqCRUD(ABC): + @abstractmethod + async def list_faqs(self, cdb: AsyncSession, place_id, publishable_only: bool) -> Tuple[ErrorType, list]: + pass + + @abstractmethod + async def add_faq(self, cdb: AsyncSession, faq: faqs) -> ErrorType: + pass + + @abstractmethod + async def expire_generated(self, cdb: AsyncSession, place_id, ts) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def transition(self, cdb: AsyncSession, faq_id, from_statuses, to_status, data: dict) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def get_faq(self, cdb: AsyncSession, place_id, faq_id) -> Tuple[ErrorType, faqs]: + pass + + +class FaqCRUD(IFaqCRUD): + async def list_faqs(self, cdb: AsyncSession, place_id, publishable_only: bool = False) -> Tuple[ErrorType, list]: + try: + conds = [faqs.place_id == place_id, faqs.deleted == False] # noqa: E712 + conds.append(faqs.status.in_(_PUBLISHABLE if publishable_only else _ACTIVE)) + query = select(faqs).where(and_(*conds)).order_by(faqs.sort_order.asc(), faqs.created_at.asc()) + err_type, rows = await DB_SESSION_MNG.execute(cdb, query) + return (err_type, list(rows) if err_type == ErrorType.SUCCESS else []) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, [] + + async def get_faq(self, cdb: AsyncSession, place_id, faq_id) -> Tuple[ErrorType, faqs]: + try: + query = select(faqs).where( + faqs.faq_id == faq_id, faqs.place_id == place_id, faqs.deleted == False # noqa: E712 + ).limit(1) + err_type, rows = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, None + if len(rows) != 1: + return ErrorType.DB_INVALID_KEY, None + return ErrorType.SUCCESS, rows[0] + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def add_faq(self, cdb: AsyncSession, faq: faqs) -> ErrorType: + try: + return await DB_SESSION_MNG.insert(cdb, faq) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def expire_generated(self, cdb: AsyncSession, place_id, ts) -> Tuple[ErrorType, int]: + """재생성 전에 **아직 확인 안 된** LLM 생성 FAQ 만 내린다. + + ★ 사람이 확인·정정한 FAQ(VERIFIED/CORRECTED)는 건드리지 않는다 — + 재생성이 사람의 판단을 덮어쓰면 fact 쪽 규칙과 어긋난다.""" + try: + query = ( + update(faqs) + .where( + faqs.place_id == place_id, + faqs.deleted == False, # noqa: E712 + faqs.status.in_((FactStatus.UNVERIFIED.value, FactStatus.PENDING_OWNER.value)), + ) + .values(status=FactStatus.EXPIRED.value, updated_at=ts) + ) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def transition(self, cdb: AsyncSession, faq_id, from_statuses, to_status: int, data: dict) -> Tuple[ErrorType, int]: + try: + query = ( + update(faqs) + .where(faqs.faq_id == faq_id, faqs.status.in_(tuple(from_statuses)), faqs.deleted == False) # noqa: E712 + .values(status=to_status, updated_at=GTime.UTC(), **data) + ) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 diff --git a/backend/crud/job_crud.py b/backend/crud/job_crud.py new file mode 100644 index 0000000..d95091e --- /dev/null +++ b/backend/crud/job_crud.py @@ -0,0 +1,274 @@ +"""작업 큐 CRUD — PostgreSQL 을 '제대로' 큐로 쓴다. (LPS `crud/job_crud.py` 이식) + + - 할당은 **단일 문장 원자 claim**: FOR UPDATE SKIP LOCKED 서브쿼리 + 같은 UPDATE + RETURNING. + → 워커 컨테이너가 몇 개든 같은 잡 이중 할당이 원천 불가. fetch 와 claim 을 분리하지 않는다. + - 모든 전이는 **조건부 CAS**(WHERE 에 status/worker_id 가드) + RETURNING. + - 복구는 timeout 추측이 아니라 **lease 만료 소유권**(reaper 가 회수). + - 재시도/백오프/dead-letter 를 큐에 내장. + +전이가 조회/변경으로 나뉘지 않으므로(RETURNING) execute_lambda_write 로 실행한다. +큐 전이만 raw SQL 이다 — 다른 crud 는 전부 SQLAlchemy 표현식을 쓴다. +""" + +import json + +from sqlalchemy import text + +from common.database.db_session_manager import DB_SESSION_MNG +from common.enums import DBType, DBWRType, JobStatus + + +# 잡 적재 시 워커를 즉시 깨우는 LISTEN/NOTIFY 채널(폴링 제거). +JOB_NOTIFY_CHANNEL = "o2o_site_job" + + +def compute_backoff(attempts: int, base: float = 5.0, cap: float = 600.0) -> float: + """지수 백오프(초). attempts 회 시도 후 다음 재시도까지 대기 = base * 2^(attempts-1), cap 상한.""" + return min(cap, base * (2 ** max(0, attempts - 1))) + + +class JobQueue: + DB = DBType.MAIN.value + + async def _tx(self, fn): + """쓰기 트랜잭션 — 값 반환이 필요한 큐 전이 전용 진입점.""" + return await DB_SESSION_MNG.execute_lambda_write(self.DB, fn) + + # ---- 적재 ---- + async def enqueue( + self, + job_type: int, + payload: dict, + priority: int = 100, + dedupe_key: str | None = None, + max_attempts: int = 3, + ) -> str | None: + """잡 적재. dedupe_key 가 활성(PENDING/RUNNING) 중복이면 삽입 없이 None 반환.""" + sql = text(""" + INSERT INTO job.jobs (job_type, priority, payload, dedupe_key, max_attempts) + VALUES (:t, :p, CAST(:payload AS jsonb), :dk, :ma) + ON CONFLICT (dedupe_key) WHERE status IN (1, 2) AND dedupe_key IS NOT NULL + DO NOTHING + RETURNING job_id + """) + + async def run(s): + row = (await s.execute(sql, { + "t": job_type, "p": priority, "payload": json.dumps(payload, ensure_ascii=False), + "dk": dedupe_key, "ma": max_attempts, + })).first() + if row: + # 커밋 시 전달됨 → LISTEN 중인 유휴 워커를 즉시 깨운다(중복 스킵 시엔 알림 안 함). + await s.execute(text("SELECT pg_notify(:ch, '')"), {"ch": JOB_NOTIFY_CHANNEL}) + return str(row[0]) if row else None + + return await self._tx(run) + + # ---- 원자적 claim ---- + async def claim(self, worker_id: str, lease_sec: int = 120) -> dict | None: + """대기 잡 1건을 원자적으로 점유. 없으면 None. + FOR UPDATE SKIP LOCKED 로 잠근 행을 같은 UPDATE 에서 RUNNING 으로 전이 → 이중 할당 불가.""" + sql = text(""" + UPDATE job.jobs SET + status = 2, + worker_id = :wid, + lease_until = now() + make_interval(secs => :lease), + run_started_at = now(), + attempts = attempts + 1, + updated_at = now() + WHERE job_id = ( + SELECT job_id FROM job.jobs + WHERE status = 1 AND run_after <= now() + ORDER BY priority ASC, created_at ASC + FOR UPDATE SKIP LOCKED + LIMIT 1 + ) + RETURNING job_id, job_type, payload, attempts, max_attempts + """) + + async def run(s): + row = (await s.execute(sql, {"wid": worker_id, "lease": lease_sec})).mappings().first() + if not row: + return None + d = dict(row) + d["job_id"] = str(d["job_id"]) + if isinstance(d.get("payload"), str): + d["payload"] = json.loads(d["payload"]) + return d + + return await self._tx(run) + + # ---- 완료/실패 (소유권 가드) ---- + async def complete(self, job_id: str, worker_id: str, result: dict | None = None) -> bool: + sql = text(""" + UPDATE job.jobs SET status = 3, result = CAST(:result AS jsonb), + lease_until = NULL, worker_id = NULL, updated_at = now() + WHERE job_id = CAST(:id AS uuid) AND status = 2 AND worker_id = :wid + RETURNING job_id + """) + + async def run(s): + row = (await s.execute(sql, { + "id": job_id, "wid": worker_id, + "result": json.dumps(result, ensure_ascii=False) if result is not None else None, + })).first() + return row is not None + + return await self._tx(run) + + async def fail(self, job_id: str, worker_id: str, error: str, backoff_sec: float = 5.0) -> int | None: + """실패 처리. 시도 남으면 PENDING(run_after=백오프)으로 재큐, 소진되면 DEAD(dead-letter). + 전이 후 status(JobStatus 값)를 반환. 소유 불일치면 None.""" + sql = text(""" + UPDATE job.jobs SET + status = CASE WHEN attempts >= max_attempts THEN 4 ELSE 1 END, + run_after = CASE WHEN attempts >= max_attempts THEN run_after + ELSE now() + make_interval(secs => :backoff) END, + last_error = :err, + lease_until = NULL, + worker_id = NULL, + updated_at = now() + WHERE job_id = CAST(:id AS uuid) AND status = 2 AND worker_id = :wid + RETURNING status + """) + + async def run(s): + row = (await s.execute(sql, { + "id": job_id, "wid": worker_id, "err": error[:2000], "backoff": backoff_sec, + })).first() + return int(row[0]) if row else None + + return await self._tx(run) + + # ---- lease 갱신(heartbeat) / 회수(reaper) ---- + async def renew_lease(self, job_id: str, worker_id: str, lease_sec: int = 120) -> bool: + sql = text(""" + UPDATE job.jobs SET lease_until = now() + make_interval(secs => :lease), updated_at = now() + WHERE job_id = CAST(:id AS uuid) AND worker_id = :wid AND status = 2 + RETURNING job_id + """) + + async def run(s): + row = (await s.execute(sql, {"id": job_id, "wid": worker_id, "lease": lease_sec})).first() + return row is not None + + return await self._tx(run) + + async def reap(self) -> list[str]: + """만료된 lease(워커 사망 등)의 RUNNING 잡을 회수. 시도 남으면 즉시 재큐, 소진되면 DEAD. + 회수된 job_id 목록 반환.""" + sql = text(""" + UPDATE job.jobs SET + status = CASE WHEN attempts >= max_attempts THEN 4 ELSE 1 END, + run_after = now(), + last_error = COALESCE(last_error, '') || ' [lease-expired reclaim]', + lease_until = NULL, + worker_id = NULL, + updated_at = now() + WHERE status = 2 AND lease_until IS NOT NULL AND lease_until < now() + RETURNING job_id + """) + + async def run(s): + rows = (await s.execute(sql)).all() + return [str(r[0]) for r in rows] + + return await self._tx(run) + + # ---- 단건 조회 (상태 폴링) ---- + async def get(self, job_id: str) -> dict | None: + """잡 단건 조회(읽기). 없으면 None. status 는 정수(JobStatus 값).""" + sql = text(""" + SELECT job_id, job_type, status, priority, attempts, max_attempts, + payload, result, last_error, run_after, run_started_at, created_at, updated_at + FROM job.jobs WHERE job_id = CAST(:id AS uuid) + """) + + async def run(s): + row = (await s.execute(sql, {"id": job_id})).mappings().first() + if not row: + return None + d = dict(row) + d["job_id"] = str(d["job_id"]) + for key in ("payload", "result"): + if isinstance(d.get(key), str): + d[key] = json.loads(d[key]) + return d + + return await DB_SESSION_MNG.execute_lambda(self.DB, DBWRType.DB_READ.value, run) + + async def find_active(self, dedupe_key: str) -> dict | None: + """dedupe_key 로 활성(PENDING/RUNNING) 잡을 찾는다. + enqueue 가 중복으로 None 을 돌려줬을 때, 이미 돌고 있는 잡의 id 를 알려주기 위함.""" + sql = text(""" + SELECT job_id, job_type, status FROM job.jobs + WHERE dedupe_key = :dk AND status IN (1, 2) + LIMIT 1 + """) + + async def run(s): + row = (await s.execute(sql, {"dk": dedupe_key})).mappings().first() + if not row: + return None + d = dict(row) + d["job_id"] = str(d["job_id"]) + return d + + return await DB_SESSION_MNG.execute_lambda(self.DB, DBWRType.DB_READ.value, run) + + # ---- 관측(관리 API/알림용) ---- + async def counts(self) -> dict[str, int]: + """상태별 잡 개수.""" + async def run(s): + rows = (await s.execute(text("SELECT status, count(*) FROM job.jobs GROUP BY status"))).all() + by_val = {int(st): int(c) for st, c in rows} + return {js.name: by_val.get(js.value, 0) for js in JobStatus} + + return await DB_SESSION_MNG.execute_lambda(self.DB, DBWRType.DB_READ.value, run) + + async def ops(self) -> dict: + """운영 스냅샷(모니터링·알림용): 상태별 카운트 + 큐 지연(가장 오래된 PENDING 나이) + + 최근 1시간 DEAD + stuck(좀비 신호). + + stuck 은 두 축 — lease 만료(워커 사망인데 reaper 미회수) OR 실행 10분 초과(핸들러 행 — + heartbeat 가 lease 를 계속 갱신해 lease 축엔 안 잡히므로 run_started_at 으로 따로 본다).""" + sql = text(""" + SELECT + count(*) FILTER (WHERE status = 1) AS pending, + count(*) FILTER (WHERE status = 2) AS running, + count(*) FILTER (WHERE status = 3) AS done, + count(*) FILTER (WHERE status = 4) AS dead, + count(*) FILTER (WHERE status = 4 AND updated_at > now() - interval '1 hour') AS dead_1h, + count(*) FILTER (WHERE status = 2 AND ( + (lease_until IS NOT NULL AND lease_until < now()) + OR run_started_at < now() - interval '10 minutes' + )) AS stuck_running, + COALESCE(EXTRACT(EPOCH FROM (now() - min(created_at) FILTER (WHERE status = 1)))::int, 0) AS oldest_pending_sec, + count(*) FILTER (WHERE last_error LIKE 'JobDeadlineExceeded%' + AND updated_at > now() - interval '1 hour') AS deadline_1h + FROM job.jobs + """) + + async def run(s): + return {k: int(v) for k, v in dict((await s.execute(sql)).mappings().first()).items()} + + return await DB_SESSION_MNG.execute_lambda(self.DB, DBWRType.DB_READ.value, run) + + async def requeue(self, job_id: str) -> str | None: + """DEAD 잡 재큐(관리자 액션): attempts 리셋 + PENDING 전이 + 워커 깨움. + DEAD 가 아니거나 없으면 None. 같은 dedupe_key 의 활성 잡이 있으면 부분 유니크 위반.""" + sql = text(""" + UPDATE job.jobs SET status = 1, attempts = 0, run_after = now(), + lease_until = NULL, worker_id = NULL, run_started_at = NULL, + last_error = NULL, updated_at = now() + WHERE job_id = CAST(:jid AS uuid) AND status = 4 + RETURNING job_id + """) + + async def run(s): + row = (await s.execute(sql, {"jid": job_id})).first() + if row: + await s.execute(text("SELECT pg_notify(:ch, '')"), {"ch": JOB_NOTIFY_CHANNEL}) + return str(row[0]) if row else None + + return await self._tx(run) diff --git a/backend/crud/local_content_crud.py b/backend/crud/local_content_crud.py new file mode 100644 index 0000000..5d88970 --- /dev/null +++ b/backend/crud/local_content_crud.py @@ -0,0 +1,81 @@ +from sqlalchemy import and_, select, update +from sqlalchemy.dialects.postgresql import insert as pg_insert + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import local_contents +from common.enums import ErrorType, LocalContentType +from common.utils.gtime import GTime + + +class LocalContentCRUD: + async def list(self, db, status: int | None = None, region_code: str | None = None): + conds = [local_contents.deleted == False, local_contents.content_type == LocalContentType.FESTIVAL.value] # noqa: E712 + if status is not None: + conds.append(local_contents.status == status) + if region_code: + conds.append(local_contents.region_code == region_code) + return await DB_SESSION_MNG.execute( + db, select(local_contents).where(and_(*conds)).order_by(local_contents.collected_at.desc()) + ) + + async def insert(self, db, row): + return await DB_SESSION_MNG.insert(db, row) + + async def get_by_external_id(self, db, region_code: str, external_id: str): + err, rows = await DB_SESSION_MNG.execute( + db, + select(local_contents).where( + local_contents.region_code == region_code, + local_contents.content_type == LocalContentType.FESTIVAL.value, + local_contents.external_id == external_id, + local_contents.deleted == False, # noqa: E712 + ).limit(1), + ) + return err, rows[0] if rows else None + + async def publish(self, db, ids: list, user_id): + return await DB_SESSION_MNG.add_with_rowcount( + db, + update(local_contents).where( + local_contents.local_content_id.in_(ids), local_contents.deleted == False # noqa: E712 + ).values(status=2, published_at=GTime.UTC(), published_by=user_id, updated_at=GTime.UTC()), + ) + + async def update(self, db, content_id, data: dict): + return await DB_SESSION_MNG.add_with_rowcount( + db, + update(local_contents).where( + local_contents.local_content_id == content_id, local_contents.deleted == False # noqa: E712 + ).values(**data, updated_at=GTime.UTC()), + ) + + async def end(self, db, content_id): + return await self.update(db, content_id, {"status": 3}) + + async def get_weather(self, db, region_code: str): + err, rows = await DB_SESSION_MNG.execute( + db, + select(local_contents).where( + local_contents.region_code == region_code, + local_contents.content_type == LocalContentType.WEATHER.value, + local_contents.external_id.is_(None), + local_contents.deleted == False, # noqa: E712 + ).limit(1), + ) + return err, rows[0] if rows else None + + async def upsert_weather(self, db, values: dict): + stmt = pg_insert(local_contents).values(**values) + stmt = stmt.on_conflict_do_update( + index_elements=[local_contents.region_code, local_contents.content_type], + index_where=and_(local_contents.deleted == False, local_contents.external_id.is_(None)), # noqa: E712 + set_={ + "source": stmt.excluded.source, + "body": stmt.excluded.body, + "status": stmt.excluded.status, + "collected_at": stmt.excluded.collected_at, + "expires_at": stmt.excluded.expires_at, + "updated_at": stmt.excluded.updated_at, + }, + ) + return await DB_SESSION_MNG.add(db, stmt) diff --git a/backend/crud/media_crud.py b/backend/crud/media_crud.py new file mode 100644 index 0000000..63b796e --- /dev/null +++ b/backend/crud/media_crud.py @@ -0,0 +1,95 @@ +from abc import ABC, abstractmethod +from typing import Tuple + +from sqlalchemy import and_, func, or_, select, update +from sqlalchemy.ext.asyncio import AsyncSession + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import media +from common.enums import ErrorType, MediaStatus +from common.logger import LOG +from common.utils.gtime import GTime + + +# 사진 CRUD. 항상 place_id 로 스코프한다. +class IMediaCRUD(ABC): + @abstractmethod + async def list_media( + self, cdb: AsyncSession, place_id, status=None, unlabeled_only=False, unit_id=None, alt_required=False + ) -> Tuple[ErrorType, list]: + pass + + @abstractmethod + async def apply_vision(self, cdb: AsyncSession, media_id, label, alt_text, confidence, status, ts) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def set_status(self, cdb: AsyncSession, place_id, media_id, status: int, ts) -> Tuple[ErrorType, int]: + pass + + +class MediaCRUD(IMediaCRUD): + async def list_media( + self, cdb: AsyncSession, place_id, status=None, unlabeled_only: bool = False, unit_id=None, alt_required: bool = False + ) -> Tuple[ErrorType, list]: + """사진 목록. unlabeled_only=True 면 아직 Vision 분석이 안 된 것만(재분석 비용 절약). + + ★ "분석 안 됨"의 기준은 **alt_text 가 비었는가**다. label 이 아니다. + 수집 어댑터가 페이지에서 주운 캡션을 label 에 넣어 두기 때문에(base.CollectedMedia + 주석: "Vision 이 확정하기 전의 후보 라벨"), label 로 판정하면 캡션이 있는 사진은 + 전부 '이미 분석됨'으로 건너뛴다 — 실제로 네이버에서 긁은 사진 10장이 통째로 + 그렇게 빠져 Vision 이 "분석할 사진이 없다"로 끝났고, alt 가 없어 발행도 못 했다. + alt 는 Vision 만 채우고 발행 조건이기도 하므로 기준으로 삼기에 정확하다. + + unit_id 는 객실·메뉴 단위 사진만 추린다(빌더가 객실 카드에 붙일 사진을 고를 때). + ★ alt_required=True 는 status 필터와 짝으로만 쓴다 — alt 가 빈 사진은 빌더가 렌더하지 + 않으므로(services/snapshot.py), '발행되면 실릴 것'을 물었을 때 승인만 보면 답이 틀린다.""" + try: + conditions = [media.place_id == place_id, media.deleted == False] # noqa: E712 + if status is not None: + conditions.append(media.status == status) + if unlabeled_only: + conditions.append( + or_(media.alt_text.is_(None), func.btrim(media.alt_text) == "") + ) + if unit_id is not None: + conditions.append(media.unit_id == unit_id) + if alt_required: + # 공백만 있는 alt 도 빌더에선 '없음'이다 — 같은 기준으로 거른다. + conditions.append(media.alt_text.is_not(None)) + conditions.append(func.btrim(media.alt_text) != "") + query = select(media).where(and_(*conditions)).order_by(media.sort_order.asc(), media.created_at.asc()) + err_type, rows = await DB_SESSION_MNG.execute(cdb, query) + return (err_type, list(rows) if err_type == ErrorType.SUCCESS else []) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, [] + + async def apply_vision(self, cdb: AsyncSession, media_id, label, alt_text, confidence, status: int, ts) -> Tuple[ErrorType, int]: + """Vision 분석 결과를 반영한다. + + ★ 신뢰도가 낮으면 status 를 PENDING_REVIEW 로 남긴다 — 자동 반영하지 않는다. + 라벨·alt 는 저장하되(사람이 보고 고칠 재료), 승인 상태로 올리지 않는 게 핵심이다.""" + try: + query = ( + update(media) + .where(media.media_id == media_id, media.deleted == False) # noqa: E712 + .values(label=label, alt_text=alt_text, vision_confidence=confidence, status=status, updated_at=ts) + ) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def set_status(self, cdb: AsyncSession, place_id, media_id, status: int, ts) -> Tuple[ErrorType, int]: + """사람이 사진을 승인/반려한다.""" + try: + query = ( + update(media) + .where(media.media_id == media_id, media.place_id == place_id, media.deleted == False) # noqa: E712 + .values(status=status, updated_at=ts) + ) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 diff --git a/backend/crud/place_crud.py b/backend/crud/place_crud.py new file mode 100644 index 0000000..8e75980 --- /dev/null +++ b/backend/crud/place_crud.py @@ -0,0 +1,278 @@ +from abc import ABC, abstractmethod +from typing import Optional, Tuple + +from sqlalchemy import and_, delete, func, or_, select, update +from sqlalchemy.ext.asyncio import AsyncSession + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import place_links, places, units +from common.enums import ErrorType +from common.logger import LOG +from common.utils.gtime import GTime + + +# 사업장 CRUD. 모든 조회는 company_id(테넌트)로 스코프한다 — 남의 회사 사업장이 보이면 안 된다. +class IPlaceCRUD(ABC): + @abstractmethod + async def add_place(self, cdb: AsyncSession, place: places) -> ErrorType: + pass + + @abstractmethod + async def get_place(self, cdb: AsyncSession, company_id, place_id) -> Tuple[ErrorType, places]: + pass + + @abstractmethod + async def list_places(self, cdb: AsyncSession, company_id, search, category, status, skip, limit) -> Tuple[ErrorType, list, int]: + pass + + @abstractmethod + async def update_place(self, cdb: AsyncSession, company_id, place_id, data: dict) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def delete_place(self, cdb: AsyncSession, company_id, place_id) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def list_units(self, cdb: AsyncSession, place_id) -> Tuple[ErrorType, list]: + pass + + @abstractmethod + async def get_unit(self, cdb: AsyncSession, place_id, unit_id) -> Tuple[ErrorType, units]: + pass + + @abstractmethod + async def add_unit(self, cdb: AsyncSession, unit: units) -> ErrorType: + pass + + @abstractmethod + async def list_links(self, cdb: AsyncSession, place_id, confirmed_only: bool) -> Tuple[ErrorType, list]: + pass + + @abstractmethod + async def add_link(self, cdb: AsyncSession, link: place_links) -> ErrorType: + pass + + @abstractmethod + async def confirm_link(self, cdb: AsyncSession, place_id, link_id, user_id, ts) -> Tuple[ErrorType, int]: + pass + + async def confirm_link_by_url(self, cdb: AsyncSession, place_id, url, user_id, ts) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def set_link_raw(self, cdb: AsyncSession, place_id, url, raw) -> Tuple[ErrorType, int]: + pass + + +class PlaceCRUD(IPlaceCRUD): + async def add_place(self, cdb: AsyncSession, place: places) -> ErrorType: + try: + return await DB_SESSION_MNG.insert(cdb, place) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def get_place(self, cdb: AsyncSession, company_id, place_id) -> Tuple[ErrorType, places]: + try: + query = ( + select(places) + .where(places.place_id == place_id, places.company_id == company_id, places.deleted == False) # noqa: E712 + .limit(1) + ) + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, None + if len(row_list) != 1: + return ErrorType.DB_INVALID_KEY, None + return ErrorType.SUCCESS, row_list[0] + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def list_places( + self, cdb: AsyncSession, company_id, search: Optional[str], category: Optional[int], + status: Optional[int], skip: int, limit: int, + ) -> Tuple[ErrorType, list, int]: + try: + conditions = [places.deleted == False, places.company_id == company_id] # noqa: E712 + if category is not None: + conditions.append(places.category == category) + if status is not None: + conditions.append(places.status == status) + if search: + conditions.append( + or_( + places.name.ilike(f"%{search}%"), + places.road_address.ilike(f"%{search}%"), + places.address.ilike(f"%{search}%"), + ) + ) + where = and_(*conditions) + + cnt_err, cnt_rows = await DB_SESSION_MNG.execute(cdb, select(func.count()).select_from(places).where(where)) + if cnt_err != ErrorType.SUCCESS: + return cnt_err, [], 0 + total = int(cnt_rows[0] or 0) if cnt_rows else 0 + + list_err, rows = await DB_SESSION_MNG.execute( + cdb, + select(places).where(where).order_by(places.created_at.desc()).offset(skip).limit(limit), + ) + if list_err != ErrorType.SUCCESS: + return list_err, [], 0 + return ErrorType.SUCCESS, list(rows), total + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, [], 0 + + async def update_place(self, cdb: AsyncSession, company_id, place_id, data: dict) -> Tuple[ErrorType, int]: + """회사 스코프를 WHERE 에 걸어 남의 회사 사업장을 못 건드리게 한다. (ErrorType, 적용행수).""" + try: + if not data: + return ErrorType.SUCCESS, 0 + query = ( + update(places) + .where(places.place_id == place_id, places.company_id == company_id, places.deleted == False) # noqa: E712 + .values(**data, updated_at=GTime.UTC()) + ) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def delete_place(self, cdb: AsyncSession, company_id, place_id) -> Tuple[ErrorType, int]: + """사업장을 실제 삭제한다. 회사 스코프 밖의 행은 건드리지 않는다.""" + try: + query = ( + delete(places) + .where(places.place_id == place_id, places.company_id == company_id, places.deleted == False) # noqa: E712 + ) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def list_units(self, cdb: AsyncSession, place_id) -> Tuple[ErrorType, list]: + try: + query = ( + select(units) + .where(units.place_id == place_id, units.deleted == False) # noqa: E712 + .order_by(units.sort_order.asc(), units.created_at.asc()) + ) + err_type, rows = await DB_SESSION_MNG.execute(cdb, query) + return (err_type, list(rows) if err_type == ErrorType.SUCCESS else []) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, [] + + async def get_unit(self, cdb: AsyncSession, place_id, unit_id) -> Tuple[ErrorType, units]: + try: + query = ( + select(units) + .where(units.unit_id == unit_id, units.place_id == place_id, units.deleted == False) # noqa: E712 + .limit(1) + ) + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, None + if len(row_list) != 1: + return ErrorType.DB_INVALID_KEY, None + return ErrorType.SUCCESS, row_list[0] + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def add_unit(self, cdb: AsyncSession, unit: units) -> ErrorType: + try: + return await DB_SESSION_MNG.insert(cdb, unit) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def list_links(self, cdb: AsyncSession, place_id, confirmed_only: bool = False) -> Tuple[ErrorType, list]: + """채널 URL 목록. confirmed_only=True 면 ★ 크롤링 대상(확정된 URL)만.""" + try: + conditions = [place_links.place_id == place_id, place_links.deleted == False] # noqa: E712 + if confirmed_only: + conditions.append(place_links.confirmed_at.is_not(None)) + query = select(place_links).where(and_(*conditions)).order_by(place_links.discovered_at.asc()) + err_type, rows = await DB_SESSION_MNG.execute(cdb, query) + return (err_type, list(rows) if err_type == ErrorType.SUCCESS else []) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, [] + + async def add_link(self, cdb: AsyncSession, link: place_links) -> ErrorType: + try: + return await DB_SESSION_MNG.insert(cdb, link) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def confirm_link_by_url(self, cdb: AsyncSession, place_id, url, user_id, ts) -> Tuple[ErrorType, int]: + """URL 로 확정한다 — 방금 넣은 링크의 link_id 를 다시 조회하지 않기 위해서다. + + (place_id, url) 은 유니크라 대상이 한 건으로 정해진다. 이미 확정된 건 rowcount 0. + ★ 쓰는 곳은 상호 일치로 찾은 네이버 플레이스 링크 하나뿐이다 — 근거 없이 확정하는 + 경로를 늘리지 않으려고 일부러 좁게 열어 둔다(collect_service.discover_naver_place).""" + try: + query = ( + update(place_links) + .where( + place_links.place_id == place_id, + place_links.url == url, + place_links.confirmed_at.is_(None), + place_links.deleted == False, # noqa: E712 + ) + .values(confirmed_at=ts, confirmed_by=user_id, updated_at=ts) + ) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def set_link_raw(self, cdb: AsyncSession, place_id, url, raw) -> Tuple[ErrorType, int]: + """수집한 원문을 링크에 박제한다. + + ★ 왜 fact 가 아니라 여기인가 (2026-08-31) + TourAPI 의 `overview` 같은 소개 원문은 **사실 목록이 아니라 글**이다. + 이걸 `intro` fact 로 넣었더니 457자 원문이 그대로 VERIFIED 가 되어 + 사장님 사이트의 '숙소 소개' 자리를 차지했다 — LLM 이 쓴 소개문은 뒤에서 대기 중인데. + `intro` 는 allow_llm=True, 즉 **LLM 의 출력 칸**이라 수집물이 들어가면 안 된다. + + 그렇다고 버리면 소개문·FAQ 의 근거가 사라진다(부대시설·주변 거리 같은 정보가 + 여기에만 있다). 그래서 **발행되지 않는 자리**에 원문을 남기고, + 생성 시점에만 근거로 넘긴다(services/copy_service.py).""" + try: + query = ( + update(place_links) + .where( + place_links.place_id == place_id, + place_links.url == url, + place_links.deleted == False, # noqa: E712 + ) + .values(raw=raw, updated_at=GTime.UTC()) + ) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def confirm_link(self, cdb: AsyncSession, place_id, link_id, user_id, ts) -> Tuple[ErrorType, int]: + """미확정 링크만 확정한다(이미 확정된 건 rowcount 0 — 동시 처리 가드).""" + try: + query = ( + update(place_links) + .where( + place_links.link_id == link_id, + place_links.place_id == place_id, + place_links.confirmed_at.is_(None), + place_links.deleted == False, # noqa: E712 + ) + .values(confirmed_at=ts, confirmed_by=user_id, updated_at=ts) + ) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 diff --git a/backend/crud/site_crud.py b/backend/crud/site_crud.py new file mode 100644 index 0000000..926712c --- /dev/null +++ b/backend/crud/site_crud.py @@ -0,0 +1,198 @@ +from abc import ABC, abstractmethod +from typing import Tuple + +from sqlalchemy import and_, func, select, update +from sqlalchemy.ext.asyncio import AsyncSession + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import publish_logs, site_versions, sites +from common.enums import BuildStatus, ErrorType +from common.logger import LOG +from common.utils.gtime import GTime + + +# 사이트/버전/발행로그 CRUD. 항상 place_id 또는 site_id 로 스코프한다. +class ISiteCRUD(ABC): + @abstractmethod + async def get_site_by_place(self, cdb: AsyncSession, place_id) -> Tuple[ErrorType, sites]: + pass + + @abstractmethod + async def get_site_by_domain(self, cdb: AsyncSession, domain: str) -> Tuple[ErrorType, sites]: + pass + + @abstractmethod + async def taken_domains(self, cdb: AsyncSession, domains: list) -> Tuple[ErrorType, set]: + pass + + @abstractmethod + async def add_site(self, cdb: AsyncSession, site: sites) -> ErrorType: + pass + + @abstractmethod + async def next_version_no(self, cdb: AsyncSession, site_id) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def add_version(self, cdb: AsyncSession, version: site_versions) -> ErrorType: + pass + + @abstractmethod + async def get_version(self, cdb: AsyncSession, site_id, site_version_id) -> Tuple[ErrorType, site_versions]: + pass + + @abstractmethod + async def finish_version(self, cdb: AsyncSession, site_version_id, data: dict) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def update_site(self, cdb: AsyncSession, site_id, data: dict) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def add_log(self, cdb: AsyncSession, log: publish_logs) -> ErrorType: + pass + + @abstractmethod + async def list_logs(self, cdb: AsyncSession, site_id, limit: int) -> Tuple[ErrorType, list]: + pass + + +class SiteCRUD(ISiteCRUD): + async def get_site_by_place(self, cdb: AsyncSession, place_id) -> Tuple[ErrorType, sites]: + try: + query = select(sites).where(sites.place_id == place_id, sites.deleted == False).limit(1) # noqa: E712 + err_type, rows = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, None + return ErrorType.SUCCESS, (rows[0] if rows else None) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def get_site_by_domain(self, cdb: AsyncSession, domain: str) -> Tuple[ErrorType, sites]: + """주소(도메인 라벨)의 주인을 찾는다. 없으면 (SUCCESS, None). + + uq_sites_domain(deleted=false AND domain IS NOT NULL)과 같은 조건으로 본다 — + 인덱스가 막는 것과 조회가 막는 것이 다르면 "확인은 통과, 저장은 실패"가 난다.""" + try: + query = select(sites).where(sites.domain == domain, sites.deleted == False).limit(1) # noqa: E712 + err_type, rows = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, None + return ErrorType.SUCCESS, (rows[0] if rows else None) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def taken_domains(self, cdb: AsyncSession, domains: list) -> Tuple[ErrorType, set]: + """후보 주소들 중 이미 쓰이는 것만 추린다. 대안 제안이 후보마다 왕복하지 않게 한 번에 본다.""" + try: + if not domains: + return ErrorType.SUCCESS, set() + query = select(sites.domain).where( + sites.domain.in_(domains), sites.deleted == False # noqa: E712 + ) + err_type, rows = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, set() + return ErrorType.SUCCESS, {r for r in rows if r} + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, set() + + async def add_site(self, cdb: AsyncSession, site: sites) -> ErrorType: + try: + return await DB_SESSION_MNG.insert(cdb, site) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def next_version_no(self, cdb: AsyncSession, site_id) -> Tuple[ErrorType, int]: + """다음 버전 번호. 1부터 시작한다.""" + try: + query = select(func.max(site_versions.version)).where( + site_versions.site_id == site_id, site_versions.deleted == False # noqa: E712 + ) + err_type, rows = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, 0 + current = rows[0] if rows else None + return ErrorType.SUCCESS, int(current or 0) + 1 + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def add_version(self, cdb: AsyncSession, version: site_versions) -> ErrorType: + try: + return await DB_SESSION_MNG.insert(cdb, version) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def get_version(self, cdb: AsyncSession, site_id, site_version_id) -> Tuple[ErrorType, site_versions]: + try: + query = ( + select(site_versions) + .where( + site_versions.site_version_id == site_version_id, + site_versions.site_id == site_id, + site_versions.deleted == False, # noqa: E712 + ) + .limit(1) + ) + err_type, rows = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, None + if len(rows) != 1: + return ErrorType.DB_INVALID_KEY, None + return ErrorType.SUCCESS, rows[0] + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def finish_version(self, cdb: AsyncSession, site_version_id, data: dict) -> Tuple[ErrorType, int]: + """빌드 결과를 버전에 기록한다(BUILT 또는 FAILED).""" + try: + query = ( + update(site_versions) + .where(site_versions.site_version_id == site_version_id, site_versions.deleted == False) # noqa: E712 + .values(**data, updated_at=GTime.UTC()) + ) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def update_site(self, cdb: AsyncSession, site_id, data: dict) -> Tuple[ErrorType, int]: + try: + query = ( + update(sites) + .where(sites.site_id == site_id, sites.deleted == False) # noqa: E712 + .values(**data, updated_at=GTime.UTC()) + ) + return await DB_SESSION_MNG.add_with_rowcount(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def add_log(self, cdb: AsyncSession, log: publish_logs) -> ErrorType: + try: + return await DB_SESSION_MNG.insert(cdb, log) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def list_logs(self, cdb: AsyncSession, site_id, limit: int = 50) -> Tuple[ErrorType, list]: + try: + query = ( + select(publish_logs) + .where(publish_logs.site_id == site_id, publish_logs.deleted == False) # noqa: E712 + .order_by(publish_logs.created_at.desc()) + .limit(limit) + ) + err_type, rows = await DB_SESSION_MNG.execute(cdb, query) + return (err_type, list(rows) if err_type == ErrorType.SUCCESS else []) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, [] diff --git a/backend/crud/user_crud.py b/backend/crud/user_crud.py new file mode 100644 index 0000000..fb9e08e --- /dev/null +++ b/backend/crud/user_crud.py @@ -0,0 +1,177 @@ +from abc import ABC, abstractmethod +from typing import Optional, Tuple + +from sqlalchemy import select, func, and_, or_, update +from sqlalchemy.ext.asyncio import AsyncSession + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import users, companies +from common.enums import ErrorType, UserRole +from common.logger import LOG +from common.utils.gtime import GTime + + +# CRUD 는 인터페이스(I*) 와 구현(*) 으로 분리한다. +# - service 는 인터페이스 타입에 의존하고 Depends 로 구현을 주입받는다 (테스트/교체 용이). +# - 모든 메서드는 (session, ...) 을 받는다. session 은 람다 호출 시 매니저가 넘겨준다. +class IUserCRUD(ABC): + @abstractmethod + async def get_user_by_login_id(self, cdb: AsyncSession, login_id: str) -> Tuple[ErrorType, users]: + pass + + @abstractmethod + async def is_user(self, cdb: AsyncSession, login_id: str) -> ErrorType: + pass + + @abstractmethod + async def add_user(self, cdb: AsyncSession, user: users) -> ErrorType: + pass + + @abstractmethod + async def update_last_accessed(self, cdb: AsyncSession, user_id) -> ErrorType: + pass + + @abstractmethod + async def get_company(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, companies]: + pass + + @abstractmethod + async def update_company_settings(self, cdb: AsyncSession, company_id, settings: dict) -> ErrorType: + pass + + @abstractmethod + async def list_by_company(self, cdb: AsyncSession, company_id, search, skip, limit, hide_dev: bool = False) -> Tuple[ErrorType, list, int]: + pass + + @abstractmethod + async def get_by_user_id(self, cdb: AsyncSession, user_id) -> Tuple[ErrorType, users]: + pass + + @abstractmethod + async def update_user(self, cdb: AsyncSession, user_id, data: dict) -> ErrorType: + pass + + +class UserCRUD(IUserCRUD): + async def get_user_by_login_id(self, cdb: AsyncSession, login_id: str) -> Tuple[ErrorType, users]: + try: + query = select(users).where(users.id == login_id, users.deleted == False).limit(1) # noqa: E712 + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_user_by_login_id(ID:{login_id}) failed.") + if err_type != ErrorType.SUCCESS: + return err_type, None + if len(row_list) != 1: + return ErrorType.DB_INVALID_KEY, None + return ErrorType.SUCCESS, row_list[0] + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def is_user(self, cdb: AsyncSession, login_id: str) -> ErrorType: + try: + query = select(users).where(users.id == login_id, users.deleted == False).limit(1) # noqa: E712 + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type + if row_list: + return ErrorType.DB_ALREADY_SAME_KEY + return ErrorType.SUCCESS + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def add_user(self, cdb: AsyncSession, user: users) -> ErrorType: + try: + return await DB_SESSION_MNG.insert(cdb, user) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def update_last_accessed(self, cdb: AsyncSession, user_id) -> ErrorType: + try: + query = update(users).where(users.user_id == user_id).values(last_accessed_at=GTime.UTC()) + return await DB_SESSION_MNG.add(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def get_company(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, companies]: + try: + query = select(companies).where(companies.company_id == company_id, companies.deleted == False).limit(1) # noqa: E712 + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, None + if len(row_list) != 1: + return ErrorType.DB_INVALID_KEY, None + return ErrorType.SUCCESS, row_list[0] + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def update_company_settings(self, cdb: AsyncSession, company_id, settings: dict) -> ErrorType: + try: + query = ( + update(companies) + .where(companies.company_id == company_id, companies.deleted == False) # noqa: E712 + .values(settings=settings, updated_at=GTime.UTC()) + ) + return await DB_SESSION_MNG.add(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def list_by_company( + self, cdb: AsyncSession, company_id, search: Optional[str], skip: int, limit: int, hide_dev: bool = False + ) -> Tuple[ErrorType, list, int]: + try: + conditions = [users.deleted == False, users.company_id == company_id] # noqa: E712 + # 개발자(내부 운영) 계정은 고객사에 존재 자체가 보이면 안 된다 — 목록에서 빼고 총계에도 넣지 않는다. + if hide_dev: + conditions.append(users.role != UserRole.DEVELOPER.value) + if search: + conditions.append( + or_( + users.id.ilike(f"%{search}%"), + users.name.ilike(f"%{search}%"), + users.email.ilike(f"%{search}%"), + ) + ) + where = and_(*conditions) + + cnt_err, cnt_rows = await DB_SESSION_MNG.execute(cdb, select(func.count()).select_from(users).where(where)) + if cnt_err != ErrorType.SUCCESS: + return cnt_err, [], 0 + total = int(cnt_rows[0] or 0) if cnt_rows else 0 + + list_err, rows = await DB_SESSION_MNG.execute( + cdb, + select(users).where(where).order_by(users.created_at.desc()).offset(skip).limit(limit), + ) + if list_err != ErrorType.SUCCESS: + return list_err, [], 0 + return ErrorType.SUCCESS, list(rows), total + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, [], 0 + + async def get_by_user_id(self, cdb: AsyncSession, user_id) -> Tuple[ErrorType, users]: + try: + query = select(users).where(users.user_id == user_id, users.deleted == False).limit(1) # noqa: E712 + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, None + if len(row_list) != 1: + return ErrorType.DB_INVALID_KEY, None + return ErrorType.SUCCESS, row_list[0] + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def update_user(self, cdb: AsyncSession, user_id, data: dict) -> ErrorType: + try: + if not data: + return ErrorType.SUCCESS + query = update(users).where(users.user_id == user_id).values(**data) + return await DB_SESSION_MNG.add(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED diff --git a/backend/demo_site.html b/backend/demo_site.html new file mode 100644 index 0000000..b238cba --- /dev/null +++ b/backend/demo_site.html @@ -0,0 +1,247 @@ + + + + + + 핑크비치펜션 - 숙박 + + + + + +
+ +
+

핑크비치펜션

+

숙박

+
+
+

하조대 해변에서 도보 3분 거리에 있는 2개 동 규모의 펜션입니다. 모든 객실에서 바다가 보이며, 취사가 가능하고 야외 바비큐 공간을 갖추고 있습니다.

+
+
+

위치·연락처

+
+
주소
강원특별자치도 양양군 현북면 하조대3길 11
+
전화
033-672-0000
+
+
+
+

이용 정보

+
+
체크인 시간
15:00
+
체크아웃 시간
11:00
+
취소·환불 규정
이용 7일 전 100% 환불, 3일 전 50% 환불, 당일 취소 불가
+
취사 가능
가능
+
반려동물 동반
불가
+
흡연 가능
불가
+
프런트 운영시간
09:00 - 21:00
+
주차 가능
가능
+
주차 대수
6대
+
와이파이
가능
+
바비큐 이용
가능
+
바비큐 이용료
20,000원
+
조식 제공
불가
+
+
+
+

객실

+
+

A동 스탠다드

+
+
객실 타입
스탠다드
+
기준 인원
2명
+
최대 인원
4명
+
침대 구성
퀸 1
+
주방 여부
가능
+
전망
오션뷰
+
주중 요금
150,000원
+
+
+
+

B동 복층

+
+
객실 타입
복층
+
기준 인원
4명
+
최대 인원
6명
+
침대 구성
퀸 1 + 싱글 2
+
주방 여부
가능
+
전망
오션뷰
+
주중 요금
220,000원
+
+
+
+
+

사진

+
+
+ +
외관
+
+
+ +
A동 침실
+
+
+ +
A동 거실
+
+
+ +
바비큐장
+
+
+ +
B동 복층
+
+
+
+
+

자주 묻는 질문

+
+ 체크인·체크아웃은 몇 시인가요? +

체크인은 15:00, 체크아웃은 11:00 입니다.

+
+
+ 반려동물과 함께 갈 수 있나요? +

반려동물 동반은 불가합니다.

+
+
+ 객실에서 취사가 가능한가요? +

취사가 가능하며 모든 객실에 주방이 있습니다.

+
+
+ 바비큐를 이용하려면 얼마인가요? +

바비큐 이용료는 20,000원입니다.

+
+
+ 주차는 가능한가요? +

주차가 가능하며 6대까지 주차할 수 있습니다.

+
+
+
+ +
전화하기
+ + + diff --git a/backend/pytest.ini b/backend/pytest.ini new file mode 100644 index 0000000..85c900a --- /dev/null +++ b/backend/pytest.ini @@ -0,0 +1,9 @@ +[pytest] +asyncio_mode = auto +# DB_SESSION_MNG(싱글톤)의 커넥션 풀이 첫 이벤트 루프에 묶이므로, +# 모든 테스트/픽스처가 단일 session 루프를 공유하게 한다. +asyncio_default_fixture_loop_scope = session +asyncio_default_test_loop_scope = session +testpaths = tests +filterwarnings = + ignore::pytest.PytestUnraisableExceptionWarning diff --git a/backend/requirements.txt b/backend/requirements.txt new file mode 100644 index 0000000..bd1cd65 --- /dev/null +++ b/backend/requirements.txt @@ -0,0 +1,14 @@ +fastapi +uvicorn[standard] +sqlalchemy>=2.0 +greenlet +asyncpg +python-jose[cryptography] +bcrypt +orjson +pydantic>=2.0 +python-multipart +httpx +apscheduler>=3.10 +python-dotenv # 레포 최상위 .env 로드(외부 API 키·DB 접속 주입) +azure-storage-blob>=12.19 diff --git a/backend/router/router.py b/backend/router/router.py new file mode 100644 index 0000000..462f484 --- /dev/null +++ b/backend/router/router.py @@ -0,0 +1,91 @@ +import time +from contextlib import asynccontextmanager + +from fastapi import FastAPI, Request +from fastapi.middleware.cors import CORSMiddleware +from fastapi.middleware.gzip import GZipMiddleware + +from common.database.db_session_manager import DB_SESSION_MNG +from common.logger import LOG +from common.utils.gtime import GTime +from config.server_configs import web_server_config +from scheduler import shutdown_scheduler, start_scheduler +import router.v1.auth.account +import router.v1.place.place +import router.v1.fact.fact +import router.v1.faq.faq +import router.v1.media.media +import router.v1.job.job +import router.v1.site.site +import router.v1.local.local + +API_SERVER_START_TIME = GTime.UTCStr() + + +@asynccontextmanager +async def lifespan(app: FastAPI): + # startup: 배치 스케줄러 기동(SCHEDULER_ENABLED=1 인 프로세스에서만) + start_scheduler() + yield + # shutdown: 스케줄러 정지 + DB 엔진 커넥션 풀 정리 + shutdown_scheduler() + await DB_SESSION_MNG.dispose_all() + + +app = FastAPI(title="Web4Ai API", lifespan=lifespan) + +# CORS — 관리자 프론트(client_url) + 랜딩(landing_url, 미설정이면 제외). +# +# ★ client_url 은 쉼표로 여러 오리진을 받는다. 로컬 개발에서 vite 는 3000 이 막혀 있으면 +# 3001, 3002… 로 옮겨 뜨는데(--port 는 희망값이지 고정이 아니다), 그때마다 서버 설정을 +# 고치게 하면 원인이 CORS 라는 걸 알아내는 데만 반나절이 든다. 개발 포트 몇 개를 한 줄에 적어 둔다. +# 운영은 실제 도메인 하나만 적으면 된다. +def _origins(*values: str) -> list[str]: + seen: list[str] = [] + for value in values: + for origin in value.split(","): + origin = origin.strip().rstrip("/") + if origin and origin not in seen: + seen.append(origin) + return seen + + +ALLOWED_ORIGINS = _origins(web_server_config.client_url, web_server_config.landing_url) + +app.add_middleware( + CORSMiddleware, + allow_origins=ALLOWED_ORIGINS, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Accept-Encoding: gzip 요청에 대해 1000 bytes 이상 응답을 압축. +app.add_middleware(GZipMiddleware, minimum_size=1000) + + +@app.middleware("http") +async def log_time(request: Request, call_next): + start_time = time.time() + response = await call_next(request) + elapsed = time.time() - start_time + # status_code 를 함께 남긴다(403/4xx 등을 로그만으로 식별 가능하게). + LOG.d(f"{response.status_code} {request.method} {request.url.path} - {elapsed:.4f}s") + return response + + +@app.get(path="/healthz", responses={404: {"description": "Not found"}}) +async def healthz(): + return API_SERVER_START_TIME + + +# 각 도메인 라우터를 등록한다. 새 기능 추가 시 router.v1.. 를 import 후 include. +app.include_router(router.v1.auth.account.router) +app.include_router(router.v1.place.place.router) +app.include_router(router.v1.fact.fact.router) +app.include_router(router.v1.faq.faq.router) +app.include_router(router.v1.media.media.router) +app.include_router(router.v1.job.job.router) +app.include_router(router.v1.site.site.router) +app.include_router(router.v1.local.local.router) +app.include_router(router.v1.local.local.weather_router) diff --git a/backend/router/v1/auth/account.py b/backend/router/v1/auth/account.py new file mode 100644 index 0000000..8eb38ca --- /dev/null +++ b/backend/router/v1/auth/account.py @@ -0,0 +1,48 @@ +from fastapi import APIRouter, Depends, Request +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer + +from common.models.gmodel import UserInfo +from router.v1.validator.dependencies import IsValidAccessToken, IsValidRefreshToken, RemoveNoneResponse +from services.auth_service import AuthService +from .protocol import Req_Login, Req_UpdateMe, Res_Login, Res_Me, Res_RefreshToken + +security = HTTPBearer() + +# 라우터(MVC 의 컨트롤러). 요청 검증 -> service 호출 -> RemoveNoneResponse 반환만 담당. +router = APIRouter(prefix="/v1/auth", tags=["Auth"], responses={404: {"description": "Not found"}}) + + +@router.post(path="/login", response_model=Res_Login, summary="로그인", description="id/pw 로 로그인하고 JWT 토큰을 발급한다.") +async def login(request: Request, req: Req_Login, service: AuthService = Depends()): + return RemoveNoneResponse(await service.attempt_login(req.id, req.password, request.client.host)) + + +@router.post( + path="/refresh_token", + dependencies=[Depends(IsValidRefreshToken)], + response_model=Res_RefreshToken, + summary="액세스 토큰 갱신", + description="refresh 토큰으로 access 토큰을 재발급한다.", +) +async def refresh_token(service: AuthService = Depends(), credentials: HTTPAuthorizationCredentials = Depends(security)): + return RemoveNoneResponse(await service.refresh_token(credentials.credentials)) + + +@router.get( + path="/me", + response_model=Res_Me, + summary="내 정보", + description="유효한 access 토큰이 있어야 호출 가능. 토큰의 유저+회사 정보를 반환한다.", +) +async def me(service: AuthService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)): + return RemoveNoneResponse(await service.get_me(user_info)) + + +@router.patch( + path="/me", + response_model=Res_Me, + summary="내 정보 수정", + description="본인 이름/이메일/연락처/비밀번호를 수정한다(권한·소속·ID 변경 불가).", +) +async def update_me(req: Req_UpdateMe, service: AuthService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)): + return RemoveNoneResponse(await service.update_me(user_info, req)) diff --git a/backend/router/v1/auth/protocol.py b/backend/router/v1/auth/protocol.py new file mode 100644 index 0000000..1134e1e --- /dev/null +++ b/backend/router/v1/auth/protocol.py @@ -0,0 +1,50 @@ +from typing import Optional + +from pydantic import Field + +from common.enums import UserRole +from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol + + +# 라우터 폴더마다 protocol.py 를 두고 Req_/Res_ 를 정의한다 (protocol 규약). +class AuthProtocol(WebPacketProtocol): + pass + + +class Req_Login(AuthProtocol): + id: str = "" + password: str = "" + + +class Res_Login(Res_WebPacketProtocol): + access_token: str = "" + refresh_token: str = "" + token_type: str = "bearer" + + +class Req_UpdateMe(AuthProtocol): + # 본인 정보 수정. role·company·id 는 받지 않는다(자기 권한·소속 변경 불가). + name: Optional[str] = None + email: Optional[str] = None + contact_number: Optional[str] = None + password: Optional[str] = None # 비밀번호 변경(옵션). 비우면 유지 + + +class Res_RefreshToken(Res_WebPacketProtocol): + access_token: str = "" + token_type: str = "bearer" + + +class CompanyData(WebPacketProtocol): + company_id: str = "" + name: str = "" + + +class Res_Me(Res_WebPacketProtocol): + user_id: str = "" + id: str = "" + name: Optional[str] = None + email: Optional[str] = None + contact_number: Optional[str] = None + role: UserRole = UserRole.USER + company: Optional[CompanyData] = Field(default=None) diff --git a/backend/router/v1/fact/fact.py b/backend/router/v1/fact/fact.py new file mode 100644 index 0000000..9ce6ec7 --- /dev/null +++ b/backend/router/v1/fact/fact.py @@ -0,0 +1,88 @@ +from typing import Optional +from uuid import UUID + +from fastapi import APIRouter, Depends, Query + +from common.models.gmodel import UserInfo +from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse +from services.fact_service import FactService +from .protocol import ( + Req_ExtractFacts, Req_TransitionFact, Req_UpsertFact, + Res_CategorySchema, Res_ExtractFacts, Res_Fact, Res_FactList, +) + +# fact 라우터. 사업장(place_id) 하위 리소스이며, 회사 스코프는 service 가 사업장 조회로 강제한다. +router = APIRouter(prefix="/v1/place/{place_id}/fact", tags=["Fact"], responses={404: {"description": "Not found"}}) + + +@router.get( + path="/schema", + response_model=Res_CategorySchema, + summary="업종 fact 스키마", + description="이 사업장의 업종에 존재하는 fact 필드 정의. 관리 화면이 입력 폼을 그리는 데 쓴다.", +) +async def get_schema(place_id: UUID, service: FactService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)): + return RemoveNoneResponse(await service.get_category_schema(user_info, str(place_id))) + + +@router.get( + path="/list", + response_model=Res_FactList, + summary="fact 목록", + description="publishable_only=true 면 ★ 사이트에 나갈 수 있는 것(VERIFIED·CORRECTED)만.", +) +async def list_facts( + place_id: UUID, + service: FactService = Depends(), + user_info: UserInfo = Depends(IsValidAccessToken), + unit_id: Optional[UUID] = Query(None, description="객실·메뉴·프로그램 단위 fact 만"), + publishable_only: bool = Query(False), +): + return RemoveNoneResponse(await service.list_facts(user_info, str(place_id), unit_id, publishable_only)) + + +@router.post( + path="", + response_model=Res_Fact, + summary="fact 기록", + description="같은 key 의 활성 fact 는 EXPIRED 로 밀리고 새 행이 들어간다(값 이력 보존). " + "★ 자동 수집(api/crawl/llm)은 사장님 수정본(CORRECTED)을 덮어쓸 수 없다.", +) +async def upsert_fact( + place_id: UUID, req: Req_UpsertFact, service: FactService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.upsert_fact(user_info, str(place_id), req)) + + +@router.post( + path="/{fact_id}/transition", + response_model=Res_Fact, + summary="검증 상태 전이", + description="허용 전이만 통과한다(FACT_STATUS_TRANSITIONS). CORRECTED 로 갈 때는 value 가 필수다.", +) +async def transition_fact( + place_id: UUID, + fact_id: UUID, + req: Req_TransitionFact, + service: FactService = Depends(), + user_info: UserInfo = Depends(IsValidAccessToken), +): + return RemoveNoneResponse(await service.transition(user_info, str(place_id), str(fact_id), req)) + + +@router.post( + path="/extract", + response_model=Res_ExtractFacts, + summary="붙여넣은 텍스트에서 fact 추출", + description="사장님이 붙여넣은 소개글·안내문에서 업종 스키마 fact 를 뽑는다. " + "★ 뽑은 값의 **근거 문장이 원문에 실제로 있는지 대조**해 통과한 것만 저장한다. " + "저장된 값은 전부 후보(UNVERIFIED)라 사장님이 확인해야 사이트에 나간다. " + "버려진 항목은 사유와 함께 돌려준다.", +) +async def extract_facts_from_text( + place_id: UUID, + req: Req_ExtractFacts, + service: FactService = Depends(), + user_info: UserInfo = Depends(IsValidAccessToken), +): + return RemoveNoneResponse(await service.extract_from_text(user_info, str(place_id), req.text)) diff --git a/backend/router/v1/fact/protocol.py b/backend/router/v1/fact/protocol.py new file mode 100644 index 0000000..91db197 --- /dev/null +++ b/backend/router/v1/fact/protocol.py @@ -0,0 +1,116 @@ +import uuid +from datetime import datetime +from typing import Optional + +from pydantic import ConfigDict + +from common.enums import FactStatus, FactWriteOutcome, SourceType +from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol + + +class FactProtocol(WebPacketProtocol): + pass + + +class Req_UpsertFact(FactProtocol): + """fact 기록. key 는 사업장 업종의 스키마에 있는 것만 허용한다. + + ★ source_type 이 owner 가 아니면 source_url 이 필수다 — 출처 없는 사실은 받지 않는다.""" + + key: str = "" + value: Optional[str] = None + unit_id: Optional[uuid.UUID] = None + source_type: SourceType = SourceType.OWNER + source_url: Optional[str] = None + expires_at: Optional[datetime] = None + + +class Req_ExtractFacts(FactProtocol): + """사장님이 붙여넣은 원문에서 fact 를 뽑는다. + + ★ 왜 이 입구가 필요한가 (2026-08-31) + TourAPI 에 없고 네이버에도 요금표뿐인 업소가 흔하다(실측: 조이모텔 — 수집 fact 6건이 + 전부 대실·숙박 요금이었다). 그런 업소는 자동 수집만으로는 발행 근거가 영영 안 찬다. + 폴백 3단계의 2번(사장님이 직접 붙여넣기)이 여기다. + + ★ 뽑은 값은 전부 **후보(UNVERIFIED)** 로 들어간다. 사장님이 확인해야 사이트에 나간다.""" + + text: str = "" + + +class Res_ExtractedFact(WebPacketProtocol): + key: str = "" + label: str = "" + value: str = "" + unit_name: Optional[str] = None + stored: bool = False + reason: Optional[str] = None # 저장 못 한 이유(사람이 읽는 문장) + + +class Res_ExtractFacts(Res_WebPacketProtocol): + """뽑힌 것과 버려진 것을 **둘 다** 돌려준다. + + ★ 조용히 버리지 않는다 — 사장님이 "내가 쓴 체크인 시간이 왜 안 들어갔지" 를 + 화면에서 바로 확인할 수 있어야 한다.""" + + stored: int = 0 + rejected: int = 0 + facts: list[Res_ExtractedFact] = [] + # (버린 항목, 사유). 모델이 지어낸 값·스키마 밖 key 가 여기로 온다. + rejections: list[list[str]] = [] + + +class Req_TransitionFact(FactProtocol): + """검증 상태 전이. 허용 전이는 FACT_STATUS_TRANSITIONS 가 유일한 소스다.""" + + status: FactStatus = FactStatus.VERIFIED + value: Optional[str] = None # CORRECTED 로 갈 때 고친 값(다른 전이에선 무시) + + +class FactData(WebPacketProtocol): + model_config = ConfigDict(from_attributes=True) + + fact_id: uuid.UUID + place_id: uuid.UUID + unit_id: Optional[uuid.UUID] = None + key: str + value: Optional[str] = None + unit: Optional[str] = None + source_type: SourceType + source_url: Optional[str] = None + collected_at: Optional[datetime] = None + verified_by: Optional[uuid.UUID] = None + verified_at: Optional[datetime] = None + status: FactStatus + expires_at: Optional[datetime] = None + + +class FieldSpecData(WebPacketProtocol): + """업종 스키마의 필드 정의 — 관리 화면이 입력 폼을 그리는 데 쓴다.""" + + key: str + label: str + type: str + scope: str + required: bool + critical: bool # ★ 미검증 노출 금지 대상 + allow_llm: bool + unit: Optional[str] = None + + +class Res_FactList(Res_WebPacketProtocol): + facts: list[FactData] = [] + publishable: int = 0 # ★ 사이트에 나갈 수 있는 fact 수(VERIFIED·CORRECTED) + pending_review: int = 0 # 재수집이 올려놓은 확인 대기 후보 수(관리 화면 배지) + + +class Res_Fact(Res_WebPacketProtocol): + fact: Optional[FactData] = None + # 기록/전이가 무엇을 했는지. PUBLISHED_REPLACED 면 사이트 재빌드 대상이다. + outcome: Optional[FactWriteOutcome] = None + + +class Res_CategorySchema(Res_WebPacketProtocol): + category: Optional[str] = None + label: Optional[str] = None + fields: list[FieldSpecData] = [] diff --git a/backend/router/v1/faq/faq.py b/backend/router/v1/faq/faq.py new file mode 100644 index 0000000..a50e0f2 --- /dev/null +++ b/backend/router/v1/faq/faq.py @@ -0,0 +1,58 @@ +from uuid import UUID + +from fastapi import APIRouter, Depends, Query + +from common.models.gmodel import UserInfo +from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse +from services.faq_service import FaqService +from .protocol import Req_CreateFaq, Req_TransitionFaq, Res_Faq, Res_FaqList + +# FAQ 라우터. 사업장(place_id) 하위 리소스이며, 회사 스코프는 service 가 사업장 조회로 강제한다. +router = APIRouter(prefix="/v1/place/{place_id}/faq", tags=["Faq"], responses={404: {"description": "Not found"}}) + + +@router.get( + path="/list", + response_model=Res_FaqList, + summary="FAQ 목록", + description="publishable_only=true 면 ★ 사이트에 나갈 수 있는 것(VERIFIED·CORRECTED)만. " + "기본은 승인 대기(UNVERIFIED)까지 함께 준다 — 승인할 대상을 봐야 하기 때문이다.", +) +async def list_faqs( + place_id: UUID, + service: FaqService = Depends(), + user_info: UserInfo = Depends(IsValidAccessToken), + publishable_only: bool = Query(False), +): + return RemoveNoneResponse(await service.list_faqs(user_info, str(place_id), publishable_only)) + + +@router.post( + path="", + response_model=Res_Faq, + summary="FAQ 직접 추가", + description="사장님이 직접 쓴 FAQ. fact 의 owner 입력과 같이 바로 노출값(VERIFIED)이 된다 — " + "사람이 곧 출처다. 출처(generated_by)는 서버가 OWNER 로 고정한다.", +) +async def create_faq( + place_id: UUID, req: Req_CreateFaq, service: FaqService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.create_faq(user_info, str(place_id), req)) + + +@router.post( + path="/{faq_id}/transition", + response_model=Res_Faq, + summary="검증 상태 전이(승인·정정·반려)", + description="허용 전이만 통과한다(FACT_STATUS_TRANSITIONS — fact 와 같은 표). " + "CORRECTED 로 갈 때는 고친 question/answer 중 하나 이상이 필요하고, " + "그 뒤로는 ★ 잠긴 상태라 재생성이 덮어쓰지 못한다.", +) +async def transition_faq( + place_id: UUID, + faq_id: UUID, + req: Req_TransitionFaq, + service: FaqService = Depends(), + user_info: UserInfo = Depends(IsValidAccessToken), +): + return RemoveNoneResponse(await service.transition(user_info, str(place_id), str(faq_id), req)) diff --git a/backend/router/v1/faq/protocol.py b/backend/router/v1/faq/protocol.py new file mode 100644 index 0000000..bdb7aa6 --- /dev/null +++ b/backend/router/v1/faq/protocol.py @@ -0,0 +1,64 @@ +import uuid +from datetime import datetime +from typing import Optional + +from pydantic import ConfigDict + +from common.enums import FactStatus, SourceType +from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol + + +class FaqProtocol(WebPacketProtocol): + pass + + +class Req_CreateFaq(FaqProtocol): + """사장님이 직접 쓴 FAQ. + + ★ generated_by 를 요청으로 받지 않는다 — 받으면 LLM 생성물을 사람이 쓴 것처럼 올려 + 승인 절차를 통째로 건너뛸 수 있다. 출처는 서버가 OWNER 로 고정한다.""" + + question: str = "" + answer: str = "" + sort_order: Optional[int] = None # 미지정이면 기존 FAQ 뒤에 붙인다 + + +class Req_TransitionFaq(FaqProtocol): + """검증 상태 전이. 허용 전이는 fact 와 같은 표(FACT_STATUS_TRANSITIONS)가 유일한 소스다. + + CORRECTED 로 갈 때는 고친 question / answer 중 하나 이상이 필요하다(다른 전이에선 무시).""" + + status: FactStatus = FactStatus.VERIFIED + question: Optional[str] = None + answer: Optional[str] = None + + +class FaqData(WebPacketProtocol): + model_config = ConfigDict(from_attributes=True) + + faq_id: uuid.UUID + place_id: uuid.UUID + question: str + answer: str + # 근거 목록. 컬럼명은 ids 지만 copy 잡이 담는 값은 fact 의 **key** 다 — + # 사람이 승인 화면에서 "무슨 사실로 쓴 문장인지" 읽을 수 있어야 하기 때문이다. + source_fact_ids: Optional[list[str]] = None + generated_by: SourceType + status: FactStatus + sort_order: int = 0 + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + + +class Res_FaqList(Res_WebPacketProtocol): + faqs: list[FaqData] = [] + # ★ 사이트에 나갈 수 있는 건수(VERIFIED·CORRECTED). FAQPage JSON-LD 는 이 건수만큼만 나간다. + publishable: int = 0 + # 승인 대기 건수 — 관리 화면의 '검토할 것' 배지. + # fact 와 달리 UNVERIFIED 도 포함한다: FAQ 에는 '재수집 후보' 개념이 없고, + # LLM 이 만들어 둔 UNVERIFIED 가 곧 사장님 승인 대기 큐다. + pending_review: int = 0 + + +class Res_Faq(Res_WebPacketProtocol): + faq: Optional[FaqData] = None diff --git a/backend/router/v1/job/job.py b/backend/router/v1/job/job.py new file mode 100644 index 0000000..2c2ff2a --- /dev/null +++ b/backend/router/v1/job/job.py @@ -0,0 +1,42 @@ +from uuid import UUID + +from fastapi import APIRouter, Depends + +from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, RequireDeveloper +from services.job_service import JobService +from .protocol import Res_Job, Res_JobOps + +# 작업 큐 라우터. 수집·비전분석·빌드는 몇 분 걸리므로 클라이언트가 여기를 폴링한다. +router = APIRouter(prefix="/v1/job", tags=["Job"], responses={404: {"description": "Not found"}}) + + +@router.get( + path="/ops", + response_model=Res_JobOps, + dependencies=[Depends(RequireDeveloper)], + summary="큐 운영 스냅샷", + description="상태별 카운트 + 큐 지연 + 최근 1시간 DEAD + 좀비(stuck). 내부 운영 전용.", +) +async def job_ops(service: JobService = Depends()): + return RemoveNoneResponse(await service.ops()) + + +@router.get( + path="/{job_id}", + response_model=Res_Job, + dependencies=[Depends(IsValidAccessToken)], + summary="잡 상태 조회(폴링)", +) +async def get_job(job_id: UUID, service: JobService = Depends()): + return RemoveNoneResponse(await service.get_job(str(job_id))) + + +@router.post( + path="/{job_id}/requeue", + response_model=Res_Job, + dependencies=[Depends(RequireDeveloper)], + summary="DEAD 잡 재큐", + description="max_attempts 를 소진해 dead-letter 로 간 잡을 다시 대기로 돌린다. 내부 운영 전용.", +) +async def requeue_job(job_id: UUID, service: JobService = Depends()): + return RemoveNoneResponse(await service.requeue(str(job_id))) diff --git a/backend/router/v1/job/protocol.py b/backend/router/v1/job/protocol.py new file mode 100644 index 0000000..1737d1d --- /dev/null +++ b/backend/router/v1/job/protocol.py @@ -0,0 +1,43 @@ +import uuid +from datetime import datetime +from typing import Any, Optional + +from common.enums import JobStatus, JobType +from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol + + +class JobProtocol(WebPacketProtocol): + pass + + +class JobData(WebPacketProtocol): + job_id: uuid.UUID + job_type: JobType + status: JobStatus + attempts: int = 0 + max_attempts: int = 3 + result: Optional[Any] = None + last_error: Optional[str] = None + run_after: Optional[datetime] = None + run_started_at: Optional[datetime] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + + +class Res_Job(Res_WebPacketProtocol): + """잡 상태 폴링 응답. 수집·빌드는 몇 분 걸리므로 클라이언트가 이 엔드포인트를 폴링한다.""" + + job: Optional[JobData] = None + + +class Res_JobOps(Res_WebPacketProtocol): + """운영 스냅샷 — 큐 지연·DEAD·좀비 감시용.""" + + pending: int = 0 + running: int = 0 + done: int = 0 + dead: int = 0 + dead_1h: int = 0 + stuck_running: int = 0 + oldest_pending_sec: int = 0 + deadline_1h: int = 0 diff --git a/backend/router/v1/local/__init__.py b/backend/router/v1/local/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/backend/router/v1/local/__init__.py @@ -0,0 +1 @@ + diff --git a/backend/router/v1/local/local.py b/backend/router/v1/local/local.py new file mode 100644 index 0000000..7b4b870 --- /dev/null +++ b/backend/router/v1/local/local.py @@ -0,0 +1,48 @@ +from fastapi import APIRouter, Depends, Query + +from common.enums import LocalContentStatus +from common.models.gmodel import UserInfo +from router.v1.validator.dependencies import RequireOwner, RemoveNoneResponse +from services.local_content_service import LocalContentService +from .protocol import ReqPublishLocalContent, ReqSyncFestivals, ReqUpdateLocalContent, ResLocalContentList, ResSyncFestivals, ResWeather + +router = APIRouter(prefix="/v1/admin/local-content", tags=["LocalContent"]) +weather_router = APIRouter(prefix="/v1/local", tags=["LocalContent"]) + + +@weather_router.get("/weather", response_model=ResWeather, summary="현재 날씨 조회 (cache-aside)") +async def get_weather( + region_code: str = Query(min_length=1, max_length=10), + latitude: float = Query(ge=-90, le=90), + longitude: float = Query(ge=-180, le=180), + service: LocalContentService = Depends(), +): + return RemoveNoneResponse(await service.get_weather(region_code, latitude, longitude)) + + +@router.get("", response_model=ResLocalContentList) +async def list_contents( + status: LocalContentStatus | None = Query(None), region_code: str | None = Query(None), + service: LocalContentService = Depends(), _user: UserInfo = Depends(RequireOwner), +): + return RemoveNoneResponse(await service.list(status.value if status else None, region_code)) + + +@router.post("/sync-festivals", response_model=ResSyncFestivals) +async def sync_festivals(req: ReqSyncFestivals, service: LocalContentService = Depends(), _user=Depends(RequireOwner)): + return RemoveNoneResponse(await service.sync_festivals(req)) + + +@router.post("/publish", response_model=ResLocalContentList) +async def publish(req: ReqPublishLocalContent, service: LocalContentService = Depends(), user=Depends(RequireOwner)): + return RemoveNoneResponse(await service.publish(req.content_ids, user.user_id)) + + +@router.patch("/{content_id}", response_model=ResLocalContentList) +async def update_content(content_id: str, req: ReqUpdateLocalContent, service: LocalContentService = Depends(), _user=Depends(RequireOwner)): + return RemoveNoneResponse(await service.update(content_id, req)) + + +@router.post("/{content_id}/end", response_model=ResLocalContentList) +async def end_content(content_id: str, service: LocalContentService = Depends(), _user=Depends(RequireOwner)): + return RemoveNoneResponse(await service.end(content_id)) diff --git a/backend/router/v1/local/protocol.py b/backend/router/v1/local/protocol.py new file mode 100644 index 0000000..9e54327 --- /dev/null +++ b/backend/router/v1/local/protocol.py @@ -0,0 +1,67 @@ +import uuid +from datetime import datetime +from typing import Any + +from pydantic import ConfigDict, Field + +from common.enums import LocalContentStatus, LocalContentType, LocalSource +from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol + + +class LocalContentData(WebPacketProtocol): + model_config = ConfigDict(from_attributes=True) + + local_content_id: uuid.UUID + region_code: str + content_type: LocalContentType + source: LocalSource + external_id: str | None = None + title: str | None = None + body: dict[str, Any] + status: LocalContentStatus + collected_at: datetime | None = None + published_at: datetime | None = None + display_start_at: datetime | None = None + display_end_at: datetime | None = None + + +class ReqSyncFestivals(WebPacketProtocol): + region_code: str = Field(min_length=1, max_length=10) + area_code: str | None = None + start_date: str | None = Field(default=None, pattern=r"^\d{8}$") + + +class ReqPublishLocalContent(WebPacketProtocol): + content_ids: list[uuid.UUID] = Field(min_length=1, max_length=100) + + +class ReqUpdateLocalContent(WebPacketProtocol): + title: str | None = Field(default=None, min_length=1, max_length=300) + body: dict[str, Any] | None = None + display_start_at: datetime | None = None + display_end_at: datetime | None = None + + +class ResLocalContentList(Res_WebPacketProtocol): + contents: list[LocalContentData] = [] + + +class ResSyncFestivals(Res_WebPacketProtocol): + collected: int = 0 + skipped: int = 0 + + +class WeatherData(WebPacketProtocol): + temperature: float + weather_code: int + wind_speed: float | None = None + observed_at: str + timezone: str | None = None + latitude: float + longitude: float + + +class ResWeather(Res_WebPacketProtocol): + weather: WeatherData | None = None + cached: bool = False + stale: bool = False diff --git a/backend/router/v1/media/media.py b/backend/router/v1/media/media.py new file mode 100644 index 0000000..aa451a0 --- /dev/null +++ b/backend/router/v1/media/media.py @@ -0,0 +1,32 @@ +from typing import Optional +from uuid import UUID + +from fastapi import APIRouter, Depends, Query + +from common.models.gmodel import UserInfo +from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse +from services.media_service import MediaService +from .protocol import Res_MediaList + +# 사진 라우터. 사업장(place_id) 하위 리소스이며, 회사 스코프는 service 가 사업장 조회로 강제한다. +router = APIRouter(prefix="/v1/place/{place_id}/media", tags=["Media"], responses={404: {"description": "Not found"}}) + + +@router.get( + path="/list", + response_model=Res_MediaList, + summary="사진 목록", + description="publishable_only=true 면 ★ 사이트에 실제로 나갈 수 있는 것(승인 + alt 있음)만 — " + "빌드 스냅샷과 같은 기준이다. unit_id 를 주면 그 객실·메뉴 사진만. " + "★ 응답에는 항상 source_type(owner/crawl)과 origin_url 이 실린다 — " + "크롤링 이미지 재게시 권리가 미결이라(docs/DECISIONS.md 1-2) 결론에 따라 " + "CRAWL 을 통째로 걸러내야 하고, 화면이 출처를 모르면 그 판단을 못 한다.", +) +async def list_media( + place_id: UUID, + service: MediaService = Depends(), + user_info: UserInfo = Depends(IsValidAccessToken), + unit_id: Optional[UUID] = Query(None, description="객실·메뉴 단위 사진만"), + publishable_only: bool = Query(False), +): + return RemoveNoneResponse(await service.list_media(user_info, str(place_id), unit_id, publishable_only)) diff --git a/backend/router/v1/media/protocol.py b/backend/router/v1/media/protocol.py new file mode 100644 index 0000000..dd18bc3 --- /dev/null +++ b/backend/router/v1/media/protocol.py @@ -0,0 +1,52 @@ +import uuid +from datetime import datetime +from decimal import Decimal +from typing import Optional + +from pydantic import ConfigDict + +from common.enums import MediaStatus, SourceType +from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol + + +# 라우터 폴더마다 protocol.py 를 두고 Req_/Res_ 를 정의한다 (protocol 규약). +class MediaProtocol(WebPacketProtocol): + pass + + +class MediaData(WebPacketProtocol): + """사진 1건. + + ★ source_type 과 origin_url 을 반드시 함께 내려보낸다 — 크롤링 이미지의 재게시 권리가 + 아직 미결이라(docs/DECISIONS.md 1-2), 결론이 '불가'로 나면 발행에서 source_type = CRAWL 을 + 통째로 제외해야 한다. 화면이 출처를 모르면 무엇이 빠질지도 미리 보여줄 수 없다. + origin_url 은 그때 '이 사진은 어디서 왔는가'를 증명하는 유일한 근거다.""" + + model_config = ConfigDict(from_attributes=True) + + media_id: uuid.UUID + place_id: uuid.UUID + unit_id: Optional[uuid.UUID] = None # 객실·메뉴 사진이면 연결 + url: str # 우리가 보관하는 접근 URL + origin_url: Optional[str] = None # ★ 수집 원본 이미지 URL — 권리 판단의 근거 + source_type: SourceType # ★ OWNER 업로드 / CRAWL 수집 — 발행 필터 키 + source_url: Optional[str] = None # 수집한 페이지 URL + label: Optional[str] = None # Vision 분류 라벨 (예: "A동 침실") + alt_text: Optional[str] = None # Vision 생성 alt + vision_confidence: Optional[Decimal] = None # 0.000~1.000 + status: MediaStatus # PENDING_REVIEW 는 사람 확인 큐에 남아 있다는 뜻 + width: Optional[int] = None + height: Optional[int] = None + sort_order: int = 0 + created_at: Optional[datetime] = None + # DB 컬럼이 아니라 계산값이다 — '지금 발행하면 이 사진이 사이트에 실리는가'. + # 판단 기준을 services/snapshot.py 와 똑같이 맞춘다(승인 + alt 있음). 화면이 "왜 이 사진은 + # 안 나오나"를 사장님에게 설명할 수 있어야 하는데, 그 답이 상태 하나로는 안 나오기 때문이다. + publishable: bool = False + + +class Res_MediaList(Res_WebPacketProtocol): + media: list[MediaData] = [] + publishable: int = 0 # ★ 실제로 사이트에 나갈 수 있는 사진 수(승인 + alt 있음) + pending_review: int = 0 # 사람 확인 큐에 남은 사진 수(관리 화면 배지) + crawled: int = 0 # ★ 재게시 권리 미결(1-2) — 결론이 '불가'면 통째로 빠질 사진 수 diff --git a/backend/router/v1/place/place.py b/backend/router/v1/place/place.py new file mode 100644 index 0000000..4c725c1 --- /dev/null +++ b/backend/router/v1/place/place.py @@ -0,0 +1,218 @@ +from typing import Optional +from uuid import UUID + +from fastapi import APIRouter, Depends, Query + +from common.enums import PlaceCategory, PlaceStatus +from common.models.gmodel import PageParams, UserInfo +from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse +from router.v1.job.protocol import Res_Job +from services.place_service import PlaceService +from .protocol import ( + Req_CreateLink, + Req_CreatePlace, + Req_CreateUnit, + Req_StartCollect, + Req_StartCopy, + Req_StartVision, + Req_UpdatePlace, + Req_VerifyPlace, + Req_VerifyPlaceByUrl, + Res_Link, + Res_LinkList, + Res_Place, + Res_PlaceList, + Res_StartCollect, + Res_StartCopy, + Res_StartVision, + Res_VerifyCandidates, + Res_Unit, + Res_UnitList, +) + +# 사업장 라우터. 모든 조회·변경은 토큰의 회사(company_id)로 스코프된다. +router = APIRouter(prefix="/v1/place", tags=["Place"], responses={404: {"description": "Not found"}}) + + +@router.get(path="/list", response_model=Res_PlaceList, summary="사업장 목록") +async def list_places( + service: PlaceService = Depends(), + user_info: UserInfo = Depends(IsValidAccessToken), + pg: PageParams = Depends(), + search: Optional[str] = Query(None, description="상호명·주소 부분일치"), + category: Optional[PlaceCategory] = Query(None, description="업종"), + status: Optional[PlaceStatus] = Query(None, description="상태"), +): + return RemoveNoneResponse(await service.list_places(user_info, pg, search, category, status)) + + +@router.post( + path="", + response_model=Res_Place, + summary="사업장 등록", + description="상호명 하나로 시작한다. 주소·좌표는 동일 업소 검증(verify)이 채운다.", +) +async def create_place(req: Req_CreatePlace, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)): + return RemoveNoneResponse(await service.create_place(user_info, req)) + + +@router.get(path="/{place_id}", response_model=Res_Place, summary="사업장 단건") +async def get_place(place_id: UUID, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)): + return RemoveNoneResponse(await service.get_place(user_info, str(place_id))) + + +@router.patch(path="/{place_id}", response_model=Res_Place, summary="사업장 수정") +async def update_place( + place_id: UUID, req: Req_UpdatePlace, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.update_place(user_info, str(place_id), req)) + + +@router.delete(path="/{place_id}", response_model=Res_Place, summary="사업장 삭제") +async def delete_place( + place_id: UUID, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.delete_place(user_info, str(place_id))) + + +@router.get(path="/{place_id}/collect/active", response_model=Res_Job, summary="진행 중인 수집 잡") +async def get_active_collect( + place_id: UUID, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.get_active_collect(user_info, str(place_id))) + + +@router.post( + path="/{place_id}/verify", + response_model=Res_Place, + summary="동일 업소 검증", + description="카카오 로컬 조회 결과를 박제해 동일 업소를 확정한다. ★ 이걸 통과해야 수집이 열린다.", +) +async def verify_place( + place_id: UUID, req: Req_VerifyPlace, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.verify_place(user_info, str(place_id), req)) + + +@router.post( + path="/{place_id}/verify/by-url", + response_model=Res_Place, + summary="네이버 플레이스 URL 로 동일 업소 확정", + description="사장님이 붙여넣은 네이버 플레이스 주소로 상호·주소·좌표를 읽어 확정하고, " + "그 URL 을 수집 채널로 등록·확정한다. " + "★ 상호 검색이 실패하는 가게(동명·지점명 표기 차이)를 위한 확실한 경로다.", +) +async def verify_place_by_url( + place_id: UUID, req: Req_VerifyPlaceByUrl, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.verify_place_by_url(user_info, str(place_id), req)) + + +@router.get(path="/{place_id}/unit/list", response_model=Res_UnitList, summary="하위 단위 목록(객실·메뉴·프로그램)") +async def list_units(place_id: UUID, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)): + return RemoveNoneResponse(await service.list_units(user_info, str(place_id))) + + +@router.post(path="/{place_id}/unit", response_model=Res_Unit, summary="하위 단위 등록") +async def create_unit( + place_id: UUID, req: Req_CreateUnit, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.create_unit(user_info, str(place_id), req)) + + +@router.get( + path="/{place_id}/link/list", + response_model=Res_LinkList, + summary="채널 URL 목록", + description="confirmed_only=true 면 크롤링 대상(확정된 URL)만.", +) +async def list_links( + place_id: UUID, + service: PlaceService = Depends(), + user_info: UserInfo = Depends(IsValidAccessToken), + confirmed_only: bool = Query(False), +): + return RemoveNoneResponse(await service.list_links(user_info, str(place_id), confirmed_only)) + + +@router.post( + path="/{place_id}/link", + response_model=Res_Link, + summary="채널 URL 등록", + description="등록만으로는 크롤링 대상이 되지 않는다 — 확정(confirm)이 따로 필요하다.", +) +async def create_link( + place_id: UUID, req: Req_CreateLink, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.create_link(user_info, str(place_id), req)) + + +@router.post( + path="/{place_id}/link/{link_id}/confirm", + response_model=Res_Link, + summary="채널 URL 확정", + description="★ 확정된 URL 만 크롤링 대상이 된다. 사업장 검증이 끝나야 확정할 수 있다.", +) +async def confirm_link( + place_id: UUID, link_id: UUID, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.confirm_link(user_info, str(place_id), str(link_id))) + + +@router.post( + path="/{place_id}/collect", + response_model=Res_StartCollect, + summary="수집 시작(비동기)", + description="수집 파이프라인을 큐에 넣고 즉시 job_id 를 돌려준다. 한 건에 몇 분 걸리므로 " + "GET /v1/job/{job_id} 로 진행 상태를 폴링한다. " + "★ 동일 업소 검증과 채널 URL 확정이 끝나야 시작할 수 있다.", +) +async def start_collect( + place_id: UUID, req: Req_StartCollect, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.start_collect(user_info, str(place_id), req)) + + +@router.post( + path="/{place_id}/vision", + response_model=Res_StartVision, + summary="사진 분석 시작(비동기)", + description="Gemini Vision 으로 사진 분류 라벨과 alt 를 생성한다. 수집이 사진을 저장하면 자동으로 걸리며, " + "사장님이 직접 올린 사진이나 재분석(force)에 이 엔드포인트를 쓴다. " + "★ 신뢰도가 낮은 결과는 자동 반영되지 않고 사람 확인 큐에 남는다.", +) +async def start_vision( + place_id: UUID, req: Req_StartVision, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.start_vision(user_info, str(place_id), req)) + + +@router.get( + path="/{place_id}/verify/candidates", + response_model=Res_VerifyCandidates, + summary="동일 업소 후보 조회", + description="외부 장소 DB(카카오 키가 있으면 카카오, 없으면 네이버)에서 후보를 찾아 그대로 돌려준다. " + "★ 서버가 자동 확정하지 않는다 — UI 가 후보를 보여주고 사람이 고른 뒤 POST /verify 로 확정한다. " + "auto_selectable=true 면 판정이 명확해 '이거 맞나요?' 한 번만 물어도 된다.", +) +async def verify_candidates( + place_id: UUID, + service: PlaceService = Depends(), + user_info: UserInfo = Depends(IsValidAccessToken), + query: Optional[str] = Query(None, description="검색어. 비우면 등록된 상호명"), +): + return RemoveNoneResponse(await service.find_candidates(user_info, str(place_id), query)) + + +@router.post( + path="/{place_id}/copy", + response_model=Res_StartCopy, + summary="소개문·FAQ 생성(비동기)", + description="확인된 fact 만 근거로 소개문과 FAQ 를 작성한다. " + "★ 근거 없는 수치·시설 언급은 코드로 검증해 반려한다(LLM 은 사실을 만들지 않는다). " + "생성물도 미검증 상태로 들어가 사람이 승인해야 사이트에 나간다.", +) +async def start_copy( + place_id: UUID, req: Req_StartCopy, service: PlaceService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.start_copy(user_info, str(place_id), req)) diff --git a/backend/router/v1/place/protocol.py b/backend/router/v1/place/protocol.py new file mode 100644 index 0000000..e74b4f5 --- /dev/null +++ b/backend/router/v1/place/protocol.py @@ -0,0 +1,223 @@ +import uuid +from datetime import datetime +from decimal import Decimal +from typing import Optional + +from pydantic import ConfigDict + +from common.enums import ExternalPlaceSource, JobStatus, LinkChannel, PlaceCategory, PlaceStatus, SourceType +from common.models.gmodel import Res_PageProtocol, Res_WebPacketProtocol, WebPacketProtocol + + +# 라우터 폴더마다 protocol.py 를 두고 Req_/Res_ 를 정의한다 (protocol 규약). +class PlaceProtocol(WebPacketProtocol): + pass + + +class Req_CreatePlace(PlaceProtocol): + # 상호명 하나로 시작한다. 나머지는 카카오 로컬 검증이 채운다. + name: str = "" + category: PlaceCategory = PlaceCategory.LODGING + owner_user_id: Optional[uuid.UUID] = None + + +class Req_VerifyPlace(PlaceProtocol): + """카카오 로컬 조회 결과를 사업장에 박제한다(동일 업소 확정). + + ★ 이 단계를 통과해야 수집이 열린다. + external_place_id 는 소스에 따라 없을 수 있다 — 네이버는 고유 장소 id 를 주지 않는다. + 그 경우 상호명 + 도로명주소가 중복 판정 키가 되므로 road_address 를 반드시 채워야 한다.""" + + source: ExternalPlaceSource = ExternalPlaceSource.NAVER + external_place_id: str = "" + # 외부 장소 DB 가 함께 준 업체 홈페이지 URL. 있으면 공식 홈페이지 채널로 자동 등록한다. + # (네이버 지역검색 응답의 link 가 이것 — Perplexity 로는 잘 안 잡히는 채널이라 여기서 건진다.) + place_url: Optional[str] = None + road_address: Optional[str] = None + address: Optional[str] = None + phone: Optional[str] = None + latitude: Optional[Decimal] = None + longitude: Optional[Decimal] = None + region_code: Optional[str] = None + + +class Req_VerifyPlaceByUrl(PlaceProtocol): + """네이버 플레이스 URL 하나로 동일 업소를 확정한다. + + ★ 왜 이 경로가 필요한가 + 상호 검색으로 place id 를 자동 해석하는 경로는 실패한다(실측: '롯데호텔 서울'). + Perplexity 도 네이버 플레이스를 못 찾는다 — 안내 페이지를 물어온 적도 있다. + 그런데 사장님은 **자기 가게 주소를 이미 알고 있다.** 붙여넣게 하는 것이 가장 + 정확하고 빠르며, 그 붙여넣기 자체가 "이 가게가 맞다"는 사람의 확인이다. + + 서버는 그 URL 로 네이버 상세를 읽어 상호·주소·좌표를 가져온다 — 사장님이 손으로 + 옮겨 적게 하지 않는다(오타가 곧 남의 가게가 된다). + """ + + url: str = "" + + +class Req_UpdatePlace(PlaceProtocol): + name: Optional[str] = None + owner_user_id: Optional[uuid.UUID] = None + status: Optional[PlaceStatus] = None + + +class Req_CreateUnit(PlaceProtocol): + name: str = "" + sort_order: int = 0 + + +class Req_CreateLink(PlaceProtocol): + channel: LinkChannel = LinkChannel.ETC + url: str = "" + title: Optional[str] = None + discovered_by: SourceType = SourceType.OWNER + + +class PlaceData(WebPacketProtocol): + model_config = ConfigDict(from_attributes=True) + + place_id: uuid.UUID + name: str + category: PlaceCategory + status: PlaceStatus + owner_user_id: Optional[uuid.UUID] = None + external_source: Optional[ExternalPlaceSource] = None + external_place_id: Optional[str] = None + road_address: Optional[str] = None + address: Optional[str] = None + phone: Optional[str] = None + latitude: Optional[Decimal] = None + longitude: Optional[Decimal] = None + region_code: Optional[str] = None + verified_at: Optional[datetime] = None + content_updated_at: Optional[datetime] = None # ★ 노출값 변경 시각 — 개별 재빌드 대상 판별 + created_at: Optional[datetime] = None + + +class UnitData(WebPacketProtocol): + model_config = ConfigDict(from_attributes=True) + + unit_id: uuid.UUID + place_id: uuid.UUID + name: str + sort_order: int = 0 + + +class LinkData(WebPacketProtocol): + model_config = ConfigDict(from_attributes=True) + + link_id: uuid.UUID + place_id: uuid.UUID + channel: LinkChannel + url: str + title: Optional[str] = None + discovered_by: SourceType + discovered_at: Optional[datetime] = None + confirmed_at: Optional[datetime] = None # ★ NULL = 크롤링 대상 아님 + + +class Res_PlaceList(Res_PageProtocol): + places: list[PlaceData] = [] + + +class Res_Place(Res_WebPacketProtocol): + place: Optional[PlaceData] = None + + +class Res_UnitList(Res_WebPacketProtocol): + units: list[UnitData] = [] + + +class Res_Unit(Res_WebPacketProtocol): + unit: Optional[UnitData] = None + + +class Res_LinkList(Res_WebPacketProtocol): + links: list[LinkData] = [] + confirmed: int = 0 # 크롤링 가능한 링크 수 + + +class Res_Link(Res_WebPacketProtocol): + link: Optional[LinkData] = None + + +class Req_StartCollect(PlaceProtocol): + """수집 시작. 몇 분 걸리므로 동기로 처리하지 않고 잡을 적재한 뒤 즉시 응답한다.""" + + # 확정된 채널 URL 만 크롤링한다. 비우면 이 사업장의 확정 링크 전체. + link_ids: list[uuid.UUID] = [] + # 이미 확보한 fact 를 다시 긁을지. 기본은 아니오(외부 API 호출 비용을 아낀다). + force: bool = False + # 상호·주소로 공개 채널 URL 을 Perplexity 에서 추가 탐색할지. + # 기본 False — 사용자가 화면에서 명시적으로 선택한 회차에만 유료 검색을 실행한다. + discover_channels: bool = False + + +class Res_StartCollect(Res_WebPacketProtocol): + """수집 잡 적재 결과. 클라이언트는 job_id 로 GET /v1/job/{job_id} 를 폴링한다.""" + + job_id: Optional[uuid.UUID] = None + status: Optional[JobStatus] = None + # 이미 같은 사업장 수집이 돌고 있어 새로 만들지 않았다면 False (기존 잡의 id 를 돌려준다). + created: bool = True + confirmed_links: int = 0 + + +class Req_StartVision(PlaceProtocol): + """사진 분석 시작. 사진 20~50장이라 몇 분 걸린다 — 잡으로 처리한다.""" + + # 이미 분석된 사진도 다시 태울지. 기본은 아니오(같은 사진 재분석은 요금만 나간다). + force: bool = False + + +class Res_StartVision(Res_WebPacketProtocol): + job_id: Optional[uuid.UUID] = None + status: Optional[JobStatus] = None + created: bool = True + pending_media: int = 0 # 분석 대상 사진 수 + + +# ---- 동일 업소 후보 (UI 가 사람에게 고르게 한다) ---------------------------- +class PlaceCandidate(WebPacketProtocol): + """외부 장소 DB 에서 찾은 후보 1건. UI 가 이걸 카드로 그려 사람이 고른다.""" + + external_place_id: Optional[str] = None # 네이버는 안 준다 + name: str = "" + road_address: Optional[str] = None + address: Optional[str] = None + phone: Optional[str] = None # 네이버는 안 준다 + latitude: Optional[Decimal] = None + longitude: Optional[Decimal] = None + category_name: Optional[str] = None + place_url: Optional[str] = None # 업체 홈페이지 — 확정 시 공식 채널로 등록된다 + naver_place_url: Optional[str] = None # 자동 발견한 네이버 플레이스. 없으면 UI가 URL 입력을 요청한다 + + +class Res_VerifyCandidates(Res_WebPacketProtocol): + """동일 업소 후보 목록. + + ★ 자동 판정을 신뢰하지 않는다. outcome 이 MATCHED 여도 후보를 전부 내려보내 + UI 가 사람에게 확인시킬 수 있게 한다 — 남의 가게가 섞이면 그게 제일 비싼 실수다.""" + + source: Optional[ExternalPlaceSource] = None + outcome: str = "" # matched | ambiguous | no_candidate + reason: Optional[str] = None # 판정 근거(name_exact / name_duplicate / name_no_exact …) + auto_selectable: bool = False # True 면 UI 가 '이거 맞나요?' 한 번만 물어도 된다 + candidates: list[PlaceCandidate] = [] + + +class Req_StartCopy(PlaceProtocol): + """소개문·FAQ 생성 시작. + + ★ 확인된 fact 만 근거로 쓴다. 근거가 없으면 생성하지 않는다(유료 호출조차 안 한다).""" + + pass + + +class Res_StartCopy(Res_WebPacketProtocol): + job_id: Optional[uuid.UUID] = None + status: Optional[JobStatus] = None + created: bool = True + grounded_facts: int = 0 # 근거로 쓸 수 있는 확인된 fact 수 diff --git a/backend/router/v1/site/protocol.py b/backend/router/v1/site/protocol.py new file mode 100644 index 0000000..6750ec6 --- /dev/null +++ b/backend/router/v1/site/protocol.py @@ -0,0 +1,194 @@ +import uuid +from datetime import datetime +from typing import Any, Optional + +from pydantic import ConfigDict + +from common.enums import BuildStatus, JobStatus, PublishAction, PublishRejectReason, PublishResult, SiteStatus +from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol + + +class SiteProtocol(WebPacketProtocol): + pass + + +class Req_StartBuild(SiteProtocol): + """정적 빌드 시작. + + publish=true 면 발행 검수 게이트를 통과했을 때 바로 발행까지 한다. + ★ 게이트를 통과하지 못하면 발행되지 않는다 — 우회 옵션은 없다.""" + + publish: bool = False + + +class Res_StartBuild(Res_WebPacketProtocol): + job_id: Optional[uuid.UUID] = None + status: Optional[JobStatus] = None + created: bool = True + + +class SiteVersionData(WebPacketProtocol): + model_config = ConfigDict(from_attributes=True) + + site_version_id: uuid.UUID + version: int + build_status: BuildStatus + unique_content_count: int = 0 + build_error: Optional[str] = None + built_at: Optional[datetime] = None + created_at: Optional[datetime] = None + + +class SiteData(WebPacketProtocol): + model_config = ConfigDict(from_attributes=True) + + site_id: uuid.UUID + place_id: uuid.UUID + status: SiteStatus + domain: Optional[str] = None + # 사장님이 고른 템플릿. 화면이 발행 전에 "지금 어느 템플릿으로 나가는지"를 보여줄 근거다. + template_id: Optional[str] = None + # 저장된 디자인(색·서체·섹션). ★ 반드시 응답으로 내려줘야 한다 — + # 에디터가 다시 열렸을 때 저장된 값을 읽을 곳이 없으면, 저장은 됐는데 화면은 기본값으로 돌아간다. + # 저장할 때와 같은 모양 그대로 돌려준다(서버가 해석하지 않으므로 변형할 이유도 없다). + theme: Optional[dict[str, Any]] = None + current_version_id: Optional[uuid.UUID] = None + published_at: Optional[datetime] = None + + +class PublishLogData(WebPacketProtocol): + model_config = ConfigDict(from_attributes=True) + + publish_log_id: uuid.UUID + action: PublishAction + result: PublishResult + reject_reason: Optional[PublishRejectReason] = None + detail: Optional[Any] = None + created_at: Optional[datetime] = None + + +class Req_SiteTemplate(SiteProtocol): + """템플릿 선택 저장. + + ★ 서버는 값을 검증하지 않는다. 템플릿 목록은 프론트(배리에이션 레지스트리)가 소유하므로 + 여기서 화이트리스트를 두면 템플릿을 하나 늘릴 때마다 백엔드를 같이 고쳐야 한다. + 잘못된 키가 들어와도 발행 잡이 업종 기본으로 떨어뜨린다 — 화면이 깨지지 않는다.""" + + template_id: str = "" + + +class Req_SiteTheme(SiteProtocol): + """디자인(색·서체·섹션) 저장. 에디터 좌측 패널과 [디자인] 탭이 만든 결과 그대로 온다. + + ★ Req_SiteTemplate 과 같은 철학이다 — 서버는 값을 해석하지도 검증하지도 않는다. + 섹션 목록도, 배리에이션 키도, 색 토큰 이름도 프론트(배리에이션 레지스트리)가 소유한다. + 여기에 화이트리스트를 두면 프론트에 섹션이나 배리에이션이 하나 늘 때마다 백엔드를 같이 고쳐야 하고, + 그 사이 사장님이 고른 값은 조용히 버려진다. 모르는 값이 들어와도 발행 잡이 업종 기본으로 + 떨어뜨리므로 화면은 깨지지 않는다. + + ★ 그래서 필드를 펼치지 않고 dict 하나로 받는다. 계약은 이렇다: + {"theme": {"colors": {...}, "fontStyle": "...", "colorPaletteId": "...", "sections": [...]}} + sections 는 {id, name, enabled, locked, variantId?} 의 목록이고 **배열 순서가 곧 섹션 순서**다 + (별도 order 필드가 없다). variantId 는 고른 게 있을 때만 키가 붙는다. + pydantic 으로 모양을 고정하면 프론트가 항목을 추가한 순간 백엔드가 그걸 조용히 떨어뜨린다 — + 서버는 배달부지 심판이 아니다. + + ★ colorPaletteId 는 **에디터 복원 전용**이다. 사장님이 고른 색 프리셋 id 이고, + 발행 렌더러는 이걸 안 쓰고 해석된 colors 만 쓴다. DB 에는 저장하고 응답으로도 그대로 돌려주지만, + 발행 payload 의 theme 에는 싣지 않는다 — 발행 계약(SitePayload.SiteTheme)에 없는 필드다. + + ★ templateId 는 이 body 에 없다. sites.template_id 컬럼과 POST /template 이 계속 담당한다 — + 두 곳에 두면 어느 쪽이 진짜인지 갈린다. + + ★ 딱 하나 막는 것은 크기다. 해석하지 않는 값을 그대로 보관한다는 건 곧 무엇이든 들어올 수 있다는 + 뜻이라, 상한이 없으면 jsonb 컬럼 하나가 DB 와 스냅샷을 통째로 부풀린다. + 상한(services/site_service._THEME_MAX_BYTES)은 서비스가 직렬화 크기로 잰다 — + 필드 개수로 재면 값 하나가 긴 경우를 못 막는다. + """ + + theme: dict[str, Any] = {} + + +class RenderStatusData(WebPacketProtocol): + """정적 페이지가 실제로 구워졌는지. 프리렌더가 남긴 보고서를 그대로 옮긴다. + + ★ 발행 기록(DB)과 실제 페이지(파일)는 다른 곳에 산다. 이게 없으면 프리렌더가 깨져도 + DB 는 "발행됨"이라 말하고 사장님은 [사이트 열기] 를 눌러야 404 로 알게 된다.""" + + # PENDING(아직) · STALE(낡음) · OK · FAILED + state: str = "PENDING" + rendered_at: Optional[str] = None + rendered_version: Optional[int] = None + error: Optional[str] = None + + +class Res_Site(Res_WebPacketProtocol): + site: Optional[SiteData] = None + current_version: Optional[SiteVersionData] = None + # ★ 노출값이 바뀐 뒤 다시 빌드하지 않았으면 True — 개별 재빌드 대상이라는 표시. + needs_rebuild: bool = False + # ★ 빌드(DB)와 렌더(정적 파일)는 다른 단계다. 빌드가 됐다고 페이지가 있는 게 아니다. + render: RenderStatusData = RenderStatusData() + + +class Res_SiteVersions(Res_WebPacketProtocol): + versions: list[SiteVersionData] = [] + + +class Res_PublishLogs(Res_WebPacketProtocol): + logs: list[PublishLogData] = [] + + +class AuditCheckData(WebPacketProtocol): + id: str + group: str + label: str + points: int + earned: int + status: str + detail: str + recommendation: Optional[str] = None + + +class Res_SeoAudit(Res_WebPacketProtocol): + seo_score: int = 0 + aeo_score: int = 0 + overall_score: int = 0 + checks: list[AuditCheckData] = [] + summary: dict[str, Any] = {} + visibility: dict[str, int] = {} + disclaimer: str = "" + + +class Req_SiteSlug(SiteProtocol): + """사이트 주소(네임스페이스) 예약. + + ★ 서버가 상호명으로 자동 확정하지 않는다 — 사장님이 고른다. + 주소는 AI 검색이 색인하는 영구 식별자라, 한 번 정해지면 되돌리는 비용이 사장님 몫이 된다.""" + + slug: str = "" + + +class Res_SlugCheck(Res_WebPacketProtocol): + """주소 사용 가능 확인. UI 가 타이핑 중에 호출한다.""" + + available: bool = False + # 불가 사유(services/site_slug 의 REASON_*): INVALID_LENGTH / INVALID_FORMAT / RESERVED / TAKEN. + reason: Optional[str] = None + # 이름 자체는 멀쩡한데 못 쓰는 경우(예약어·중복)에만 대안을 하나 준다. + suggestion: Optional[str] = None + + +class Res_SiteSlug(Res_WebPacketProtocol): + """주소 저장 결과. 거부됐으면 왜/대안을 check 와 같은 코드로 돌려준다.""" + + site: Optional[SiteData] = None + reason: Optional[str] = None + suggestion: Optional[str] = None + + +class Req_SiteStatus(SiteProtocol): + """발행 상태 전이. ★ 해지는 삭제가 아니라 상태 전이다 — + 색인된 페이지를 갑자기 404 로 만들면 그 자리를 다시 OTA 가 가져간다.""" + + action: PublishAction = PublishAction.SUSPEND diff --git a/backend/router/v1/site/site.py b/backend/router/v1/site/site.py new file mode 100644 index 0000000..90c6bb3 --- /dev/null +++ b/backend/router/v1/site/site.py @@ -0,0 +1,167 @@ +from uuid import UUID + +from fastapi import APIRouter, Depends, Query + +from common.models.gmodel import UserInfo +from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse +from services.site_service import SiteService +from .protocol import ( + Req_SiteSlug, + Req_SiteStatus, + Req_SiteTemplate, + Req_SiteTheme, + Req_StartBuild, + Res_PublishLogs, + Res_Site, + Res_SeoAudit, + Res_SiteSlug, + Res_SiteVersions, + Res_SlugCheck, + Res_StartBuild, +) + +# 사이트/발행 라우터. 사업장 하위 리소스이며 회사 스코프는 service 가 사업장 조회로 강제한다. +router = APIRouter(prefix="/v1/place/{place_id}/site", tags=["Site"], responses={404: {"description": "Not found"}}) + + +@router.get( + path="", + response_model=Res_Site, + summary="사이트 상태", + description="현재 발행 버전과 재빌드 필요 여부(needs_rebuild). " + "노출값이 바뀐 뒤 다시 빌드하지 않았으면 true — 이 사업장만 재빌드하면 된다.", +) +async def get_site(place_id: UUID, service: SiteService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)): + return RemoveNoneResponse(await service.get_site(user_info, str(place_id))) + + +@router.get( + path="/audit", + response_model=Res_SeoAudit, + summary="SEO/AEO 준비도 진단", + description="현재 확인된 콘텐츠와 최신 빌드를 SEO·AEO 각각 100점으로 채점하고 개선 항목을 반환한다. " + "준비도 점수이며 실제 검색 순위나 AI 인용을 보장하지 않는다.", +) +async def get_seo_audit( + place_id: UUID, service: SiteService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.get_seo_audit(user_info, str(place_id))) + + +@router.get( + path="/slug/check", + response_model=Res_SlugCheck, + summary="사이트 주소 사용 가능 확인", + description="쓰고 싶은 주소를 미리 본다. 소문자 영문·숫자·하이픈 3~50자만 되고, 예약어와 남이 쓰는 주소는 막힌다. " + "★ 서버가 상호명으로 자동 확정하지 않는다 — 사람이 고른다. " + "못 쓰면 reason(INVALID_LENGTH·INVALID_FORMAT·RESERVED·TAKEN)과 대안 하나(suggestion)를 준다. " + "지금 자기가 쓰는 주소면 available=true 다.", +) +async def check_slug( + place_id: UUID, + service: SiteService = Depends(), + user_info: UserInfo = Depends(IsValidAccessToken), + slug: str = Query(..., description="쓰고 싶은 주소(예: doflo)"), +): + return RemoveNoneResponse(await service.check_slug(user_info, str(place_id), slug)) + + +@router.post( + path="/slug", + response_model=Res_SiteSlug, + summary="사이트 주소 확정", + description="주소를 sites.domain 에 저장한다(사이트 행이 없으면 만든다). " + "검증은 check 와 같은 규칙으로 서버가 다시 한다 — 클라이언트 검증을 믿지 않는다. " + "★ 이미 발행된 사이트의 주소는 바꿀 수 없다(SITE_SLUG_LOCKED) — " + "색인된 주소가 바뀌면 AI 검색이 잡아 둔 페이지가 404 가 된다.", +) +async def set_slug( + place_id: UUID, req: Req_SiteSlug, service: SiteService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.set_slug(user_info, str(place_id), req)) + + +@router.post( + path="/template", + response_model=Res_Site, + summary="템플릿(디자인) 선택 저장", + description="위저드에서 고른 템플릿을 sites.template_id 에 저장한다(사이트 행이 없으면 만든다). " + "★ 서버는 값을 검증하지 않는다 — 템플릿 목록은 프론트가 소유한다. 길이(100자)만 막는다. " + "★ 주소와 달리 발행 뒤에도 바꿀 수 있다: 디자인이 바뀌어도 URL 은 그대로라 색인이 깨지지 않는다. " + "이미 발행된 사이트면 재빌드가 필요하다는 표시로 content_updated_at 을 찍는다(needs_rebuild=true).", +) +async def set_template( + place_id: UUID, + req: Req_SiteTemplate, + service: SiteService = Depends(), + user_info: UserInfo = Depends(IsValidAccessToken), +): + return RemoveNoneResponse(await service.set_template(user_info, str(place_id), req)) + + +@router.post( + path="/theme", + response_model=Res_Site, + summary="디자인(색·서체·섹션) 저장", + description="에디터가 정한 색·서체·섹션(순서·on/off·배리에이션)을 sites.theme 에 저장한다" + "(사이트 행이 없으면 만든다). body 최상위 키는 theme 하나다: " + "{\"theme\":{\"colors\":{...},\"fontStyle\":\"...\",\"colorPaletteId\":\"...\"," + "\"sections\":[{\"id\",\"name\",\"enabled\",\"locked\",\"variantId\"}]}}. " + "★ sections 의 배열 순서가 곧 섹션 순서다(별도 order 필드 없음). " + "★ 서버는 값을 해석하지 않는다 — 섹션 목록·배리에이션 키·색 토큰은 프론트가 소유한다. " + "직렬화 크기(64KB)만 막는다. " + "★ templateId 는 여기 담지 않는다 — sites.template_id 와 POST /template 이 담당한다. " + "★ colorPaletteId 는 에디터 복원 전용이라 저장·반환만 하고 발행 payload 에는 싣지 않는다. " + "★ 빈 값({})을 보내면 NULL 로 되돌아가 업종 기본 색·서체·섹션으로 떨어진다. " + "★ 템플릿과 같이 발행 뒤에도 바꿀 수 있다(디자인이 바뀌어도 URL 은 그대로다). " + "이미 발행된 사이트면 재빌드가 필요하다는 표시로 content_updated_at 을 찍는다" + "(needs_rebuild=true).", +) +async def set_theme( + place_id: UUID, + req: Req_SiteTheme, + service: SiteService = Depends(), + user_info: UserInfo = Depends(IsValidAccessToken), +): + return RemoveNoneResponse(await service.set_theme(user_info, str(place_id), req)) + + +@router.post( + path="/build", + response_model=Res_StartBuild, + summary="정적 빌드(비동기)", + description="스냅샷을 박제해 HTML + JSON-LD 를 만들고 발행 검수 게이트를 돌린다. " + "publish=true 면 통과 시 바로 발행한다. ★ 게이트를 우회하는 옵션은 없다.", +) +async def start_build( + place_id: UUID, req: Req_StartBuild, service: SiteService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.start_build(user_info, str(place_id), req)) + + +@router.get(path="/version/list", response_model=Res_SiteVersions, summary="빌드 버전 목록") +async def list_versions(place_id: UUID, service: SiteService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)): + return RemoveNoneResponse(await service.list_versions(user_info, str(place_id))) + + +@router.get( + path="/log/list", + response_model=Res_PublishLogs, + summary="발행 기록", + description="발행 시도와 거부 사유. 게이트가 막았으면 무엇이 문제였는지 detail 에 남는다.", +) +async def list_logs(place_id: UUID, service: SiteService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)): + return RemoveNoneResponse(await service.list_logs(user_info, str(place_id))) + + +@router.post( + path="/status", + response_model=Res_Site, + summary="발행 상태 전이(중지·재개·내림)", + description="★ 해지는 삭제가 아니라 상태 전이다. 색인된 페이지를 갑자기 404 로 만들면 " + "AI 검색이 그 자리를 다시 OTA 로 채운다.", +) +async def change_status( + place_id: UUID, req: Req_SiteStatus, service: SiteService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken) +): + return RemoveNoneResponse(await service.change_status(user_info, str(place_id), req)) diff --git a/backend/router/v1/validator/dependencies.py b/backend/router/v1/validator/dependencies.py new file mode 100644 index 0000000..b70de01 --- /dev/null +++ b/backend/router/v1/validator/dependencies.py @@ -0,0 +1,133 @@ +import asyncio +import json +from typing import Any, Union + +from fastapi import Depends +from fastapi.responses import JSONResponse +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +import bcrypt +from jose import jwt, JWTError, ExpiredSignatureError + +from common.enums import ( + EXCEPTION_ACCESS_TOKEN_EXPIRED, + EXCEPTION_FORBIDDEN, + EXCEPTION_INVALID_CLIENT_ACCESS, + EXCEPTION_REFRESH_TOKEN_EXPIRED, + UserRole, +) +from common.logger import LOG +from common.models.gmodel import UserInfo +from common.utils.gtime import GTime +from config.server_configs import jwt_token_config + +security = HTTPBearer() + + +# ---- 비밀번호 해시 (bcrypt) ------------------------------------------------ +# bcrypt 는 CPU 바운드 동기 작업이라 그대로 호출하면 asyncio 이벤트 루프를 막아 +# 같은 워커의 다른 요청(healthz 등)까지 멈춘다. 스레드풀(asyncio.to_thread)로 보낸다. +# bcrypt 는 해싱 중 GIL 을 해제하므로 스레드들이 여러 코어에서 실제 병렬로 돈다. +# 입력은 최대 72 bytes 까지만 사용하므로 사전에 잘라준다. +def _hash_pw(pw: str) -> str: + return bcrypt.hashpw(pw.encode("utf-8")[:72], bcrypt.gensalt()).decode("utf-8") + + +def _verify_pw(pw: str, hashed_pw: str) -> bool: + try: + return bcrypt.checkpw(pw.encode("utf-8")[:72], hashed_pw.encode("utf-8")) + except (ValueError, TypeError): + return False + + +async def GetHashedPW(pw: str) -> str: + return await asyncio.to_thread(_hash_pw, pw) + + +async def VerifyPW(pw: str, hashed_pw: str) -> bool: + return await asyncio.to_thread(_verify_pw, pw, hashed_pw) + + +# ---- JWT 토큰 발급/검증 ---------------------------------------------------- +JWT_ALGORITHM = "HS256" +JWT_ACCESS_SECRET = jwt_token_config.access_key +JWT_REFRESH_SECRET = jwt_token_config.refresh_key +ACCESS_TOKEN_EXPIRE_MIN = jwt_token_config.access_expire_min +REFRESH_TOKEN_EXPIRE_MIN = 60 * 24 * jwt_token_config.refresh_expire_day + + +def __create_token(subject: Union[str, Any], secret_key: str, expire_min: int) -> str: + to_encode = { + "sub": str(subject), + "exp": GTime.AddMinutes(expire_min), # jose 가 exp 클레임을 자동 검증 + } + return jwt.encode(to_encode, secret_key, JWT_ALGORITHM) + + +def CreateAccessToken(subject: UserInfo) -> str: + return __create_token(subject.to_json(), JWT_ACCESS_SECRET, ACCESS_TOKEN_EXPIRE_MIN) + + +def CreateRefreshToken(subject: UserInfo) -> str: + return __create_token(subject.to_json(), JWT_REFRESH_SECRET, REFRESH_TOKEN_EXPIRE_MIN) + + +def __decode_token(jwt_token: str, secret_key: str, expired_exception) -> UserInfo: + try: + decoded = jwt.decode(jwt_token, secret_key, algorithms=[JWT_ALGORITHM]) + return UserInfo(**json.loads(decoded.get("sub"))) + except ExpiredSignatureError: + raise expired_exception + except JWTError as ex: + LOG.e_no_callstack(ex) + raise EXCEPTION_INVALID_CLIENT_ACCESS + + +def DecodeAccessToken(jwt_token: str) -> UserInfo: + return __decode_token(jwt_token, JWT_ACCESS_SECRET, EXCEPTION_ACCESS_TOKEN_EXPIRED) + + +def DecodeRefreshToken(jwt_token: str) -> UserInfo: + return __decode_token(jwt_token, JWT_REFRESH_SECRET, EXCEPTION_REFRESH_TOKEN_EXPIRED) + + +# ---- Depends 용 토큰 검증기 ------------------------------------------------ +# 보호된 엔드포인트에서 dependencies=[Depends(IsValidAccessToken)] 로 사용. +async def IsValidAccessToken(credentials: HTTPAuthorizationCredentials = Depends(security)) -> UserInfo: + return DecodeAccessToken(credentials.credentials) + + +async def IsValidRefreshToken(credentials: HTTPAuthorizationCredentials = Depends(security)) -> UserInfo: + return DecodeRefreshToken(credentials.credentials) + + +# 최고관리자 이상(OWNER/DEVELOPER) 게이트. 회원관리·회사설정에 건다. +async def RequireOwner(user_info: UserInfo = Depends(IsValidAccessToken)) -> UserInfo: + if (user_info.role or 0) < UserRole.OWNER.value: + raise EXCEPTION_FORBIDDEN + return user_info + + +# 개발자(내부 운영) 전용 게이트. 회사 스코프를 넘어 전 고객사 데이터를 보는 /v1/admin 에만 건다. +# OWNER 는 자기 회사 최상위일 뿐 남의 회사를 볼 권한이 아니라서 여기선 막힌다. +async def RequireDeveloper(user_info: UserInfo = Depends(IsValidAccessToken)) -> UserInfo: + if (user_info.role or 0) < UserRole.DEVELOPER.value: + raise EXCEPTION_FORBIDDEN + return user_info + + +# ---- ResponseNone 처리 ----------------------------------------------------- +# 응답 객체에서 값이 None 인 필드를 재귀적으로 제거하여 페이로드를 줄인다. +# 모든 라우터는 return RemoveNoneResponse(await service....) 형태로 반환한다. +def RemoveNoneValues(obj: Any) -> Any: + if isinstance(obj, dict): + return {k: RemoveNoneValues(v) for k, v in obj.items() if v is not None} + if isinstance(obj, list): + return [RemoveNoneValues(v) for v in obj] + return obj + + +def RemoveNoneResponse(obj) -> JSONResponse: + # mode="json": uuid/datetime 등 DB 네이티브 타입(asyncpg.UUID 포함)을 pydantic 단에서 + # JSON 안전한 문자열로 변환한다. content 가 이미 JSON-safe dict 이므로 표준 JSONResponse 사용 + # (ORJSONResponse 는 최신 FastAPI 에서 deprecated). + return JSONResponse(content=RemoveNoneValues(obj.model_dump(mode="json"))) diff --git a/backend/scheduler/__init__.py b/backend/scheduler/__init__.py new file mode 100644 index 0000000..a39f650 --- /dev/null +++ b/backend/scheduler/__init__.py @@ -0,0 +1,46 @@ +"""백그라운드 스케줄러(크론) 패키지 — '언제'(when) 담당. + +다중 워커(운영)에서 잡이 워커마다 중복 실행되면 안 되므로 SCHEDULER_ENABLED=1 인 프로세스에서만 등록한다. + +등록된 잡: 없음(스켈레톤). 붙을 잡 — + · 지역정보 갱신 : 축제 주 1회 / 관광정보 월 1회 / 날씨 시간 단위 — 행정구역 코드 단위 캐시 갱신 + · 수집 재시도 : 실패한 수집 작업 재시도 (외부 API 실패 시 직전 값 유지 + 내부 알림) + · 사이트 재빌드 : 검증 상태가 바뀐 place 만 개별 재빌드 (전체 재빌드 금지) +""" +import os + +from apscheduler.schedulers.asyncio import AsyncIOScheduler + +from common.logger import LOG + +__all__ = ["start_scheduler", "shutdown_scheduler"] + +_scheduler = None # AsyncIOScheduler | None + + +def _is_enabled() -> bool: + return os.environ.get("SCHEDULER_ENABLED", "0") == "1" + + +def start_scheduler(): + """lifespan startup 에서 호출. SCHEDULER_ENABLED=1 일 때만 스케줄러를 띄운다.""" + global _scheduler + if not _is_enabled(): + LOG.i("[scheduler] disabled (SCHEDULER_ENABLED != 1)") + return + if _scheduler is not None: + return + + # 한국시간 기준. 잡은 scheduler/jobs.py 에 정의하고 여기서 add_job 으로 등록한다. + _scheduler = AsyncIOScheduler(timezone="Asia/Seoul") + _scheduler.start() + LOG.i("[scheduler] started (KST: 등록된 잡 없음)") + + +def shutdown_scheduler(): + """lifespan shutdown 에서 호출.""" + global _scheduler + if _scheduler is not None: + _scheduler.shutdown(wait=False) + _scheduler = None + LOG.i("[scheduler] stopped") diff --git a/backend/scheduler/jobs.py b/backend/scheduler/jobs.py new file mode 100644 index 0000000..412bf92 --- /dev/null +++ b/backend/scheduler/jobs.py @@ -0,0 +1,5 @@ +"""스케줄 잡 로직(what). '언제 도느냐'(scheduler/__init__.py)와 분리된, 잡이 실제로 하는 일. + +잡은 '대상을 고르는 것'까지만 하고, 실제 처리는 도메인 service 가 책임진다. +(아직 등록된 잡 없음 — 지역정보 갱신 · 수집 재시도 · 개별 사이트 재빌드가 여기로 들어온다.) +""" diff --git a/backend/scripts/check_search_ready.py b/backend/scripts/check_search_ready.py new file mode 100644 index 0000000..f39fbdc --- /dev/null +++ b/backend/scripts/check_search_ready.py @@ -0,0 +1,208 @@ +"""발행본이 **인터넷에서** 검색엔진에 읽힐 준비가 됐는지 확인한다. + + python scripts/check_search_ready.py (기본 https://w4ai.o2o.kr) + python scripts/check_search_ready.py https://w4ai.o2o.kr + python scripts/check_search_ready.py --slug butter (특정 사이트만) + +★ 왜 필요한가 — 색인 여부는 며칠~몇 주 뒤에나 알 수 있다. 그때까지 기다렸다가 + "robots.txt 가 안 올라가 있었다" 같은 걸 알게 되면 그 기간을 통째로 날린다. + 색인을 기다리지 않고 **지금 당장 확인할 수 있는 것**만 여기서 본다: + 크롤러가 접근할 수 있는가 · 읽을 파일이 그 자리에 있는가 · 내용이 들어 있는가. + +★ 로컬 out/ 이 아니라 **실제 도메인**을 친다. 로컬에 파일이 있어도 업로드가 안 됐거나 + 도메인이 안 붙었으면 검색엔진에는 없는 것과 같다 — 그 차이를 잡는 게 목적이다. + +★ 크롤러 UA 로도 받아본다. CDN·WAF 가 봇을 막는 설정이 기본값인 경우가 있어서, + 브라우저로는 열리는데 Googlebot 에게는 403 이 나가는 상태를 눈으로 볼 방법이 없다. +""" +import argparse +import json +import os +import re +import sys +from urllib.parse import urljoin + +import httpx + +TIMEOUT = 15.0 +BROWSER_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/126 Safari/537.36" +CRAWLER_UAS = { + "Googlebot": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)", + "GPTBot": "Mozilla/5.0 (compatible; GPTBot/1.0; +https://openai.com/gptbot)", + "PerplexityBot": "Mozilla/5.0 (compatible; PerplexityBot/1.0; +https://perplexity.ai/perplexitybot)", + "Yeti": "Mozilla/5.0 (compatible; Yeti/1.1; +http://naver.me/spd)", +} + +PASS, WARN, FAIL = "PASS", "WARN", "FAIL" +_results: list[tuple[str, str, str]] = [] + + +def report(level: str, name: str, detail: str = "") -> None: + _results.append((level, name, detail)) + mark = {PASS: " ✓", WARN: " !", FAIL: " ✗"}[level] + print(f"{mark} {name}" + (f" — {detail}" if detail else "")) + + +def get(client: httpx.Client, url: str, ua: str = BROWSER_UA) -> httpx.Response | None: + try: + return client.get(url, headers={"User-Agent": ua}, follow_redirects=True) + except httpx.HTTPError as ex: + report(FAIL, f"연결 실패 {url}", f"{type(ex).__name__}: {ex}") + return None + + +# ── 개별 점검 ──────────────────────────────────────────────────────────── +def check_robots(client: httpx.Client, origin: str) -> None: + url = urljoin(origin, "/robots.txt") + res = get(client, url) + if res is None: + return + if res.status_code != 200: + report(FAIL, "루트 robots.txt", f"HTTP {res.status_code} — 크롤러가 읽는 유일한 자리다") + return + body = res.text + report(PASS, "루트 robots.txt", f"{len(body)}바이트 · {res.elapsed.total_seconds():.2f}s") + + missing = [bot for bot in ("GPTBot", "ClaudeBot", "PerplexityBot", "Googlebot", "Yeti") if bot not in body] + if missing: + report(WARN, "AI·검색 크롤러 명시 허용", f"목록에 없음: {', '.join(missing)}") + else: + report(PASS, "AI·검색 크롤러 명시 허용", "GPTBot·ClaudeBot·PerplexityBot·Googlebot·Yeti") + + if "Sitemap:" in body: + report(PASS, "robots 의 사이트맵 지시", re.search(r"Sitemap:\s*(\S+)", body).group(1)) + else: + report(FAIL, "robots 의 사이트맵 지시", "없다 — 크롤러가 사이트맵 위치를 알 방법이 없다") + + +def check_sitemap(client: httpx.Client, origin: str) -> list[str]: + """루트 사이트맵 — 이 호스트의 모든 사이트가 여기 한 파일에 들어 있다. + + ★ 사이트가 한 장짜리라 사이트맵 인덱스를 쓰지 않는다. 사이트별 sitemap.xml 을 두면 + URL 한 줄짜리 파일이 사이트 수만큼 생기고 크롤러 왕복만 두 배가 된다.""" + url = urljoin(origin, "/sitemap.xml") + res = get(client, url) + if res is None or res.status_code != 200: + code = res.status_code if res else "연결실패" + report(FAIL, "루트 사이트맵", f"HTTP {code} — 새 사이트가 발견되지 않는다") + return [] + locs = re.findall(r"\s*([^<\s]+)\s*", res.text) + if " 50_000: + report(WARN, "루트 사이트맵", f"URL {len(locs)}개 — 규격 상한(50,000)이다. 파일을 쪼갤 때가 됐다") + else: + report(PASS, "루트 사이트맵", f"사이트 {len(locs)}개") + return locs + + +def check_indexnow_key(client: httpx.Client, origin: str) -> None: + key = os.environ.get("INDEXNOW_KEY", "").strip() + if not key: + report(WARN, "IndexNow 키 파일", "INDEXNOW_KEY 가 비어 있다 — 네이버·Bing 통보가 꺼져 있다") + return + res = get(client, urljoin(origin, f"/{key}.txt")) + if res is None: + return + if res.status_code != 200: + report(FAIL, "IndexNow 키 파일", f"HTTP {res.status_code} — 통보가 403 으로 거절된다") + elif res.text.strip() != key: + report(FAIL, "IndexNow 키 파일", "파일 내용이 키와 다르다") + else: + report(PASS, "IndexNow 키 파일", f"/{key}.txt") + + +def check_site(client: httpx.Client, origin: str, slug: str) -> None: + print(f"\n[사이트] {slug}") + base = urljoin(origin, f"/s/{slug}/") + + res = get(client, base) + if res is None: + return + if res.status_code != 200: + report(FAIL, "홈 페이지", f"HTTP {res.status_code} — {base}") + return + html = res.text + report(PASS, "홈 페이지", f"{len(html) // 1024}KB · {res.elapsed.total_seconds():.2f}s") + + # 구조화 데이터가 HTML 소스에 들어 있는가(=JS 실행 없이 읽히는가) + blobs = re.findall(r']+type="application/ld\+json"[^>]*>(.*?)', html, re.S) + if not blobs: + report(FAIL, "구조화 데이터", "HTML 소스에 JSON-LD 가 없다 — AI 크롤러가 읽을 게 없다") + else: + types: list[str] = [] + for blob in blobs: + try: + data = json.loads(blob) + except json.JSONDecodeError: + report(FAIL, "구조화 데이터", "JSON 파싱 실패 — 깨진 채로 나가고 있다") + continue + nodes = data.get("@graph", data) if isinstance(data, dict) else data + for node in nodes if isinstance(nodes, list) else [nodes]: + if isinstance(node, dict) and node.get("@type"): + types.append(str(node["@type"])) + report(PASS if types else WARN, "구조화 데이터", " · ".join(dict.fromkeys(types)) or "타입 없음") + + # 화면에 본문이 실제로 있는가(빈 껍데기 HTML 이면 크롤러에게는 빈 페이지다) + text = re.sub(r"<[^>]+>", " ", re.sub(r"<(script|style)[^>]*>.*?", " ", html, flags=re.S)) + words = len(re.sub(r"\s+", " ", text).strip()) + report(PASS if words > 500 else WARN, "본문 분량", f"{words}자 (JS 실행 없이 읽히는 글자 수)") + + # 사이트가 한 장이라 사이트별 기계용 파일은 llms.txt 하나다. + r = get(client, urljoin(base, "llms.txt")) + if r is not None: + report(PASS if r.status_code == 200 else FAIL, "llms.txt", f"HTTP {r.status_code}") + + +def check_crawler_access(client: httpx.Client, origin: str, slug: str) -> None: + print("\n[크롤러 접근]") + url = urljoin(origin, f"/s/{slug}/") + for name, ua in CRAWLER_UAS.items(): + res = get(client, url, ua=ua) + if res is None: + continue + if res.status_code == 200: + report(PASS, name, f"HTTP 200 · {res.elapsed.total_seconds():.2f}s") + else: + report(FAIL, name, f"HTTP {res.status_code} — CDN·WAF 가 이 봇을 막고 있다") + + +# ── 실행 ───────────────────────────────────────────────────────────────── +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("origin", nargs="?", default="https://w4ai.o2o.kr", help="확인할 오리진") + parser.add_argument("--slug", help="이 사이트만 확인(기본: 사이트맵의 첫 사이트)") + args = parser.parse_args() + origin = args.origin.rstrip("/") + + print(f"[점검] {origin}\n") + print("[오리진 공통]") + with httpx.Client(timeout=TIMEOUT) as client: + check_robots(client, origin) + locs = check_sitemap(client, origin) + check_indexnow_key(client, origin) + + slug = args.slug + if not slug and locs: + found = re.search(r"/s/([^/?#]+)", locs[0]) + slug = found.group(1) if found else None + if not slug: + print("\n확인할 사이트를 못 찾았다 — --slug 로 지정해라.") + else: + check_site(client, origin, slug) + check_crawler_access(client, origin, slug) + + failed = [r for r in _results if r[0] == FAIL] + warned = [r for r in _results if r[0] == WARN] + print(f"\n[결과] 통과 {len(_results) - len(failed) - len(warned)} · 주의 {len(warned)} · 실패 {len(failed)}") + if failed: + print("\n먼저 고칠 것:") + for _, name, detail in failed: + print(f" - {name}: {detail}") + sys.exit(1) + print("크롤러가 읽을 수 있는 상태다. 색인 여부는 며칠~몇 주 뒤에 확인된다.") + + +if __name__ == "__main__": + main() diff --git a/backend/scripts/demo_build.py b/backend/scripts/demo_build.py new file mode 100644 index 0000000..aec9aa1 --- /dev/null +++ b/backend/scripts/demo_build.py @@ -0,0 +1,134 @@ +"""생성 사이트 데모 — 실 DB 에 데이터가 갖춰진 사업장을 만들고 빌드해서 HTML 을 파일로 뽑는다. + + python scripts/demo_build.py (backend/ 에서 실행) + +★ 실 DB(o2o_site_db)에 데모 회사·계정·사업장을 만든다. 개발 DB 에서만 쓸 것. +""" +import asyncio, os, sys, uuid +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +os.environ["APP_ENV"] = "local" + +from httpx import ASGITransport, AsyncClient +from sqlalchemy import text +from sqlalchemy.ext.asyncio import create_async_engine + +from common.enums import FactStatus, MediaStatus, PlaceCategory, SourceType, UserRole, UserStatus +from config.server_configs import main_db_config + +NAME = "핑크비치펜션" +PHOTOS = [ + ("외관", "https://picsum.photos/seed/pension-out/1200/800", "2층 목조 건물 외관과 앞마당 잔디"), + ("A동 침실", "https://picsum.photos/seed/pension-bed/1200/800", "퀸 침대와 창밖으로 바다가 보이는 침실"), + ("A동 거실", "https://picsum.photos/seed/pension-liv/1200/800", "소파와 원목 테이블이 있는 거실"), + ("바비큐장", "https://picsum.photos/seed/pension-bbq/1200/800", "지붕이 있는 야외 바비큐 공간"), + ("B동 복층", "https://picsum.photos/seed/pension-duo/1200/800", "계단으로 이어진 복층 구조의 객실"), +] +PLACE_FACTS = { + "check_in_time": "15:00", "check_out_time": "11:00", + "cancel_policy": "이용 7일 전 100% 환불, 3일 전 50% 환불, 당일 취소 불가", + "cooking_allowed": "true", "pet_allowed": "false", "smoking": "false", + "parking": "true", "parking_capacity": "6", "wifi": "true", + "bbq_available": "true", "bbq_fee": "20000", "breakfast": "false", + "reception_hours": "09:00 - 21:00", + "intro": "하조대 해변에서 도보 3분 거리에 있는 2개 동 규모의 펜션입니다. 모든 객실에서 바다가 보이며, 취사가 가능하고 야외 바비큐 공간을 갖추고 있습니다.", +} +UNITS = { + "A동 스탠다드": {"room_type": "스탠다드", "standard_capacity": "2", "max_capacity": "4", + "bed_type": "퀸 1", "has_kitchen": "true", "view": "오션뷰", "weekday_price": "150000"}, + "B동 복층": {"room_type": "복층", "standard_capacity": "4", "max_capacity": "6", + "bed_type": "퀸 1 + 싱글 2", "has_kitchen": "true", "view": "오션뷰", "weekday_price": "220000"}, +} +FAQS = [ + ("체크인·체크아웃은 몇 시인가요?", "체크인은 15:00, 체크아웃은 11:00 입니다.", ["check_in_time", "check_out_time"]), + ("반려동물과 함께 갈 수 있나요?", "반려동물 동반은 불가합니다.", ["pet_allowed"]), + ("객실에서 취사가 가능한가요?", "취사가 가능하며 모든 객실에 주방이 있습니다.", ["cooking_allowed", "has_kitchen"]), + ("바비큐를 이용하려면 얼마인가요?", "바비큐 이용료는 20,000원입니다.", ["bbq_available", "bbq_fee"]), + ("주차는 가능한가요?", "주차가 가능하며 6대까지 주차할 수 있습니다.", ["parking", "parking_capacity"]), +] + + +async def main(): + pw = f":{main_db_config.write_pw}" if main_db_config.write_pw else "" + dsn = f"postgresql+asyncpg://{main_db_config.write_id}{pw}@{main_db_config.write_host}:{main_db_config.write_port}/{main_db_config.name}" + engine = create_async_engine(dsn) + + from router.v1.validator.dependencies import GetHashedPW + cid, uid, login = uuid.uuid4(), uuid.uuid4(), f"demo{uuid.uuid4().hex[:6]}" + async with engine.begin() as c: + await c.execute(text("INSERT INTO company.companies (company_id,name,status) VALUES (:c,:n,1)"), + {"c": cid, "n": "데모대행사"}) + await c.execute(text("INSERT INTO company.users (user_id,company_id,id,password,name,status,role,last_accessed_at) " + "VALUES (:u,:c,:i,:p,:n,:s,:r,now())"), + {"u": uid, "c": cid, "i": login, "p": await GetHashedPW("pw1234"), + "n": "데모", "s": UserStatus.ACTIVE.value, "r": UserRole.OWNER.value}) + + from router.router import app + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://demo") as cl: + tok = (await cl.post("/v1/auth/login", json={"id": login, "password": "pw1234"})).json()["access_token"] + h = {"Authorization": f"Bearer {tok}"} + + pid = (await cl.post("/v1/place", headers=h, + json={"name": NAME, "category": PlaceCategory.LODGING.value})).json()["place"]["place_id"] + await cl.post(f"/v1/place/{pid}/verify", headers=h, json={ + "source": 2, "road_address": "강원특별자치도 양양군 현북면 하조대3길 11", + "phone": "033-672-0000", "latitude": "38.0219217", "longitude": "128.7221449"}) + print(f"사업장 등록·검증 완료 place_id={pid}") + + for k, v in PLACE_FACTS.items(): + await cl.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v}) + + unit_ids = {} + for order, (name, kv) in enumerate(UNITS.items()): + u = (await cl.post(f"/v1/place/{pid}/unit", headers=h, + json={"name": name, "sort_order": order})).json()["unit"] + unit_ids[name] = u["unit_id"] + for k, v in kv.items(): + await cl.post(f"/v1/place/{pid}/fact", headers=h, + json={"key": k, "value": v, "unit_id": u["unit_id"]}) + + async with engine.begin() as c: + for order, (label, url, alt) in enumerate(PHOTOS): + unit_id = None + for n, i in unit_ids.items(): + if label.startswith(n.split()[0]): + unit_id = uuid.UUID(i) + await c.execute( + text("INSERT INTO place.media (media_id,place_id,unit_id,url,origin_url,source_type,status,label,alt_text,sort_order) " + "VALUES (:m,:p,:u,:url,:url,:s,:st,:l,:a,:o)"), + {"m": uuid.uuid4(), "p": uuid.UUID(pid), "u": unit_id, "url": url, + "s": SourceType.OWNER.value, "st": MediaStatus.APPROVED.value, + "l": label, "a": alt, "o": order}, + ) + for order, (q, a, keys) in enumerate(FAQS): + await c.execute( + text("INSERT INTO fact.faqs (faq_id,place_id,question,answer,source_fact_ids,generated_by,status,sort_order) " + "VALUES (:f,:p,:q,:a,CAST(:k AS jsonb),:g,:st,:o)"), + {"f": uuid.uuid4(), "p": uuid.UUID(pid), "q": q, "a": a, + "k": __import__("json").dumps(keys), "g": SourceType.LLM.value, + "st": FactStatus.VERIFIED.value, "o": order}, + ) + print(f"fact {len(PLACE_FACTS)}건 · 객실 {len(UNITS)}개 · 사진 {len(PHOTOS)}장 · FAQ {len(FAQS)}건 적재") + + job_id = (await cl.post(f"/v1/place/{pid}/site/build", headers=h, + json={"publish": True})).json()["job_id"] + from crud.job_crud import JobQueue + from worker.handlers import build_handler + from worker.runner import Worker + await Worker("demo", JobQueue(), build_handler(), job_deadline_sec=120).process_one() + + job = (await cl.get(f"/v1/job/{job_id}", headers=h)).json()["job"] + r = job.get("result") or {} + print(f"\n빌드: {r.get('build_status')} · 게이트 {'통과' if r.get('gate',{}).get('passed') else '거부'}" + f" · 고유콘텐츠 {r.get('unique_content_count')}건 · 발행 {r.get('published')}") + if not r.get("gate", {}).get("passed"): + print("게이트 사유:", r.get("gate")) + return + + # ★ HTML 은 백엔드가 만들지 않는다. payload JSON 을 쓰는 것까지가 백엔드의 일이고, + # 그걸 정적 페이지로 굽는 것은 frontend/site 의 렌더러다(그게 방문자가 보는 유일한 페이지). + print(f"\npayload: {r.get('payload_path')}") + print(f"페이지: {r.get('routes')}개 · JSON-LD 노드 {len(r.get('mismatches') or []) == 0 and '검증 통과' or '불일치'}") + print("정적 파일: frontend/site/out/s// (렌더러가 굽는다)") + await engine.dispose() + +asyncio.run(main()) diff --git a/backend/scripts/demo_pipeline.py b/backend/scripts/demo_pipeline.py new file mode 100644 index 0000000..993266d --- /dev/null +++ b/backend/scripts/demo_pipeline.py @@ -0,0 +1,154 @@ +"""파이프라인 데모 — 실 DB(o2o_site_db)에 사업장 하나를 만들어 끝까지 돌린다. + + python scripts/demo_pipeline.py (backend/ 에서 실행) + +★ 실 DB 에 데모 회사·계정·사업장을 만든다. 개발 DB 에서만 쓸 것. +★ 네이버 지역검색과 Perplexity 를 **실제로 호출**한다(요금 발생). +""" +import asyncio, json, os, urllib.parse, urllib.request, uuid +os.environ["APP_ENV"] = "local" + +from httpx import ASGITransport, AsyncClient +from sqlalchemy import text +from sqlalchemy.ext.asyncio import create_async_engine + +from common.enums import LinkChannel, PlaceCategory, SourceType, UserRole, UserStatus +from config.server_configs import main_db_config, external_api_config +from services.collector import MockAdapter + +NAME = "핑크비치펜션" + + +def naver_lookup(q): + """실제 네이버 지역검색 — 동일 업소 검증 재료.""" + cid, sec = external_api_config.naver_client_id, external_api_config.naver_client_secret + if not (cid and sec): + return [] + url = f"https://openapi.naver.com/v1/search/local.json?query={urllib.parse.quote(q)}&display=5" + req = urllib.request.Request(url, headers={"X-Naver-Client-Id": cid, "X-Naver-Client-Secret": sec}) + with urllib.request.urlopen(req, timeout=15) as r: + return json.load(r).get("items", []) + + +def strip_tags(s): + import re + return re.sub(r"<[^>]+>", "", s or "").replace("&", "&") + + +async def main(): + pw = f":{main_db_config.write_pw}" if main_db_config.write_pw else "" + dsn = f"postgresql+asyncpg://{main_db_config.write_id}{pw}@{main_db_config.write_host}:{main_db_config.write_port}/{main_db_config.name}" + engine = create_async_engine(dsn) + + from router.v1.validator.dependencies import GetHashedPW + cid, uid, login = uuid.uuid4(), uuid.uuid4(), f"demo{uuid.uuid4().hex[:6]}" + async with engine.begin() as c: + await c.execute(text("INSERT INTO company.companies (company_id,name,status) VALUES (:c,:n,1)"), {"c": cid, "n": "데모대행사"}) + await c.execute(text("INSERT INTO company.users (user_id,company_id,id,password,name,status,role,last_accessed_at) " + "VALUES (:u,:c,:i,:p,:n,:s,:r,now())"), + {"u": uid, "c": cid, "i": login, "p": await GetHashedPW("pw1234"), + "n": "데모", "s": UserStatus.ACTIVE.value, "r": UserRole.OWNER.value}) + await engine.dispose() + + from router.router import app + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://demo") as cl: + tok = (await cl.post("/v1/auth/login", json={"id": login, "password": "pw1234"})).json()["access_token"] + h = {"Authorization": f"Bearer {tok}"} + + print("\n" + "="*74) + print(f" 1. 사업장 등록 — 상호명 하나만 넣는다") + print("="*74) + pl = (await cl.post("/v1/place", headers=h, json={"name": NAME, "category": PlaceCategory.LODGING.value})).json()["place"] + pid = pl["place_id"] + print(f" place_id : {pid}") + print(f" status : {pl['status']} (DRAFT) · verified_at: {pl.get('verified_at') or '없음 → 수집 잠김'}") + + print("\n" + "="*74) + print(f" 2. 네이버 지역검색 — 동일 업소 검증 (실제 API 호출)") + print("="*74) + items = naver_lookup(NAME) + exact = [i for i in items if strip_tags(i["title"]).replace(" ", "") == NAME.replace(" ", "")] + for i in items: + mark = "★" if i in exact else " " + print(f" {mark} {strip_tags(i['title'])[:28]:30s} {i.get('category',''):14s} {strip_tags(i.get('roadAddress',''))[:38]}") + print(f"\n 정확 일치 {len(exact)}건 → {'MATCHED (자동 확정)' if len(exact)==1 else 'AMBIGUOUS (사람이 골라야 함)'}") + + pick = exact[0] if len(exact) == 1 else (items[0] if items else None) + if len(exact) != 1 and pick: + print(f" ⚠ 자동 확정 불가 → 사람이 고른 셈 치고 진행: {strip_tags(pick['title'])}") + if pick: + it = pick + road = strip_tags(it["roadAddress"]) + v = (await cl.post(f"/v1/place/{pid}/verify", headers=h, json={ + "external_place_id": f"naver:{abs(hash(it['link']))%10**8}", + "road_address": road, "address": strip_tags(it.get("address","")), + "latitude": str(int(it["mapy"])/1e7), "longitude": str(int(it["mapx"])/1e7), + "region_code": "4283000", + })).json()["place"] + print(f" → 확정: {v['road_address']}") + print(f" 좌표 {v['latitude']}, {v['longitude']} · verified_at {v['verified_at']}") + + print("\n" + "="*74) + print(f" 3. 크롤링 대상 링크 (MockAdapter — 실크롤러는 법무 대기)") + print("="*74) + murl = MockAdapter.url_for(PlaceCategory.LODGING, pid, channel="naver_place") + lk = (await cl.post(f"/v1/place/{pid}/link", headers=h, json={ + "channel": LinkChannel.NAVER_PLACE.value, "url": murl, "discovered_by": SourceType.API.value})).json()["link"] + await cl.post(f"/v1/place/{pid}/link/{lk['link_id']}/confirm", headers=h) + print(f" {murl} → 확정됨") + + print("\n" + "="*74) + print(f" 4. 수집 시작 → 잡 적재 (즉시 응답)") + print("="*74) + st = (await cl.post(f"/v1/place/{pid}/collect", headers=h, json={})).json() + print(f" job_id: {st['job_id']} · status: PENDING · 확정링크 {st['confirmed_links']}건") + + print("\n 워커 실행 중 (실제 Perplexity 호출 포함, 10~30초)...") + from crud.job_crud import JobQueue + from worker.handlers import build_handler + from worker.runner import Worker + await Worker("demo", JobQueue(), build_handler(), job_deadline_sec=180).process_one() + + job = (await cl.get(f"/v1/job/{st['job_id']}", headers=h)).json()["job"] + r = job.get("result") or {} + print(f"\n 잡 상태: {job['status']} (3=DONE)") + d = r.get("discover", {}) + print(f" · Perplexity : URL {d.get('discovered',0)}건 발견 (검색 {d.get('searches',0)}회)" + + (f" — {d['error'][:50]}" if d.get('error') else "")) + print(f" · 확정 : {r.get('confirm',{})}") + print(f" · 크롤링 : {r.get('fetch',{})}") + print(f" · 객실 : {r.get('units',0)}개") + print(f" · fact : {r.get('facts',{})}") + print(f" · 사진 : {r.get('media',{})}") + + print("\n" + "="*74) + print(f" 5. 발견된 채널 URL") + print("="*74) + for l in (await cl.get(f"/v1/place/{pid}/link/list", headers=h)).json()["links"]: + ch = LinkChannel(l["channel"]).name + print(f" [{'확정' if l.get('confirmed_at') else '미확정'}] {ch:14s} {l['url'][:56]}") + + print("\n" + "="*74) + print(f" 6. 수집된 fact — ★ 전부 후보다. 사이트에 안 나간다") + print("="*74) + fl = (await cl.get(f"/v1/place/{pid}/fact/list", headers=h)).json() + units = {u["unit_id"]: u["name"] for u in (await cl.get(f"/v1/place/{pid}/unit/list", headers=h)).json().get("units", [])} + for f in fl["facts"][:14]: + scope = units.get(f.get("unit_id"), "사업장") + print(f" {scope:12s} {f['key']:20s} = {str(f.get('value'))[:30]:32s} [{'UNVERIFIED'}]") + print(f" ... 총 {len(fl['facts'])}건") + print(f"\n ★ 사이트에 나갈 수 있는 fact: {fl['publishable']}건 ← 사람이 승인해야 올라간다") + + print("\n" + "="*74) + print(f" 7. 사람이 체크인 시간을 승인해본다") + print("="*74) + ci = next(f for f in fl["facts"] if f["key"] == "check_in_time") + t = (await cl.post(f"/v1/place/{pid}/fact/{ci['fact_id']}/transition", headers=h, json={"status": 3})).json() + print(f" check_in_time = {t['fact']['value']} → VERIFIED (검증자 {t['fact']['verified_by'][:8]}…)") + fl2 = (await cl.get(f"/v1/place/{pid}/fact/list", headers=h)).json() + print(f" ★ 사이트에 나갈 수 있는 fact: {fl2['publishable']}건") + pl2 = (await cl.get(f"/v1/place/{pid}", headers=h)).json()["place"] + print(f" ★ content_updated_at: {pl2.get('content_updated_at')} ← 이 사업장만 재빌드하면 된다") + print("="*74 + "\n") + +asyncio.run(main()) diff --git a/backend/scripts/export_openapi.py b/backend/scripts/export_openapi.py new file mode 100644 index 0000000..cf0131e --- /dev/null +++ b/backend/scripts/export_openapi.py @@ -0,0 +1,45 @@ +"""OpenAPI 스펙을 파일로 뽑는다 — 서버를 띄우지 않고. + + python scripts/export_openapi.py (backend/ 에서 실행) + python scripts/export_openapi.py -o /tmp/spec.json + +프론트의 API 클라이언트는 이 스펙에서 orval 이 생성한다. 서버가 떠 있으면 +`npm run orval -w admin` 이 http://localhost:9800/openapi.json 을 직접 읽지만, +서버(와 DB)를 띄우기 싫을 때가 더 많다 — 그때 이 파일을 쓴다: + + python scripts/export_openapi.py + cd ../frontend && ORVAL_INPUT=../../backend/openapi.json npm run orval -w admin + +★ 산출물(backend/openapi.json)은 커밋하지 않는다(.gitignore). 라우터가 유일한 소스다. +""" +import argparse +import json +import os +import sys + +# backend/ 를 import 경로에 올린다(scripts/ 에서 실행해도 동작하게). +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +os.environ.setdefault("APP_ENV", "local") + +DEFAULT_OUT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "openapi.json") + + +def main() -> None: + parser = argparse.ArgumentParser(description="FastAPI OpenAPI 스펙을 JSON 으로 내보낸다.") + parser.add_argument("-o", "--out", default=DEFAULT_OUT, help=f"출력 경로 (기본: {DEFAULT_OUT})") + args = parser.parse_args() + + # import 시점에 app 이 만들어진다. DB 커넥션은 lifespan 에서 열리므로 여기선 DB 가 없어도 된다. + import router.router + + spec = router.router.app.openapi() + with open(args.out, "w", encoding="utf-8") as f: + json.dump(spec, f, ensure_ascii=False, indent=2) + f.write("\n") + + ops = sum(len([m for m in item if m in ("get", "post", "put", "patch", "delete")]) for item in spec["paths"].values()) + print(f"{args.out} ({len(spec['paths'])} paths / {ops} operations)") + + +if __name__ == "__main__": + main() diff --git a/backend/scripts/republish_all.py b/backend/scripts/republish_all.py new file mode 100644 index 0000000..2674e99 --- /dev/null +++ b/backend/scripts/republish_all.py @@ -0,0 +1,89 @@ +"""발행된 사이트 **전부**를 Azure Blob(`$web`)에 다시 올린다. + + python scripts/republish_all.py (backend/ 에서 실행) + python scripts/republish_all.py --dry-run (올리지 않고 목록만 본다) + +★ 왜 필요한가 — 렌더러(frontend/site)를 고쳐 배포하면 번들 파일명이 바뀐다 + (`assets/index-DvNTmLhy.css` → `assets/index-<새해시>.css`). 그런데 평소 업로드 경로 + (services/azure_static.publish)는 **방금 발행한 사이트 하나**만 올린다. 그래서 + 나머지 사이트의 HTML 은 Blob 에 옛 해시를 가리킨 채로 남는다. 옛 자산 블롭은 지워지지 + 않으니 화면이 깨지진 않지만, **디자인 수정이 그 사이트들에 영영 도달하지 않는다.** + 프리렌더는 기동할 때 out/ 을 전부 다시 굽는다(watch-payloads.mjs) — 그 결과를 + Blob 으로 밀어 넣는 짝이 없었다. 이 스크립트가 그 짝이다. + +★ 순서: 프리렌더가 out/ 을 다 구운 **뒤에** 돌린다. 굽는 중에 돌리면 반쯤 구워진 + HTML 이 올라간다. + +★ 공용 자산(assets/·fonts/·robots.txt·sitemap.xml)은 한 번만 올린다. + azure_static.publish 를 사이트마다 부르면 수백 KB 번들을 사이트 수만큼 다시 올린다. +""" +import argparse, os, sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +os.environ.setdefault("APP_ENV", "local") + +from azure.storage.blob import BlobServiceClient # noqa: E402 + +from services import azure_static # noqa: E402 + + +def site_slugs(root) -> list[str]: + base = root / azure_static.SITE_ROOT_DIR + if not base.is_dir(): + raise SystemExit(f"산출물 디렉터리가 없습니다: {base}") + # index.html 이 있는 디렉토리만 발행본으로 본다(작업 중 잔재를 올리지 않는다). + return sorted(d.name for d in base.iterdir() if d.is_dir() and (d / "index.html").is_file()) + + +def main() -> None: + parser = argparse.ArgumentParser() + parser.add_argument("--dry-run", action="store_true", help="업로드 없이 대상만 출력") + args = parser.parse_args() + + root = azure_static.output_dir() + slugs = site_slugs(root) + print(f"[republish] 산출물: {root} · 사이트 {len(slugs)}개") + + if args.dry_run: + for slug in slugs: + print(f" - {slug}") + return + + if not azure_static.is_configured(): + raise SystemExit("AZURE_STORAGE_CONNECTION_STRING 이 비어 있습니다 — 올릴 곳이 없습니다.") + + container_name = os.environ.get("AZURE_STORAGE_CONTAINER", azure_static.DEFAULT_CONTAINER).strip() + container_name = container_name or azure_static.DEFAULT_CONTAINER + prefix = os.environ.get("AZURE_STORAGE_PREFIX", azure_static.DEFAULT_PREFIX).strip().strip("/") + + service = BlobServiceClient.from_connection_string(os.environ["AZURE_STORAGE_CONNECTION_STRING"].strip()) + container = service.get_container_client(container_name) + + # ── 공용 자산 한 번 ── + shared = azure_static._upload_shared(container, root, prefix) + print(f"[republish] 공용 {len(shared)}개 (컨테이너 {container_name} · 접두사 {prefix or '(없음)'})") + + # ── 사이트별 ── + # 한 사이트가 실패해도 나머지는 계속 올린다. 여기서 멈추면 절반만 새 번들을 가리키는 + # 어중간한 상태로 남는다 — 어디까지 됐는지 로그로 남기고 끝까지 간다. + failed: list[tuple[str, str]] = [] + for i, slug in enumerate(slugs, 1): + try: + files = azure_static._upload_tree(container, root, f"{azure_static.SITE_ROOT_DIR}/{slug}", prefix) + site_prefix = "/".join(p for p in (prefix, azure_static.SITE_ROOT_DIR, slug) if p) + removed = azure_static._remove_stale_site_files(container, site_prefix, files) + print(f" [{i}/{len(slugs)}] {slug} — 파일 {len(files)}개, 정리 {removed}개") + except Exception as ex: # noqa: BLE001 — 사이트별 실패 격리가 목적이다 + failed.append((slug, f"{type(ex).__name__}: {ex}")) + print(f" [{i}/{len(slugs)}] {slug} — 실패: {type(ex).__name__}: {ex}") + + if failed: + print(f"\n[republish] 실패 {len(failed)}개:") + for slug, reason in failed: + print(f" - {slug}: {reason}") + raise SystemExit(1) + print(f"\n[republish] 완료 — {len(slugs)}개 사이트") + + +if __name__ == "__main__": + main() diff --git a/backend/services/auth_service.py b/backend/services/auth_service.py new file mode 100644 index 0000000..cfa320c --- /dev/null +++ b/backend/services/auth_service.py @@ -0,0 +1,150 @@ +import uuid + +from fastapi import Depends + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import users +from common.enums import DBWRType, ErrorType, UserRole, UserStatus +from common.logger import LOG +from common.models.gmodel import UserInfo +from crud.user_crud import IUserCRUD, UserCRUD +from router.v1.auth.protocol import CompanyData, Req_UpdateMe, Res_Login, Res_Me, Res_RefreshToken +from router.v1.validator.dependencies import ( + CreateAccessToken, + CreateRefreshToken, + DecodeRefreshToken, + GetHashedPW, + VerifyPW, +) + + +class AuthService: + """비즈니스 로직 계층 (MVC 의 컨트롤러-서비스 분리에서 서비스). + + - CRUD 는 Depends 로 인터페이스 타입으로 주입받는다. + - DB 접근은 DB_SESSION_MNG 의 람다 실행으로만 한다. + 조회 = execute_lambda(..., DB_READ, lambda s: crud.xxx(s, ...)) + 변경 = execute_lambda_run([DBType], [lambda s: crud.xxx(s, ...)]) + - 모든 메서드는 Res_* 를 만들어 result 에 ErrorType 을 세팅해 반환한다. + """ + + def __init__(self, user_crud: IUserCRUD = Depends(UserCRUD)): + self.user_crud = user_crud + + @staticmethod + def _user_info(user: users) -> UserInfo: + # uuid → str (JWT json 직렬화 위해). 기능 라우터는 company_id 로 스코프한다. + return UserInfo( + user_id=str(user.user_id), + id=user.id, + company_id=str(user.company_id), + role=user.role, + ) + + async def attempt_login(self, login_id: str, password: str, connect_ip: str) -> Res_Login: + LOG.i(f"LOGIN : id={login_id}") + res = Res_Login() + + # 1) 계정 조회 (Read DB) + err_type, user = await DB_SESSION_MNG.execute_lambda( + users.DBType(), + DBWRType.DB_READ.value, + lambda s: self.user_crud.get_user_by_login_id(s, login_id), + ) + if err_type != ErrorType.SUCCESS: + # 계정 없음/조회 실패 모두 로그인 실패로 일반화 + res.result.SetResult(ErrorType.ACCOUNT_INVALID_INFO) + return res + user: users + + # 2) 비밀번호 검증 + if not await VerifyPW(password, user.password): + res.result.SetResult(ErrorType.ACCOUNT_INVALID_INFO) + return res + + # 3) 상태 확인 (활성 아니면 차단) + if user.status != UserStatus.ACTIVE.value: + res.result.SetResult(ErrorType.ACCOUNT_BLOCKED_USER) + return res + + # 4) 토큰 발급 + user_info = self._user_info(user) + res.access_token = CreateAccessToken(user_info) + res.refresh_token = CreateRefreshToken(user_info) + + # 5) 마지막 접속 시간 갱신 (Write DB, 트랜잭션) + err_type = await DB_SESSION_MNG.execute_lambda_run( + [users.DBType()], + [lambda s: self.user_crud.update_last_accessed(s, user.user_id)], + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + return res + + async def get_me(self, user_info: UserInfo) -> Res_Me: + res = Res_Me() + + # 1) 유저 조회 + err_type, user = await DB_SESSION_MNG.execute_lambda( + users.DBType(), + DBWRType.DB_READ.value, + lambda s: self.user_crud.get_user_by_login_id(s, user_info.id), + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(ErrorType.ACCOUNT_INVALID_INFO) + return res + user: users + + # 2) 소속사 조회 (없어도 치명적 아님) + company = None + c_err, company_row = await DB_SESSION_MNG.execute_lambda( + users.DBType(), + DBWRType.DB_READ.value, + lambda s: self.user_crud.get_company(s, user.company_id), + ) + if c_err == ErrorType.SUCCESS and company_row is not None: + company = CompanyData(company_id=str(company_row.company_id), name=company_row.name) + + res.user_id = str(user.user_id) + res.id = user.id + res.name = user.name + res.email = user.email + res.contact_number = user.contact_number + res.role = UserRole(user.role) + res.company = company + return res + + async def update_me(self, user_info: UserInfo, req: Req_UpdateMe) -> Res_Me: + res = Res_Me() + data = req.model_dump(exclude_unset=True) + + # 비밀번호: 값 있으면 해시 교체, 비었으면 변경 안 함. + if data.get("password"): + data["password"] = await GetHashedPW(data["password"]) + else: + data.pop("password", None) + # 빈 문자열은 NULL 로 저장(미입력 = 값 비움). + for k in ("name", "email", "contact_number"): + if k in data and data[k] == "": + data[k] = None + + if data: + err_type = await DB_SESSION_MNG.execute_lambda_run( + [users.DBType()], + [lambda s: self.user_crud.update_user(s, uuid.UUID(user_info.user_id), data)], + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + # 갱신 후 최신 정보로 응답(프론트가 스토어 갱신에 사용). + return await self.get_me(user_info) + + async def refresh_token(self, refresh_token: str) -> Res_RefreshToken: + res = Res_RefreshToken() + # refresh 토큰 검증은 라우터 Depends(IsValidRefreshToken) 에서 1차 수행됨. + user_info = DecodeRefreshToken(refresh_token) + res.access_token = CreateAccessToken(user_info) + return res diff --git a/backend/services/azure_static.py b/backend/services/azure_static.py new file mode 100644 index 0000000..fb0d22e --- /dev/null +++ b/backend/services/azure_static.py @@ -0,0 +1,149 @@ +"""정적 사이트 산출물을 Azure Blob의 `$web` 컨테이너에 발행한다.""" + +import asyncio +import mimetypes +import os +from pathlib import Path + +from azure.storage.blob import BlobServiceClient, ContentSettings + +DEFAULT_CONTAINER = "$web" +DEFAULT_PREFIX = "ai-for-web" +# 사이트별 산출물이 놓이는 디렉터리(out/s/). 나머지 루트는 전부 공용이다. +SITE_ROOT_DIR = "s" + + +class AzurePublishError(RuntimeError): + pass + + +def is_configured() -> bool: + return bool(os.environ.get("AZURE_STORAGE_CONNECTION_STRING", "").strip()) + + +def output_dir() -> Path: + return Path(os.environ.get("SITE_OUTPUT_DIR", "/app/out/sites")) + + +def _content_type(path: Path) -> str: + overrides = { + ".html": "text/html; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".json": "application/json; charset=utf-8", + ".xml": "application/xml; charset=utf-8", + ".txt": "text/plain; charset=utf-8", + } + return overrides.get(path.suffix.lower()) or mimetypes.guess_type(path.name)[0] or "application/octet-stream" + + +def _cache_control(path: Path) -> str: + head = path.parts[0] if path.parts else "" + # 번들은 파일명에 해시가 박혀 있다 — 내용이 바뀌면 이름이 바뀌므로 영구 캐시가 안전하다. + if head == "assets": + return "public, max-age=31536000, immutable" + # 폰트는 이름이 고정이라 immutable 은 못 쓰지만(교체하면 갱신되어야 한다) 거의 안 바뀐다. + # 60초로 두면 방문자가 수 MB 짜리 폰트를 계속 다시 받는다. + if head == "fonts": + return "public, max-age=604800" + # HTML · robots.txt · sitemap.xml — 발행하면 곧바로 반영되어야 한다. + return "public, max-age=60, must-revalidate" + + +def _upload_file(container, root: Path, file: Path, prefix: str) -> str: + relative_name = file.relative_to(root).as_posix() + blob_name = f"{prefix}/{relative_name}" if prefix else relative_name + with file.open("rb") as stream: + container.upload_blob( + name=blob_name, + data=stream, + overwrite=True, + content_settings=ContentSettings(content_type=_content_type(file)), + cache_control=_cache_control(Path(relative_name)), + ) + return blob_name + + +def _upload_tree(container, root: Path, relative_root: str, prefix: str) -> set[str]: + base = root / relative_root + if not base.is_dir(): + raise AzurePublishError(f"정적 산출물 디렉터리가 없습니다: {base}") + + return { + _upload_file(container, root, file, prefix) + for file in base.rglob("*") + if file.is_file() and not file.name.startswith(".") + } + + +def _upload_shared(container, root: Path, prefix: str) -> set[str]: + """out/ 루트의 공용 산출물 — 사이트별 파일(`s/` 아래)을 뺀 전부. + + ★ 왜 이게 필요한가: 예전에는 `assets/` 만 올렸다. 그래서 프리렌더가 굽는 루트 + `robots.txt` 와 사이트맵 인덱스(`sitemap.xml`)가 **한 번도 올라간 적이 없다**. + 크롤러는 robots.txt 를 오리진 루트에서만 읽으므로(RFC 9309), AI 크롤러 명시 허용도 + `Sitemap:` 지시도 전달되지 않았다 — 사이트맵을 굽기만 하고 그 존재를 알릴 방법이 + 없었으니 크롤러가 새 사이트를 찾아올 경로 자체가 없었다. + + ★ 왜 이름을 하나씩 적지 않고 `s/` 만 빼는가: 루트에 무엇이 놓이는지는 프리렌더가 + 정한다(`writeSharedAssets` 가 `site/public/` 을 통째로 루트에 복사한다 — 폰트를 + 넣으면 폰트가 는다). 여기에 파일 목록을 두면 나중에 늘어난 파일이 조용히 빠진다. + 지금 고치는 버그가 정확히 그것이므로 같은 모양을 다시 만들지 않는다. + """ + if not root.is_dir(): + raise AzurePublishError(f"정적 산출물 디렉터리가 없습니다: {root}") + + uploaded: set[str] = set() + for entry in sorted(root.iterdir()): + # `s/` 는 사이트별 디렉터리다 — 발행한 사이트 하나만 따로 올린다. + # (여기서 함께 올리면 한 명이 발행할 때마다 전체 사이트를 다시 올리게 된다.) + if entry.name.startswith(".") or entry.name == SITE_ROOT_DIR: + continue + if entry.is_dir(): + uploaded |= _upload_tree(container, root, entry.name, prefix) + elif entry.is_file(): + uploaded.add(_upload_file(container, root, entry, prefix)) + return uploaded + + +def _remove_stale_site_files(container, site_prefix: str, current: set[str]) -> int: + stale = [blob.name for blob in container.list_blobs(name_starts_with=f"{site_prefix}/") if blob.name not in current] + for blob_name in stale: + container.delete_blob(blob_name) + return len(stale) + + +def _publish_sync(slug: str) -> dict: + connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"].strip() + container_name = os.environ.get("AZURE_STORAGE_CONTAINER", DEFAULT_CONTAINER).strip() or DEFAULT_CONTAINER + prefix = os.environ.get("AZURE_STORAGE_PREFIX", DEFAULT_PREFIX).strip().strip("/") + root = output_dir() + + try: + service = BlobServiceClient.from_connection_string(connection_string) + container = service.get_container_client(container_name) + + # 공용 산출물은 덮어써도 안전하다(번들은 해시 파일이고, robots·사이트맵은 매 발행마다 + # 프리렌더가 현재 발행본 전체를 보고 다시 쓴다). 사이트 경로만 현재 발행본으로 교체한다. + shared = _upload_shared(container, root, prefix) + site = _upload_tree(container, root, f"{SITE_ROOT_DIR}/{slug}", prefix) + site_prefix = "/".join(part for part in (prefix, SITE_ROOT_DIR, slug) if part) + removed = _remove_stale_site_files(container, site_prefix, site) + return { + "container": container_name, + "prefix": prefix, + "shared_files": len(shared), + "site_files": len(site), + "removed_stale": removed, + } + except AzurePublishError: + raise + except Exception as ex: + raise AzurePublishError(f"Azure 정적 파일 업로드 실패: {type(ex).__name__}: {ex}") from ex + + +async def publish(slug: str) -> dict | None: + """설정된 경우에만 업로드한다. SDK의 동기 I/O는 별도 스레드에서 실행한다.""" + if not is_configured(): + return None + return await asyncio.to_thread(_publish_sync, slug) diff --git a/backend/services/build_service.py b/backend/services/build_service.py new file mode 100644 index 0000000..b626ce4 --- /dev/null +++ b/backend/services/build_service.py @@ -0,0 +1,291 @@ +"""정적 빌드 + 발행 — BUILD 잡이 하는 일. + + 스냅샷 조립 → 빌드(HTML + JSON-LD) → 발행 검수 게이트 → site_version 기록 + +★ 정적 빌드다. DB 는 여기서만 읽고, 그 결과가 site_versions.snapshot 에 박제된다. + 방문자는 DB 와 만나지 않는다. +★ 개별 재빌드 단위다. 사이트 1,000개에서 전체 재빌드는 못 쓴다 — + places.content_updated_at 이 바뀐 사업장만 다시 빌드하면 된다. +★ 게이트를 통과하지 못하면 버전은 FAILED 로 남고 발행되지 않는다. 사유가 publish_logs 에 남는다. +""" +import os +import uuid + +from sqlalchemy import select + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import place_links, places, publish_logs, site_versions, sites +from common.enums import ( + BuildStatus, + DBWRType, + ErrorType, + PlaceCategory, + PlaceStatus, + PublishAction, + PublishResult, + SiteStatus, +) +from common.logger import LOG +from common.utils.gtime import GTime +from crud.site_crud import SiteCRUD +from crud.place_crud import PlaceCRUD +from services import azure_static, indexnow, publish_gate, render_report, site_payload +from services.site_payload import emit_payload +from services.snapshot import build_snapshot + +_site_crud = SiteCRUD() +_place_crud = PlaceCRUD() + +# 렌더러가 이 버전을 굽고 보고서를 돌려줄 때까지 기다리는 시간. +# ★ 넉넉해야 한다. 짧으면 멀쩡한 발행이 "렌더 대기 초과"로 실패한다 — +# 렌더러는 payload 를 2초 주기로 보고, 사이트 하나 굽는 데 1초 남짓 걸린다. +RENDER_TIMEOUT_SEC = float(os.environ.get("RENDER_TIMEOUT_SEC") or 180) + + +class BuildAborted(RuntimeError): + """재시도해도 소용없는 중단 — 잡의 last_error 로 남는다.""" + + +async def ensure_site(place_id: str) -> "sites": + """사업장의 사이트 행을 보장한다(없으면 만든다). 사업장당 1개.""" + pid = uuid.UUID(place_id) + err, site = await DB_SESSION_MNG.execute_lambda( + sites.DBType(), DBWRType.DB_READ.value, lambda s: _site_crud.get_site_by_place(s, pid) + ) + if err == ErrorType.SUCCESS and site is not None: + return site + row = sites(place_id=pid, status=SiteStatus.DRAFT.value) + run_err = await DB_SESSION_MNG.execute_lambda_run( + [sites.DBType()], [lambda s: _site_crud.add_site(s, row)] + ) + if run_err != ErrorType.SUCCESS: + raise BuildAborted(f"사이트 생성 실패: {run_err.name}") + return row + + +async def _load_links(place_id: str) -> list: + """채널 링크(야놀자·네이버 플레이스·인스타…). + + 스냅샷에 담기지 않는 유일한 발행 재료라 여기서 읽어 payload 로 넘긴다. + ★ 실패해도 빈 목록으로 진행한다 — 링크가 없다고 발행을 막을 이유가 없다.""" + err, rows = await DB_SESSION_MNG.execute_lambda( + place_links.DBType(), + DBWRType.DB_READ.value, + lambda s: DB_SESSION_MNG.execute( + s, + select(place_links).where( + place_links.place_id == uuid.UUID(place_id), + place_links.deleted == False, # noqa: E712 + ), + ), + ) + return list(rows) if err == ErrorType.SUCCESS else [] + + +async def _log(site_id, version_id, action: PublishAction, result: PublishResult, gate=None, actor=None): + """발행 시도를 기록한다. 거부됐으면 사유와 상세를 그대로 남긴다 — 운영자가 뭘 고칠지 알아야 한다.""" + row = publish_logs( + site_id=site_id, + site_version_id=version_id, + action=action.value, + result=result.value, + reject_reason=(gate.reason.value if gate is not None and gate.reason else None), + detail=(gate.as_log() if gate is not None and not gate.passed else None), + actor_user_id=uuid.UUID(actor) if actor else None, + ) + await DB_SESSION_MNG.execute_lambda_run([publish_logs.DBType()], [lambda s: _site_crud.add_log(s, row)]) + + +async def run_build(job: dict) -> dict: + """BUILD 잡 핸들러. payload: {place_id, company_id, publish?, requested_by?} + + publish=True 면 게이트를 통과했을 때 바로 발행까지 한다.""" + payload = job["payload"] + place_id = payload["place_id"] + company_id = payload["company_id"] + want_publish = bool(payload.get("publish")) + + err, place = await DB_SESSION_MNG.execute_lambda( + places.DBType(), + DBWRType.DB_READ.value, + lambda s: _place_crud.get_place(s, uuid.UUID(company_id), uuid.UUID(place_id)), + ) + if err != ErrorType.SUCCESS or place is None: + raise BuildAborted(f"사업장을 찾을 수 없다: {place_id}") + + site = await ensure_site(place_id) + snapshot = await build_snapshot(place) + + v_err, version_no = await DB_SESSION_MNG.execute_lambda( + site_versions.DBType(), DBWRType.DB_READ.value, lambda s: _site_crud.next_version_no(s, site.site_id) + ) + if v_err != ErrorType.SUCCESS: + raise BuildAborted(f"버전 번호 조회 실패: {v_err.name}") + + version = site_versions( + site_id=site.site_id, + version=version_no, + build_status=BuildStatus.BUILDING.value, + snapshot=snapshot, + ) + add_err = await DB_SESSION_MNG.execute_lambda_run( + [site_versions.DBType()], [lambda s: _site_crud.add_version(s, version)] + ) + if add_err != ErrorType.SUCCESS: + raise BuildAborted(f"버전 생성 실패: {add_err.name}") + + result = {"place_id": place_id, "site_id": str(site.site_id), "version": version_no, + "site_version_id": str(version.site_version_id)} + now = GTime.UTC() + + async def _fail(reason: str, gate: publish_gate.GateResult | None = None, extra: dict | None = None): + """버전을 FAILED 로 남기고 사유를 기록한다. 발행하지 않는다.""" + await DB_SESSION_MNG.execute_lambda_claim( + site_versions.DBType(), + lambda s: _site_crud.finish_version( + s, version.site_version_id, + {"build_status": BuildStatus.FAILED.value, "build_error": reason[:2000], **(extra or {})}, + ), + ) + action = PublishAction.PUBLISH if gate is not None else PublishAction.REBUILD + outcome = PublishResult.REJECTED if gate is not None else PublishResult.FAILED + await _log(site.site_id, version.site_version_id, action, outcome, gate, payload.get("requested_by")) + result["build_status"] = "FAILED" + result["error"] = reason + LOG.w(f"[build] place={place_id} v{version_no} 실패: {reason}") + return result + + # ---- 1차 게이트: 렌더 없이 판정 가능한 것 ---- + # ★ 미검증 fact 는 payload 를 쓰기 전에 막는다. 렌더러에 넘긴 뒤에 막으면 검증 안 된 값이 + # 디스크에 한 번 나갔다 들어오는 셈이 된다. + place_name = str((snapshot.get("place") or {}).get("name") or "").strip() + if not place_name: + return await _fail("상호명이 없다 — 사이트를 만들 수 없다") + if (snapshot.get("place") or {}).get("category") is None: + return await _fail("업종이 없다 — 어떤 스키마로 렌더할지 알 수 없다") + + facts_gate = publish_gate.check_facts_verified(snapshot["facts"]) + if not facts_gate.passed: + result["gate"] = {"passed": False, **facts_gate.as_log()} + return await _fail(f"{facts_gate.reason.name}: {facts_gate.as_log()}", facts_gate) + + # ---- 렌더러에 넘긴다 ---- + # ★ 여기가 "발행 기록"과 "실제 페이지"를 잇는 자리다. 렌더러(frontend/site)의 유일한 입력이 + # 이 payload JSON 이고, 그게 굽는 HTML 이 방문자와 크롤러가 보는 유일한 페이지다. + # ★ payload 에 실릴 발행 상태를 미리 맞춘다. 렌더러는 이 값으로 datePublished 를 굽는데, + # 발행 뒤에 payload 를 쓰던 예전 순서에서는 그게 채워져 있었다. 순서가 바뀌었다고 + # 페이지의 발행일이 비면 AI 검색이 보는 신선도 신호가 사라진다. + # ★ 게이트에서 떨어지면 DB 에는 반영하지 않는다(아래에서 실제로 쓸 때만 저장한다). + if want_publish: + site.status = SiteStatus.PUBLISHED.value + site.published_at = site.published_at or now + + links = await _load_links(place_id) + payload_path = emit_payload(place, snapshot, site, version, links) + if not payload_path: + return await _fail("payload 를 쓰지 못했다 — 렌더러에 넘길 입력이 없다") + result["payload_path"] = payload_path + + slug = site_payload.publish_slug(place, site) + + # ---- 렌더 결과를 기다린다 ---- + # ★ 게이트는 **실제로 나갈 HTML** 을 보고 판정해야 한다. 렌더러가 자기 산출물을 대조해 + # 구조화 데이터 불일치와 고유 콘텐츠 수를 보고서로 돌려준다. + report = await render_report.wait_for(slug, version_no, RENDER_TIMEOUT_SEC) + if report is None: + # ★ 발행하지 않는다. 페이지가 있는지 확인하지 못한 채 "발행됨"으로 남기면 + # 사장님은 [사이트 열기] 를 눌러야 404 로 알게 된다. + return await _fail( + f"렌더 결과를 {RENDER_TIMEOUT_SEC}초 안에 받지 못했다 — 렌더러가 도는지 확인이 필요하다" + ) + + mismatches = list(report.get("mismatches") or []) + unique_count = report.get("uniqueContentCount") or 0 + jsonld = report.get("jsonld") or [] + result["unique_content_count"] = unique_count + result["mismatches"] = mismatches[:20] + stamp = {"jsonld": jsonld, "unique_content_count": unique_count} + + # ---- 2차 게이트: 렌더 산출물 기준 ---- + # ★ 렌더가 실패했더라도 게이트를 **먼저** 돌린다. 렌더러가 페이지 쓰기를 거부한 이유가 + # 대개 게이트 사유(고유 콘텐츠 0건·구조화 데이터 불일치)이기 때문이다. + # 여기서 사유를 정확히 골라야 publish_logs 에 '무엇을 고쳐야 하는지' 가 남는다 — + # 전부 "렌더 실패"로 뭉뚱그리면 운영자가 손댈 곳을 알 수 없다. + gate = publish_gate.evaluate(PlaceCategory(place.category), snapshot["facts"], unique_count, mismatches) + result["gate"] = {"passed": gate.passed, **gate.as_log()} + + if not gate.passed: + return await _fail(f"{gate.reason.name}: {gate.as_log()}", gate, stamp) + + if not report.get("ok"): + # 게이트로 설명되지 않는 실패(디스크·번들·payload 파손). 재시도가 의미 있는 쪽이다. + return await _fail(str(report.get("error") or "렌더 실패"), None, stamp) + + # DB 발행 상태를 바꾸기 전에 정적 파일을 외부 저장소에 올린다. + if want_publish: + try: + azure_result = await azure_static.publish(slug) + except azure_static.AzurePublishError as ex: + return await _fail(str(ex), None, stamp) + if azure_result: + result["azure"] = azure_result + # ★ 정적 파일이 올라간 **뒤에** 통보한다. 먼저 알리면 크롤러가 옛 파일을 가져간다. + # 실패해도 발행은 성공이다 — 색인 통보는 부수 효과이고, 다음 발행에서 다시 보낸다. + indexnow_result = await indexnow.submit(slug) + if indexnow_result: + result["indexnow"] = indexnow_result + + # ---- 빌드 성공 ---- + # ★ jsonld·고유콘텐츠 수는 **렌더러가 실제로 내보낸 값**이다. 백엔드가 따로 계산하지 않는다 — + # 따로 계산하던 시절엔 게이트가 통과시킨 근거와 실제 페이지가 어긋날 수 있었다. + await DB_SESSION_MNG.execute_lambda_claim( + site_versions.DBType(), + lambda s: _site_crud.finish_version( + s, version.site_version_id, + { + "build_status": BuildStatus.BUILT.value, + "jsonld": jsonld, + "unique_content_count": unique_count, + "built_at": now, + "build_error": None, + }, + ), + ) + result["build_status"] = "BUILT" + result["routes"] = report.get("routes") + + if want_publish: + await DB_SESSION_MNG.execute_lambda_claim( + sites.DBType(), + lambda s: _site_crud.update_site( + s, site.site_id, + {"status": SiteStatus.PUBLISHED.value, "current_version_id": version.site_version_id, + "published_at": now}, + ), + ) + # ★ 사업장 상태도 같이 올린다. 여기서 안 올리면 places.status 는 영원히 REVIEW 라, + # 발행을 마친 가게가 사업장 목록에서 '발행 전'으로 남는다 — 사장님은 목록만 보고 + # 자기 사이트가 나갔는지 알 수 없다. 목록은 사이트 행을 읽지 않는다(N+1). + await DB_SESSION_MNG.execute_lambda_claim( + places.DBType(), + lambda s: _place_crud.update_place( + s, uuid.UUID(company_id), uuid.UUID(place_id), {"status": PlaceStatus.PUBLISHED.value} + ), + ) + await _log(site.site_id, version.site_version_id, PublishAction.PUBLISH, PublishResult.SUCCESS, None, + payload.get("requested_by")) + site.status = SiteStatus.PUBLISHED.value + site.current_version_id = version.site_version_id + site.published_at = now + result["published"] = True + LOG.i(f"[build] place={place_id} v{version_no} 발행 완료 " + f"(고유 콘텐츠 {unique_count}건 · {report.get('routes')} 페이지)") + else: + await _log(site.site_id, version.site_version_id, PublishAction.REBUILD, PublishResult.SUCCESS, None, + payload.get("requested_by")) + LOG.i(f"[build] place={place_id} v{version_no} 빌드 완료(미발행)") + + version.build_status = BuildStatus.BUILT.value + version.built_at = now + return result + diff --git a/backend/services/collect_service.py b/backend/services/collect_service.py new file mode 100644 index 0000000..8234d26 --- /dev/null +++ b/backend/services/collect_service.py @@ -0,0 +1,573 @@ +"""채널 발견 → 확정 URL 크롤링 → fact·사진 후보 저장. + +수집 결과는 사용자가 승인하기 전까지 사이트에 노출하지 않는다. +""" +import uuid + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import facts as facts_model +from common.database.model.models import media, place_links, places, units +from common.enums import DBWRType, ErrorType, LinkChannel, MediaStatus, PlaceCategory, PlaceStatus, SourceType +from common.logger import LOG +from common.utils.gtime import GTime +from crud.fact_crud import FactCRUD +from crud.place_crud import PlaceCRUD +from common.category_schema import get_schema +from services.collector import AdapterDisabled, AdapterNotFound, REGISTRY +from services.external import naver_place_lookup, perplexity, tour_lookup +from services.fact_service import FactService +from router.v1.fact.protocol import Req_UpsertFact + +_place_crud = PlaceCRUD() +_fact_crud = FactCRUD() + + +class CollectAborted(RuntimeError): + """재시도해도 소용없는 중단 — 잡의 last_error 로 남아 운영자가 본다.""" + + +# ---- 단계 1: 채널 URL 발견 ------------------------------------------------- +async def _add_link(place_id: str, channel, url: str, title: str, discovered_by, raw=None) -> bool: + """링크 한 건 적재. 이미 있으면 False(유니크 충돌은 재수집의 정상 경로다).""" + err = await DB_SESSION_MNG.execute_lambda_run( + [place_links.DBType()], + [lambda s: _place_crud.add_link(s, place_links( + place_id=uuid.UUID(place_id), channel=channel.value, url=url, title=title, + discovered_by=discovered_by.value, discovered_at=GTime.UTC(), raw=raw, + ))], + ) + return err == ErrorType.SUCCESS + + +async def discover_naver_place(place, place_id: str) -> str: + """상호·주소로 네이버 플레이스 링크를 직접 찾아 등록한다. + + 반환값은 결과 상태다 — 호출측이 "자동으로 못 찾았다"를 사장님 화면까지 올려야 하므로 + 성공/실패를 bool 로 뭉개지 않는다: + "resolved" 상호가 일치하는 place id 를 찾아 새로 등록·확정했다 + "already" 같은 URL 이 이미 있었다(재수집의 정상 경로) — 확정만 다시 걸었다 + "not_found" 상호가 일치하는 후보가 없다 → **자동 등록하지 않는다**(남의 가게 방지) + + ★ 왜 Perplexity 에 맡기지 않나 + 실측(2026-08-27 '도플로'·'버터브루'·'힐튼 가든 인 서울 강남'): Perplexity 는 야놀자만 + 물어오고 네이버 플레이스는 **한 건도** 못 찾았다. 도메인 필터를 넓혀도 안내 페이지 + (pages.map.naver.com/useful-tips)가 걸릴 뿐이었다. 검색 언어모델은 "이 가게의 공식 + 플레이스 주소"를 안정적으로 집어내지 못한다 — 게다가 검색 1회당 요금이 붙는다. + + 그런데 우리는 이미 **이 가게가 누구인지 안다**(동일 업소 검증을 통과한 상호·주소). + 추측할 이유가 없으므로 상호가 일치하는 place id 를 직접 해석한다. 일치하지 않으면 + 등록하지 않는다 — 남의 가게를 공식 채널로 붙이는 것이 여기서 가장 비싼 실수다. + """ + place_id_naver = await naver_place_lookup.find_place_id( + place.name, place.road_address or place.address + ) + if not place_id_naver: + # ★ 조용히 넘어가지 않는다 — 이 실패가 곧 "사장님이 주소를 직접 넣어야 한다"는 신호다. + # 실측: '롯데호텔 서울' 이 여기서 떨어졌다(네이버 표기와 상호가 갈린다). + LOG.i(f"[collect] 네이버 플레이스 자동 해석 실패 — 사장님이 주소를 붙여넣어야 한다 (place={place_id})") + return "not_found" + + url = naver_place_lookup.place_url(place_id_naver) + added = await _add_link( + place_id, LinkChannel.NAVER_PLACE, url, + f"{place.name} 네이버 플레이스", SourceType.API, + ) + + # ★ 이 링크만은 자동 확정한다. + # + # 보통 확정은 사람이 한다 — 검색모델이 물어온 URL 은 "비슷한 이름의 다른 가게"일 수 있어서, + # 그걸 자동 확정하면 남의 가게 페이지를 긁어 이 가게 사이트에 싣게 된다. + # 그런데 이 링크는 그 경로로 온 것이 아니다. **상호가 정확히 일치할 때만** 등록되고 + # (find_place_id 가 불일치면 None), 그 상호는 이미 동일 업소 검증을 통과한 값이다. + # 근거가 사람 확인과 같은 수준이므로 클릭을 한 번 더 받는 것은 이득 없이 막기만 한다 — + # 실제로 이 클릭 때문에 힐튼·도플로가 "수집했는데 0건"으로 끝났다. + err, _rows = await DB_SESSION_MNG.execute_lambda_claim( + place_links.DBType(), + lambda s: _place_crud.confirm_link_by_url(s, uuid.UUID(place_id), url, place.verified_by, GTime.UTC()), + ) + LOG.i(f"[collect] 네이버 플레이스 링크 {'등록·확정' if added else '확정'} — place {place_id_naver}") + return "resolved" if added else "already" + + +async def discover_tour_api(place, place_id: str) -> str: + """검증된 상호·좌표로 TourAPI 콘텐츠를 찾아 등록한다. 반환값은 discover_naver_place 와 같은 규약이다. + + ★ 왜 필요한가 (2026-08-31) + `tour_api` 어댑터를 등록해도 **아무도 TourAPI URL 을 만들어주지 않아** 영영 안 불렸다. + 채널 발견 프롬프트는 "야놀자·여기어때·네이버 플레이스" 만 찾기 때문이다. + 실측: 롯데호텔 월드가 네이버 플레이스 하나로만 수집돼 fact 4건 · FAQ 2건에서 끝났다. + 같은 업소를 TourAPI 로 받으면 **fact 93건 · 객실 11개 · 사진 30장**이다. + + ★ 자동 확정하는 이유는 네이버 플레이스와 같다 — 추측이 아니라 해석이기 때문이다. + tour_lookup 이 **상호 일치 + 좌표 500m 이내**를 모두 통과할 때만 id 를 돌려준다 + (부산 좌표로 '롯데호텔 월드' 를 조회하면 314km 떨어져 None 이 된다). + 근거가 사람 확인과 같은 수준이라 클릭을 한 번 더 받는 것은 막기만 한다. + """ + if not tour_lookup.is_configured(): + return "not_configured" + + try: + found = await tour_lookup.find_content_id( + place.name, + PlaceCategory(place.category), + latitude=place.latitude, + longitude=place.longitude, + ) + except Exception as ex: # noqa: BLE001 — 발견 실패가 수집을 죽이면 안 된다 + LOG.w(f"[collect] TourAPI 조회 실패(계속): {type(ex).__name__}: {ex}") + return "error" + + if not found: + # 관광공사에 등록되지 않은 업소는 흔하다 — 실패가 아니라 정상적인 결말이다. + LOG.i(f"[collect] TourAPI 미등록 업소 — 다른 채널로 진행 (place={place_id})") + return "not_found" + + content_id, content_type = found + url = f"tour://{content_type}/{content_id}" + added = await _add_link( + place_id, LinkChannel.ETC, url, f"{place.name} 한국관광공사 TourAPI", SourceType.API, + ) + err, _rows = await DB_SESSION_MNG.execute_lambda_claim( + place_links.DBType(), + lambda s: _place_crud.confirm_link_by_url(s, uuid.UUID(place_id), url, place.verified_by, GTime.UTC()), + ) + LOG.i(f"[collect] TourAPI 링크 {'등록·확정' if added else '확정'} — contentId {content_id}") + return "resolved" if added else "already" + + +async def discover_links(place, place_id: str, *, include_perplexity: bool = False) -> dict: + """채널 URL 을 찾아 place_links 에 적재한다(미확정 상태). + + ★ 순서가 곧 신뢰도다. 지금 자동 발견 경로는 **네이버 플레이스 직접 해석 하나뿐**이고, + Perplexity 는 사용자가 추가 채널 탐색 옵션을 고른 회차에만 실행한다. + 둘 다 실패하면 그건 정상적인 결말이다 — 사장님이 네이버 플레이스 주소를 붙여넣는 + 경로가 1순위이기 때문이다(화면 3단계가 그 입력을 맨 위에 둔다). + + ★ Perplexity 답변을 사실로 쓰지 않는다 — URL 발견 전용이다. 본문은 raw 에 박제만 한다.""" + stat = {"discovered": 0, "skipped_duplicate": 0, "searches": 0, "enabled": False} + + # 네이버 플레이스는 검색모델에 맡기지 않고 직접 해석한다(위 주석 참고). + # Perplexity 설정 여부와 무관하게 먼저 시도한다 — 키가 없어도 이건 된다. + try: + stat["naver_place"] = await discover_naver_place(place, place_id) + if stat["naver_place"] == "resolved": + stat["discovered"] += 1 + except Exception as ex: # noqa: BLE001 — 발견 실패가 수집을 죽이면 안 된다 + LOG.w(f"[collect] 네이버 플레이스 조회 실패(계속): {type(ex).__name__}: {ex}") + stat["naver_place"] = "error" + + # TourAPI 도 같은 성격의 '직접 해석' 이다 — 검색모델을 거치지 않고, 키가 있으면 항상 시도한다. + # ★ 네이버보다 훨씬 많은 fact 를 준다(실측 롯데호텔 월드: 네이버 4건 vs TourAPI 93건). + try: + stat["tour_api"] = await discover_tour_api(place, place_id) + if stat["tour_api"] == "resolved": + stat["discovered"] += 1 + except Exception as ex: # noqa: BLE001 + LOG.w(f"[collect] TourAPI 조회 실패(계속): {type(ex).__name__}: {ex}") + stat["tour_api"] = "error" + + # 오직 요청 옵션으로만 연다. 서버 env 로 일괄 활성화하면 일반 크롤링·재수집에서도 + # 사용자가 모르는 유료 검색이 반복될 수 있으므로 COLLECT_USE_PERPLEXITY 는 더 쓰지 않는다. + if not include_perplexity: + LOG.i("[collect] 추가 채널 자동 발견 미선택 — Perplexity URL 검색 건너뜀") + return stat + + stat["enabled"] = perplexity.is_configured() + if not stat["enabled"]: + LOG.i("[collect] Perplexity 미설정 — URL 발견 건너뜀(등록된 링크로 진행)") + return stat + + try: + found = await perplexity.discover_channels( + place.name, + address=place.road_address or place.address, + category_hint=PlaceCategory(place.category).name, + ) + except perplexity.PerplexityNotConfigured: + stat["enabled"] = False + return stat + except perplexity.PerplexityError as ex: + # ★ 실패해도 파이프라인을 죽이지 않는다 — 이미 등록된 링크로 크롤링은 계속한다. + LOG.w(f"[collect] URL 발견 실패(계속): {type(ex).__name__}: {ex}") + stat["error"] = str(ex)[:200] + return stat + + stat["searches"] = found.search_count + # 필터 탈락 내역 — 조용히 버리지 않는다. 운영자가 "왜 이 URL 이 빠졌나" 를 볼 수 있어야 한다. + if hasattr(found, "reason_counts"): + stat["filtered_out"] = found.reason_counts() + now = GTime.UTC() + for link in found.links: + row = place_links( + place_id=uuid.UUID(place_id), + channel=link.channel.value, + url=link.url, + title=link.title, + discovered_by=SourceType.API.value, + discovered_at=now, + raw=found.raw, # 본문 + search_results 원문 — 환각 추적용 + ) + err = await DB_SESSION_MNG.execute_lambda_run( + [place_links.DBType()], + [lambda s, r=row: _place_crud.add_link(s, r)], + ) + if err == ErrorType.SUCCESS: + stat["discovered"] += 1 + else: + # (place_id, url) 부분 유니크 — 이미 있는 URL 이면 무시한다(재수집 시 정상 경로). + stat["skipped_duplicate"] += 1 + LOG.i(f"[collect] URL 발견 {stat['discovered']}건(중복 {stat['skipped_duplicate']}) · 검색 {stat['searches']}회") + return stat + + +# ---- 단계 2: 크롤링 대상 확정 ---------------------------------------------- +async def confirm_targets(place, place_id: str, only_link_ids: list[str] | None) -> tuple[list, dict]: + """크롤링할 링크를 고른다. + + ★ 사업장이 카카오 로컬로 동일 업소 검증을 통과해야만 여기까지 온다(호출측이 막는다). + 검증된 사업장에 대해 도메인 필터를 통과한 URL 이므로 자동 확정한다. + **그래도 여기서 나온 값은 전부 후보로 들어간다** — 사람이 승인해야 사이트에 나간다. + 이 2중 방어가 '남의 가게 정보가 사이트에 실리는 것'을 막는 실제 장치다. + """ + stat = {"confirmed": 0, "already": 0, "unsupported": 0} + err, links = await DB_SESSION_MNG.execute_lambda( + place_links.DBType(), + DBWRType.DB_READ.value, + lambda s: _place_crud.list_links(s, uuid.UUID(place_id), False), + ) + if err != ErrorType.SUCCESS: + raise CollectAborted(f"채널 링크 조회 실패: {err.name}") + + wanted = set(only_link_ids or []) + now = GTime.UTC() + targets = [] + for link in links: + if wanted and str(link.link_id) not in wanted: + continue + # 처리할 어댑터가 없는 URL 은 확정하지 않는다 — 확정해봐야 긁지 못한다. + if not REGISTRY.can_handle(link.url): + stat["unsupported"] += 1 + continue + if link.confirmed_at is not None: + stat["already"] += 1 + targets.append(link) + continue + _e, rowcount = await DB_SESSION_MNG.execute_lambda_claim( + place_links.DBType(), + lambda s, l=link: _place_crud.confirm_link(s, uuid.UUID(place_id), l.link_id, place.verified_by, now), + ) + if rowcount: + stat["confirmed"] += 1 + targets.append(link) + + LOG.i(f"[collect] 크롤링 대상 {len(targets)}건(신규확정 {stat['confirmed']} · 기확정 {stat['already']} " + f"· 어댑터없음 {stat['unsupported']})") + return targets, stat + + +# ---- 단계 3: 크롤링 ------------------------------------------------------- +async def coverage(place, place_id: str) -> dict: + """이 사업장이 사이트를 만들 만큼 정보를 갖췄는지 — 업종 스키마의 필수 항목 기준. + + 이미 확보한 fact(노출값·후보 모두)의 key 를 세어 required 를 얼마나 덮었는지 본다.""" + schema = get_schema(PlaceCategory(place.category)) + required = set(schema.required_keys("place")) + + err, rows = await DB_SESSION_MNG.execute_lambda( + facts_model.DBType(), + DBWRType.DB_READ.value, + lambda s: _fact_crud.list_facts(s, uuid.UUID(place_id), None, None, False, True), + ) + have = {r.key for r in (rows or []) if (r.value or "").strip()} if err == ErrorType.SUCCESS else set() + covered = required & have + return { + "required": sorted(required), + "missing": sorted(required - covered), + "covered": len(covered), + "total": len(required), + "enough": not (required - covered), + } + + +async def fetch_one(link): + """링크 하나를 긁는다. 실패해도 예외를 던지지 않는다 — 나머지 링크가 살아야 한다.""" + try: + adapter = REGISTRY.get_adapter(link.url) + except (AdapterNotFound, AdapterDisabled) as ex: + # 법무 검토 전이라 미등록된 어댑터(헤드리스 등)면 여기로 온다. + LOG.w(f"[collect] 어댑터 없음 — 건너뜀 {link.url}: {type(ex).__name__}") + return None, "no_adapter" + try: + source = await adapter.fetch(link.url) + except Exception as ex: + LOG.w(f"[collect] 수집 실패(계속) {link.url}: {type(ex).__name__}: {ex}") + return None, "failed" + if not source.ok: + LOG.w(f"[collect] 수집 실패(계속) {link.url}: {source.error}") + return None, "failed" + return source, "fetched" + + +# ---- 단계 4: 하위 단위 시드 ------------------------------------------------ +async def ensure_units(place_id: str, sources: list) -> dict: + """수집된 unit_name(객실·메뉴·프로그램)을 place.units 에 맞춰 {이름: unit_id} 를 만든다. + + 수집 시점엔 unit_id 를 모르므로 이름으로 매핑한다. 없는 이름만 새로 만든다.""" + names = [] + for source in sources: + for name in source.unit_names(): + if name not in names: + names.append(name) + if not names: + return {} + + err, rows = await DB_SESSION_MNG.execute_lambda( + units.DBType(), + DBWRType.DB_READ.value, + lambda s: _place_crud.list_units(s, uuid.UUID(place_id)), + ) + existing = {r.name: r.unit_id for r in (rows or [])} if err == ErrorType.SUCCESS else {} + + created = 0 + for order, name in enumerate(names): + if name in existing: + continue + row = units(place_id=uuid.UUID(place_id), name=name, sort_order=order) + run_err = await DB_SESSION_MNG.execute_lambda_run( + [units.DBType()], + [lambda s, r=row: _place_crud.add_unit(s, r)], + ) + if run_err == ErrorType.SUCCESS: + existing[name] = row.unit_id + created += 1 + if created: + LOG.i(f"[collect] 하위 단위 {created}건 생성") + return existing + + +# ---- 단계 5: fact / 사진 적재 ---------------------------------------------- +async def store_facts(user_info, place_id: str, sources: list, unit_map: dict) -> dict: + """수집값을 fact 로 적재한다. + + ★ FactService 를 그대로 통과시킨다 — 업종 스키마 검증 · 출처 필수 · LLM 제한 · + 정정본 보호 · 노출값 유지가 전부 거기 있다. 크롤러가 우회할 수 있는 뒷문을 만들지 않는다. + """ + service = FactService(_fact_crud, _place_crud) + stat = {"stored": 0, "refreshed": 0, "candidate": 0, "rejected": 0, "by_reason": {}} + + for source in sources: + for cf in source.facts: + unit_id = unit_map.get(cf.unit_name) if cf.scope == "unit" else None + if cf.scope == "unit" and unit_id is None: + stat["rejected"] += 1 + stat["by_reason"]["UNIT_NOT_FOUND"] = stat["by_reason"].get("UNIT_NOT_FOUND", 0) + 1 + continue + req = Req_UpsertFact( + key=cf.key, + value=cf.value, + unit_id=unit_id, + source_type=SourceType.CRAWL, + source_url=cf.source_url, + ) + res = await service.upsert_fact(user_info, place_id, req) + if not res.result.success: + stat["rejected"] += 1 + stat["by_reason"][res.result.desc] = stat["by_reason"].get(res.result.desc, 0) + 1 + continue + stat["stored"] += 1 + if res.outcome is not None and res.outcome.name == "REFRESHED": + stat["refreshed"] += 1 + elif res.outcome is not None and res.outcome.name.startswith("CANDIDATE"): + stat["candidate"] += 1 + return stat + + +async def store_media(place_id: str, sources: list, unit_map: dict) -> dict: + """수집한 사진을 적재한다. 같은 origin_url 은 다시 넣지 않는다(재수집 멱등). + + ★ source_type=CRAWL 과 origin_url 을 반드시 남긴다 — 이미지 재게시 권리가 미결이라 + 결론에 따라 발행 시 통째로 걸러낼 수 있어야 한다(docs/DECISIONS.md 1-2). + ★ Vision 분석 전이므로 status 는 PENDING_REVIEW 다. 사람 확인 큐로 간다.""" + from sqlalchemy import select + + err, rows = await DB_SESSION_MNG.execute_lambda( + media.DBType(), + DBWRType.DB_READ.value, + lambda s: DB_SESSION_MNG.execute( + s, select(media).where(media.place_id == uuid.UUID(place_id), media.deleted == False) # noqa: E712 + ), + ) + seen = {r.origin_url for r in (rows or []) if r.origin_url} if err == ErrorType.SUCCESS else set() + + stat = {"stored": 0, "skipped_duplicate": 0} + for source in sources: + for order, cm in enumerate(source.media): + if cm.origin_url in seen: + stat["skipped_duplicate"] += 1 + continue + row = media( + place_id=uuid.UUID(place_id), + unit_id=unit_map.get(cm.unit_name), + url=cm.origin_url, # Vision·재게시 결론 전까지는 원본 URL 을 그대로 둔다 + origin_url=cm.origin_url, + source_type=SourceType.CRAWL.value, + source_url=cm.source_url, + label=cm.label, + status=MediaStatus.PENDING_REVIEW.value, + sort_order=order, + ) + run_err = await DB_SESSION_MNG.execute_lambda_run( + [media.DBType()], + [lambda s, r=row: DB_SESSION_MNG.insert(s, r, raise_error=False)], + ) + if run_err == ErrorType.SUCCESS: + seen.add(cm.origin_url) + stat["stored"] += 1 + return stat + + +# ---- 오케스트레이션 -------------------------------------------------------- +async def run_collect(job: dict) -> dict: + """COLLECT 잡 핸들러. 반환값이 jobs.result 에 저장돼 폴링·감사에 쓰인다.""" + payload = job["payload"] + place_id = payload["place_id"] + company_id = payload["company_id"] + + err, place = await DB_SESSION_MNG.execute_lambda( + places.DBType(), + DBWRType.DB_READ.value, + lambda s: _place_crud.get_place(s, uuid.UUID(company_id), uuid.UUID(place_id)), + ) + if err != ErrorType.SUCCESS or place is None: + raise CollectAborted(f"사업장을 찾을 수 없다: {place_id}") + # ★ 동일 업소 검증 게이트 — 잡 실행 시점에도 다시 확인한다(적재 후 취소됐을 수 있다). + if place.verified_at is None: + raise CollectAborted("동일 업소 검증(verify) 전에는 수집하지 않는다 — 남의 가게가 섞인다") + + result: dict = {"place_id": place_id} + result["discover"] = await discover_links( + place, + place_id, + include_perplexity=bool(payload.get("discover_channels", False)), + ) + targets, result["confirm"] = await confirm_targets(place, place_id, payload.get("link_ids")) + + # ★ 자동 해석 실패를 사장님에게 알리는 유일한 창구. + # 지금 네이버 플레이스는 "URL 만 있으면 100%, 상호로 찾는 건 4곳 중 3곳" 이다. + # 못 찾았을 때 조용히 넘어가면 사장님은 "수집했는데 아무것도 안 나왔다"만 본다 — + # 실제로 해야 할 일(네이버 지도에서 내 가게 주소를 복사해 붙여넣기)을 화면이 말해줄 수 + # 있도록 결과에 싣는다. 판정 기준은 "지금 긁을 네이버 플레이스 링크가 있느냐" 다: + # 자동 해석이 실패해도 사장님이 이미 붙여넣었으면 알릴 이유가 없다. + result["naver_place_missing"] = not any( + link.channel == LinkChannel.NAVER_PLACE.value for link in targets + ) + + if not targets: + result["note"] = "크롤링 대상이 없다(어댑터가 처리할 수 있는 확정 URL 0건)" + await _finish(place_id, company_id, PlaceStatus.REVIEW) + return result + + # ★ 이미 충분하면 크롤링 자체를 건너뛴다(force 가 아닐 때). + before = await coverage(place, place_id) + if before["enough"] and not payload.get("force"): + result["coverage"] = before + result["note"] = "이미 필수 항목이 다 차 있다 — 크롤링 생략(force=true 로 강제 가능)" + await _finish(place_id, company_id, PlaceStatus.REVIEW) + LOG.i(f"[collect] 충분함 place={place_id} {before['covered']}/{before['total']} — 크롤링 생략") + return result + + from common.models.gmodel import UserInfo + + actor = UserInfo( + user_id=payload.get("requested_by") or str(place.verified_by or uuid.uuid4()), + id="collector", + company_id=company_id, + role=1, + ) + + # ★ 링크를 하나씩 긁고 **바로 적재한 뒤** 충분한지 본다. + # 전부 긁어놓고 나중에 적재하면 "이미 충분한데 더 긁는" 낭비를 못 막는다. + # 단계마다 커밋되므로 중간에 죽어도 여기까지의 결과는 남는다. + fetch_stat = {"fetched": 0, "failed": 0, "no_adapter": 0, "skipped_enough": 0, "stopped_early": False} + facts_stat = {"stored": 0, "refreshed": 0, "candidate": 0, "rejected": 0, "by_reason": {}} + media_stat = {"stored": 0, "skipped_duplicate": 0} + unit_total = 0 + + for index, link in enumerate(targets): + if index > 0: + cov = await coverage(place, place_id) + if cov["enough"]: + fetch_stat["skipped_enough"] = len(targets) - index + fetch_stat["stopped_early"] = True + LOG.i(f"[collect] 필수 항목 {cov['covered']}/{cov['total']} 확보 — " + f"남은 링크 {fetch_stat['skipped_enough']}건 크롤링 생략") + break + + source, outcome = await fetch_one(link) + fetch_stat[outcome] += 1 + if source is None: + continue + + # ★ 수집 원문을 링크에 남긴다 — fact 가 아니라 '생성 근거' 자리다. + # intro 같은 allow_llm 필드에 원문을 넣으면 발행본이 원문으로 덮인다(2026-08-31 사고). + if (source.text or "").strip(): + await DB_SESSION_MNG.execute_lambda_claim( + place_links.DBType(), + lambda sess, u=link.url, t=source.text: _place_crud.set_link_raw( + sess, uuid.UUID(place_id), u, {"text": t[:8000]}, + ), + ) + + unit_map = await ensure_units(place_id, [source]) + unit_total = max(unit_total, len(unit_map)) + f = await store_facts(actor, place_id, [source], unit_map) + m = await store_media(place_id, [source], unit_map) + for k in ("stored", "refreshed", "candidate", "rejected"): + facts_stat[k] += f[k] + for reason, n in f["by_reason"].items(): + facts_stat["by_reason"][reason] = facts_stat["by_reason"].get(reason, 0) + n + media_stat["stored"] += m["stored"] + media_stat["skipped_duplicate"] += m["skipped_duplicate"] + + result["fetch"] = fetch_stat + result["units"] = unit_total + result["facts"] = facts_stat + result["media"] = media_stat + result["coverage"] = await coverage(place, place_id) + + # 사진이 들어왔으면 분석을 이어서 건다 — 수집과 분석은 각각 몇 분이라 한 잡에 묶지 않는다. + # (묶으면 분석에서 죽었을 때 수집까지 다시 하게 되고, 유료 API 를 두 번 태운다.) + if result["media"]["stored"] > 0: + result["vision_job_id"] = await _enqueue_vision(place_id, company_id) + + await _finish(place_id, company_id, PlaceStatus.REVIEW) + LOG.i(f"[collect] 완료 place={place_id} fact {result['facts']['stored']}건 · 사진 {result['media']['stored']}장") + return result + + +async def _finish(place_id: str, company_id: str, status: PlaceStatus): + """수집이 끝나면 사업장을 검수 대기로 돌린다 — 수집값은 전부 후보라 사람이 봐야 한다.""" + await DB_SESSION_MNG.execute_lambda_claim( + places.DBType(), + lambda s: _place_crud.update_place( + s, uuid.UUID(company_id), uuid.UUID(place_id), {"status": status.value} + ), + ) + + +async def _enqueue_vision(place_id: str, company_id: str) -> str | None: + """사진 분석 잡을 적재한다. 키가 없거나 중복이면 조용히 건너뛴다(수집 자체는 성공이다).""" + from common.enums import JobType + from crud.job_crud import JobQueue + from services.external import gemini + from services.job_service import enqueue_job + + if not gemini.is_configured(): + LOG.i("[collect] GEMINI_API_KEY 미설정 — 사진 분석 건너뜀(사진은 확인 큐에 남는다)") + return None + job_id, _created = await enqueue_job( + JobQueue(), JobType.VISION, + {"place_id": place_id, "company_id": company_id}, + dedupe_key=f"vision:{place_id}", + ) + return job_id diff --git a/backend/services/collector/__init__.py b/backend/services/collector/__init__.py new file mode 100644 index 0000000..76a5ac3 --- /dev/null +++ b/backend/services/collector/__init__.py @@ -0,0 +1,46 @@ +"""수집 파이프라인의 소스 어댑터 계층. + +어댑터는 URL 하나를 받아 RawSource 하나를 돌려준다. 어디서 긁어오든(가짜든 실제든) +결과 모양이 같으므로, 그 뒤 단계(fact 후보 적재 · 사람 확인 큐 · 사이트 빌드)는 +수집 방식이 바뀌어도 손대지 않는다. + +★ Phase 1 은 MockAdapter 만 등록한다 — 크롤링 법적 검토 대기(docs/DECISIONS.md 1-1). + 캡차 우회 · 봇 탐지 우회 · IP 회전은 검토 결과와 무관하게 영구 금지다. +""" +from services.collector.base import ( + AdapterDisabled, + AdapterNotFound, + CollectedFact, + CollectedMedia, + CollectError, + FetchFailed, + RawSource, + SourceAdapter, +) +from services.collector.mock_adapter import MockAdapter +from services.collector.registry import ( + ENABLED_ADAPTERS, + REGISTRY, + AdapterRegistry, + adapter_ids, + get_adapter, + log_registry, +) + +__all__ = [ + "ENABLED_ADAPTERS", + "REGISTRY", + "AdapterDisabled", + "AdapterNotFound", + "AdapterRegistry", + "CollectError", + "CollectedFact", + "CollectedMedia", + "FetchFailed", + "MockAdapter", + "RawSource", + "SourceAdapter", + "adapter_ids", + "get_adapter", + "log_registry", +] diff --git a/backend/services/collector/base.py b/backend/services/collector/base.py new file mode 100644 index 0000000..800bd47 --- /dev/null +++ b/backend/services/collector/base.py @@ -0,0 +1,153 @@ +"""수집 어댑터 계약 — '어디서 긁어오든 결과 모양은 하나' 를 강제한다. + +어댑터는 URL 하나를 받아 RawSource 하나를 돌려준다. 그 안에는 원문과 함께 +**출처(source_url)** 가 반드시 들어 있다. 수집된 값이 fact 로 넘어갈 때 +출처 없이 넘어가면 그 사실은 검증도 추적도 불가능해지기 때문에, +여기서 구조적으로 막는다(RawSource 가 생성 시점에 모든 fact/media 에 출처를 찍는다). + +어댑터를 늘리는 방법은 registry.py 에 등록하는 것뿐이다. 이 파일은 계약만 정의한다. +""" +from dataclasses import dataclass, field +from datetime import datetime, timezone +from typing import Optional, Protocol, runtime_checkable + +from common.enums import LinkChannel + + +# ---- 도메인 예외 ----------------------------------------------------------- +class CollectError(RuntimeError): + """수집 계층 공통 예외.""" + + +class AdapterNotFound(CollectError): + """이 URL 을 처리할 어댑터가 없다. → ErrorType.COLLECT_ADAPTER_NOT_FOUND""" + + +class AdapterDisabled(CollectError): + """어댑터는 존재하나 이 환경에서 꺼져 있다(법무 검토 전 등). → ErrorType.COLLECT_ADAPTER_DISABLED""" + + +class FetchFailed(CollectError): + """가져오기 자체가 실패했다(네트워크·파싱). → ErrorType.COLLECT_FETCH_FAILED""" + + +# ---- 수집 결과 구성요소 ----------------------------------------------------- +@dataclass +class CollectedFact: + """수집된 fact 후보 1건. + + scope='place' 면 사업장 단위, 'unit' 이면 객실·메뉴·프로그램 단위다. + unit 단위는 같은 key 가 단위 수만큼 반복되므로(A동 기준인원 / B동 기준인원) + dict 가 아니라 리스트로 모은다. unit_name 은 place.units.name 과 맞춰 매핑하는 힌트다. + + source_url 은 RawSource 가 생성 시점에 찍어준다 — 비워둔 채로 만들어도 출처 없이 흘러가지 않는다. + """ + + key: str + value: Optional[str] + scope: str = "place" # place | unit + unit_name: Optional[str] = None # scope='unit' 일 때 어느 단위 것인지 + source_url: str = "" # RawSource.__post_init__ 이 채운다 + + def __post_init__(self): + if self.scope not in ("place", "unit"): + raise CollectError(f"CollectedFact.scope 값 오류: {self.scope} (place|unit)") + if self.scope == "unit" and not self.unit_name: + raise CollectError(f"unit 스코프 fact 는 unit_name 이 필요하다: key={self.key}") + + +@dataclass +class CollectedMedia: + """수집된 사진 1장. + + origin_url 은 ★ 반드시 남긴다 — 크롤링 이미지의 재게시 권리가 미결이라(docs/DECISIONS.md 1-2), + 결론에 따라 출처별로 걸러낼 수 있어야 한다. + label 은 Gemini Vision 이 확정하기 전의 후보 라벨(페이지에서 주운 캡션 등)일 뿐이다. + + license 는 **출처가 라이선스를 명시한 경우에만** 채운다(예: TourAPI 의 공공누리 `Type1`/`Type3`). + ★ 왜 필요한가 — 공공누리 제3·4유형은 **변경 금지**다. 크롭·리사이즈도 변형에 해당할 수 있어 + 썸네일을 만들면 조건을 어긴다. 어느 사진이 손대면 안 되는 사진인지는 수집 시점에만 알 수 있으므로 + 여기서 들고 나간다. 값이 None 이면 '라이선스 미상' 이며, 재게시 판단은 여전히 1-2 결론을 따른다. + """ + + origin_url: str + label: Optional[str] = None + unit_name: Optional[str] = None + source_url: str = "" # RawSource.__post_init__ 이 채운다 + license: Optional[str] = None # 출처가 밝힌 이용 조건 코드. 미상이면 None + + def __post_init__(self): + if not (self.origin_url or "").strip(): + raise CollectError("CollectedMedia.origin_url 이 비었다 — 출처 없는 사진은 담지 않는다") + + +@dataclass +class RawSource: + """어댑터 1회 수집 결과. + + ok=False 면 error 만 의미가 있다(facts/media 는 비어 있다). 부분 실패도 결과로 돌려주고 + 예외를 던지지 않는 것이 기본이다 — 채널 하나가 막혀도 나머지 수집은 이어져야 한다. + """ + + url: str + adapter_id: str + channel: LinkChannel = LinkChannel.ETC + fetched_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc).replace(tzinfo=None)) + ok: bool = True + error: Optional[str] = None + html: Optional[str] = None # 원문(디버깅·재파싱용) + text: Optional[str] = None # 태그 걷어낸 본문 + facts: list[CollectedFact] = field(default_factory=list) + media: list[CollectedMedia] = field(default_factory=list) + + def __post_init__(self): + if not (self.url or "").strip(): + raise CollectError("RawSource.url 이 비었다 — 출처 없는 수집 결과는 만들 수 없다") + if not (self.adapter_id or "").strip(): + raise CollectError("RawSource.adapter_id 가 비었다") + # ★ 출처 강제: 개별 항목이 출처를 안 들고 있으면 여기서 찍는다. + # fact 로 변환될 때 source_url 이 비면 FACT_SOURCE_REQUIRED 로 거부되므로, + # 그 전에 구조가 보장한다. + for item in (*self.facts, *self.media): + if not item.source_url: + item.source_url = self.url + + @property + def source_url(self) -> str: + """이 결과 전체의 출처. facts/media 의 source_url 과 같은 값이다.""" + return self.url + + def fact_map(self) -> dict: + """사업장 단위 fact 만 {key: value} 로. 단위 스코프는 key 가 겹치므로 제외한다.""" + return {f.key: f.value for f in self.facts if f.scope == "place"} + + def unit_names(self) -> list[str]: + """수집된 단위(객실·메뉴·프로그램) 이름 목록 — 등록 순서 유지.""" + seen: list[str] = [] + for f in self.facts: + if f.scope == "unit" and f.unit_name and f.unit_name not in seen: + seen.append(f.unit_name) + return seen + + @classmethod + def failure(cls, url: str, adapter_id: str, error: str, channel: LinkChannel = LinkChannel.ETC) -> "RawSource": + """실패 결과. 호출측이 예외 처리 없이 ok 만 보고 넘어갈 수 있게 한다.""" + return cls(url=url, adapter_id=adapter_id, channel=channel, ok=False, error=error) + + +# ---- 어댑터 계약 ----------------------------------------------------------- +@runtime_checkable +class SourceAdapter(Protocol): + """수집 소스 어댑터. + + id : 레지스트리 키이자 로그 식별자 + can_handle : 이 URL 을 처리할 수 있는가(부수효과 없이 즉시 판정) + fetch : 실제 수집. 실패는 RawSource.failure 로 돌려주는 것이 기본이고, + 호출 자체가 불가능한 경우(꺼진 어댑터 등)에만 예외를 던진다 + """ + + id: str + + def can_handle(self, url: str) -> bool: ... + + async def fetch(self, url: str) -> RawSource: ... diff --git a/backend/services/collector/mock_adapter.py b/backend/services/collector/mock_adapter.py new file mode 100644 index 0000000..c48a592 --- /dev/null +++ b/backend/services/collector/mock_adapter.py @@ -0,0 +1,290 @@ +"""MockAdapter — 네트워크를 타지 않는 가짜 수집기. **Phase 1 에 등록된 유일한 어댑터.** + +크롤링 법적 검토가 끝나지 않아(docs/DECISIONS.md 1-1) 실제 수집 어댑터를 등록할 수 없다. +그렇다고 수집 이후 단계(fact 검증 전이 · 사람 확인 큐 · 사이트 빌드)를 못 만들 이유는 없으므로, +같은 계약(SourceAdapter)을 만족하는 가짜 소스를 두고 파이프라인 전체를 여기에 물려 돌린다. + +**뱉는 fact key 는 전부 업종 스키마(common/category_schema)에 있는 것만 쓴다.** +스키마에 없는 key 는 fact 기록 단계에서 FACT_INVALID_KEY 로 전부 거부되므로, +그런 목데이터는 파이프라인을 검증하지 못하는 무의미한 데이터가 된다. +그래서 이 파일은 기동 시 자기 목데이터를 스키마와 대조하고, 어긋나면 즉시 예외를 던진다. + +URL 규약 (업종을 URL 에서 읽어 결정적으로 동작한다) + mock://lodging/pension-1 + mock://cafe/cafe-1?channel=naver_place + https://mock.test/restaurant/r-1 +""" +from urllib.parse import parse_qs, urlparse + +from common.category_schema import get_schema +from common.enums import LinkChannel, PlaceCategory +from common.logger import LOG +from services.collector.base import CollectedFact, CollectedMedia, CollectError, RawSource + +_SCHEMES = ("mock",) +_HOSTS = ("mock.test",) + +# URL 에 쓰는 업종 이름 → PlaceCategory. category_schema 의 `name` 과 같은 표기를 쓴다. +_CATEGORY_BY_NAME = { + "lodging": PlaceCategory.LODGING, + "cafe": PlaceCategory.CAFE, + "restaurant": PlaceCategory.RESTAURANT, + "tour_activity": PlaceCategory.TOUR_ACTIVITY, +} + +_CHANNEL_BY_NAME = {c.name.lower(): c for c in LinkChannel} + + +# ---- 업종별 목데이터 -------------------------------------------------------- +# (key, value) — 전부 해당 업종 스키마에 존재하는 key 여야 한다. +# 소개문 계열(intro/room_intro/…)은 넣지 않는다. 그건 수집물이 아니라 generator 가 쓰는 문장이다. +_PLACE_FACTS = { + PlaceCategory.LODGING: [ + ("check_in_time", "15:00"), + ("check_out_time", "11:00"), + ("cancel_policy", "이용 7일 전 100% 환불, 3일 전 50% 환불, 당일 취소 불가"), + ("cooking_allowed", "true"), + ("pet_allowed", "false"), + ("smoking", "false"), + ("parking", "true"), + ("parking_capacity", "10"), + ("wifi", "true"), + ("bbq_available", "true"), + ("bbq_fee", "20000"), + ("breakfast", "false"), + ("reception_hours", "09:00~21:00"), + ], + PlaceCategory.CAFE: [ + ("business_hours", "10:00~22:00"), + ("closed_days", "매주 화요일"), + ("break_time", "15:00~16:00"), + ("last_order", "21:30"), + ("pet_allowed", "true"), + ("kids_allowed", "true"), + ("parking", "true"), + ("parking_free_hours", "2"), + ("seat_count", "40"), + ("wifi", "true"), + ("power_outlet", "true"), + ("takeout", "true"), + ("signature_menu", "흑임자 라떼"), + ("price_range", "5,000~9,000원"), + ], + PlaceCategory.RESTAURANT: [ + ("business_hours", "11:00~21:00"), + ("closed_days", "매주 월요일"), + ("break_time", "15:00~17:00"), + ("last_order", "20:30"), + ("reservation_required", "true"), + ("reservation_channel", "전화 예약"), + ("pet_allowed", "false"), + ("kids_allowed", "true"), + ("room_available", "true"), + ("group_seat_max", "20"), + ("parking", "true"), + ("takeout", "true"), + ("signature_menu", "한우 물회"), + ("price_range", "15,000~30,000원"), + ], + PlaceCategory.TOUR_ACTIVITY: [ + ("operating_hours", "09:00~18:00"), + ("closed_days", "매주 수요일"), + ("reservation_required", "true"), + ("reservation_channel", "네이버 예약"), + ("cancel_policy", "체험 3일 전까지 100% 환불, 당일 취소 불가"), + ("age_limit", "만 7세 이상"), + ("safety_notice", "구명조끼 착용 필수, 음주 후 참여 불가"), + ("weather_dependent", "우천 시 당일 오전 8시에 개별 안내"), + ("what_to_bring", "여벌 옷, 수건"), + ("parking", "true"), + ], +} + +# 단위(객실·메뉴·프로그램)별 목데이터 — {단위이름: [(key, value)]} +_UNIT_FACTS = { + PlaceCategory.LODGING: { + "A동 스탠다드": [ + ("room_type", "스탠다드"), + ("standard_capacity", "2"), + ("max_capacity", "4"), + ("bed_type", "퀸 1"), + ("has_kitchen", "true"), + ("weekday_price", "120000"), + ("weekend_price", "180000"), + ], + "B동 복층": [ + ("room_type", "복층"), + ("standard_capacity", "4"), + ("max_capacity", "6"), + ("bed_type", "퀸 1 + 싱글 2"), + ("has_kitchen", "true"), + ("weekday_price", "190000"), + ("weekend_price", "260000"), + ], + }, + PlaceCategory.CAFE: { + "흑임자 라떼": [("menu_name", "흑임자 라떼"), ("menu_price", "6500")], + "바스크 치즈케이크": [("menu_name", "바스크 치즈케이크"), ("menu_price", "7000")], + }, + PlaceCategory.RESTAURANT: { + "한우 물회": [("menu_name", "한우 물회"), ("menu_price", "18000")], + "성게 비빔밥": [("menu_name", "성게 비빔밥"), ("menu_price", "22000"), ("menu_min_order", "2")], + }, + PlaceCategory.TOUR_ACTIVITY: { + "서핑 입문 클래스": [ + ("program_name", "서핑 입문 클래스"), + ("program_duration", "120"), + ("program_capacity", "8"), + ("price_adult", "70000"), + ("price_child", "50000"), + ], + "패들보드 체험": [ + ("program_name", "패들보드 체험"), + ("program_duration", "90"), + ("program_capacity", "6"), + ("price_adult", "55000"), + ], + }, +} + +# 사진 — (라벨 후보, 단위 이름). 단위 이름이 None 이면 사업장 공용 사진. +_MEDIA = { + PlaceCategory.LODGING: [ + ("외관", None), + ("A동 침실", "A동 스탠다드"), + ("A동 거실", "A동 스탠다드"), + ("B동 침실", "B동 복층"), + ("바비큐장", None), + ], + PlaceCategory.CAFE: [ + ("매장 내부", None), + ("테라스", None), + ("흑임자 라떼", "흑임자 라떼"), + ("바스크 치즈케이크", "바스크 치즈케이크"), + ], + PlaceCategory.RESTAURANT: [ + ("매장 외관", None), + ("홀 전경", None), + ("한우 물회", "한우 물회"), + ("성게 비빔밥", "성게 비빔밥"), + ], + PlaceCategory.TOUR_ACTIVITY: [ + ("해변 전경", None), + ("장비 보관소", None), + ("서핑 강습", "서핑 입문 클래스"), + ("패들보드", "패들보드 체험"), + ], +} + + +def _validate_mock_data(): + """목데이터의 모든 key 가 업종 스키마에 있는지 확인한다. 최초 import 시 1회. + + 어긋나면 즉시 예외 — 스키마에 없는 key 로 만든 목데이터는 fact 기록에서 전부 거부되므로, + '테스트는 도는데 실제로는 하나도 안 들어가는' 상태를 배포 전에 드러낸다.""" + for category, rows in _PLACE_FACTS.items(): + schema = get_schema(category) + for key, _value in rows: + spec = schema.get(key) + if spec is None: + raise CollectError(f"MockAdapter 목데이터 오류: {schema.name} 스키마에 없는 key={key}") + if spec.scope != "place": + raise CollectError(f"MockAdapter 목데이터 오류: {schema.name}.{key} 는 place 스코프가 아니다") + + for category, units in _UNIT_FACTS.items(): + schema = get_schema(category) + for unit_name, rows in units.items(): + for key, _value in rows: + spec = schema.get(key) + if spec is None: + raise CollectError(f"MockAdapter 목데이터 오류: {schema.name} 스키마에 없는 key={key} (단위 {unit_name})") + if spec.scope != "unit": + raise CollectError(f"MockAdapter 목데이터 오류: {schema.name}.{key} 는 unit 스코프가 아니다") + + +_validate_mock_data() + + +class MockAdapter: + """가짜 수집기. 같은 URL 이면 항상 같은 결과를 돌려준다(fetched_at 만 다르다). + + 업종은 URL 에서 읽는다 — SourceAdapter.fetch(url) 계약을 그대로 지키면서 + 업종별 목데이터를 고를 수 있게 하기 위함이다. + """ + + id = "mock" + + def can_handle(self, url: str) -> bool: + try: + parsed = urlparse(url or "") + except ValueError: + return False + if parsed.scheme in _SCHEMES: + return True + return parsed.scheme in ("http", "https") and parsed.hostname in _HOSTS + + async def fetch(self, url: str) -> RawSource: + """URL 에서 업종을 읽어 그 업종의 목데이터를 돌려준다. + + 업종을 못 읽으면 예외가 아니라 실패 결과(ok=False)로 돌려준다 — + 채널 하나가 이상해도 나머지 수집이 멈추면 안 된다.""" + if not self.can_handle(url): + return RawSource.failure(url, self.id, f"MockAdapter 가 처리할 수 없는 URL: {url}") + + category = self._category_of(url) + if category is None: + return RawSource.failure(url, self.id, f"URL 에서 업종을 읽지 못했다(가능: {sorted(_CATEGORY_BY_NAME)}): {url}") + + facts = [CollectedFact(key=k, value=v, scope="place") for k, v in _PLACE_FACTS[category]] + for unit_name, rows in _UNIT_FACTS[category].items(): + facts += [CollectedFact(key=k, value=v, scope="unit", unit_name=unit_name) for k, v in rows] + + media = [ + CollectedMedia( + origin_url=f"https://mock.test/img/{category.name.lower()}/{idx}.jpg", + label=label, + unit_name=unit_name, + ) + for idx, (label, unit_name) in enumerate(_MEDIA[category], start=1) + ] + + schema = get_schema(category) + LOG.d(f"[collector:{self.id}] {schema.name} fact {len(facts)}건 · 사진 {len(media)}장 (url={url})") + return RawSource( + url=url, + adapter_id=self.id, + channel=self._channel_of(url), + html=f"

{schema.label} 목데이터

", + text=f"{schema.label} 목데이터", + facts=facts, + media=media, + ) + + # ---- URL 파싱 ---------------------------------------------------------- + @staticmethod + def _category_of(url: str): + """mock://lodging/... 또는 https://mock.test/lodging/... 에서 업종을 읽는다.""" + parsed = urlparse(url) + # mock:// 는 첫 조각이 hostname 으로, https://mock.test/ 는 path 첫 조각으로 들어온다. + candidates = [parsed.hostname or ""] + [p for p in parsed.path.split("/") if p] + for token in candidates: + category = _CATEGORY_BY_NAME.get(token.lower()) + if category is not None: + return category + return None + + @staticmethod + def _channel_of(url: str) -> LinkChannel: + """?channel=yanolja 로 채널을 지정할 수 있다. 없으면 ETC.""" + query = parse_qs(urlparse(url).query) + name = (query.get("channel") or [""])[0].lower() + return _CHANNEL_BY_NAME.get(name, LinkChannel.ETC) + + # ---- 편의 --------------------------------------------------------------- + @staticmethod + def url_for(category, slug: str = "1", channel: str | None = None) -> str: + """이 어댑터가 처리할 수 있는 mock URL 을 만든다(테스트·시드용).""" + cat = category if isinstance(category, PlaceCategory) else PlaceCategory(category) + name = next(n for n, c in _CATEGORY_BY_NAME.items() if c is cat) + suffix = f"?channel={channel}" if channel else "" + return f"mock://{name}/{slug}{suffix}" diff --git a/backend/services/collector/naver_place_adapter.py b/backend/services/collector/naver_place_adapter.py new file mode 100644 index 0000000..3898d07 --- /dev/null +++ b/backend/services/collector/naver_place_adapter.py @@ -0,0 +1,370 @@ +"""네이버 플레이스 어댑터 — 모바일 상세 페이지의 __APOLLO_STATE__ 를 읽는다. + +★ 왜 GraphQL(pcmap-api)이 아니라 모바일 페이지인가 + `o2o-castad-backend/app/utils/nvMapScraper.py` 는 pcmap-api GraphQL 을 직접 친다. + 그 경로는 익명 요청을 IP 단위로 429 로 막는다(호스트·컨테이너 양쪽에서 확인). + 반면 모바일 상세 페이지는 200 을 주고, 같은 데이터가 `window.__APOLLO_STATE__` 에 + 통째로 들어 있다 — 브라우저가 받는 것과 같은 응답을 한 번 받아 파싱할 뿐이다. + 쿠키도 우회 장치도 필요 없다. + +**금지 (docs/DECISIONS.md 1-1, 결론과 무관하게 영구)** + 캡차 우회 · 봇 탐지 우회 · IP 회전. 이 어댑터는 공개 엔드포인트에 평범한 요청 한 번을 + 보내고, 막히면 그대로 실패로 돌려준다. 우회하지 않는다. + +수집물은 전부 **후보**로 들어간다(UNVERIFIED). 사장님이 확인해야 사이트에 나간다 — +그 게이트는 fact 계층이 담당하므로 여기서는 값과 출처만 정확히 만든다. +""" +import json +import os +import re +from typing import Optional + +import httpx + +from common.enums import LinkChannel +from common.logger import LOG +from services.collector.base import CollectedFact, CollectedMedia, RawSource + +DETAIL_URL = "https://m.place.naver.com/{kind}/{place_id}/home" +REQUEST_TIMEOUT = 30 +MAX_MEDIA = 30 + +# 업종별 상세 경로. 숙박이 아니면 네이버가 다른 경로를 쓴다 — 순서대로 시도한다. +DETAIL_KINDS = ("accommodation", "place", "restaurant") + +_APOLLO = re.compile(r"window\.__APOLLO_STATE__\s*=\s*(\{.*?\});", re.S) + +_HOSTS = ("map.naver.com", "pcmap.place.naver.com", "m.place.naver.com", "place.naver.com", "naver.me") +_PLACE_ID = re.compile(r"/place/(\d+)") +_PCMAP_ID = re.compile(r"pcmap\.place\.naver\.com/[a-z]+/(\d+)") +# ★ naver.me 단축주소는 /place/ 로 가지 않는다. 앱 딥링크로 리다이렉트되며 id 가 +# 쿼리스트링에 담긴다: m.map.naver.com/appLink.naver?pinId=1273971279&…&id=1273971279 +# 이 형태를 안 보면 사장님이 [공유]로 복사한 주소가 통째로 실패한다(실측). +_QUERY_ID = re.compile(r"[?&](?:pinId|id|entryId)=(\d{6,12})") + +HEADERS = { + "User-Agent": ("Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) " + "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"), + "Accept-Language": "ko-KR,ko;q=0.9", + "Referer": "https://m.place.naver.com/", +} + +# 부정 표현. ★ 이걸 먼저 보지 않으면 "반려동물 동반 **불가**" 가 pet_allowed=true 로 뒤집힌다. +# pet_allowed 는 critical 항목이라(틀리면 예약 클레임) 반드시 부호를 먼저 판정한다. +_NEGATIONS = ("불가", "없음", "없슴", "미제공", "제공하지", "안됨", "안 됨", "불가능", "금지") + +# 네이버가 주는 편의시설 문자열 → 업종 스키마의 bool key. +# +# ★ 표기가 업종마다 다르다. 숙박은 "와이파이", 호텔은 "무선 인터넷", 카페는 "무선인터넷" 으로 온다 — +# 한 표기만 넣으면 있는 시설을 통째로 놓친다(실측: 힐튼에서 wifi 를 못 잡아 fact 가 2건이었다). +# 그래서 실제로 관측된 표기를 전부 적는다. 여기 없는 표현은 fact 로 만들지 않는다 — +# 억지 매핑은 "없다"를 "있다"로 바꾼다. +# +# 여러 업종 스키마에 같은 key 가 있으므로(parking·wifi·pet_allowed) 업종을 가리지 않고 쓴다. +# 스키마에 없는 key 는 fact 기록 단계에서 거부되므로 잘못 들어가도 화면에는 안 나온다. +_CONVENIENCE_BOOL = { + "주차": "parking", + "발렛파킹": "parking", + "발렛": "parking", + "무료주차": "parking", + "와이파이": "wifi", + "무선 인터넷": "wifi", + "무선인터넷": "wifi", + "바비큐": "bbq_available", + "바베큐": "bbq_available", + "취사": "cooking_allowed", + "조식": "breakfast", + "반려동물": "pet_allowed", + "애견동반": "pet_allowed", + "픽업": "pickup_service", + "유아용품": "baby_amenities", + "에어컨": "has_aircon", + "테라스": "terrace", + "포장": "takeout", + "배달": "delivery", + "콘센트": "power_outlet", + "휠체어": "wheelchair_accessible", + "장애인": "wheelchair_accessible", + # ★ "단체 이용 가능"은 여기 넣지 않는다. 스키마의 group_seat_max 는 **인원수**(number)라 + # true 를 넣으면 "단체석 최대 true명"이 된다. 값의 형이 다르면 매핑하지 않는다. +} + +# 업종을 가리지 않고 "영업시간" 자리를 차지하는 key. 스키마에 없는 것은 기록 단계에서 걸러진다. +_HOURS_KEYS = ("business_hours", "operating_hours", "reception_hours") + +# ★ 요금표(`Menu:*`) 항목 이름 앞에 붙는 요일 구분. +# 네이버는 모텔·펜션의 요금을 "평일 대실 / 주말(금,토) 숙박" 처럼 **요일 × 상품** 으로 준다. +# 이걸 이름 그대로 단위로 만들면 같은 상품이 요일 수만큼 쪼개져 "객실 4개"가 된다 — +# 실제로는 상품 2개(대실·숙박)에 주중·주말 요금이 각각 붙은 것이다. +# 그래서 요일 토큰을 떼어 **상품 이름으로 묶고**, 요금은 weekday/weekend 로 갈라 담는다. +_WEEKDAY_TOKENS = ("평일", "주중") +_WEEKEND_TOKENS = ("주말", "금토", "토일", "공휴일") +# 요일 토큰과, 바로 뒤에 붙는 괄호 보충설명("주말(금,토)")까지 한 번에 걷어낸다. +_DAY_TAG = re.compile(rf"({'|'.join(_WEEKDAY_TOKENS + _WEEKEND_TOKENS)})\s*(\([^)]*\))?\s*") + + +class NaverPlaceAdapter: + """네이버 플레이스 상세 → fact·사진 후보.""" + + id = "naver_place" + + def _headers(self) -> dict: + """요청 헤더. 쿠키는 있으면 얹고 없으면 그냥 간다. + + ★ NAVER_COOKIES 는 **우회 장치가 아니다**. 로그인 없이도 응답이 오지만 익명 요청은 + 자주 429 로 막히므로, 정상적으로 보유한 세션을 그대로 쓰는 통로만 열어둔다. + IP 회전·핑거프린트 위조 같은 봇 탐지 우회는 하지 않는다(docs/DECISIONS.md 1-1). + """ + headers = dict(HEADERS) + cookies = os.getenv("NAVER_COOKIES", "").strip() + if cookies: + headers["Cookie"] = cookies + return headers + + def can_handle(self, url: str) -> bool: + u = (url or "").lower() + return any(h in u for h in _HOSTS) + + async def fetch(self, url: str) -> RawSource: + channel = LinkChannel.NAVER_PLACE + try: + place_id = await self._resolve_place_id(url) + except Exception as ex: + return RawSource.failure(url, self.id, f"place id 를 찾지 못했다: {ex}", channel) + + try: + state = await self._load_state(place_id) + except Exception as ex: + return RawSource.failure(url, self.id, str(ex), channel) + + base = state.get(f"PlaceDetailBase:{place_id}") or next( + (v for k, v in state.items() if k.startswith("PlaceDetailBase")), None + ) + if not base: + return RawSource.failure(url, self.id, "응답에 PlaceDetailBase 가 없다", channel) + + facts = self._to_facts(base, state) + media = self._to_media(state) + + LOG.i(f"[naver_place] {base.get('name')} — fact {len(facts)}건 · 사진 {len(media)}장 (id={place_id})") + return RawSource( + url=url, + adapter_id=self.id, + channel=channel, + # ★ 소개 원문은 fact 가 아니라 여기로 나간다 — 생성 근거로만 쓰인다. + # 업소가 직접 쓴 description 을 앞에, 한 줄 요약(microReviews)을 뒤에 붙인다. + text=" ".join( + x for x in ( + str(base.get("description") or "").strip(), + *(base.get("microReviews") or []), + ) if x + ), + facts=facts, + media=media, + ) + + # ---- 내부 ---------------------------------------------------------- + async def _resolve_place_id(self, url: str) -> str: + """URL 에서 place id 를 뽑는다. + + ★ 형태가 세 가지다 — 하나라도 빠지면 사장님이 복사한 주소가 통째로 실패한다. + .../place/1133638931 지도·플레이스 상세 + pcmap.place.naver.com/accommodation/… PC 지도 + ?pinId=1273971279 naver.me 단축주소가 풀린 앱 딥링크 + 단축주소는 서버가 한 번 따라가서 최종 주소를 본다. + """ + found = self._match_id(url) + if found: + return found + + # 단축주소·리다이렉트. naver.me 뿐 아니라 다른 짧은 형태도 한 번은 따라가 본다. + try: + async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT, follow_redirects=True) as client: + res = await client.get(url, headers=self._headers()) + found = self._match_id(str(res.url)) or self._match_id(res.text[:20000]) + if found: + return found + except httpx.HTTPError as ex: + raise ValueError(f"주소를 따라가지 못했다: {ex}") + + raise ValueError(f"place id 없음: {url}") + + @staticmethod + def _match_id(text: str) -> Optional[str]: + m = _PLACE_ID.search(text) or _PCMAP_ID.search(text) or _QUERY_ID.search(text) + return m.group(1) if m else None + + async def _load_state(self, place_id: str) -> dict: + """모바일 상세 페이지에서 __APOLLO_STATE__ 를 뽑는다. + + 업종에 따라 경로가 달라서(accommodation / place / restaurant) 200 이 올 때까지 순서대로 친다. + ★ 막히면 그대로 실패로 돌려준다 — 재시도 폭주도 우회도 하지 않는다. + """ + last = "알 수 없는 오류" + try: + async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT, follow_redirects=True) as client: + for kind in DETAIL_KINDS: + res = await client.get( + DETAIL_URL.format(kind=kind, place_id=place_id), headers=self._headers() + ) + if res.status_code == 429: + last = "네이버가 요청을 제한했다(429). 잠시 후 재시도" + continue + if res.status_code != 200: + last = f"HTTP {res.status_code} ({kind})" + continue + m = _APOLLO.search(res.text) + if not m: + last = f"__APOLLO_STATE__ 를 찾지 못했다 ({kind})" + continue + return json.loads(m.group(1)) + except httpx.TimeoutException: + raise RuntimeError(f"{REQUEST_TIMEOUT}s 안에 응답이 없다") + except httpx.HTTPError as ex: + raise RuntimeError(f"네트워크 오류: {ex}") + raise RuntimeError(last) + + def _to_facts(self, base: dict, state: dict) -> list[CollectedFact]: + """★ 스키마에 있는 key 만 만든다. 없는 key 는 fact 기록 단계에서 통째로 거부된다.""" + facts: list[CollectedFact] = [] + + # ★ 소개문은 두 자리에 온다. microReviews(짧은 한 줄 요약)가 없어도 + # description(업소가 직접 쓴 소개글)이 차 있는 경우가 있다 — 조이모텔은 둘 다 + # 비었지만, 한쪽만 보면 있는 소개문을 통째로 놓친다. 순서는 업소가 쓴 글이 우선이다. + # ★ intro(소개문)는 수집하지 않는다 — allow_llm=True, 즉 LLM 의 출력 칸이다(절대규칙 7). + # 수집한 원문은 RawSource.text 로 나가 생성 근거로만 쓰인다. + + # ★ 숙박은 체크인·체크아웃이 별도 블록에 있다(Naverhotel3HotelData). 이 둘은 critical 이라 + # 놓치면 사장님이 손으로 채워야 하고, 비면 AI 검색이 OTA 설명을 대신 인용한다. + hotel = next((v for k, v in state.items() if k.startswith("Naverhotel3HotelData")), None) + if hotel: + for field, key in (("checkInStr", "check_in_time"), ("checkOutStr", "check_out_time")): + value = str(hotel.get(field) or "").strip() + if value: + facts.append(CollectedFact(key=key, value=value)) + + # 영업시간. 업종마다 key 가 달라 스키마에 있는 것만 남는다(없는 key 는 기록 단계에서 거부). + hours = self._business_hours(state) + if hours: + for key in _HOURS_KEYS: + facts.append(CollectedFact(key=key, value=hours)) + + # 편의시설 신호는 두 곳에 흩어져 있다 — + # base.conveniences 간단 태그("주차") + # InformationFacilities:* 상세 시설 목록("와이파이", "개별샤워실", …) + # 둘을 합쳐서 본다. 한쪽만 보면 있는 시설을 놓친다. + labels = [str(x) for x in (base.get("conveniences") or [])] + labels += [ + str(v.get("name") or v.get("i18nName") or "") + for k, v in state.items() + if k.startswith("InformationFacilities") + ] + + # 항목 하나에서 (key, 부호)를 읽는다. + # + # ★ 목록에 없다고 "없다"로 단정하지 않는다 — 네이버가 안 적었을 뿐일 수 있다. + # 반대로 "불가/없음"이 적혀 있으면 그건 명시적인 '아니오'이므로 false 로 담는다. + # 둘을 구분하지 못하면 "반려동물 동반 불가"가 "동반 가능"으로 뒤집힌다. + seen: set[str] = set() + for text in labels: + if not text: + continue + negated = any(neg in text for neg in _NEGATIONS) + for needle, key in _CONVENIENCE_BOOL.items(): + if needle not in text or key in seen: + continue + seen.add(key) + facts.append(CollectedFact(key=key, value="false" if negated else "true")) + + facts.extend(self._to_unit_facts(state)) + return facts + + def _to_unit_facts(self, state: dict) -> list[CollectedFact]: + """요금표(`Menu:*`) → 단위(객실·메뉴·프로그램) 스코프 fact. + + ★ 왜 필요한가 + 이 자리를 아무도 읽지 않아서 place.units 가 전 사업장 0건이었다 — 발행본의 + '객실 안내' 가 영구히 비어 있었다. 수집 파이프라인(ensure_units)은 이미 + unit 스코프 fact 의 unit_name 으로 단위를 만든다. 없던 것은 그 입력뿐이다. + + ★ 요일 × 상품을 상품으로 묶는다. + "평일 대실 / 주말(금,토) 대실 / 평일 숙박 / 주말(금,토) 숙박" 은 객실 4개가 아니라 + 상품 2개(대실·숙박)다. 요일 토큰을 떼어 묶고 요금만 주중·주말로 나눠 담는다. + + ★ 요일 표기가 없는 요금은 **담지 않는다.** + 스키마의 요금 key 는 weekday_price·weekend_price 뿐이라, 요일이 안 적힌 값을 + 아무 쪽에나 넣으면 출처에 없는 조건을 우리가 지어내는 것이 된다. 손님이 그 금액으로 + 오면 클레임이다 — 이름(room_type)만 담고 요금은 사장님이 채운다. + """ + rows = [v for k, v in state.items() if k.startswith("Menu") and isinstance(v, dict)] + rows.sort(key=lambda v: int(v.get("index") or 0)) + + out: list[CollectedFact] = [] + seen_names: list[str] = [] + for row in rows: + raw_name = str(row.get("name") or "").strip() + if not raw_name: + continue + + # 상품 이름 = 요일 토큰을 걷어낸 나머지. "평일" 처럼 요일뿐이면 이름이 없다 → 버린다. + unit_name = _DAY_TAG.sub("", raw_name).strip(" -·/") or "" + if not unit_name: + continue + + if unit_name not in seen_names: + seen_names.append(unit_name) + # room_type 은 숙박 스키마의 unit 필수 필드다. 이름 자체가 상품 구분이므로 그대로 싣는다. + out.append(CollectedFact( + key="room_type", value=unit_name, scope="unit", unit_name=unit_name, + )) + + # 요금. 네이버는 문자열 숫자("20000")로 준다 — 표기는 렌더 단계(format_value)가 만든다. + price = str(row.get("price") or "").strip().replace(",", "") + if not price.isdigit(): + continue + if any(t in raw_name for t in _WEEKEND_TOKENS): + price_key = "weekend_price" + elif any(t in raw_name for t in _WEEKDAY_TOKENS): + price_key = "weekday_price" + else: + # 요일이 안 적힌 요금 — 위 주석대로 지어내지 않는다. + LOG.i(f"[naver_place] 요일 표기 없는 요금은 건너뛴다: {raw_name} ({price})") + continue + out.append(CollectedFact( + key=price_key, value=price, scope="unit", unit_name=unit_name, + )) + + if out: + LOG.i(f"[naver_place] 요금표 → 단위 {len(seen_names)}개 · fact {len(out)}건") + return out + + def _business_hours(self, state: dict) -> str: + """영업시간 한 줄. 네이버가 요일별로 쪼개 주면 그대로 이어 붙인다. + + ★ 파싱해서 재조립하지 않는다 — "매일 09:00~21:00" 과 "평일만" 을 구조화하려다 + 틀리면 손님이 헛걸음한다. 원문 표기를 그대로 옮기고 판단은 사장님이 한다. + """ + rows = [v for k, v in state.items() if "BusinessHour" in k or "NewBusinessHour" in k] + parts: list[str] = [] + for row in rows: + if not isinstance(row, dict): + continue + day = str(row.get("day") or row.get("dayOfWeek") or "").strip() + span = str(row.get("businessHours") or row.get("time") or "").strip() + text = f"{day} {span}".strip() if day else span + if text and text not in parts: + parts.append(text) + return " · ".join(parts)[:500] + + def _to_media(self, state: dict) -> list[CollectedMedia]: + """상단 사진. 업소가 올린 것(mediaSource='business')을 앞에 둔다 — + 방문자 리뷰 사진보다 재게시 근거가 분명하다(docs/DECISIONS.md 1-2).""" + items = [v for k, v in state.items() if k.startswith("PlaceDetailTopPhotoItem")] + items.sort(key=lambda v: 0 if v.get("mediaSource") == "business" else 1) + + out: list[CollectedMedia] = [] + for item in items[:MAX_MEDIA]: + origin = item.get("originalUrl") or item.get("thumbnailUrl") + if origin: + out.append(CollectedMedia(origin_url=origin, label=item.get("title") or None)) + return out diff --git a/backend/services/collector/registry.py b/backend/services/collector/registry.py new file mode 100644 index 0000000..897830b --- /dev/null +++ b/backend/services/collector/registry.py @@ -0,0 +1,107 @@ +"""어댑터 레지스트리 — 'URL 하나에 어댑터 하나' 를 결정하는 유일한 지점. + +등록된 어댑터 + naver_place 네이버 플레이스 상세(pcmap GraphQL). 이식 출처는 + o2o-castad-backend/app/utils/nvMapScraper.py — 파싱 규칙을 두 벌 두지 않는다. + tour_api 한국관광공사 TourAPI(KorService2). 숙박 32 · 음식점 39. 공식 API 라 재게시가 자유롭고 + 사진마다 공공누리 유형이 붙어 온다 — 상업적 이용 불가 유형은 수집 단계에서 버린다. + static_html 사장님이 확정한 자기 홈페이지. JSON-LD·OpenGraph 만 읽고 robots.txt 를 따른다. + docs/DECISIONS.md 1-1 이 보류했던 어댑터로, 2026-08-28 실측 결론 + (docs/DATA_SOURCE_RESEARCH.md)에 따라 **사장님 확정 URL 한정**으로 등록했다. + mock mock:// 전용. 네트워크 없이 파이프라인 전체를 돌리는 테스트용. + + 켜고 끄는 것은 환경변수 COLLECT_ADAPTERS 다(쉼표 구분). 코드를 고치지 않고 한 채널만 + 내릴 수 있어야 한다 — 특정 사이트가 막히거나 정책이 바뀌었을 때 배포 없이 멈추기 위해서다. + +**금지 (검토 결과와 무관하게 영구)** + 캡차 우회 · 봇 탐지 우회 · IP 회전. 어떤 어댑터도 이걸 구현하지 않는다. + 막히면 폴백 3단계로 간다 — 공식 API → 사장님이 직접 붙여넣기 → 최소 정보로 생성 + 보완 요청. + 수집이 막혔다고 생성 자체를 실패시키지 않는다. +""" +import os +from typing import Optional + +from common.logger import LOG +from services.collector.base import AdapterDisabled, AdapterNotFound, SourceAdapter +from services.collector.mock_adapter import MockAdapter +from services.collector.naver_place_adapter import NaverPlaceAdapter +from services.collector.static_html_adapter import StaticHtmlAdapter +from services.collector.tour_api_adapter import TourApiAdapter + +# 이 환경에서 켜둘 어댑터 id 집합. 등록돼 있어도 여기 없으면 AdapterDisabled 로 막힌다. +ENABLED_ADAPTERS: frozenset = frozenset( + x.strip() for x in os.getenv("COLLECT_ADAPTERS", "mock,naver_place,tour_api,static_html").split(",") if x.strip() +) + + +class AdapterRegistry: + """등록 순서대로 can_handle 을 물어 첫 번째로 손드는 어댑터를 쓴다. + + 순서가 곧 우선순위다 — 좁은 어댑터(특정 도메인)를 먼저, 넓은 어댑터(범용 HTML)를 뒤에 둔다. + """ + + def __init__(self, enabled: Optional[frozenset] = None): + self._adapters: list[SourceAdapter] = [] + self._enabled = ENABLED_ADAPTERS if enabled is None else enabled + + def register(self, adapter: SourceAdapter) -> None: + if any(a.id == adapter.id for a in self._adapters): + raise ValueError(f"어댑터 id 중복: {adapter.id}") + self._adapters.append(adapter) + + def adapter_ids(self) -> list[str]: + """등록된 어댑터 id — 기동 로그·테스트가 '지금 뭐가 켜져 있나' 를 확인하는 창구.""" + return [a.id for a in self._adapters] + + def enabled_ids(self) -> list[str]: + return [a.id for a in self._adapters if a.id in self._enabled] + + def get_adapter(self, url: str) -> SourceAdapter: + """URL 을 처리할 어댑터. 없으면 AdapterNotFound, 꺼져 있으면 AdapterDisabled.""" + for adapter in self._adapters: + if not adapter.can_handle(url): + continue + if adapter.id not in self._enabled: + raise AdapterDisabled(f"어댑터 '{adapter.id}' 는 이 환경에서 꺼져 있다: {url}") + return adapter + raise AdapterNotFound(f"이 URL 을 처리할 어댑터가 없다: {url}") + + def can_handle(self, url: str) -> bool: + """예외 없이 처리 가능 여부만 — 확정 링크를 수집 대상으로 거를 때 쓴다.""" + try: + self.get_adapter(url) + return True + except (AdapterNotFound, AdapterDisabled): + return False + + +def _register_default() -> AdapterRegistry: + registry = AdapterRegistry() + # 좁은 어댑터(특정 도메인)를 먼저, 넓은 어댑터를 뒤에. mock 은 mock:// 스킴 전용이라 순서 무관. + # ★ static_html 은 http(s) 를 통째로 받는 넓은 어댑터라 **반드시 맨 뒤**다. + # 앞에 두면 네이버 플레이스 URL 까지 이쪽으로 빨려 들어간다. + registry.register(NaverPlaceAdapter()) + registry.register(TourApiAdapter()) + registry.register(MockAdapter()) + registry.register(StaticHtmlAdapter()) + return registry + + +REGISTRY = _register_default() + + +def get_adapter(url: str) -> SourceAdapter: + """기본 레지스트리에서 어댑터를 찾는다.""" + return REGISTRY.get_adapter(url) + + +def adapter_ids() -> list[str]: + return REGISTRY.adapter_ids() + + +def log_registry() -> None: + """기동 로그용 — 이 프로세스가 실제로 긁을 수 있는 소스.""" + ids = REGISTRY.enabled_ids() + LOG.i(f"[collector] 사용 가능 어댑터: {', '.join(ids) if ids else '없음'}") + if ids == ["mock"]: + LOG.w("[collector] MockAdapter 만 켜져 있습니다 — 실제 수집은 일어나지 않습니다") diff --git a/backend/services/collector/static_html_adapter.py b/backend/services/collector/static_html_adapter.py new file mode 100644 index 0000000..f14b20b --- /dev/null +++ b/backend/services/collector/static_html_adapter.py @@ -0,0 +1,530 @@ +"""정적 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 로 **구조적으로** 막는다. 운영자가 실수로 넣어도 안 긁힌다. + +★ 표본 근거 — 왜 이 어댑터가 숙박에서 특히 값이 큰가 + 네이버 지역검색 `link` 필드 충전율(업종별 25건 표본): 숙박 96% 중 자체 도메인 19건, + 음식점 64%, 카페 92% 중 인스타 17건. 숙박은 자체 홈페이지 보유율이 3업종 중 가장 높다. + +**금지 (docs/DECISIONS.md 1-1, 결론과 무관하게 영구)** + 캡차 우회 · 봇 탐지 우회 · IP 회전. 여기에 하나 더 — + **robots.txt 를 확인하고 그대로 따른다.** 사장님 홈페이지라도 예외 없다. + 막히면 실패로 돌려주고 폴백 3단계로 간다(공식 API → 사장님 붙여넣기 → 최소 정보 생성). + +★ 값을 만드는 원칙 + 구조화된 것(JSON-LD schema.org, OpenGraph)만 fact 로 올린다. 본문 텍스트에서 + 키워드를 주워 억지로 매핑하지 않는다 — 유일한 예외가 체크인·체크아웃 시각인데, + 숙박에서 critical 이고 "체크인" 이라는 낱말과 시각이 붙어 있는 형태만 좁게 본다. +""" +import asyncio +import json +import re +import time +from html import unescape +from html.parser import HTMLParser +from typing import Optional +from urllib.parse import urljoin, urlparse +from urllib.robotparser import RobotFileParser + +import httpx + +from common.enums import LinkChannel +from common.logger import LOG +from services.collector.base import CollectedFact, CollectedMedia, RawSource + +# 우리를 밝히는 UA. ★ 브라우저인 척하지 않는다 — robots.txt 판정도 이 이름으로 받는다. +# ★ ASCII 만 쓴다. HTTP 헤더는 latin-1 로 인코딩되므로 한글을 넣으면 +# 요청이 나가기도 전에 UnicodeEncodeError 로 죽는다(실측). +BOT_NAME = "o2o-web4ai-collector" +USER_AGENT = f"{BOT_NAME}/1.0 (+owner-confirmed URL only; contact: owner of the listed business)" + +REQUEST_TIMEOUT = 20 +MAX_BYTES = 3 * 1024 * 1024 # 본문 상한. 넘으면 거기까지만 읽는다. +MAX_MEDIA = 30 +ROBOTS_TTL = 3600 # 호스트당 robots.txt 캐시 수명(초) + +HEADERS = { + "User-Agent": USER_AGENT, + "Accept": "text/html,application/xhtml+xml", + "Accept-Language": "ko-KR,ko;q=0.9", +} + +# ★ 이 호스트들은 이 어댑터가 절대 건드리지 않는다. +# - 전용 어댑터가 따로 있거나(naver_place) +# - 실측·판례로 수집 불가 결론이 난 곳이거나(야놀자·여기어때·카카오맵) +# - 공식 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억 선례 + "dailyhotel.com", "catchtable.co.kr", + "airbnb.co.kr", "airbnb.com", + "booking.com", "agoda.com", "expedia.co.kr", + "instagram.com", "facebook.com", # Graph API(사장님 OAuth)로만 + "baemin.com", "yogiyo.co.kr", "coupangeats.com", + "diningcode.com", "siksinhot.com", "mangoplate.com", +) + +# schema.org 타입 → 우리가 관심 있는 업소인가. 목록에 없는 타입은 fact 를 만들지 않는다. +_LB_TYPES = { + "localbusiness", "lodgingbusiness", "hotel", "motel", "resort", "hostel", + "bedandbreakfast", "campground", "vacationrental", + "restaurant", "cafeorcoffeeshop", "foodestablishment", "bakery", "barorpub", + "touristattraction", "store", +} + +# 부정 표현. ★ naver_place_adapter 와 같은 판정을 쓴다 — "주차 불가" 가 parking=true 로 뒤집히면 +# 업종을 가리지 않고 같은 사고가 난다. +_NEGATIONS = ("불가", "없음", "없슴", "미제공", "제공하지", "안됨", "안 됨", "불가능", "금지", "not available") + +# 편의시설 표기 → 업종 스키마의 bool key. 사장님 홈페이지는 표기가 제각각이라 +# 한국어·영어를 같이 본다. ★ 여기 없는 표현은 fact 로 만들지 않는다. +_AMENITY_BOOL = { + "주차": "parking", "발렛": "parking", "parking": "parking", + "와이파이": "wifi", "무선인터넷": "wifi", "무선 인터넷": "wifi", "wifi": "wifi", "wi-fi": "wifi", + "바비큐": "bbq_available", "바베큐": "bbq_available", "bbq": "bbq_available", + "취사": "cooking_allowed", "조리": "cooking_allowed", + "조식": "breakfast", "breakfast": "breakfast", + "반려동물": "pet_allowed", "애견": "pet_allowed", "pet": "pet_allowed", + "픽업": "pickup_service", + "유아용품": "baby_amenities", "아기": "baby_amenities", + "에어컨": "has_aircon", "냉방": "has_aircon", + "주방": "has_kitchen", "취사시설": "has_kitchen", + "테라스": "terrace", + "포장": "takeout", "테이크아웃": "takeout", + "배달": "delivery", + "콘센트": "power_outlet", + "휠체어": "wheelchair_accessible", "장애인": "wheelchair_accessible", +} + +# 업종마다 "영업시간" 자리를 차지하는 key. 스키마에 없는 것은 fact 기록 단계에서 거부된다. +_HOURS_KEYS = ("business_hours", "operating_hours", "reception_hours") + +# ★ 본문에서 유일하게 허용하는 정규식 — 체크인·체크아웃. +# 숙박에서 critical 이고(틀리면 예약 클레임) 비면 AI 검색이 OTA 설명을 대신 인용한다. +# "체크인" 이라는 낱말 **바로 뒤**의 시각만 본다. 떨어져 있으면 잡지 않는다. +_CHECKIN = re.compile(r"체크\s*인[^0-9]{0,12}((?:오전|오후)?\s*\d{1,2}\s*[:시]\s*\d{0,2})") +_CHECKOUT = re.compile(r"체크\s*아웃[^0-9]{0,12}((?:오전|오후)?\s*\d{1,2}\s*[:시]\s*\d{0,2})") + +_robots_cache: dict[str, tuple[float, Optional[RobotFileParser]]] = {} + + +class _Extract(HTMLParser): + """한 번 훑으면서 JSON-LD · meta · 본문 텍스트를 같이 걷는다. + + 표준 라이브러리만 쓴다 — 이것 하나 때문에 파서 의존성을 새로 얹지 않는다. + """ + + def __init__(self): + super().__init__(convert_charrefs=True) + self.ld_raw: list[str] = [] + self.meta: dict[str, str] = {} + self.title: str = "" + self._text: list[str] = [] + self._skip = 0 # script/style 안쪽 깊이 + self._in_ld = False + self._in_title = False + + def handle_starttag(self, tag, attrs): + a = {k.lower(): (v or "") for k, v in attrs} + if tag in ("script", "style", "noscript"): + self._skip += 1 + if tag == "script" and a.get("type", "").lower().strip() == "application/ld+json": + self._in_ld = True + self.ld_raw.append("") + elif tag == "title": + self._in_title = True + elif tag == "meta": + name = (a.get("property") or a.get("name") or "").lower().strip() + content = a.get("content", "").strip() + if name and content and name not in self.meta: + self.meta[name] = content + + def handle_endtag(self, tag): + if tag in ("script", "style", "noscript"): + self._skip = max(0, self._skip - 1) + self._in_ld = False + elif tag == "title": + self._in_title = False + + def handle_data(self, data): + if self._in_ld: + self.ld_raw[-1] += data + elif self._in_title: + self.title += data + elif not self._skip: + s = data.strip() + if s: + self._text.append(s) + + @property + def text(self) -> str: + return " ".join(self._text) + + +class StaticHtmlAdapter: + """사장님 확정 홈페이지 → fact·사진 후보.""" + + id = "static_html" + + def can_handle(self, url: str) -> bool: + """http(s) 이고, 전용 어댑터·수집 불가 결론이 난 호스트가 아니면 손든다. + + ★ 이 어댑터는 **넓다**. 레지스트리에서 반드시 좁은 어댑터 뒤에 등록해야 한다. + """ + u = (url or "").strip().lower() + if not u.startswith(("http://", "https://")): + return False + host = urlparse(u).netloc.split(":")[0] + if not host: + return False + return not any(host == d or host.endswith("." + d) for d in _DENY_HOSTS) + + async def fetch(self, url: str) -> RawSource: + channel = self._channel(url) + + allowed, why = await self._robots_allows(url) + if not allowed: + # ★ 우회하지 않는다. 사장님 홈페이지라도 robots 가 막으면 그대로 실패다. + return RawSource.failure(url, self.id, f"robots.txt 가 수집을 허용하지 않는다: {why}", channel) + + try: + html = await self._get_html(url) + except Exception as ex: + return RawSource.failure(url, self.id, str(ex), channel) + + parser = _Extract() + try: + parser.feed(html) + except Exception as ex: # 깨진 HTML 도 여기까지 온 만큼은 쓴다 + LOG.w(f"[static_html] HTML 파싱 도중 중단: {ex} ({url})") + + nodes = self._ld_nodes(parser.ld_raw) + biz = self._pick_business(nodes) + + facts = self._to_facts(biz, parser) + media = self._to_media(biz, parser, url) + + if not facts and not media: + return RawSource.failure( + url, self.id, "구조화 데이터(JSON-LD·OpenGraph)가 없어 확신할 수 있는 값을 찾지 못했다", channel + ) + + LOG.i(f"[static_html] {parser.title.strip()[:40] or url} — fact {len(facts)}건 · 사진 {len(media)}장") + return RawSource( + url=url, + adapter_id=self.id, + channel=channel, + text=parser.text[:20000], + facts=facts, + media=media, + ) + + # ---- robots --------------------------------------------------------- + async def _robots_allows(self, url: str) -> tuple[bool, str]: + """robots.txt 를 우리 UA 이름으로 판정한다. + + ★ 못 가져오면 허용으로 본다(관례). 하지만 **가져왔는데 막고 있으면 무조건 따른다.** + 호스트 단위로 캐시해서 페이지마다 다시 묻지 않는다. + """ + parts = urlparse(url) + origin = f"{parts.scheme}://{parts.netloc}" + now = time.monotonic() + + cached = _robots_cache.get(origin) + if cached and now - cached[0] < ROBOTS_TTL: + rp = cached[1] + else: + rp = await self._load_robots(origin) + _robots_cache[origin] = (now, rp) + + if rp is None: + return True, "" + if rp.can_fetch(BOT_NAME, url): + return True, "" + return False, f"{origin}/robots.txt 가 {BOT_NAME} 에게 이 경로를 금지한다" + + async def _load_robots(self, origin: str) -> Optional[RobotFileParser]: + try: + async with httpx.AsyncClient(timeout=10, follow_redirects=True) as client: + res = await client.get(f"{origin}/robots.txt", headers=HEADERS) + if res.status_code != 200: + return None + # HTML 을 돌려주는 서버가 있다(robots.txt 가 없어서 SPA 로 떨어지는 경우). 그건 규칙이 아니다. + body = res.text + if body.lstrip()[:15].lower().startswith((" str: + """HTML 본문. text/html 이 아니거나 상한을 넘으면 거기서 멈춘다. + + ★ 재시도하지 않는다. 429·403 은 그대로 실패로 올린다 — 재시도 폭주가 곧 차단 사유다. + """ + try: + async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT, follow_redirects=True) as client: + async with client.stream("GET", url, headers=HEADERS) as res: + if res.status_code == 429: + raise RuntimeError("서버가 요청을 제한했다(429)") + if res.status_code != 200: + raise RuntimeError(f"HTTP {res.status_code}") + ctype = res.headers.get("content-type", "").lower() + if "html" not in ctype: + raise RuntimeError(f"HTML 이 아니다: {ctype or '알 수 없음'}") + + chunks: list[bytes] = [] + total = 0 + async for chunk in res.aiter_bytes(): + chunks.append(chunk) + total += len(chunk) + if total >= MAX_BYTES: + break + raw = b"".join(chunks) + enc = res.encoding or "utf-8" + return raw.decode(enc, errors="replace") + except httpx.TimeoutException: + raise RuntimeError(f"{REQUEST_TIMEOUT}s 안에 응답이 없다") + except httpx.HTTPError as ex: + raise RuntimeError(f"네트워크 오류: {ex}") + + # ---- JSON-LD -------------------------------------------------------- + @staticmethod + def _ld_nodes(raw_blocks: list[str]) -> list[dict]: + """JSON-LD 블록들을 평평한 dict 목록으로. @graph·배열·중첩을 모두 편다.""" + out: list[dict] = [] + + def walk(node): + if isinstance(node, list): + for x in node: + walk(x) + elif isinstance(node, dict): + out.append(node) + for key in ("@graph", "mainEntity", "itemListElement"): + if key in node: + walk(node[key]) + + for block in raw_blocks: + block = block.strip() + if not block: + continue + try: + walk(json.loads(block)) + except (json.JSONDecodeError, ValueError): + continue # 깨진 블록 하나가 전체를 죽이지 않는다 + return out + + @staticmethod + def _pick_business(nodes: list[dict]) -> Optional[dict]: + """업소를 가리키는 노드 하나. 여러 개면 필드가 가장 많은 것을 쓴다.""" + cands = [] + for n in nodes: + types = n.get("@type") + types = [types] if isinstance(types, str) else (types or []) + if any(str(t).lower() in _LB_TYPES for t in types): + cands.append(n) + return max(cands, key=len) if cands else None + + # ---- fact ----------------------------------------------------------- + def _to_facts(self, biz: Optional[dict], parser: _Extract) -> list[CollectedFact]: + """★ 스키마에 있는 key 만 만든다. 없는 key 는 fact 기록 단계에서 통째로 거부된다.""" + facts: list[CollectedFact] = [] + biz = biz or {} + + # ★ 소개문(intro)은 수집하지 않는다 — allow_llm=True, LLM 의 출력 칸이다(절대규칙 7). + # JSON-LD description·og:description 원문은 RawSource.text 로 나가 + # 생성 근거로만 쓰인다(services/copy_service.py). + + # 영업시간. ★ 재조립하지 않고 원문 표기를 그대로 옮긴다 — + # "매일 09:00~21:00" 과 "평일만" 을 구조화하려다 틀리면 손님이 헛걸음한다. + hours = self._hours(biz) + if hours: + for key in _HOURS_KEYS: + facts.append(CollectedFact(key=key, value=hours)) + + # 체크인·체크아웃. JSON-LD 가 우선이고, 없을 때만 본문 정규식으로 좁게 본다. + for ld_key, our_key, pattern in ( + ("checkinTime", "check_in_time", _CHECKIN), + ("checkoutTime", "check_out_time", _CHECKOUT), + ): + value = self._clean(biz.get(ld_key)) + if not value: + m = pattern.search(parser.text) + value = re.sub(r"\s+", "", m.group(1)) if m else "" + if value: + facts.append(CollectedFact(key=our_key, value=value[:40])) + + # 가격대 · 결제수단 — 값이 그대로 문자열인 것들. + for ld_key, our_key in (("priceRange", "price_range"), ("paymentAccepted", "payment_methods")): + value = self._clean(biz.get(ld_key)) + if value: + facts.append(CollectedFact(key=our_key, value=value[:200])) + + facts.extend(self._bool_facts(biz)) + facts.extend(self._menu_facts(biz)) + return facts + + def _bool_facts(self, biz: dict) -> list[CollectedFact]: + """편의시설 → bool fact. + + ★ 목록에 없다고 "없다"로 단정하지 않는다 — 사장님이 안 적었을 뿐일 수 있다. + 반대로 "불가/없음"이 적혀 있으면 명시적인 '아니오'이므로 false 로 담는다. + """ + labels: list[str] = [] + + for item in self._as_list(biz.get("amenityFeature")): + if isinstance(item, dict): + name = self._clean(item.get("name")) + # LocationFeatureSpecification.value 가 false 면 '없다'는 뜻이다. + if item.get("value") is False: + name = f"{name} 없음" + if name: + labels.append(name) + elif isinstance(item, str): + labels.append(item) + + # schema.org 가 전용 필드로 주는 것들. bool 이면 부호를 그대로 쓴다. + for ld_key, our_key in (("petsAllowed", "pet_allowed"), ("smokingAllowed", "smoking")): + raw = biz.get(ld_key) + if isinstance(raw, bool): + labels.append(f"{ld_key} {'' if raw else '없음'}") + _AMENITY_BOOL.setdefault(ld_key.lower(), our_key) + elif isinstance(raw, str) and raw.strip(): + labels.append(f"{ld_key} {raw}") + _AMENITY_BOOL.setdefault(ld_key.lower(), our_key) + + out: list[CollectedFact] = [] + seen: set[str] = set() + for text in labels: + low = text.lower() + negated = any(neg in low for neg in _NEGATIONS) + for needle, key in _AMENITY_BOOL.items(): + if needle not in low or key in seen: + continue + seen.add(key) + out.append(CollectedFact(key=key, value="false" if negated else "true")) + return out + + def _menu_facts(self, biz: dict) -> list[CollectedFact]: + """hasMenu → 단위(메뉴) 스코프 fact. + + ★ 이름 없는 항목은 담지 않는다 — unit_name 이 비면 base 계약이 예외를 던진다. + 가격은 통화 기호 없이 숫자만 오는 경우가 많아 원문 표기를 그대로 옮긴다. + """ + sections = self._as_list(biz.get("hasMenu")) + self._as_list(biz.get("menu")) + items: list[dict] = [] + for sec in sections: + if isinstance(sec, dict): + items += [x for x in self._as_list(sec.get("hasMenuItem")) if isinstance(x, dict)] + for sub in self._as_list(sec.get("hasMenuSection")): + if isinstance(sub, dict): + items += [x for x in self._as_list(sub.get("hasMenuItem")) if isinstance(x, dict)] + + out: list[CollectedFact] = [] + seen: list[str] = [] + for item in items: + name = self._clean(item.get("name")) + if not name or name in seen: + continue + seen.append(name) + out.append(CollectedFact(key="menu_name", value=name, scope="unit", unit_name=name)) + + offer = item.get("offers") + offer = offer[0] if isinstance(offer, list) and offer else offer + price = self._clean(offer.get("price")) if isinstance(offer, dict) else "" + if price: + out.append(CollectedFact(key="menu_price", value=price[:40], scope="unit", unit_name=name)) + + # ★ menu_intro 도 allow_llm=True 라 수집하지 않는다 — 메뉴 설명 문장은 + # LLM 이 쓰는 칸이다. 원문은 RawSource.text 로 나가 근거로만 쓰인다. + return out + + def _hours(self, biz: dict) -> str: + """openingHours(문자열) / openingHoursSpecification(구조) 둘 다 받는다.""" + parts: list[str] = [] + for x in self._as_list(biz.get("openingHours")): + s = self._clean(x) + if s and s not in parts: + parts.append(s) + for spec in self._as_list(biz.get("openingHoursSpecification")): + if not isinstance(spec, dict): + continue + days = ", ".join( + str(d).rsplit("/", 1)[-1] for d in self._as_list(spec.get("dayOfWeek")) if d + ) + span = f"{self._clean(spec.get('opens'))}~{self._clean(spec.get('closes'))}".strip("~") + text = f"{days} {span}".strip() + if text and text not in parts: + parts.append(text) + return " · ".join(parts)[:500] + + # ---- 사진 ----------------------------------------------------------- + def _to_media(self, biz: Optional[dict], parser: _Extract, base_url: str) -> list[CollectedMedia]: + """JSON-LD image 를 앞에, OpenGraph og:image 를 뒤에. + + ★ origin_url 은 절대 URL 로 만들어 둔다 — 상대경로로 저장하면 나중에 출처를 되짚을 수 없고, + docs/DECISIONS.md 1-2(이미지 재게시 권리) 결론에 따라 걸러낼 수도 없게 된다. + """ + raw: list[str] = [] + for item in self._as_list((biz or {}).get("image")): + if isinstance(item, str): + raw.append(item) + elif isinstance(item, dict): + raw.append(str(item.get("url") or item.get("contentUrl") or "")) + for key in ("og:image", "og:image:secure_url", "twitter:image"): + if parser.meta.get(key): + raw.append(parser.meta[key]) + + out: list[CollectedMedia] = [] + seen: set[str] = set() + for src in raw: + src = (src or "").strip() + if not src or src.startswith("data:"): + continue + absolute = urljoin(base_url, src) + if absolute in seen: + continue + seen.add(absolute) + out.append(CollectedMedia(origin_url=absolute)) + if len(out) >= MAX_MEDIA: + break + return out + + # ---- 잡동사니 -------------------------------------------------------- + @staticmethod + def _channel(url: str) -> LinkChannel: + """사장님 확정 URL 이므로 기본은 공식 홈페이지다. 블로그만 따로 표시한다.""" + u = (url or "").lower() + if any(b in u for b in ("blog.", "/blog", "tistory.com", "brunch.co.kr")): + return LinkChannel.BLOG + return LinkChannel.OFFICIAL_SITE + + @staticmethod + def _as_list(value) -> list: + if value is None: + return [] + return value if isinstance(value, list) else [value] + + @staticmethod + def _clean(value) -> str: + """문자열로 정규화. 숫자·bool 도 받아서 표기를 그대로 남긴다.""" + if value is None or isinstance(value, (dict, list)): + return "" + text = unescape(str(value)) + return re.sub(r"\s+", " ", text).strip() diff --git a/backend/services/collector/tour_api_adapter.py b/backend/services/collector/tour_api_adapter.py new file mode 100644 index 0000000..07f5264 --- /dev/null +++ b/backend/services/collector/tour_api_adapter.py @@ -0,0 +1,409 @@ +"""한국관광공사 TourAPI(KorService2) 어댑터 — 숙박·음식점. + +★ 왜 이 어댑터가 다른 어댑터보다 우선인가 (docs/DATA_SOURCE_RESEARCH.md) + 네이버·카카오·OTA 에서 긁어온 값은 **출처를 밝힐 수 없다**. robots 를 어겼거나 재게시 근거가 없어서다. + 출처를 못 밝히는 사실은 `llms.txt`·`AnswerBlock` 의 "출처와 검증 시각" 신호를 채우지 못하고, + AI 검색이 인용할 이유도 없다(GEO 연구: 인용률을 올리는 요인 1위가 '출처 인용'이다). + + TourAPI 는 반대다 — **무료·이용허락범위 제한없음**이라 재게시에 제약이 없고, 출처를 당당히 밝힐 수 있다. + 같은 사실이라도 여기서 온 것이 값이 더 크다. + (단 '대한민국구석구석' 에 contentId 로 열리는 공개 페이지는 **없다** — 아래 SOURCE_URL 주석 참고.) + +★ 수집 경로 + detailCommon2 개요·홈페이지·좌표·대표사진 + detailIntro2 업종별 소개정보(체크인·주차·취사 / 영업시간·대표메뉴 …) + detailInfo2 숙박은 **객실 단위** 정보(인원·요금·면적·객실사진), 음식점은 반복정보 + detailImage2 추가 사진 + +★ 이미지 저작권 — 여기서 끝낸다 (docs/DECISIONS.md 1-2) + TourAPI 는 사진마다 공공누리 유형(`cpyrhtDivCd`)을 준다. + Type1 출처표시 상업적 이용 O · 변형 O + Type2 출처표시 + 상업적이용금지 상업적 이용 X ← 버린다 + Type3 출처표시 + 변경금지 상업적 이용 O · 변형 X + Type4 출처표시 + 상업적이용금지 + 변경금지 ← 버린다 + 사장님 홈페이지는 **상업적 이용**이므로 Type2·Type4 는 수집 단계에서 통째로 버린다. + Type3 는 담되 `license` 에 표시해 둔다 — 뒤에서 크롭·리사이즈하면 '변경금지' 를 어긴다. + +**금지 (docs/DECISIONS.md 1-1, 결론과 무관하게 영구)** + 캡차 우회 · 봇 탐지 우회 · IP 회전. 여기는 공식 API 라 해당 사항이 없고, 앞으로도 만들지 않는다. +""" +import re +from typing import Optional +from urllib.parse import unquote, urlencode + +import httpx + +from common.enums import LinkChannel +from common.logger import LOG +from config.server_configs import external_api_config +from services.collector.base import CollectedFact, CollectedMedia, RawSource + +BASE_URL = "https://apis.data.go.kr/B551011/KorService2" + +# fact 의 출처로 남기는 주소. **인증키를 뺀** 해당 레코드의 API 주소다. +# +# ★ 왜 '대한민국구석구석' 페이지가 아닌가 (2026-08-31 실측) +# 처음엔 korean.visitkorea.or.kr/detail/ms_detail.do?cotid={contentId} 를 썼는데 **틀렸다.** +# 구석구석의 `cotid` 는 TourAPI 의 `contentid` 와 다른 체계(GUID)라, 어떤 contentId 를 넣어도 +# 같은 크기(7,702B)의 "안내 페이지" 가 돌아온다. 검색 결과 페이지도 전부 JS 렌더라 +# contentId 로 바로 열리는 공개 URL 이 존재하지 않는다. +# +# 그래서 **그 레코드를 정확히 가리키면서 재현 가능한 주소**를 쓴다. 키가 없으면 데이터 대신 +# 인증 오류가 오지만, 자기 키를 가진 사람은 같은 값을 그대로 받아볼 수 있다 — +# 출처의 목적(어디서 왔고 어떻게 확인하는가)은 이것으로 충족된다. +# ★ 인증키는 절대 넣지 않는다. 이 주소는 DB 에 저장되고 발행본에도 나간다. +SOURCE_URL = ( + "https://apis.data.go.kr/B551011/KorService2/detailCommon2" + "?contentId={content_id}&MobileOS=ETC&MobileApp=o2o-web4ai&_type=json" +) +# 화면에 적을 출처 이름. URL 만으로는 무엇인지 알 수 없어서 함께 남긴다. +SOURCE_LABEL = "한국관광공사 TourAPI" + +REQUEST_TIMEOUT = 25 +MAX_MEDIA = 30 + +CONTENT_TYPE_LODGING = "32" +CONTENT_TYPE_RESTAURANT = "39" +_SUPPORTED = (CONTENT_TYPE_LODGING, CONTENT_TYPE_RESTAURANT) + +# ★ 상업적 이용이 허용된 공공누리 유형만 담는다. 목록에 없는 코드는 '모른다' 로 보고 버린다 — +# 새 코드가 생겼을 때 조용히 통과시키는 것보다 빠뜨리는 쪽이 안전하다. +COMMERCIAL_OK_LICENSES = frozenset({"type1", "type3"}) +# 변형(크롭·리사이즈)까지 금지된 유형. 뒤 단계가 이걸 보고 원본 그대로 써야 한다. +NO_DERIVATIVE_LICENSES = frozenset({"type3", "type4"}) + +# 이 어댑터가 받는 주소. 사장님이 붙여넣는 것은 구석구석 주소이고, +# tour:// 는 내부에서 콘텐츠 id 를 바로 지정할 때 쓴다(채널 발견·재수집). +_COTID = re.compile(r"[?&]cotid=([0-9a-zA-Z\-]+)", re.I) +_TOUR_SCHEME = re.compile(r"^tour://(\d+)/(\d+)$", re.I) +_HOSTS = ("visitkorea.or.kr",) + +_BR = re.compile(r"", re.I) +_TAGS = re.compile(r"<[^>]+>") +_HREF = re.compile(r'href=["\']([^"\']+)["\']', re.I) +# "13실", "16명", "대지 면적 11,570㎡" 처럼 숫자에 단위가 붙어 온다. number 필드는 숫자만 남긴다. +_LEADING_NUM = re.compile(r"^\s*([\d,]+(?:\.\d+)?)") + +# ★ "가능 / 불가" 로 시작하는 필드들. 뒤에 괄호 설명이 붙는다: +# parkinglodging = "가능 (객실당 1대 무료 주차)" +# parkingfood = "불가 (인근 주차장 이용)" ← 뒤에 '이용' 이 있다고 true 로 읽으면 안 된다 +# 그래서 **맨 앞 토큰**으로만 부호를 판정한다. 문자열 전체를 훑으면 뒤집힌다(실측). +_NEG_HEAD = ("불가", "없음", "미제공", "불가능", "없슴") +_POS_HEAD = ("가능", "있음", "제공", "무료", "부분") + + +class TourApiAdapter: + """TourAPI 콘텐츠 → fact·사진 후보.""" + + id = "tour_api" + + # ---- 계약 ---------------------------------------------------------- + def can_handle(self, url: str) -> bool: + u = (url or "").strip().lower() + if _TOUR_SCHEME.match(u): + return True + return any(h in u for h in _HOSTS) and bool(_COTID.search(u)) + + async def fetch(self, url: str) -> RawSource: + channel = LinkChannel.ETC + key = (external_api_config.tour_api_key or "").strip() + if not key: + return RawSource.failure(url, self.id, "TOUR_API_KEY 가 설정되지 않았다", channel) + + parsed = self._parse_url(url) + if not parsed: + return RawSource.failure(url, self.id, f"콘텐츠 id 를 찾지 못했다: {url}", channel) + content_id, content_type = parsed + + try: + async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client: + common = await self._call(client, key, "detailCommon2", contentId=content_id) + if not common: + return RawSource.failure(url, self.id, f"detailCommon2 결과 없음(contentId={content_id})", channel) + common = common[0] + + # URL 에 타입이 없으면 공통정보가 알려준다. + content_type = content_type or str(common.get("contenttypeid") or "") + if content_type not in _SUPPORTED: + return RawSource.failure( + url, self.id, + f"지원하지 않는 콘텐츠 타입: {content_type} (숙박 32 · 음식점 39 만 받는다)", + channel, + ) + + intro = await self._call(client, key, "detailIntro2", contentId=content_id, contentTypeId=content_type) + info = await self._call(client, key, "detailInfo2", contentId=content_id, contentTypeId=content_type) + images = await self._call(client, key, "detailImage2", contentId=content_id, imageYN="Y") + except httpx.TimeoutException: + return RawSource.failure(url, self.id, f"{REQUEST_TIMEOUT}s 안에 응답이 없다", channel) + except httpx.HTTPError as ex: + return RawSource.failure(url, self.id, f"네트워크 오류: {ex}", channel) + except RuntimeError as ex: + return RawSource.failure(url, self.id, str(ex), channel) + + source_url = SOURCE_URL.format(content_id=content_id) + intro_row = intro[0] if intro else {} + + facts = self._common_facts(common) + if content_type == CONTENT_TYPE_LODGING: + facts += self._lodging_facts(intro_row) + facts += self._room_facts(info) + else: + facts += self._restaurant_facts(intro_row) + + media = self._media(common, images, info if content_type == CONTENT_TYPE_LODGING else []) + + LOG.i( + f"[tour_api] {common.get('title')} — fact {len(facts)}건 · 사진 {len(media)}장 " + f"(contentId={content_id} type={content_type})" + ) + return RawSource( + url=source_url, + adapter_id=self.id, + channel=channel, + text=self._plain(common.get("overview")), + facts=facts, + media=media, + ) + + # ---- HTTP ---------------------------------------------------------- + async def _call(self, client: httpx.AsyncClient, key: str, op: str, **params) -> list[dict]: + """오퍼레이션 1회. 결과가 없으면 빈 목록 — 없는 것과 실패를 구분한다. + + ★ 포털의 'Encoding' 키를 그대로 넣어도 이중 인코딩되지 않도록 원문으로 되돌린다 + (services/external/tour_api.py 와 같은 처리다). + """ + query = urlencode( + {"serviceKey": unquote(key), "MobileOS": "ETC", "MobileApp": "o2o-web4ai", + "_type": "json", "numOfRows": "50", "pageNo": "1", **params}, + safe="", + ) + res = await client.get(f"{BASE_URL}/{op}?{query}") + if res.status_code != 200: + raise RuntimeError(f"{op} HTTP {res.status_code}") + + try: + payload = res.json() + except ValueError: + # 인증 실패·쿼터 초과는 XML 로 온다. 본문 앞부분을 그대로 올려 원인을 감추지 않는다. + raise RuntimeError(f"{op} 응답이 JSON 이 아니다: {res.text[:160]}") + + header = payload.get("response", {}).get("header", {}) + code = str(header.get("resultCode") or "") + if code not in ("0000", "00"): + raise RuntimeError(f"{op} 실패 [{code}] {header.get('resultMsg')}") + + items = (payload.get("response", {}).get("body", {}).get("items") or {}).get("item") + if isinstance(items, dict): + return [items] + return items or [] + + @staticmethod + def _parse_url(url: str) -> Optional[tuple[str, str]]: + """(contentId, contentTypeId) — 타입을 모르면 빈 문자열.""" + m = _TOUR_SCHEME.match((url or "").strip()) + if m: + return m.group(2), m.group(1) + m = _COTID.search(url or "") + return (m.group(1), "") if m else None + + # ---- 값 다듬기 ------------------------------------------------------- + @classmethod + def _plain(cls, value) -> str: + """
은 줄바꿈으로, 나머지 태그는 제거. ★ 글자는 지우지 않는다 — '불가' 가 사라지면 부호가 뒤집힌다.""" + if value is None: + return "" + text = _TAGS.sub("", _BR.sub("\n", str(value))) + return re.sub(r"[ \t]+", " ", text).strip() + + @classmethod + def _yn(cls, value) -> Optional[bool]: + """'Y'/'N' 또는 '1'/'0'. 그 외에는 판단하지 않는다(None).""" + v = str(value or "").strip().upper() + if v in ("Y", "1"): + return True + if v in ("N", "0"): + return False + return None + + @classmethod + def _head_bool(cls, value) -> Optional[bool]: + """'가능 (…)' / '불가 (…)' 처럼 **맨 앞 토큰**이 부호인 필드. + + ★ 문자열 전체를 훑으면 "불가 (인근 주차장 이용)" 이 true 로 뒤집힌다(실측). + """ + text = cls._plain(value) + if not text: + return None + head = text[:6] + if any(neg in head for neg in _NEG_HEAD): + return False + if any(pos in head for pos in _POS_HEAD): + return True + return None + + @classmethod + def _number(cls, value) -> Optional[str]: + """'13실' · '11,570㎡' → '13' · '11570'. 숫자로 시작하지 않으면 담지 않는다.""" + m = _LEADING_NUM.match(cls._plain(value)) + if not m: + return None + num = m.group(1).replace(",", "") + return num if num not in ("", "0") else None + + @staticmethod + def _fact(key: str, value: Optional[str], *, unit: Optional[str] = None) -> Optional[CollectedFact]: + if value is None or not str(value).strip(): + return None + return CollectedFact( + key=key, value=str(value).strip(), + scope="unit" if unit else "place", unit_name=unit, + ) + + @classmethod + def _collect(cls, pairs) -> list[CollectedFact]: + return [f for f in (cls._fact(*p[:2], unit=p[2] if len(p) > 2 else None) for p in pairs) if f] + + # ---- 업종별 매핑 ----------------------------------------------------- + def _common_facts(self, common: dict) -> list[CollectedFact]: + """모든 업종 공통. + + ★ overview 를 `intro` fact 로 만들지 않는다 (2026-08-31 수정). + `intro` 는 스키마에서 allow_llm=True — **LLM 이 쓰는 칸**이지 수집하는 사실이 아니다 + (절대규칙 7, tests/test_collector.py::test_adapters_do_not_collect_llm_written_fields). + + 한 번 어겼더니 이렇게 됐다: TourAPI overview 457자가 그대로 VERIFIED 로 들어가 + 사장님 사이트의 '숙소 소개' 를 차지하고, 정작 Gemini 가 쓴 162자 소개문은 + PENDING_OWNER 로 뒤에 밀렸다. 원문을 그대로 싣는 것은 GEO 관점에서도 복제 콘텐츠다. + + 원문은 버리지 않는다 — RawSource.text 로 나가 place_links.raw 에 박제되고, + 소개문·FAQ 생성 시점에만 근거로 쓰인다(services/copy_service.py). + """ + return [] + + def _lodging_facts(self, intro: dict) -> list[CollectedFact]: + """숙박 detailIntro2 → 사업장 단위 fact. + + ★ 스키마에 없는 값은 만들지 않는다. roomcount·scalelodging·foodplace 는 + lodging 스키마에 자리가 없어서 **일부러 버린다** — 억지로 다른 key 에 넣으면 + '식음료장 있음' 이 '조식 제공' 으로 둔갑한다. + """ + return self._collect([ + ("check_in_time", self._plain(intro.get("checkintime"))[:40]), + ("check_out_time", self._plain(intro.get("checkouttime"))[:40]), + ("cancel_policy", self._plain(intro.get("refundregulation"))[:1000]), + ("cooking_allowed", self._bool_str(self._head_bool(intro.get("chkcooking")))), + ("parking", self._bool_str(self._head_bool(intro.get("parkinglodging")))), + ("pickup_service", self._bool_str(self._head_bool(intro.get("pickup")))), + ("bbq_available", self._bool_str(self._yn(intro.get("barbecue")))), + ]) + + def _restaurant_facts(self, intro: dict) -> list[CollectedFact]: + """음식점 detailIntro2 → 사업장 단위 fact. + + ★ 일부러 매핑하지 않는 필드 — 뜻이 미묘하게 다른 것들이다. + kidsfacility '어린이놀이방 유무' 이지 '아이 동반 가능' 이 아니다. + 놀이방이 없다고 kids_allowed=false 로 올리면 아이를 데려올 수 있는 가게를 + '아이 동반 불가' 로 만든다(실측: 가문 → kids_allowed=false 로 잘못 나왔다). + chkcreditcardfood '가능/없음' 이라 payment_methods(결제수단 **목록**)에 넣을 수 없다. + smoking '모두 금연석' 은 restaurant 스키마에 자리가 없다. + infocenterfood 문의 전화일 뿐 예약 채널이라는 근거가 없다. + """ + facts = self._collect([ + ("business_hours", self._plain(intro.get("opentimefood"))[:500]), + ("closed_days", self._plain(intro.get("restdatefood"))[:200]), + ("signature_menu", self._plain(intro.get("firstmenu"))[:200]), + ("parking", self._bool_str(self._head_bool(intro.get("parkingfood")))), + ("takeout", self._bool_str(self._head_bool(intro.get("packing")))), + ("reservation_required", self._bool_str(self._head_bool(intro.get("reservationfood")))), + ]) + # treatmenu 는 "돔베고기 / 멸치국수 / 물만두 등" 처럼 취급 메뉴를 이어 붙여 준다. + # ★ 가격이 없으므로 이름만 단위로 만든다. 이름 없는 단위는 base 계약이 막는다. + for name in self._split_menu(intro.get("treatmenu")): + facts.append(CollectedFact(key="menu_name", value=name, scope="unit", unit_name=name)) + return facts + + @classmethod + def _split_menu(cls, value) -> list[str]: + """'게살해물요리 / 난자완스 / 특색냉채 등' → 3건. 꼬리의 '등' 은 메뉴가 아니다.""" + text = cls._plain(value) + if not text: + return [] + out: list[str] = [] + for token in re.split(r"[/,·]", text): + name = re.sub(r"\s*등\s*$", "", token).strip() + if len(name) >= 2 and name not in out: + out.append(name) + return out[:20] + + def _room_facts(self, rooms: list[dict]) -> list[CollectedFact]: + """숙박 detailInfo2 → **객실 단위** fact. + + ★ 이 자리가 비어 있어서 place.units 가 전 사업장 0건이었다(naver_place_adapter 주석 참조). + TourAPI 는 객실을 행으로 주므로 여기서 가장 깨끗하게 채워진다. + ★ 면적은 roomsize2(㎡)를 쓴다 — 스키마의 room_size 단위가 ㎡ 다. roomsize1 은 평이라 섞으면 3배 틀린다. + ★ 요금은 비수기 최소요금(offseason)을 주중·주말로, 성수기(peak) 주중값을 peak_price 로 담는다. + '최소요금' 이라는 것을 사장님이 확인 화면에서 보고 고칠 수 있게 후보로만 올린다. + """ + facts: list[CollectedFact] = [] + seen: list[str] = [] + for row in rooms: + name = self._plain(row.get("roomtitle")) + if not name or name in seen: + continue + seen.append(name) + facts += self._collect([ + ("room_type", name, name), + ("standard_capacity", self._number(row.get("roombasecount")), name), + ("max_capacity", self._number(row.get("roommaxcount")), name), + ("room_size", self._number(row.get("roomsize2")), name), + ("weekday_price", self._number(row.get("roomoffseasonminfee1")), name), + ("weekend_price", self._number(row.get("roomoffseasonminfee2")), name), + ("peak_price", self._number(row.get("roompeakseasonminfee1")), name), + ("has_kitchen", self._bool_str(self._yn(row.get("roomcook"))), name), + ("has_aircon", self._bool_str(self._yn(row.get("roomaircondition"))), name), + ]) + return facts + + @staticmethod + def _bool_str(value: Optional[bool]) -> Optional[str]: + """★ None(모름)과 False(아니오)를 구분한다. 모르는 것을 '아니오' 로 만들지 않는다.""" + return None if value is None else ("true" if value else "false") + + # ---- 사진 ----------------------------------------------------------- + def _media(self, common: dict, images: list[dict], rooms: list[dict]) -> list[CollectedMedia]: + """대표사진 + 추가사진 + 객실사진. 상업적 이용이 막힌 유형은 여기서 버린다.""" + out: list[CollectedMedia] = [] + seen: set[str] = set() + dropped = 0 + + def add(url, license_code, label=None, unit=None) -> None: + nonlocal dropped + url = (url or "").strip() + if not url or url in seen: + return + code = str(license_code or "").strip().lower() + # ★ 라이선스를 모르면 담지 않는다. 상업 사이트에 실을 사진이라 '모름' 은 위험 쪽이다. + if code not in COMMERCIAL_OK_LICENSES: + dropped += 1 + return + seen.add(url) + out.append(CollectedMedia( + origin_url=url, label=label or None, unit_name=unit, + license=code, + )) + + add(common.get("firstimage"), common.get("cpyrhtDivCd"), label=self._plain(common.get("title"))) + for img in images: + add(img.get("originimgurl"), img.get("cpyrhtDivCd"), label=self._plain(img.get("imgname"))) + for row in rooms: + unit = self._plain(row.get("roomtitle")) or None + for i in range(1, 6): + add(row.get(f"roomimg{i}"), row.get(f"cpyrhtDivCd{i}"), + label=self._plain(row.get(f"roomimg{i}alt")), unit=unit) + if len(out) >= MAX_MEDIA: + break + + if dropped: + LOG.i(f"[tour_api] 상업적 이용이 허용되지 않은 사진 {dropped}장 제외(공공누리 유형)") + return out[:MAX_MEDIA] diff --git a/backend/services/copy_service.py b/backend/services/copy_service.py new file mode 100644 index 0000000..d796553 --- /dev/null +++ b/backend/services/copy_service.py @@ -0,0 +1,222 @@ +"""소개문·FAQ 생성 — COPY 잡이 하는 일. + +★ LLM 은 사실을 만들지 않는다. 문장만 쓴다. + - 입력은 **확보된 fact(노출 가능한 것)만**. 미검증 값으로 문장을 쓰면 그 문장도 미검증이다. + - 생성물은 `ground_check` 를 통과한 것만 저장한다(클라이언트가 이미 걸러 보내지만 근거를 다시 요구한다). + - 소개문은 fact 로 들어가되 **UNVERIFIED 후보**다. 사람이 승인해야 사이트에 나간다. + - FAQ 도 같은 검증 흐름을 탄다. 근거 fact 가 없는 FAQ 는 저장하지 않는다. +""" +import uuid + +from common.category_schema import CategorySchemaError, get_schema +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import facts, faqs, place_links, places, 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.external import gemini_text +from services.fact_service import FactService + +_fact_crud = FactCRUD() +_faq_crud = FaqCRUD() +_place_crud = PlaceCRUD() + + +class CopyAborted(RuntimeError): + """재시도해도 소용없는 중단 — 잡의 last_error 로 남는다.""" + + +async def run_copy(job: dict) -> dict: + """COPY 잡 핸들러. payload: {place_id, company_id, requested_by?}""" + payload = job["payload"] + place_id = payload["place_id"] + company_id = payload["company_id"] + + if not gemini_text.is_configured(): + raise CopyAborted("GEMINI_API_KEY 미설정 — 소개문·FAQ 를 생성할 수 없다") + + err, place = await DB_SESSION_MNG.execute_lambda( + places.DBType(), + DBWRType.DB_READ.value, + lambda s: _place_crud.get_place(s, uuid.UUID(company_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( + 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_links.raw 에 박제된 글이다. + # + # 왜 필요한가: 소개 원문(TourAPI overview·네이버 description)에만 있는 정보가 있다. + # '전면 통창 실내 온수풀', '판교역에서 3분' 같은 것들인데, 이게 근거에 없으면 + # ground_check 가 그 문장을 전부 반려해 소개문·FAQ 가 앙상해진다. + # + # 왜 fact 로 넣지 않는가: `intro` 는 allow_llm=True 라 LLM 의 출력 칸이다. + # 원문을 그 칸에 넣었더니 457자 원문이 발행본의 '숙소 소개' 를 차지했다(2026-08-31). + # 근거로만 쓰고 저장은 하지 않는다 — 원문은 화면에 나가지 않는다. + l_err, link_rows = await DB_SESSION_MNG.execute_lambda( + place_links.DBType(), + DBWRType.DB_READ.value, + lambda s: _place_crud.list_links(s, pid, True), + ) + if l_err == ErrorType.SUCCESS: + for link in (link_rows or []): + text = ((link.raw or {}).get("text") or "").strip() if isinstance(link.raw, dict) else "" + if text: + 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( + 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)) + ] + + if not grounded and not unit_summaries: + # 근거가 없으면 아무것도 쓰지 않는다 — 유료 호출조차 하지 않는다. + return {"place_id": place_id, "intro": False, "faqs": 0, "note": "근거로 쓸 확인된 fact 가 없다"} + + try: + copy = await gemini_text.generate_copy( + place.name, + PlaceCategory(place.category), + grounded, + unit_summaries=unit_summaries or None, + 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, + # ★ 반려된 문장을 그대로 남긴다 — 소개문이 왜 안 나왔는지 운영자가 알아야 한다. + "rejected": [list(r) for r in (copy.rejected or [])][:20], + } + + actor = UserInfo( + user_id=payload.get("requested_by") or str(place.verified_by or uuid.uuid4()), + id="generator", + company_id=company_id, + role=1, + ) + service = FactService(_fact_crud, _place_crud) + + # 소개문·메타는 fact 로 들어간다 — FactService 가 allow_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( + 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 = faqs( + place_id=pid, + question=faq.question, + answer=faq.answer, + source_fact_ids=list(faq.fact_keys), + generated_by=SourceType.LLM.value, + status=FactStatus.UNVERIFIED.value, + sort_order=order, + ) + run_err = await DB_SESSION_MNG.execute_lambda_run( + [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(grounded)}개)") + return stat diff --git a/backend/services/external/gemini.py b/backend/services/external/gemini.py new file mode 100644 index 0000000..12f718b --- /dev/null +++ b/backend/services/external/gemini.py @@ -0,0 +1,256 @@ +"""사진 라벨·접근성 alt 생성 — 겹들을 엮어 결과를 만드는 자리. + +이 파일이 하는 일은 **엮는 것뿐**이다. 고칠 것이 생기면 해당 겹으로 바로 간다: + + 무엇을 묻는가 services/prompts/vision.py 프롬프트·응답 스키마 + 어떻게 부르는가 services/llm/gemini.py HTTP·재시도·토큰·비용 + 무엇을 돌려주는가 여기 배치 나누기 → 호출 → ref 매칭 → 조립 + +결과는 순서가 아니라 `ref` 로 매칭하고, 신뢰도가 낮으면 사람 확인 대상으로 남긴다. +(문장 생성과 달리 여기엔 grounding 겹이 없다 — 사진 설명은 대조할 fact 가 없고, + 대신 신뢰도 임계값과 사람 확인 큐가 그 몫을 한다.) +""" +import base64 +import json +from dataclasses import dataclass, field +from typing import Optional + +import httpx + +from common.enums import PlaceCategory +from common.logger import LOG +from services.llm.gemini import ( + DEFAULT_MODEL, + GeminiError, + GeminiInvalidOutput, + GeminiNotConfigured, + Usage, + call, + extract_text, + is_configured, + price, + read_usage, +) +from services.prompts.vision import RESPONSE_SCHEMA, build_prompt + +# URL 확장자 대신 파일 시그니처로 MIME을 판별한다. +_MAGIC = ( + (b"\x89PNG\r\n\x1a\n", "image/png"), + (b"\xff\xd8\xff", "image/jpeg"), + (b"GIF87a", "image/gif"), + (b"GIF89a", "image/gif"), +) + + +@dataclass +class ImageInput: + """분석할 사진 1장. origin_url 이 결과 매칭 키다(place.media.origin_url 과 같은 값).""" + + origin_url: str + data: Optional[bytes] = None # 이미 받아둔 바이트. 없으면 fetch_url 에서 내려받는다 + fetch_url: Optional[str] = None # 내려받을 주소. 비면 origin_url 을 쓴다 + mime_type: Optional[str] = None # 없으면 시그니처로 판별 + unit_name_hint: Optional[str] = None # "A동 스탠다드" 같은 힌트가 있으면 라벨에 반영 + + +@dataclass +class VisionResult: + """사진 1장의 분석 결과. 입력과 1:1 로 대응하며 실패해도 자리를 지킨다.""" + + origin_url: str + label: Optional[str] = None + alt_text: Optional[str] = None + confidence: float = 0.0 + needs_review: bool = True # ★ 기본이 '사람 확인 필요'다. 확신이 있을 때만 내려간다 + ok: bool = False + error: Optional[str] = None + + +@dataclass +class _Usage: + input_tokens: int = 0 + output_tokens: int = 0 + batches: int = 0 + failed_batches: int = 0 + by_model: dict = field(default_factory=dict) + + +def _sniff_mime(data: bytes) -> str: + for magic, mime in _MAGIC: + if data.startswith(magic): + return mime + if data[:4] == b"RIFF" and data[8:12] == b"WEBP": + return "image/webp" + return "image/jpeg" # 판별 실패 시 가장 흔한 형식으로 시도한다 + + +async def _load_bytes(client: httpx.AsyncClient, image: ImageInput) -> bytes: + """이미지 바이트 확보. 이미 있으면 그대로, 없으면 내려받는다. + + 직접 내려받는 이유: 타임아웃을 우리가 통제하고, 사진별 실패를 개별로 보고하기 위해서다.""" + if image.data: + return image.data + url = image.fetch_url or image.origin_url + resp = await client.get(url, follow_redirects=True) + if resp.status_code != 200: + raise GeminiError(f"이미지 내려받기 실패 status={resp.status_code}") + return resp.content + + +async def _run_batch( + client: httpx.AsyncClient, + batch: list[ImageInput], + *, + model: str, + category: Optional[PlaceCategory], + unit_names: Optional[list[str]], + confidence_threshold: float, + max_retries: int, + usage: _Usage, +) -> dict[str, VisionResult]: + """배치 1개 처리. 반환 {origin_url: VisionResult}. + + ★ 배치가 통째로 실패해도 예외를 밖으로 던지지 않는다 — 호출측이 나머지 배치를 계속 돌려야 한다.""" + out: dict[str, VisionResult] = {} + ref_map: dict[str, ImageInput] = {} + parts: list[dict] = [{"text": ""}] # 자리를 잡아두고 프롬프트는 아래에서 채운다 + + for i, image in enumerate(batch): + ref = f"img-{i}" + try: + data = await _load_bytes(client, image) + except Exception as ex: + # 이 사진만 실패. 배치의 나머지는 그대로 보낸다. + out[image.origin_url] = VisionResult( + origin_url=image.origin_url, ok=False, needs_review=True, + error=f"이미지 로드 실패: {type(ex).__name__}: {ex}", + ) + continue + ref_map[ref] = image + parts.append({"text": f"[{ref}]" + (f" (힌트: {image.unit_name_hint})" if image.unit_name_hint else "")}) + parts.append({ + "inline_data": {"mime_type": image.mime_type or _sniff_mime(data), "data": base64.b64encode(data).decode()} + }) + + if not ref_map: + return out + + parts[0] = {"text": build_prompt(category, unit_names, sorted(ref_map))} + body = { + "contents": [{"role": "user", "parts": parts}], + "generationConfig": { + "responseMimeType": "application/json", + "responseSchema": RESPONSE_SCHEMA, + "temperature": 0, + }, + } + + usage.batches += 1 + try: + payload = await call(client, model, body, max_retries) + parsed = json.loads(extract_text(payload)) + except GeminiNotConfigured: + raise # 키 문제는 전체를 중단시킨다 — 나머지 배치도 어차피 실패한다 + except Exception as ex: + usage.failed_batches += 1 + LOG.w(f"[gemini] 배치 실패(계속) {len(ref_map)}장: {type(ex).__name__}: {ex}") + for image in ref_map.values(): + out[image.origin_url] = VisionResult( + origin_url=image.origin_url, ok=False, needs_review=True, + error=f"{type(ex).__name__}: {str(ex)[:200]}", + ) + return out + + batch_usage = read_usage(payload) + usage.input_tokens += batch_usage.input_tokens + usage.output_tokens += batch_usage.output_tokens + + # ★ 순서가 아니라 ref 로 매칭한다. + seen: set[str] = set() + for item in parsed.get("items") or []: + ref = str(item.get("ref", "")).strip() + image = ref_map.get(ref) + if image is None: + continue # 모델이 없는 ref 를 지어냈다 — 버린다 + seen.add(ref) + try: + confidence = float(item.get("confidence") or 0.0) + except (TypeError, ValueError): + confidence = 0.0 + confidence = max(0.0, min(1.0, confidence)) + label = (item.get("label") or "").strip() or None + alt = (item.get("alt_text") or "").strip() or None + out[image.origin_url] = VisionResult( + origin_url=image.origin_url, + label=label, + alt_text=alt, + confidence=confidence, + # ★ 신뢰도 미달이거나 라벨/alt 가 비면 자동 반영하지 않는다. + needs_review=confidence < confidence_threshold or not label or not alt, + ok=True, + ) + + # 응답에서 빠진 사진 — 조용히 사라지지 않게 자리를 채운다. + for ref, image in ref_map.items(): + if ref not in seen: + out[image.origin_url] = VisionResult( + origin_url=image.origin_url, ok=False, needs_review=True, + error="응답에 해당 ref 가 없다", + ) + return out + + +async def analyze_images( + images: list[ImageInput], + *, + category: Optional[PlaceCategory] = None, + unit_names: Optional[list[str]] = None, + model: str = DEFAULT_MODEL, + batch_size: int = 10, + confidence_threshold: float = 0.7, + max_retries: int = 2, + client: Optional[httpx.AsyncClient] = None, +) -> list[VisionResult]: + """사진들을 분류하고 alt 를 만든다. + + ★ 반환 길이는 항상 입력과 같다. 실패분도 ok=False 로 자리를 지킨다 — + 호출측이 길이나 순서로 매칭하다 어긋나면 엉뚱한 사진에 alt 가 붙는다. + ★ needs_review=True 인 항목은 자동 반영하지 말고 사람 확인 큐(MediaStatus.PENDING_REVIEW)로 보낸다. + """ + if not is_configured(): + raise GeminiNotConfigured("GEMINI_API_KEY 가 설정되지 않았다") + if not images: + return [] + + owns_client = client is None + # 사진 여러 장을 배치로 보내므로 타임아웃을 넉넉히 잡는다. + client = client or httpx.AsyncClient(timeout=httpx.Timeout(180.0, connect=10.0)) + usage = _Usage() + merged: dict[str, VisionResult] = {} + + try: + for start in range(0, len(images), max(1, batch_size)): + batch = images[start:start + max(1, batch_size)] + merged.update(await _run_batch( + client, batch, + model=model, category=category, unit_names=unit_names, + confidence_threshold=confidence_threshold, max_retries=max_retries, usage=usage, + )) + finally: + if owns_client: + await client.aclose() + + results = [ + merged.get(img.origin_url) + or VisionResult(origin_url=img.origin_url, ok=False, needs_review=True, error="결과 누락") + for img in images + ] + + ok = sum(1 for r in results if r.ok) + review = sum(1 for r in results if r.needs_review) + LOG.i( + f"[gemini] 사진분석 {len(results)}장 (성공 {ok} · 확인필요 {review}) · " + f"배치 {usage.batches}(실패 {usage.failed_batches}) · model={model} · " + f"tokens in={usage.input_tokens} out={usage.output_tokens} · 약 ${price(model, Usage(usage.input_tokens, usage.output_tokens))}" + ) + return results diff --git a/backend/services/external/gemini_extract.py b/backend/services/external/gemini_extract.py new file mode 100644 index 0000000..9c2a267 --- /dev/null +++ b/backend/services/external/gemini_extract.py @@ -0,0 +1,137 @@ +"""원문 텍스트 → fact 후보 추출 — 겹들을 엮어 결과를 만드는 자리. + +이 파일이 하는 일은 **엮는 것뿐**이다. 고칠 것이 생기면 해당 겹으로 바로 간다: + + 무엇을 묻는가 services/prompts/extract.py 프롬프트·응답 스키마 + 어떻게 부르는가 services/llm/gemini.py HTTP·재시도·토큰·비용 + 답을 믿을 것인가 services/grounding/extract.py evidence 원문 대조 + 무엇을 돌려주는가 여기 호출 → 검증 → CollectedFact 조립 + +★ 입력이 무엇이든 여기로 모인다 + 사장님이 붙여넣은 텍스트도, static_html 어댑터가 받아온 페이지 본문도 + 똑같이 '원문 문자열' 하나다. 도메인마다 파서를 짜는 대신 여기 한 곳을 쓴다. + +★ 나가는 값은 전부 후보다 + 통과한 fact 도 UNVERIFIED 로 들어간다. 사장님이 확인해야 사이트에 나간다 — + 그 게이트는 fact 계층이 담당한다. 여기서는 '원문에 있었다' 까지만 보장한다. +""" +import json +from dataclasses import dataclass, field +from typing import Optional + +import httpx + +from common.category_schema import get_schema +from common.enums import PlaceCategory +from common.logger import LOG +from services.collector.base import CollectedFact +from services.grounding.extract import verify +from services.llm.gemini import ( + DEFAULT_MODEL, + GeminiInvalidOutput, + GeminiNotConfigured, + call, + extract_text, + is_configured, + price, + read_usage, +) +from services.prompts.extract import RESPONSE_SCHEMA, build_prompt + +# 이보다 짧은 원문은 호출하지 않는다. 메뉴판 한 줄도 안 되는 분량에서 나올 fact 는 없고, +# 호출비만 나간다. +MIN_SOURCE_CHARS = 80 + + +@dataclass +class ExtractResult: + """추출 결과. facts 는 검증을 통과한 것만 담긴다. + + rejected 에는 (항목, 사유) 가 들어간다 — 조용히 버리지 않는다. + 운영자가 "왜 체크인 시간이 안 들어왔나" 를 이 목록으로 읽는다. + """ + + facts: list[CollectedFact] = field(default_factory=list) + rejected: list[tuple[str, str]] = field(default_factory=list) + + @property + def ok(self) -> bool: + return bool(self.facts) + + +async def extract_facts( + place_name: str, + category: PlaceCategory, + source_text: str, + *, + source_url: str, + model: str = DEFAULT_MODEL, + max_retries: int = 2, + client: Optional[httpx.AsyncClient] = None, +) -> ExtractResult: + """원문 텍스트에서 업종 스키마 fact 를 뽑는다. + + ★ source_url 은 필수다. 출처 없는 fact 는 FACT_SOURCE_REQUIRED 로 거부되므로 + 여기서 구조적으로 찍어 둔다(사장님 붙여넣기면 'owner:paste' 같은 식별자라도 넣는다). + ★ 원문이 짧으면 **API 를 호출하지 않는다** — 근거가 없는데 부르면 그게 곧 환각 유발이다. + """ + if not is_configured(): + raise GeminiNotConfigured("GEMINI_API_KEY 가 설정되지 않았다") + if not (source_url or "").strip(): + raise ValueError("source_url 이 비었다 — 출처 없는 추출은 하지 않는다") + + text = (source_text or "").strip() + if len(text) < MIN_SOURCE_CHARS: + LOG.i(f"[gemini-extract] '{place_name}' 원문 {len(text)}자 — 짧아서 호출하지 않는다") + return ExtractResult(rejected=[("(전체)", f"원문이 {len(text)}자로 너무 짧다 — 호출하지 않았다")]) + + body = { + "contents": [{"role": "user", "parts": [{"text": build_prompt(place_name, category, text)}]}], + "generationConfig": { + "responseMimeType": "application/json", + "responseSchema": RESPONSE_SCHEMA, + # ★ 0.0 — 옮겨 적는 작업이다. 창의성이 개입할 자리가 없다. + "temperature": 0.0, + }, + } + + owns_client = client is None + client = client or httpx.AsyncClient(timeout=httpx.Timeout(120.0, connect=10.0)) + try: + payload = await call(client, model, body, max_retries) + parsed = json.loads(extract_text(payload)) + except json.JSONDecodeError as ex: + raise GeminiInvalidOutput(f"구조화 출력 파싱 실패: {ex}") from ex + finally: + if owns_client: + await client.aclose() + + rows = parsed.get("facts") + if not isinstance(rows, list): + raise GeminiInvalidOutput(f"facts 가 배열이 아니다: {type(rows).__name__}") + + # ★ 여기가 관문이다. 모델이 뭘 적어 냈든 원문과 대조해서 통과한 것만 나간다. + passed, rejected = verify(rows, source_text=text, schema=get_schema(category)) + + facts = [ + CollectedFact( + key=row["key"], + value=row["value"], + scope=row["scope"], + unit_name=row["unit_name"], + source_url=source_url, + ) + for row in passed + ] + + usage = read_usage(payload) + LOG.i( + f"[gemini-extract] '{place_name}' 추출 {len(rows)}건 → 통과 {len(facts)}건 · " + f"반려 {len(rejected)}건 · model={model} · " + f"tokens in={usage.input_tokens} out={usage.output_tokens} · 약 ${price(model, usage)}" + ) + if rejected: + for label, why in rejected[:10]: + LOG.w(f"[gemini-extract] 반려 {label} — {why}") + + return ExtractResult(facts=facts, rejected=rejected) diff --git a/backend/services/external/gemini_text.py b/backend/services/external/gemini_text.py new file mode 100644 index 0000000..f5add58 --- /dev/null +++ b/backend/services/external/gemini_text.py @@ -0,0 +1,195 @@ +"""소개문·메타설명·FAQ 생성 — 겹들을 엮어 결과를 만드는 자리. + +이 파일이 하는 일은 **엮는 것뿐**이다. 고칠 것이 생기면 해당 겹으로 바로 간다: + + 무엇을 묻는가 services/prompts/copy.py 프롬프트·응답 스키마 + 어떻게 부르는가 services/llm/gemini.py HTTP·재시도·토큰·비용 + 답을 믿을 것인가 services/grounding/copy.py ground_check · faq_polarity_ok + 무엇을 돌려주는가 여기 근거 모으기 → 호출 → 검증 → 조립 + +한때 이 네 가지가 한 파일 500줄에 뭉쳐 있었다. "FAQ 답이 이상하다" 를 고치러 와도 +어디를 봐야 할지가 파일 안에서 갈리지 않았다. +""" +import json +from dataclasses import dataclass, field +from typing import Optional + +import httpx + +from common.enums import PlaceCategory +from common.logger import LOG +from services.grounding.copy import FactInput, faq_polarity_ok, ground_check +from services.llm.gemini import ( + DEFAULT_MODEL as DEFAULT_TEXT_MODEL, + GeminiError, + GeminiInvalidOutput, + GeminiNotConfigured, + Usage, + call, + extract_text, + is_configured, + price, + read_usage, +) +from services.prompts.copy import RESPONSE_SCHEMA, build_prompt + + +@dataclass +class GeneratedFaq: + question: str + answer: str + fact_keys: list[str] = field(default_factory=list) + + +@dataclass +class GeneratedCopy: + """생성 결과. 검증을 통과한 것만 담긴다. + + rejected 에는 (버린 내용, 사유) 가 들어간다 — 조용히 버리지 않는다. + 운영자가 "왜 소개문이 안 나왔나" 를 이 목록으로 읽는다.""" + + intro: Optional[str] = None + intro_fact_keys: list[str] = field(default_factory=list) + meta_description: Optional[str] = None + faqs: list[GeneratedFaq] = field(default_factory=list) + rejected: list[tuple[str, str]] = field(default_factory=list) + + +def _unit_facts(unit_summaries: Optional[list[dict]]) -> list[FactInput]: + """객실·프로그램 요약을 근거 fact 로 펼친다. + + {"name": "A동", "facts": {"max_capacity": "4"}} → FactInput("A동:max_capacity", …) + 이렇게 해야 "최대 4명" 같은 문장이 근거 있는 것으로 통과한다. + + ★ `labels` 가 함께 오면 스키마 라벨·단위를 쓴다({key: {"label","unit"}}). + 이 목록은 프롬프트에도 그대로 실리므로, 라벨이 없으면 모델이 'weekday_price' 라는 + 날 key 를 보고 글을 쓴다 — "weekday_price는 20000입니다" 같은 문장이 나온다. + 없으면 지금까지처럼 key 를 라벨 자리에 둔다(호출측이 스키마를 모를 수 있다). + """ + out: list[FactInput] = [] + for unit in unit_summaries or []: + name = str(unit.get("name") or "").strip() + labels = unit.get("labels") or {} + if name: + out.append(FactInput(key=f"unit:{name}", label="객실·프로그램명", value=name)) + for key, value in (unit.get("facts") or {}).items(): + if value is None or str(value).strip() == "": + continue + spec = labels.get(key) or {} + out.append(FactInput( + key=f"{name}:{key}" if name else key, + label=spec.get("label") or key, + value=str(value), + unit=spec.get("unit"), + )) + return out + + +def _valid_keys(claimed: list, allowed: set[str]) -> list[str]: + """모델이 적어준 근거 key 중 실제로 존재하는 것만 남긴다(없는 key 를 지어내기도 한다).""" + return [k for k in (claimed or []) if isinstance(k, str) and k in allowed] + + +async def generate_copy( + place_name: str, + category: PlaceCategory, + facts: list[FactInput], + *, + unit_summaries: Optional[list[dict]] = None, + max_faqs: int = 8, + model: str = DEFAULT_TEXT_MODEL, + max_retries: int = 2, + client: Optional[httpx.AsyncClient] = None, +) -> GeneratedCopy: + """확보된 fact 만으로 소개문·메타설명·FAQ 를 만든다. + + ★ facts 가 비면 **API 를 호출하지 않고** 빈 결과를 돌려준다 — + 근거 없이 문장을 쓰면 그게 곧 환각이다. + ★ 생성 결과는 전부 ground_check 를 통과한 것만 담긴다. 통과 못 한 항목은 rejected 로 간다. + ★ 생성 대상 필드는 업종 스키마의 allow_llm=True 인 것뿐이다(호출측이 필터링해서 넘긴다). + """ + if not is_configured(): + raise GeminiNotConfigured("GEMINI_API_KEY 가 설정되지 않았다") + # ★ 사업장 fact 가 없어도 객실·메뉴 근거가 있으면 쓴다. 요금표만 있는 모텔이 그 경우다 — + # "대실 20,000원" 은 근거 있는 사실이고, 손님이 가장 먼저 묻는 것이기도 하다. + unit_grounding = _unit_facts(unit_summaries) + if not facts and not unit_grounding: + LOG.i(f"[gemini-text] '{place_name}' 근거 fact 0건 — 생성하지 않는다(호출 없음)") + return GeneratedCopy(rejected=[("(전체)", "근거 fact 가 없다 — 생성하지 않았다")]) + + # 검증에 쓸 근거 = 넘겨받은 fact + 객실 요약 + 상호명(상호에 숫자가 있어도 근거로 본다) + grounding = list(facts) + unit_grounding + grounding.append(FactInput(key="place_name", label="상호명", value=place_name)) + allowed_keys = {f.key for f in facts} | {f.key for f in grounding} + + body = { + "contents": [{"role": "user", "parts": [{ + "text": build_prompt(place_name, category, facts, max_faqs, unit_grounding) + }]}], + "generationConfig": { + "responseMimeType": "application/json", + "responseSchema": RESPONSE_SCHEMA, + "temperature": 0.2, + }, + } + + owns_client = client is None + client = client or httpx.AsyncClient(timeout=httpx.Timeout(120.0, connect=10.0)) + try: + payload = await call(client, model, body, max_retries) + parsed = json.loads(extract_text(payload)) + except json.JSONDecodeError as ex: + raise GeminiInvalidOutput(f"구조화 출력 파싱 실패: {ex}") from ex + finally: + if owns_client: + await client.aclose() + + usage = read_usage(payload) + + result = GeneratedCopy() + + # ── 소개문 ── + intro = (parsed.get("intro") or "").strip() + if intro: + ok, reasons = ground_check(intro, grounding) + if ok: + result.intro = intro + result.intro_fact_keys = _valid_keys(parsed.get("intro_fact_keys"), allowed_keys) + else: + result.rejected.append((intro, " / ".join(reasons))) + + # ── 메타 설명 ── + meta_desc = (parsed.get("meta_description") or "").strip() + if meta_desc: + ok, reasons = ground_check(meta_desc, grounding) + if ok: + result.meta_description = meta_desc + else: + result.rejected.append((meta_desc, " / ".join(reasons))) + + # ── FAQ ── 항목마다 따로 검사한다. 하나가 걸려도 나머지는 산다. + for item in (parsed.get("faqs") or [])[:max_faqs]: + question = (item.get("question") or "").strip() + answer = (item.get("answer") or "").strip() + if not question or not answer: + continue + keys = _valid_keys(item.get("fact_keys"), allowed_keys) + if not keys: + # ★ 근거를 못 대는 FAQ 는 버린다 — 사실인지 확인할 방법이 없다. + result.rejected.append((question, "근거 fact_keys 가 없다")) + continue + ok, reasons = ground_check(f"{question} {answer}", grounding) + # 질문은 주장이 아니라 값-반대 판정에서 빠진다. 그 빈틈은 답변 쪽에서 따로 막는다. + polar_ok, polar_reasons = faq_polarity_ok(question, answer, grounding) + if not ok or not polar_ok: + result.rejected.append((question, " / ".join(reasons + polar_reasons))) + continue + result.faqs.append(GeneratedFaq(question=question, answer=answer, fact_keys=keys)) + + LOG.i( + f"[gemini-text] '{place_name}' 생성 — 소개문 {'O' if result.intro else 'X'} · " + f"메타 {'O' if result.meta_description else 'X'} · FAQ {len(result.faqs)}건 · " + f"반려 {len(result.rejected)}건 · model={model} · " + f"tokens in={usage.input_tokens} out={usage.output_tokens} · 약 ${price(model, usage)}" + ) + return result diff --git a/backend/services/external/kakao.py b/backend/services/external/kakao.py new file mode 100644 index 0000000..d5dc4e9 --- /dev/null +++ b/backend/services/external/kakao.py @@ -0,0 +1,431 @@ +"""카카오 로컬 API 클라이언트 — 동일 업소 검증 + 지역 정보. + +이 서비스에서 카카오 로컬이 하는 일은 두 가지다. + +1. **동일 업소 검증** (가장 중요) + Perplexity 가 찾아온 채널 URL 이 정말 그 가게 것인지 확인하는 유일한 근거다. + 이 단계가 없으면 동명 업소 정보가 섞이고, 남의 가게 체크인 시간이 우리 사이트로 나간다. + ★ 애매하면 자동 판정하지 않고 사람에게 넘긴다(pick_match 참고). + +2. **지역 정보** (주변 맛집·시설) + 좌표 → 행정구역 코드로 바꾸고, 그 코드 단위로 주변 정보를 모은다. + +── 비용 (2026-08 기준) ─────────────────────────────────────────────── +무료 쿼터: 키워드 검색 일 10만 · 좌표 변환 일 10만 · 전체 월 300만 +초과 단가: 키워드/카테고리 검색 **2원** · 좌표 변환 **0.5원** + → ★ 키워드/카테고리 검색이 좌표 변환보다 **4배 비싸다** + +★ 무료 쿼터는 개발자 계정의 '첫 번째 활성 앱' 에만 붙는다. dev/stage/prod 앱을 따로 파면 하나만 무료다. + +그래서 호출 정책이 이렇다. + - 키워드 검색(search_keyword) : 사업장 등록·재검증 때만. 비싸다 + - 좌표 변환(coord_to_region) : 싸다. 사업장당 1회면 충분(좌표는 안 바뀐다) + - 카테고리 검색(search_category): 비싸다. ★ **행정구역 코드 단위로 캐싱**해야 한다. + 같은 지역에 사이트가 50개 생겨도 조회는 1회여야 한다. + 캐싱 자체는 local 모듈(local.local_contents, 캐시 키 = region_code)이 책임진다 — + 이 클라이언트는 캐시를 두지 않는다. 호출 전에 캐시를 먼저 보라는 뜻이다. + +호출 횟수는 전부 LOG.i 로 남긴다(비용 추적). _CALL_COUNTS 로 프로세스 누적도 볼 수 있다. +""" + +import re +from collections import Counter +from dataclasses import dataclass, field +from enum import Enum +from typing import Optional + +import httpx + +from common.logger import LOG +from config.server_configs import external_api_config + +_BASE_URL = "https://dapi.kakao.com" +_KEYWORD_URL = f"{_BASE_URL}/v2/local/search/keyword.json" +_COORD2REGION_URL = f"{_BASE_URL}/v2/local/geo/coord2regioncode.json" +_CATEGORY_URL = f"{_BASE_URL}/v2/local/search/category.json" + +# 초과 단가(원). 로그에 함께 남겨 어떤 호출이 비싼지 바로 보이게 한다. +_UNIT_COST_KRW = {"keyword": 2.0, "category": 2.0, "coord2region": 0.5} + +# 프로세스 누적 호출 수 — 생성 1건당 검색 횟수를 세는 근거. +_CALL_COUNTS: Counter = Counter() + +# 카테고리 그룹 코드(카카오 정의). 지역 정보에서 쓰는 것만 추려 둔다. +CATEGORY_RESTAURANT = "FD6" # 음식점 +CATEGORY_CAFE = "CE7" # 카페 +CATEGORY_ATTRACTION = "AT4" # 관광명소 +CATEGORY_ACCOMMODATION = "AD5" # 숙박 +CATEGORY_CONVENIENCE = "CS2" # 편의점 +CATEGORY_PARKING = "PK6" # 주차장 + + +class KakaoNotConfigured(RuntimeError): + """KAKAO_REST_API_KEY 미설정 — 이 어댑터만 비활성이다. + + 서버 부팅을 막지 않는다(외부 계약에 부팅이 묶이면 안 된다). 호출측이 잡아 + ErrorType.LOCAL_NOT_CONFIGURED 로 응답한다.""" + + +class KakaoRequestFailed(RuntimeError): + """카카오 로컬 호출 실패(네트워크·타임아웃·5xx·인증오류). + + ★ 실패했다고 빈 값을 내보내면 안 된다 — 호출측은 직전 값을 유지하고 내부 알림만 낸다.""" + + +class MatchOutcome(str, Enum): + """동일 업소 판정 결과. + + ※ 이 서비스 안에서만 쓰는 판정 결과라 모듈 지역 enum 으로 둔다. + 라우터 응답으로 내보낼 일이 생기면 common/enums.py 로 올려야 한다.""" + + MATCHED = "matched" # 이 가게가 맞다고 확정 + AMBIGUOUS = "ambiguous" # ★ 동명 업소 등 — 사람이 골라야 한다 + NO_CANDIDATE = "no_candidate" # 카카오에서 후보를 못 찾음 + + +@dataclass(frozen=True) +class KakaoPlace: + """카카오 로컬이 돌려준 장소 1건. + + ★ 카카오 응답의 x 는 경도(longitude), y 는 위도(latitude) 다. 뒤집으면 엉뚱한 지역이 된다.""" + + kakao_place_id: str # id — 동일 업소 판정의 유일 키 + name: str # place_name + road_address: Optional[str] # road_address_name + address: Optional[str] # address_name (지번) + phone: Optional[str] + latitude: Optional[float] # y + longitude: Optional[float] # x + category_name: Optional[str] + place_url: Optional[str] + + @classmethod + def from_document(cls, doc: dict) -> "KakaoPlace": + return cls( + kakao_place_id=str(doc.get("id") or ""), + name=doc.get("place_name") or "", + road_address=(doc.get("road_address_name") or None), + address=(doc.get("address_name") or None), + phone=(doc.get("phone") or None), + latitude=_to_float(doc.get("y")), # ★ y = 위도 + longitude=_to_float(doc.get("x")), # ★ x = 경도 + category_name=(doc.get("category_name") or None), + place_url=(doc.get("place_url") or None), + ) + + +@dataclass(frozen=True) +class RegionCode: + """행정구역 코드. ★ 지역 정보 캐시의 키다(같은 지역 사이트 50개여도 조회 1회).""" + + code: str # 행정동/법정동 코드 + region_1depth_name: str # 시·도 + region_2depth_name: str # 시·군·구 + region_3depth_name: str # 읍·면·동 + region_type: Optional[str] = None # "H"=행정동, "B"=법정동 + + @property + def full_name(self) -> str: + parts = [self.region_1depth_name, self.region_2depth_name, self.region_3depth_name] + return " ".join(p for p in parts if p) + + @classmethod + def from_document(cls, doc: dict) -> "RegionCode": + return cls( + code=str(doc.get("code") or ""), + region_1depth_name=doc.get("region_1depth_name") or "", + region_2depth_name=doc.get("region_2depth_name") or "", + region_3depth_name=doc.get("region_3depth_name") or "", + region_type=doc.get("region_type"), + ) + + +@dataclass +class MatchResult: + """동일 업소 판정 결과 + **판정 근거**. + + 근거를 같이 들고 다니는 이유: ambiguous 로 떨어졌을 때 사람이 무엇을 보고 골라야 하는지 + 알아야 하고, matched 로 확정됐을 때도 나중에 '왜 이 가게로 붙었나' 를 추적해야 한다.""" + + outcome: MatchOutcome + place: Optional[KakaoPlace] = None # MATCHED 일 때만 채워진다 + candidates: list[KakaoPlace] = field(default_factory=list) # 사람이 고를 후보 전체 + reason: str = "" # 근거 코드(기계 판독용) + detail: str = "" # 근거 설명(사람 판독용) + + @property + def is_matched(self) -> bool: + return self.outcome == MatchOutcome.MATCHED + + +# ---- 문자열 정규화 ------------------------------------------------------- +# ★ 과하게 정규화하면 다른 가게가 같은 이름으로 보인다. 공백/대소문자까지만 건드린다. +_WS_RE = re.compile(r"\s+") +_DIGIT_RE = re.compile(r"\D") + + +def normalize_name(name: str) -> str: + """상호명 비교용 정규화 — 공백 제거 + 소문자화. 그 이상은 하지 않는다. + + '하조대 펜션' 과 '하조대펜션' 은 같게 보되, '하조대펜션' 과 '하조대펜션 별관' 은 다르게 본다.""" + return _WS_RE.sub("", (name or "")).lower() + + +def normalize_phone(phone: str) -> str: + """전화번호 비교용 정규화 — 숫자만 남긴다('033-672-0000' → '0336720000').""" + return _DIGIT_RE.sub("", phone or "") + + +def _to_float(value) -> Optional[float]: + try: + return float(value) + except (TypeError, ValueError): + return None + + +# ---- 동일 업소 판정 ------------------------------------------------------ +def pick_match(name: str, candidates: list[KakaoPlace], phone: Optional[str] = None) -> MatchResult: + """★ 검색 결과에서 '이 가게가 맞다' 를 판정한다. 이 서비스에서 가장 비싼 실수가 나는 지점이다. + + 판정 순서 + 1. 후보 0건 → NO_CANDIDATE + 2. 전화번호가 주어졌고 정확히 1건 일치 → MATCHED (가장 강한 근거) + 전화번호 일치가 2건 이상 → 그 부분집합으로 좁혀 상호명 판정을 이어간다 + 3. 정규화 상호명이 정확히 1건 일치 → MATCHED + 4. 정규화 상호명이 2건 이상 일치 → AMBIGUOUS (동명 업소) + 5. 정확히 일치하는 상호명이 없음 → AMBIGUOUS (부분일치만으로는 확정하지 않는다) + + ★ 애매하면 반드시 AMBIGUOUS 로 떨어뜨린다. 억지로 하나 고르면 남의 가게 정보가 섞이고, + 그건 사이트가 발행된 뒤에야 드러난다(그때는 이미 예약 클레임이 난 뒤다).""" + if not candidates: + return MatchResult( + outcome=MatchOutcome.NO_CANDIDATE, + candidates=[], + reason="no_candidate", + detail=f"'{name}' 으로 카카오 로컬에서 후보를 찾지 못했습니다.", + ) + + pool = list(candidates) + phone_note = "" + + # 2) 전화번호 — 동명 업소를 가르는 가장 강한 근거. + normalized_phone = normalize_phone(phone) if phone else "" + if normalized_phone: + phone_hits = [c for c in pool if normalize_phone(c.phone or "") == normalized_phone] + if len(phone_hits) == 1: + return MatchResult( + outcome=MatchOutcome.MATCHED, + place=phone_hits[0], + candidates=pool, + reason="phone_exact", + detail=f"전화번호({phone})가 정확히 1건과 일치합니다: {phone_hits[0].name}", + ) + if len(phone_hits) > 1: + # 전화번호까지 같은 후보가 여럿 — 지점 등록 등. 그 안에서 상호명으로 다시 본다. + pool = phone_hits + phone_note = f" (전화번호 일치 {len(phone_hits)}건으로 좁힘)" + + # 3~5) 상호명 정확 일치 + target = normalize_name(name) + name_hits = [c for c in pool if normalize_name(c.name) == target] + + if len(name_hits) == 1: + return MatchResult( + outcome=MatchOutcome.MATCHED, + place=name_hits[0], + candidates=pool, + reason="name_exact", + detail=f"상호명이 정확히 1건과 일치합니다{phone_note}: {name_hits[0].name}", + ) + + if len(name_hits) > 1: + return MatchResult( + outcome=MatchOutcome.AMBIGUOUS, + candidates=name_hits, + reason="name_duplicate", + detail=( + f"'{name}' 과 상호명이 같은 업소가 {len(name_hits)}건입니다{phone_note}. " + f"주소로 구분해야 합니다: " + + " / ".join(f"{c.name}({c.road_address or c.address or '주소없음'})" for c in name_hits) + ), + ) + + return MatchResult( + outcome=MatchOutcome.AMBIGUOUS, + candidates=pool, + reason="name_no_exact", + detail=( + f"'{name}' 과 정확히 일치하는 상호명이 없습니다{phone_note}. 후보 {len(pool)}건 중 사람이 골라야 합니다: " + + " / ".join(f"{c.name}({c.road_address or c.address or '주소없음'})" for c in pool[:5]) + ), + ) + + +# ---- 클라이언트 ---------------------------------------------------------- +class KakaoLocalClient: + """카카오 로컬 API 호출기. + + 키가 없으면 생성은 되지만 호출 시 KakaoNotConfigured 를 던진다 — + 부팅이 외부 계약에 묶이지 않게 하기 위함이다(설정이 비면 이 어댑터만 비활성).""" + + def __init__(self, api_key: Optional[str] = None, transport=None, timeout: float = 10.0): + # api_key 를 명시하지 않으면 설정에서 읽는다. 테스트는 transport 를 주입한다. + self._api_key = external_api_config.kakao_rest_api_key if api_key is None else api_key + self._transport = transport + self._timeout = timeout + self._client: Optional[httpx.AsyncClient] = None + + # ---- 내부 ---- + @property + def enabled(self) -> bool: + """키가 설정돼 있는지. 호출 전에 확인해 조용히 건너뛸 수 있게 한다.""" + return bool(self._api_key) + + def _headers(self) -> dict: + if not self._api_key: + raise KakaoNotConfigured( + "KAKAO_REST_API_KEY 가 설정되지 않았습니다 — .env 또는 config 의 [ExternalApiConfig] 를 확인하세요" + ) + return {"Authorization": f"KakaoAK {self._api_key}"} + + def _get_client(self) -> httpx.AsyncClient: + if self._client is None or self._client.is_closed: + kwargs = {"timeout": httpx.Timeout(self._timeout, connect=5.0)} + if self._transport is not None: + kwargs["transport"] = self._transport + self._client = httpx.AsyncClient(**kwargs) + return self._client + + async def aclose(self): + if self._client is not None and not self._client.is_closed: + await self._client.aclose() + self._client = None + + async def _get(self, url: str, params: dict, kind: str) -> dict: + """공통 GET. 호출 1건마다 비용을 로그로 남긴다.""" + headers = self._headers() # 키 없으면 여기서 KakaoNotConfigured + _CALL_COUNTS[kind] += 1 + LOG.i( + f"[kakao] {kind} 호출 (누적 {_CALL_COUNTS[kind]}회, " + f"초과 시 건당 {_UNIT_COST_KRW.get(kind, 0):g}원) params={ {k: v for k, v in params.items() if k != 'query'} }" + ) + try: + resp = await self._get_client().get(url, params=params, headers=headers) + except httpx.TimeoutException as ex: + raise KakaoRequestFailed(f"카카오 로컬 {kind} 타임아웃: {ex}") from ex + except httpx.HTTPError as ex: + raise KakaoRequestFailed(f"카카오 로컬 {kind} 요청 실패: {type(ex).__name__}: {ex}") from ex + + if resp.status_code == 401: + # 키가 있지만 잘못됐다 — 설정 문제라 재시도해도 소용없다. + raise KakaoNotConfigured(f"카카오 로컬 인증 실패(401) — REST API 키를 확인하세요: {resp.text[:200]}") + if resp.status_code != 200: + raise KakaoRequestFailed(f"카카오 로컬 {kind} 응답 오류 status={resp.status_code} body={resp.text[:200]}") + + try: + return resp.json() + except ValueError as ex: + raise KakaoRequestFailed(f"카카오 로컬 {kind} 응답 파싱 실패: {ex}") from ex + + # ---- 1) 상호명 → 주소·좌표·전화 ---- + async def search_keyword( + self, name: str, x: Optional[float] = None, y: Optional[float] = None, size: int = 15 + ) -> list[KakaoPlace]: + """상호명으로 장소를 찾는다. **동일 업소 검증의 입력**이다. + + ★ 비싸다(초과 시 건당 2원). 사업장 등록·재검증 때만 부른다. + x/y 를 주면 그 좌표 근처를 우선한다(x=경도, y=위도). 지역을 아는 경우 후보가 훨씬 깨끗해진다. + + 반환된 목록은 그대로 pick_match 에 넘긴다 — 여기서 하나를 고르지 않는다.""" + params: dict = {"query": name, "size": max(1, min(size, 15))} + if x is not None and y is not None: + params["x"] = str(x) # 경도 + params["y"] = str(y) # 위도 + data = await self._get(_KEYWORD_URL, params, "keyword") + return [KakaoPlace.from_document(d) for d in (data.get("documents") or [])] + + # ---- 2) 좌표 → 행정구역 코드 ---- + async def coord_to_region(self, lat: float, lon: float) -> RegionCode: + """좌표를 행정구역 코드로 바꾼다. ★ 이 코드가 지역 정보 캐시의 키다. + + 싸다(초과 시 건당 0.5원, 키워드 검색의 1/4). 좌표는 안 바뀌므로 사업장당 1회면 충분하다. + 행정동(H)을 우선 반환하고, 없으면 첫 문서를 쓴다.""" + data = await self._get(_COORD2REGION_URL, {"x": str(lon), "y": str(lat)}, "coord2region") + docs = data.get("documents") or [] + if not docs: + raise KakaoRequestFailed(f"좌표 → 행정구역 변환 결과 없음 (lat={lat}, lon={lon})") + # 행정동(H) 우선 — 생활권 기준이라 주변 정보와 더 잘 맞는다. + picked = next((d for d in docs if d.get("region_type") == "H"), docs[0]) + return RegionCode.from_document(picked) + + # ---- 3) 주변 맛집·시설 ---- + async def search_category( + self, + region_x: float, + region_y: float, + category_group_code: str, + radius: int = 2000, + size: int = 15, + region_code: Optional[str] = None, + ) -> list[KakaoPlace]: + """좌표 반경 안의 카테고리 장소(주변 맛집·카페·관광지 등)를 찾는다. + + ★ 비싸다(초과 시 건당 2원 — 좌표 변환의 4배). **반드시 행정구역 코드 단위로 캐싱해서 부른다.** + 같은 지역에 사이트가 50개 생겨도 이 호출은 1회여야 한다. + + 캐싱은 이 클라이언트가 하지 않는다 — local 모듈이 local.local_contents 에 + `region_code + content_type` 키로 저장하고, 캐시 미스일 때만 여기를 부른다. + `region_code` 인자는 그 캐시 키를 호출 지점에서 명시하게 하려고 받는다(로그에도 남는다). + 호출측이 region_code 를 못 주면 캐시 없이 부르고 있다는 뜻이라 경고를 남긴다. + + region_x = 경도(longitude), region_y = 위도(latitude). 그 지역의 중심 좌표를 넘긴다.""" + if not region_code: + LOG.w( + "[kakao] search_category 를 region_code 없이 호출했습니다 — " + "행정구역 코드 단위 캐시를 거치지 않으면 같은 지역을 사이트 수만큼 반복 조회합니다" + ) + params = { + "category_group_code": category_group_code, + "x": str(region_x), # 경도 + "y": str(region_y), # 위도 + "radius": str(max(0, min(radius, 20000))), # 카카오 상한 20km + "size": str(max(1, min(size, 15))), + "sort": "distance", + } + data = await self._get(_CATEGORY_URL, params, "category") + docs = [KakaoPlace.from_document(d) for d in (data.get("documents") or [])] + LOG.i(f"[kakao] category={category_group_code} region_code={region_code or '미지정'} → {len(docs)}건") + return docs + + # ---- 조합: 상호명 하나로 동일 업소까지 ---- + async def verify_place( + self, + name: str, + phone: Optional[str] = None, + *, + search_query: Optional[str] = None, + ) -> MatchResult: + """상호명(+전화번호)으로 검색해서 동일 업소를 판정한다. + + 키워드 검색 1회만 쓴다. 결과가 MATCHED 가 아니면 사람이 골라야 한다 — + 호출측은 AMBIGUOUS → ErrorType.PLACE_VERIFY_AMBIGUOUS, + NO_CANDIDATE → ErrorType.PLACE_VERIFY_NO_CANDIDATE 로 응답한다. + + ★ name 에는 상호명만 넣는다 — 판정이 정확일치를 보기 때문이다. + 지역이 섞인 검색어는 search_query 로 넘긴다(naver.verify_place 와 같은 규약). + """ + candidates = await self.search_keyword(search_query or name) + result = pick_match(name, candidates, phone) + detail = f"'{name}'" if not search_query or search_query == name else f"'{name}' (검색어 '{search_query}')" + LOG.i(f"[kakao] 동일 업소 판정 {detail} → {result.outcome.value} ({result.reason})") + return result + + +def call_counts() -> dict: + """프로세스 누적 호출 수 — 생성 1건당 검색 횟수를 세는 근거(비용 리포트용).""" + return dict(_CALL_COUNTS) + + +def reset_call_counts(): + """테스트/리포트 구간 분리용.""" + _CALL_COUNTS.clear() diff --git a/backend/services/external/naver.py b/backend/services/external/naver.py new file mode 100644 index 0000000..2ed64e1 --- /dev/null +++ b/backend/services/external/naver.py @@ -0,0 +1,497 @@ +"""네이버 지역검색 API 클라이언트 — 동일 업소 검증 + 지역 정보. + +카카오 REST 키가 없어서 네이버로 간다. `services/external/kakao.py` 와 **같은 형태**로 만들어 +나중에 카카오 키가 나오면 갈아끼울 수 있게 한다(판정 결과 enum 은 카카오 것을 그대로 쓴다). + +── 카카오 대비 제약 (실측 확인, 2026-08-27) ───────────────────────────── + 후보 수 : **최대 5건** (카카오 15건). display 를 6·30 으로 줘도 400 이 아니라 + 조용히 5건으로 잘린다 — 그래서 클라이언트에서 명시적으로 5 로 클램프한다. + 전화번호 : **항상 빈 문자열** — 동명 업소를 가르는 가장 강한 근거가 없다. + 고유 place id: **없다.** `link` 는 네이버 플레이스 URL 이 아니라 **업체 자체 홈페이지**다 + (예: 스타벅스 → http://www.starbucks.co.kr/). 그래서 naver_place_id 는 보통 None 이다. + 행정구역 코드: **없다.** 대신 도로명주소에서 region_key() 로 캐시 키를 만든다. + +→ ★ 판정 근거가 카카오보다 약하다. 그만큼 pick_match 가 **더 쉽게 AMBIGUOUS 로 떨어진다.** + 후보를 억지로 하나 고르면 남의 가게 정보가 우리 사이트로 나가고, 그건 발행된 뒤에야 드러난다. + +── 응답 필드 (실측) ───────────────────────────────────────────────────── + title : `` 태그와 HTML 엔티티가 섞여 온다 → strip_tags 로 반드시 벗긴다 + link : 업체 홈페이지 URL (없으면 빈 문자열). 채널 URL 발견에 쓸 수 있는 부수입이다 + category : "숙박>펜션" 처럼 '>' 로 구분된 문자열 + telephone : 항상 "" + address : 지번 주소 / roadAddress : 도로명 주소 + mapx, mapy : **WGS84 를 1e7 배한 정수 문자열**. mapx=경도, mapy=위도. + 네이버가 2021년 이후 TM128(KATEC) 에서 WGS84*1e7 로 바꿨다. + 검산(2026-08-27): 서울특별시청 mapx=1269783882 mapy=375666103 → 126.97839, 37.56661 + (실제 37.5663, 126.9779 / 오차 0.0005 이내). 경복궁·해운대해수욕장도 동일하게 일치. + → 그래서 단순히 1e7 로 나눈다. 별도 좌표계 변환이 필요 없다. + +── 비용 ───────────────────────────────────────────────────────────────── +네이버 검색 API 는 무료지만 **일 25,000회 쿼터**가 있다(애플리케이션당). +호출 횟수는 LOG.i 로 남긴다 — 생성 1건당 검색 횟수를 세는 근거. +주변 정보는 반경 검색이 없어 "지역명 + 키워드" 로 찾으므로, ★ 반드시 지역 캐시를 거쳐 부른다. +""" + +import html +import re +from collections import Counter +from dataclasses import dataclass, field +from typing import Optional + +import httpx + +from common.logger import LOG +from config.server_configs import external_api_config + +# 판정 결과 enum 은 카카오 것을 그대로 쓴다 — 두 소스를 갈아끼워도 호출측 분기가 그대로여야 한다. +from services.external.kakao import MatchOutcome + +_LOCAL_URL = "https://openapi.naver.com/v1/search/local.json" + +# ★ 네이버 지역검색은 최대 5건이다. 더 요청해도 조용히 5건으로 잘린다(실측). +_MAX_DISPLAY = 5 + +# 프로세스 누적 호출 수 — 생성 1건당 검색 횟수를 세는 근거. +_CALL_COUNTS: Counter = Counter() + + +class NaverNotConfigured(RuntimeError): + """NAVER_CLIENT_ID / NAVER_CLIENT_SECRET 미설정 — 이 어댑터만 비활성이다. + + 서버 부팅을 막지 않는다(외부 계약에 부팅이 묶이면 안 된다). 호출측이 잡아 + ErrorType.LOCAL_NOT_CONFIGURED 로 응답한다.""" + + +class NaverRequestFailed(RuntimeError): + """네이버 지역검색 호출 실패(네트워크·타임아웃·5xx·파싱오류). + + ★ 실패했다고 빈 값을 내보내면 안 된다 — 호출측은 직전 값을 유지하고 내부 알림만 낸다.""" + + +# ---- 값 객체 ------------------------------------------------------------- +@dataclass(frozen=True) +class NaverPlace: + """네이버 지역검색이 돌려준 장소 1건. KakaoPlace 와 같은 필드 이름을 쓴다(갈아끼우기용). + + ★ phone 은 거의 항상 None 이다(네이버가 telephone 을 빈 값으로 준다). + ★ place_url 은 **업체 자체 홈페이지**다 — 네이버 플레이스 페이지가 아니다.""" + + name: str # title 에서 태그·엔티티를 벗긴 값 + road_address: Optional[str] # roadAddress + address: Optional[str] # address (지번) + phone: Optional[str] # telephone — 실측상 항상 None + latitude: Optional[float] # mapy / 1e7 + longitude: Optional[float] # mapx / 1e7 + category_name: Optional[str] # "숙박>펜션" + place_url: Optional[str] # link — 업체 홈페이지(네이버 플레이스 아님) + naver_place_id: Optional[str] # link 가 네이버 플레이스 URL 일 때만. 보통 None + + @classmethod + def from_item(cls, item: dict) -> "NaverPlace": + link = (item.get("link") or "").strip() or None + return cls( + name=strip_tags(item.get("title") or ""), + road_address=(item.get("roadAddress") or None), + address=(item.get("address") or None), + phone=(item.get("telephone") or None), # 빈 문자열 → None + latitude=_scaled_coord(item.get("mapy")), # ★ mapy = 위도 + longitude=_scaled_coord(item.get("mapx")), # ★ mapx = 경도 + category_name=(item.get("category") or None), + place_url=link, + naver_place_id=_extract_place_id(link), + ) + + +@dataclass +class MatchResult: + """동일 업소 판정 결과 + **판정 근거**. KakaoMatchResult 와 구조가 같다. + + 근거를 같이 들고 다니는 이유: ambiguous 로 떨어졌을 때 사람이 무엇을 보고 골라야 하는지 + 알아야 하고, matched 로 확정됐을 때도 나중에 '왜 이 가게로 붙었나' 를 추적해야 한다.""" + + outcome: MatchOutcome + place: Optional[NaverPlace] = None # MATCHED 일 때만 채워진다 + candidates: list[NaverPlace] = field(default_factory=list) # 사람이 고를 후보 전체 + reason: str = "" # 근거 코드(기계 판독용) + detail: str = "" # 근거 설명(사람 판독용) + + @property + def is_matched(self) -> bool: + return self.outcome == MatchOutcome.MATCHED + + +# ---- 문자열 정리 --------------------------------------------------------- +_TAG_RE = re.compile(r"<[^>]+>") +_WS_RE = re.compile(r"\s+") +# 네이버 플레이스 URL 에서 place id 를 뽑는다. link 는 보통 업체 홈페이지라 대개 안 걸린다. +_PLACE_ID_RE = re.compile(r"(?:place\.naver\.com|map\.naver\.com)[^\s]*?/(\d{6,})") + + +def strip_tags(text: str) -> str: + """title 에서 `` 하이라이트 태그와 HTML 엔티티를 벗긴다. + + ★ 순서가 중요하다 — 태그를 먼저 지우고 그 다음에 엔티티를 푼다. + 엔티티를 먼저 풀면 본문에 있던 '<b>'(진짜 텍스트)가 태그로 둔갑해 지워진다.""" + return html.unescape(_TAG_RE.sub("", text or "")).strip() + + +def normalize_name(name: str) -> str: + """상호명 비교용 정규화 — 공백 제거 + 소문자화. 그 이상은 하지 않는다. + + '하조대 펜션' 과 '하조대펜션' 은 같게 보되, '하조대펜션' 과 '하조대펜션 별관' 은 다르게 본다. + 과하게 정규화하면 다른 가게가 같은 이름으로 보인다.""" + return _WS_RE.sub("", strip_tags(name)).lower() + + +def _scaled_coord(value) -> Optional[float]: + """mapx/mapy(정수 문자열) → WGS84 도(degree). + + 네이버는 WGS84 를 1e7 배한 정수로 준다(2021년 TM128 에서 전환). 검산은 모듈 독스트링 참고.""" + try: + return int(value) / 1e7 + except (TypeError, ValueError): + return None + + +def _extract_place_id(link: Optional[str]) -> Optional[str]: + if not link: + return None + m = _PLACE_ID_RE.search(link) + return m.group(1) if m else None + + +# ---- 지역 캐시 키 -------------------------------------------------------- +# ★ 네이버는 행정구역 코드를 주지 않는다. 도로명주소에서 '시도 + 시군구' 를 뽑아 캐시 키를 만든다. +# 이 키가 local.local_contents.region_code(VARCHAR(10)) 에 들어간다 — 길이를 반드시 지켜야 한다. +# +# 시도 이름은 흔들린다(강원도 ↔ 강원특별자치도). 별칭을 전부 같은 코드로 모아야 +# 같은 지역이 두 키로 갈리지 않는다 — 갈리면 캐시가 무의미해진다. +_SIDO_CODES = { + "서울특별시": "11", "서울": "11", + "부산광역시": "26", "부산": "26", + "대구광역시": "27", "대구": "27", + "인천광역시": "28", "인천": "28", + "광주광역시": "29", # ※ '광주' 단독은 광역시. 경기도 광주시는 시도 토큰이 '경기도'라 안 겹친다 + "대전광역시": "30", "대전": "30", + "울산광역시": "31", "울산": "31", + "세종특별자치시": "36", "세종시": "36", "세종": "36", + "경기도": "41", "경기": "41", + "강원특별자치도": "51", "강원도": "51", "강원": "51", # 2023 개편 — 옛 이름도 같은 키로 + "충청북도": "43", "충북": "43", + "충청남도": "44", "충남": "44", + "전북특별자치도": "52", "전라북도": "52", "전북": "52", # 2024 개편 — 옛 이름도 같은 키로 + "전라남도": "46", "전남": "46", + "경상북도": "47", "경북": "47", + "경상남도": "48", "경남": "48", + "제주특별자치도": "50", "제주도": "50", "제주": "50", +} + +# 시군구가 없는 시도(단층제) — 시도 코드만으로 키를 만든다. +_SINGLE_TIER = {"36"} # 세종특별자치시 + +_REGION_KEY_MAX = 10 # local_contents.region_code = VARCHAR(10) + + +def region_key(road_address: Optional[str]) -> Optional[str]: + """도로명주소 → 지역 캐시 키(시도코드 2자리 + 시군구명). 못 만들면 None. + + ★ 이 키 단위로 지역 정보(날씨·축제·관광지·맛집)를 캐싱한다. + 같은 지역에 사이트가 50개 생겨도 외부 조회는 1회여야 한다. + + 예) + "강원특별자치도 양양군 현북면 하조대3길 25" → "51양양군" + "강원도 양양군 ..." → "51양양군" (옛 이름도 같은 키) + "서울특별시 강남구 도산대로57길 24" → "11강남구" + "세종특별자치시 한누리대로 2130" → "36세종" (시군구 단층제) + "경기도 성남시 분당구 ..." → "41성남시" (일반구는 시 단위로 묶는다) + "Tokyo, Japan" → None + + 일반구(성남시 분당구 등)를 시 단위로 묶는 이유: 날씨·축제·관광지는 구 단위로 다르지 않고, + 묶을수록 캐시 히트율이 올라간다. 특별시·광역시의 자치구(강남구 등)는 시도 바로 다음 토큰이라 + 그대로 구 단위로 남는다 — 생활권이 실제로 다르다.""" + if not road_address: + return None + tokens = _WS_RE.sub(" ", road_address.strip()).split(" ") + if not tokens: + return None + + sido_code = _SIDO_CODES.get(tokens[0]) + if sido_code is None: + # 매핑에 없는 시도(해외 주소·오타 등) — 억지로 만들지 않고 호출측에 넘긴다. + LOG.w(f"[naver] 지역 키를 만들 수 없는 주소(시도 미매핑): {road_address[:60]}") + return None + + if sido_code in _SINGLE_TIER: + key = f"{sido_code}세종" + else: + if len(tokens) < 2: + LOG.w(f"[naver] 지역 키를 만들 수 없는 주소(시군구 없음): {road_address[:60]}") + return None + key = f"{sido_code}{tokens[1]}" + + if len(key) > _REGION_KEY_MAX: + # 실측상 최대 8자라 여기 오지 않는다. 와도 DB 가 자르기 전에 우리가 자르고 남긴다. + LOG.w(f"[naver] 지역 키가 {len(key)}자라 {_REGION_KEY_MAX}자로 자릅니다: {key}") + key = key[:_REGION_KEY_MAX] + return key + + +# ---- 동일 업소 판정 ------------------------------------------------------ +def pick_match(name: str, candidates: list[NaverPlace], address_hint: Optional[str] = None) -> MatchResult: + """★ 검색 결과에서 '이 가게가 맞다' 를 판정한다. 이 서비스에서 가장 비싼 실수가 나는 지점이다. + + 카카오보다 **보수적이다.** 네이버는 전화번호를 주지 않아 동명 업소를 가를 결정적 근거가 + 하나 없고, 후보도 5건까지만 온다. 그만큼 더 쉽게 AMBIGUOUS 로 떨어뜨린다. + + 판정 순서 + 1. 후보 0건 → NO_CANDIDATE + 2. 정규화 상호명이 정확히 1건 일치 → MATCHED (name_exact) + 3. 정확 일치가 2건 이상 → address_hint 로 좁혀 1건이면 MATCHED (name_address) + 그래도 여럿이면 AMBIGUOUS (name_duplicate) + 4. 정확히 일치하는 상호명이 없음 → AMBIGUOUS (name_no_exact) + ★ 부분일치로는 절대 확정하지 않는다 + + ★ 억지로 하나 고르면 남의 가게 정보가 섞이고, 그건 사이트가 발행된 뒤에야 드러난다.""" + if not candidates: + return MatchResult( + outcome=MatchOutcome.NO_CANDIDATE, + candidates=[], + reason="no_candidate", + detail=f"'{name}' 으로 네이버 지역검색에서 후보를 찾지 못했습니다.", + ) + + pool = list(candidates) + target = normalize_name(name) + name_hits = [c for c in pool if normalize_name(c.name) == target] + + if len(name_hits) == 1: + return MatchResult( + outcome=MatchOutcome.MATCHED, + place=name_hits[0], + candidates=pool, + reason="name_exact", + detail=f"상호명이 정확히 1건과 일치합니다: {name_hits[0].name}", + ) + + if len(name_hits) > 1: + # 동명 업소 — 주소 힌트로 좁혀 본다. 전화번호가 없으니 이게 유일한 추가 근거다. + narrowed = _narrow_by_address(name_hits, address_hint) + if len(narrowed) == 1: + return MatchResult( + outcome=MatchOutcome.MATCHED, + place=narrowed[0], + candidates=pool, + reason="name_address", + detail=( + f"동명 업소 {len(name_hits)}건 중 주소('{address_hint}')로 1건으로 좁혔습니다: " + f"{narrowed[0].name}({narrowed[0].road_address or narrowed[0].address or '주소없음'})" + ), + ) + return MatchResult( + outcome=MatchOutcome.AMBIGUOUS, + candidates=name_hits, + reason="name_duplicate", + detail=( + f"'{name}' 과 상호명이 같은 업소가 {len(name_hits)}건입니다. " + f"네이버는 전화번호를 주지 않아 주소로 구분해야 합니다: " + + " / ".join(f"{c.name}({c.road_address or c.address or '주소없음'})" for c in name_hits) + ), + ) + + return MatchResult( + outcome=MatchOutcome.AMBIGUOUS, + candidates=pool, + reason="name_no_exact", + detail=( + f"'{name}' 과 정확히 일치하는 상호명이 없습니다. 후보 {len(pool)}건 중 사람이 골라야 합니다: " + + " / ".join(f"{c.name}({c.road_address or c.address or '주소없음'})" for c in pool[:_MAX_DISPLAY]) + ), + ) + + +def _narrow_by_address(candidates: list[NaverPlace], address_hint: Optional[str]) -> list[NaverPlace]: + """주소 힌트에 들어 있는 토큰으로 후보를 좁힌다. + + 힌트의 각 토큰(시군구·읍면동 등)이 후보 주소에 들어 있는지만 본다 — 도로명·번지까지 + 정확히 맞추라고 하면 표기 차이(괄호 법정동, 건물명)로 다 떨어진다.""" + if not address_hint: + return list(candidates) + tokens = [t for t in _WS_RE.sub(" ", address_hint.strip()).split(" ") if len(t) >= 2] + if not tokens: + return list(candidates) + + scored = [] + for c in candidates: + blob = f"{c.road_address or ''} {c.address or ''}" + hits = sum(1 for t in tokens if t in blob) + scored.append((hits, c)) + best = max((h for h, _ in scored), default=0) + if best == 0: + return list(candidates) # 아무것도 안 걸리면 좁히지 않는다(잘못 좁히면 남의 가게로 확정된다) + return [c for h, c in scored if h == best] + + +# ---- 클라이언트 ---------------------------------------------------------- +class NaverLocalClient: + """네이버 지역검색 API 호출기. + + 키가 없으면 생성은 되지만 호출 시 NaverNotConfigured 를 던진다 — + 부팅이 외부 계약에 묶이지 않게 하기 위함이다(설정이 비면 이 어댑터만 비활성).""" + + def __init__( + self, + client_id: Optional[str] = None, + client_secret: Optional[str] = None, + transport=None, + timeout: float = 10.0, + ): + # 명시하지 않으면 설정에서 읽는다. 테스트는 transport 를 주입한다. + self._client_id = external_api_config.naver_client_id if client_id is None else client_id + self._client_secret = external_api_config.naver_client_secret if client_secret is None else client_secret + self._transport = transport + self._timeout = timeout + self._client: Optional[httpx.AsyncClient] = None + + # ---- 내부 ---- + @property + def enabled(self) -> bool: + """키가 설정돼 있는지. 호출 전에 확인해 조용히 건너뛸 수 있게 한다.""" + return bool(self._client_id and self._client_secret) + + def _headers(self) -> dict: + if not self.enabled: + raise NaverNotConfigured( + "NAVER_CLIENT_ID / NAVER_CLIENT_SECRET 가 설정되지 않았습니다 — " + ".env 또는 config 의 [ExternalApiConfig] 를 확인하세요" + ) + return { + "X-Naver-Client-Id": self._client_id, + "X-Naver-Client-Secret": self._client_secret, + } + + def _get_client(self) -> httpx.AsyncClient: + if self._client is None or self._client.is_closed: + kwargs = {"timeout": httpx.Timeout(self._timeout, connect=5.0)} + if self._transport is not None: + kwargs["transport"] = self._transport + self._client = httpx.AsyncClient(**kwargs) + return self._client + + async def aclose(self): + if self._client is not None and not self._client.is_closed: + await self._client.aclose() + self._client = None + + async def _get(self, params: dict, kind: str) -> dict: + """공통 GET. 호출 1건마다 누적 횟수를 로그로 남긴다(쿼터 추적).""" + headers = self._headers() # 키 없으면 여기서 NaverNotConfigured + _CALL_COUNTS[kind] += 1 + LOG.i(f"[naver] {kind} 호출 (누적 {_CALL_COUNTS[kind]}회, 일 25,000회 쿼터) display={params.get('display')}") + try: + resp = await self._get_client().get(_LOCAL_URL, params=params, headers=headers) + except httpx.TimeoutException as ex: + raise NaverRequestFailed(f"네이버 지역검색 {kind} 타임아웃: {ex}") from ex + except httpx.HTTPError as ex: + raise NaverRequestFailed(f"네이버 지역검색 {kind} 요청 실패: {type(ex).__name__}: {ex}") from ex + + if resp.status_code in (401, 403): + # 키가 있지만 잘못됐거나 권한이 없다 — 설정 문제라 재시도해도 소용없다. + raise NaverNotConfigured( + f"네이버 지역검색 인증 실패({resp.status_code}) — 클라이언트 ID/Secret 과 " + f"검색 API 사용 설정을 확인하세요: {resp.text[:200]}" + ) + if resp.status_code != 200: + raise NaverRequestFailed( + f"네이버 지역검색 {kind} 응답 오류 status={resp.status_code} body={resp.text[:200]}" + ) + + try: + return resp.json() + except ValueError as ex: + raise NaverRequestFailed(f"네이버 지역검색 {kind} 응답 파싱 실패: {ex}") from ex + + # ---- 1) 상호명 → 주소·좌표 ---- + async def search_local(self, query: str, display: int = _MAX_DISPLAY, sort: str = "random") -> list[NaverPlace]: + """지역검색. **동일 업소 검증의 입력**이다. + + ★ display 는 5 가 상한이다. 더 요청해도 조용히 5건으로 잘리므로 여기서 명시적으로 클램프한다 + — '15건 요청했는데 5건만 왔다' 를 장애로 오해하지 않게 하려는 것이다. + + 반환된 목록은 그대로 pick_match 에 넘긴다 — 여기서 하나를 고르지 않는다.""" + params = { + "query": query, + "display": max(1, min(display, _MAX_DISPLAY)), + "sort": sort, + } + data = await self._get(params, "local") + return [NaverPlace.from_item(it) for it in (data.get("items") or [])] + + # ---- 2) 주변 맛집·시설 ---- + async def search_nearby( + self, + region_name: str, + keyword: str, + display: int = _MAX_DISPLAY, + region_key_hint: Optional[str] = None, + ) -> list[NaverPlace]: + """주변 맛집·시설을 찾는다. + + ★ 네이버 지역검색에는 **반경 검색이 없다.** 그래서 좌표가 아니라 "지역명 + 키워드" + (예: "양양군 맛집") 로 찾는다. 카카오의 category 검색과 결과 성격이 다르다 — + 거리순이 아니고, 그 지역 안이라는 것만 보장된다. + + ★ 반드시 지역 캐시를 거쳐 부른다. 같은 지역에 사이트가 50개 생겨도 조회는 1회여야 한다. + 캐싱은 이 클라이언트가 하지 않는다 — local 모듈이 local.local_contents 에 + `region_code + content_type` 키로 저장하고, 캐시 미스일 때만 여기를 부른다. + `region_key_hint` 는 그 캐시 키를 호출 지점에서 명시하게 하려고 받는다(로그에도 남는다).""" + if not region_key_hint: + LOG.w( + "[naver] search_nearby 를 지역 키 없이 호출했습니다 — " + "지역 단위 캐시를 거치지 않으면 같은 지역을 사이트 수만큼 반복 조회합니다" + ) + places = await self.search_local(f"{region_name} {keyword}", display=display) + LOG.i(f"[naver] 주변검색 '{region_name} {keyword}' region_key={region_key_hint or '미지정'} → {len(places)}건") + return places + + # ---- 조합: 상호명 하나로 동일 업소까지 ---- + async def verify_place( + self, + name: str, + address_hint: Optional[str] = None, + *, + search_query: Optional[str] = None, + ) -> MatchResult: + """상호명(+주소 힌트)으로 검색해서 동일 업소를 판정한다. + + 지역검색 1회만 쓴다. 주소 힌트가 있으면 검색어에도 섞어 후보를 깨끗하게 만든다 + (5건 상한이라 후보 품질이 카카오보다 중요하다). + + ★ **name 에는 상호명만 넣는다.** pick_match 가 후보 상호명과 정확일치를 보는데, + 여기에 지역까지 붙은 검색어('타코튜즈데이 성수 서울 성동구')를 넣으면 후보명 + ('타코튜즈데이 성수 본점')과 정확히 같을 수가 없다 — 판정이 구조적으로 언제나 + AMBIGUOUS(name_no_exact) 로 떨어진다. 실측(2026-08-28) 10건 전부 그랬고, + 후보가 단 1건일 때도 "비슷한 이름의 가게가 여럿입니다" 가 떴다. + 검색은 넓게, 판정은 좁게 — 그래서 검색어를 따로 받는다. + + 결과가 MATCHED 가 아니면 사람이 골라야 한다 — 호출측은 + AMBIGUOUS → ErrorType.PLACE_VERIFY_AMBIGUOUS, + NO_CANDIDATE → ErrorType.PLACE_VERIFY_NO_CANDIDATE 로 응답한다.""" + query = search_query or (f"{address_hint} {name}".strip() if address_hint else name) + candidates = await self.search_local(query) + if not candidates and query != name: + # 넓은 검색어로 0건이면 상호명만으로 한 번 더 본다(표기 차이로 0건이 나는 경우가 있다). + candidates = await self.search_local(name) + result = pick_match(name, candidates, address_hint) + detail = f"'{name}'" if query == name else f"'{name}' (검색어 '{query}')" + LOG.i(f"[naver] 동일 업소 판정 {detail} → {result.outcome.value} ({result.reason})") + return result + + +def call_counts() -> dict: + """프로세스 누적 호출 수 — 생성 1건당 검색 횟수를 세는 근거(쿼터 리포트용).""" + return dict(_CALL_COUNTS) + + +def reset_call_counts(): + """테스트/리포트 구간 분리용.""" + _CALL_COUNTS.clear() diff --git a/backend/services/external/naver_place_lookup.py b/backend/services/external/naver_place_lookup.py new file mode 100644 index 0000000..b8a9db4 --- /dev/null +++ b/backend/services/external/naver_place_lookup.py @@ -0,0 +1,131 @@ +"""상호·주소 → 네이버 플레이스 id. + +★ 왜 필요한가 + 채널 URL 발견은 Perplexity 가 맡는데, 네이버 플레이스만은 잘 못 찾는다. + 실측(2026-08-27 '도플로'·'버터브루'): 발견 URL 이 전부 야놀자·인스타였고, 필터를 + map.naver.com 까지 넓힌 뒤에도 네이버 쪽은 `pages.map.naver.com/useful-tips` 같은 + 안내 페이지가 걸렸다. 검색 언어모델에 맡기기엔 결과가 불안정하고 검색 요금도 든다. + + 그런데 우리는 이미 **이 가게가 누구인지 알고 있다**(동일 업소 검증을 통과한 상호·주소). + 그러면 추측할 이유가 없다 — 통합검색 결과에서 상호가 일치하는 place id 를 직접 고른다. + +★ 우회하지 않는다. 공개 검색 결과 페이지를 한 번 받아 id 를 읽을 뿐이고, + 막히면 그대로 빈 값을 돌려준다(호출측이 다른 경로로 간다). +""" +import re +from html import unescape +from typing import Optional + +import httpx + +from common.logger import LOG + +SEARCH_URL = "https://m.search.naver.com/search.naver" +REQUEST_TIMEOUT = 20 + +HEADERS = { + "User-Agent": ("Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) " + "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"), + "Accept-Language": "ko-KR,ko;q=0.9", +} + +_PLACE_ID = re.compile(r"(?:place\.naver\.com/[a-z]+/|/place/|\"placeId\"\s*:\s*\"?)(\d{8,12})") + +# id 주변에서 상호를 찾을 때 훑는 범위. +# +# ★ `"name":"…"` JSON 필드를 뽑아 비교하면 안 된다. 그 자리에 실제로 들어 있는 것은 +# 리뷰 키워드("주차하기 편해요")나 블로거 닉네임이고, 상호는 다른 형태로 박혀 있다. +# 그래서 **정규화한 원문 조각에 상호가 들어 있는지**로 판정한다 — 마크업 모양이 바뀌어도 버틴다. +_CONTEXT_BEFORE = 600 +_CONTEXT_AFTER = 300 + + + +def _normalize(text: str) -> str: + """상호 비교용 정규화. 네이버는 '스테이,머뭄'처럼 구두점을 넣어 표기한다. + + ★ `&` 도 지운다. 검색 결과 원문에는 `&` 로 실려 오기 때문에, 엔티티를 풀어도 + `&` 가 남으면 지역검색이 준 상호(`누에베 풀빌라&리조트`)와 원문 조각의 표기가 + 어긋난다. 실측(2026-08-28): 이 한 글자 때문에 place id 를 못 찾아 사장님이 + 네이버 지도 주소를 손으로 붙여넣어야 했다 — 10건 중 1건. + """ + return re.sub(r"[\s,·.\-_'\"()&]", "", (text or "")).lower() + + +async def _fetch_search_html(query: str) -> Optional[str]: + """통합검색 결과 페이지 원문. 실패는 None — 호출측이 조용히 폴백한다.""" + try: + async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT, follow_redirects=True) as client: + res = await client.get(SEARCH_URL, params={"query": query, "where": "m"}, headers=HEADERS) + if res.status_code != 200: + LOG.w(f"[naver_lookup] 검색 실패 HTTP {res.status_code} — query={query}") + return None + return res.text + except httpx.HTTPError as ex: + LOG.w(f"[naver_lookup] 검색 실패: {ex}") + return None + + +def _match_in_html(html: str, name: str) -> Optional[str]: + """검색 결과 원문에서 이 상호에 해당하는 place id 를 고른다. + + ★ `"name":"…"` 를 뽑아 비교하지 않는다. 그 자리에 실제로 들어 있는 것은 리뷰 키워드 + ("주차하기 편해요")나 블로거 닉네임이라 상호가 아니다. 그래서 **id 주변 원문을 + 정규화해 상호가 들어 있는지**로 판정한다 — 마크업이 바뀌어도 버틴다. + """ + target = _normalize(name) + if not target: + return None + for match in _PLACE_ID.finditer(html): + # ★ 엔티티를 먼저 푼다. 원문에는 상호가 `누에베 풀빌라&리조트` 처럼 인코딩돼 있어, + # 그대로 정규화하면 `amp` 라는 없는 글자가 상호 한가운데 남는다. + # 조각(≈900자)에만 적용한다 — 1.3MB 원문 전체를 후보마다 푸는 것은 낭비다. + window = _normalize( + unescape(html[max(0, match.start() - _CONTEXT_BEFORE): match.start() + _CONTEXT_AFTER]) + ) + if target in window: + return match.group(1) + return None + + +async def find_place_ids(query: str, names: list[str]) -> dict[str, str]: + """후보 상호들에 대해 {상호: place_id} 를 채운다. 못 찾은 상호는 빠진다. + + ★ 왜 후보 목록에 id 를 실어야 하나: 사장님이 후보를 고르는 순간 네이버 플레이스 id 가 + 확정되면, 나중에 수집 단계에서 상호를 다시 맞춰 볼 필요가 없다. 이름 맞추기는 + 동명 업소·지점명 표기 차이에서 틀리고, 틀리면 남의 가게를 긁는다. + + 검색은 **한 번만** 한다 — 후보 5건에 5번 요청하면 네이버가 막는다(429). + """ + html = await _fetch_search_html(query) + if not html: + return {} + found: dict[str, str] = {} + for name in names: + place_id = _match_in_html(html, name) + if place_id: + found[name] = place_id + return found + + +async def find_place_id(name: str, address: Optional[str] = None) -> Optional[str]: + """상호(+주소)로 네이버 플레이스 id 를 찾는다. 확신이 없으면 None. + + ★ 이름이 일치하는 후보만 받는다. '비슷한 것 중 첫 번째'를 고르면 남의 가게를 + 이 가게의 공식 채널로 등록하게 된다 — 이 제품에서 가장 비싼 실수다. + """ + query = " ".join(x for x in (name, (address or "").split()[0] if address else "") if x) + html = await _fetch_search_html(query) + if not html: + return None + place_id = _match_in_html(html, name) + if place_id: + LOG.i(f"[naver_lookup] '{name}' → place {place_id}") + return place_id + LOG.w(f"[naver_lookup] '{name}' 상호가 일치하는 후보를 찾지 못했다 — 자동 등록하지 않는다") + return None + + +def place_url(place_id: str) -> str: + """수집 어댑터가 그대로 처리할 수 있는 정규 주소.""" + return f"https://m.place.naver.com/place/{place_id}/home" diff --git a/backend/services/external/open_meteo.py b/backend/services/external/open_meteo.py new file mode 100644 index 0000000..ba1340e --- /dev/null +++ b/backend/services/external/open_meteo.py @@ -0,0 +1,43 @@ +"""Open-Meteo current-weather adapter. + +The adapter only knows the upstream protocol. Cache policy belongs to +LocalContentService so callers cannot accidentally bypass it. +""" + +from datetime import datetime +from typing import Any + +import httpx + + +OPEN_METEO_URL = "https://api.open-meteo.com/v1/forecast" + + +class OpenMeteoRequestFailed(RuntimeError): + pass + + +async def fetch_current_weather(latitude: float, longitude: float) -> dict[str, Any]: + params = { + "latitude": latitude, + "longitude": longitude, + "current": "temperature_2m,weather_code,wind_speed_10m", + "timezone": "auto", + } + try: + async with httpx.AsyncClient(timeout=httpx.Timeout(10.0, connect=5.0)) as client: + response = await client.get(OPEN_METEO_URL, params=params) + response.raise_for_status() + payload = response.json() + current = payload["current"] + return { + "temperature": current["temperature_2m"], + "weather_code": current["weather_code"], + "wind_speed": current.get("wind_speed_10m"), + "observed_at": current["time"], + "timezone": payload.get("timezone"), + "latitude": payload.get("latitude", latitude), + "longitude": payload.get("longitude", longitude), + } + except (httpx.HTTPError, KeyError, TypeError, ValueError) as ex: + raise OpenMeteoRequestFailed("Open-Meteo 날씨 조회에 실패했습니다.") from ex diff --git a/backend/services/external/perplexity.py b/backend/services/external/perplexity.py new file mode 100644 index 0000000..8f185eb --- /dev/null +++ b/backend/services/external/perplexity.py @@ -0,0 +1,143 @@ +"""채널 URL 발견 — 겹들을 엮어 결과를 만드는 자리. + +이 파일이 하는 일은 **엮는 것뿐**이다. 고칠 것이 생기면 해당 겹으로 바로 간다: + + 무엇을 묻는가 services/prompts/channel_discovery.py 프롬프트·응답 스키마 + 어떻게 부르는가 services/llm/perplexity.py HTTP·타임아웃·인증 + 답을 믿을 것인가 services/grounding/channels.py 채널 판정·상세 페이지 필터 + 무엇을 돌려주는가 여기 호출 → 필터 → 결과 조립 + +★ Perplexity 응답을 **사실로 쓰지 않는다.** 산출물은 "여기를 보라"는 URL 포인터일 뿐이고, + 사실은 그 URL 을 크롤링해 얻는다. 원문(raw)은 감사·환각 추적용으로 통째로 박제한다. +""" +from dataclasses import dataclass, field + +import httpx + +from common.logger import LOG +from services.grounding.channels import ( + DiscoveredLink, + classify_url, + collect_links, + filter_links, + search_count, +) +from services.llm.perplexity import ( + DEFAULT_MAX_TOKENS, + DEFAULT_MODEL, + DEFAULT_TIMEOUT, + PerplexityError, + PerplexityNotConfigured, + call, + is_configured, +) +from services.prompts.channel_discovery import RESPONSE_SCHEMA, SYSTEM_PROMPT, build_prompt + +# 후기 유입을 막기 위해 공식 채널 도메인만 검색한다. +SEARCH_DOMAIN_FILTER = [ + "yanolja.com", + "goodchoice.kr", + "place.naver.com", + "map.naver.com", + "naver.me", +] + +# 이 횟수를 넘으면 프롬프트·도메인 필터를 의심한다 — 검색 요금은 토큰 요금과 별도다. +SEARCH_COUNT_WARN_THRESHOLD = 8 + + + +@dataclass +class ChannelDiscovery: + """채널 발견 결과. + + links : 상세 페이지로 판정돼 살아남은 후보 URL. 동일 업소 검증을 통과해야 크롤링 대상이 된다 + raw : 응답 원문(본문 + search_results). place_links.raw 에 통째로 박제한다 + search_count : 이번 호출에서 발생한 검색 횟수 — **검색 요금이 토큰 요금과 별도**라 추적한다 + filtered_out : 걸러낸 URL 과 사유 [(url, reason), ...]. + ★ 조용히 버리지 않는다 — 운영자가 "왜 이 URL 이 빠졌나"를 볼 수 있어야 + 필터가 과했는지(진짜 채널을 버렸는지) 판단할 수 있다 + """ + + links: list[DiscoveredLink] = field(default_factory=list) + raw: dict = field(default_factory=dict) + search_count: int = 0 + filtered_out: list[tuple[str, str]] = field(default_factory=list) + + def reason_counts(self) -> dict[str, int]: + """탈락 사유별 건수. 로그·운영 화면에서 쓴다.""" + counts: dict[str, int] = {} + for _url, reason in self.filtered_out: + counts[reason] = counts.get(reason, 0) + 1 + return counts + + +async def discover_channels( + name: str, + address: str | None = None, + category_hint: str | None = None, + *, + model: str = DEFAULT_MODEL, + include_blogs: bool = False, + client: httpx.AsyncClient | None = None, +) -> ChannelDiscovery: + """상호명으로 채널 URL 후보를 찾는다. **URL 발견 전용 — 답변을 사실로 쓰지 마라.** + + 돌려주는 URL 은 아직 '이 가게의 것'이라는 보장이 없다. 동일 업소 검증을 통과해 + 확정(place_links.confirmed_at)된 URL 만 크롤링 대상이 된다. + + 발견된 URL 중 **상세 페이지가 아닌 것(루트·목록·SEO 랜딩)과 블로그는 걸러낸다.** + 걸러낸 목록은 `filtered_out` 에 사유와 함께 남는다 — 조용히 버리지 않는다. + + args: + include_blogs : 블로그·카페 URL 도 후보로 남길지. **기본 False** — + 블로그는 채널이 아니라 후기라 크롤링해도 공식 정보가 아니다 + + raises: + PerplexityNotConfigured : 키 미설정(이 어댑터만 비활성) + PerplexityError : 타임아웃·5xx·응답 파싱 불가 + """ + if not (name or "").strip(): + raise PerplexityError("상호명이 비어 있다") + + body = { + "model": model, + "messages": [ + { + "role": "system", + "content": SYSTEM_PROMPT, + }, + {"role": "user", "content": build_prompt(name, address, category_hint)}, + ], + "max_tokens": DEFAULT_MAX_TOKENS, + "temperature": 0, # URL 수집이라 창의성이 해롭다 + "response_format": RESPONSE_SCHEMA, + "search_domain_filter": SEARCH_DOMAIN_FILTER, # ★ 야놀자·여기어때·네이버로 한정 + } + payload = await call(body, client=client) + + found, dropped_raw = collect_links(payload) + links, dropped_quality = filter_links(found, include_blogs) + filtered_out = dropped_raw + dropped_quality + searches = search_count(payload) + + result = ChannelDiscovery( + links=links, raw=payload, search_count=searches, filtered_out=filtered_out + ) + + # 내부 검색 횟수는 품질·지연 관측값이다. Sonar 과금은 토큰 + 요청 컨텍스트 요금이다. + usage = payload.get("usage") or {} + reasons = result.reason_counts() + reason_text = " ".join(f"{k}{v}" for k, v in sorted(reasons.items())) or "없음" + LOG.i( + f"[perplexity] '{name}' 검색={searches}회 발견={len(found)} 통과={len(links)} " + f"탈락={len(filtered_out)}({reason_text}) tokens={usage.get('total_tokens', '?')}" + ) + if searches > SEARCH_COUNT_WARN_THRESHOLD: + LOG.w( + f"[perplexity] 검색 {searches}회 — 기준({SEARCH_COUNT_WARN_THRESHOLD}회) 초과. " + f"지연·오탐 후보가 늘 수 있으니 도메인 필터·프롬프트를 확인하라" + ) + + # raw 는 응답 전체를 그대로 둔다 — 나중에 환각 추적에 쓴다(사실 근거로는 쓰지 않는다). + return result diff --git a/backend/services/external/tour_api.py b/backend/services/external/tour_api.py new file mode 100644 index 0000000..a4102ae --- /dev/null +++ b/backend/services/external/tour_api.py @@ -0,0 +1,73 @@ +"""공공데이터포털 전국문화축제표준데이터 클라이언트. + +설정 키 이름은 기존 배포 계약을 유지하기 위해 TOUR_API_KEY를 그대로 사용한다. +""" + +import hashlib +from datetime import date +from urllib.parse import unquote + +import httpx + +from config.server_configs import external_api_config + +_URL = "https://api.data.go.kr/openapi/tn_pubr_public_cltur_fstvl_api" + + +class TourApiNotConfigured(RuntimeError): + pass + + +class TourApiRequestFailed(RuntimeError): + pass + + +def _normalize(item: dict) -> dict: + """표준데이터 필드명을 화면/저장소의 공통 축제 필드로 변환한다.""" + identity = "|".join(str(item.get(key) or "") for key in ("fstvlNm", "fstvlStartDate", "fstvlEndDate", "insttCode")) + return { + "contentid": hashlib.sha256(identity.encode("utf-8")).hexdigest()[:32], + "title": item.get("fstvlNm"), + "eventstartdate": str(item.get("fstvlStartDate") or "").replace("-", ""), + "eventenddate": str(item.get("fstvlEndDate") or "").replace("-", ""), + "addr1": item.get("rdnmadr") or item.get("lnmadr") or item.get("eventPlace"), + "mapx": item.get("longitude"), + "mapy": item.get("latitude"), + "tel": item.get("phoneNumber"), + "homepage": item.get("homepageUrl"), + "organizer": item.get("suprtInsttNm"), + "overview": item.get("relateInfo") or item.get("opar"), + "raw": item, + } + + +async def search_festivals(*, start_date: date, area_code: str | None = None, rows: int = 100) -> list[dict]: + key = (external_api_config.tour_api_key or "").strip() + if not key: + raise TourApiNotConfigured("TOUR_API_KEY is not configured") + params = { + # 포털의 "Encoding" 키를 넣어도 httpx가 이중 인코딩하지 않도록 원문으로 되돌린다. + "serviceKey": unquote(key), + "type": "json", + "numOfRows": max(1, min(rows, 1000)), + "pageNo": 1, + } + try: + async with httpx.AsyncClient(timeout=httpx.Timeout(20.0, connect=5.0)) as client: + response = await client.get(_URL, params=params) + response.raise_for_status() + payload = response.json() + response_data = payload.get("response", payload) + header = response_data.get("header", {}) + if header.get("resultCode") not in (None, "00", "0000"): + raise TourApiRequestFailed(header.get("resultMsg") or "TourAPI returned an error") + items_node = response_data.get("body", {}).get("items", []) + items = items_node.get("item", []) if isinstance(items_node, dict) else items_node + if isinstance(items, dict): + items = [items] + normalized = [_normalize(item) for item in (items or [])] + # API가 날짜 필터를 제공하지 않으므로 종료된 축제는 애플리케이션에서 제외한다. + cutoff = start_date.strftime("%Y%m%d") + return [item for item in normalized if not item["eventenddate"] or item["eventenddate"] >= cutoff] + except (httpx.HTTPError, ValueError, TypeError) as ex: + raise TourApiRequestFailed(str(ex)) from ex diff --git a/backend/services/external/tour_lookup.py b/backend/services/external/tour_lookup.py new file mode 100644 index 0000000..91884a5 --- /dev/null +++ b/backend/services/external/tour_lookup.py @@ -0,0 +1,243 @@ +"""TourAPI 콘텐츠 조회 — 검증된 상호·좌표로 contentId 를 직접 해석한다. + +★ 왜 Perplexity 에 맡기지 않나 (services/collect_service.discover_naver_place 와 같은 이유) + 우리는 이미 **이 가게가 누구인지 안다** — 동일 업소 검증을 통과한 상호와 좌표가 있다. + 추측할 이유가 없다. 게다가 채널 발견 프롬프트는 야놀자·여기어때·네이버만 찾으므로 + TourAPI URL 은 애초에 그 경로로 들어올 수 없다. + +★ 남의 가게를 붙이지 않는 것이 여기서 가장 비싼 실수다 + 상호만 비슷한 다른 업소를 공식 채널로 등록하면, 그 집 객실 요금이 우리 사장님 사이트에 실린다. + 그래서 두 관문을 **모두** 통과해야 등록한다: + ① 정규화한 상호가 일치(포함 관계 허용 — "롯데호텔 월드" ↔ "롯데호텔월드") + ② 좌표 거리가 MAX_DISTANCE_M 이내(좌표를 모르면 이 관문은 건너뛴다) + 하나라도 어긋나면 None 을 돌려준다. 자동 등록하지 않는다. + +★ 업종 매핑 + TourAPI 는 카페를 별도 타입으로 두지 않는다 — 음식점(39)의 소분류(cat3=A05020900)다. + 그래서 카페·음식점은 같은 contentTypeId 로 조회하고, 어느 쪽인지는 우리 업종 코드가 정한다. +""" +import math +import re +from typing import Optional +from urllib.parse import unquote, urlencode + +import httpx + +from common.enums import PlaceCategory +from common.logger import LOG +from config.server_configs import external_api_config +# ★ 출처 주소 규칙은 어댑터 한 곳에서만 정의한다. 두 곳이 다른 URL 을 만들면 +# 같은 레코드가 다른 출처로 기록돼 재수집 때 중복 fact 가 생긴다. +from services.collector.tour_api_adapter import SOURCE_URL + +BASE_URL = "https://apis.data.go.kr/B551011/KorService2" +REQUEST_TIMEOUT = 20 + +# 우리 업종 → TourAPI contentTypeId. 관광체험은 타입이 여러 개로 갈려(12·14·28) 단정할 수 없으므로 뺀다. +CATEGORY_TO_CONTENT_TYPE = { + PlaceCategory.LODGING: "32", + PlaceCategory.CAFE: "39", + PlaceCategory.RESTAURANT: "39", +} + +# 같은 업소로 볼 좌표 거리 상한. 대형 호텔은 등록 좌표가 정문/로비로 갈려 수백 m 벌어진다 — +# 너무 좁히면 맞는 업소를 놓치고, 너무 넓히면 옆 건물 가게가 붙는다. +MAX_DISTANCE_M = 500 + +# 상호를 짧혀가며 다시 물어보는 최대 횟수. ★ 무한정 짧히면 "그래비티" 같은 한 토큰까지 가서 +# 전혀 다른 업소가 후보로 올라온다 — 게이트가 막아주긴 하지만 호출만 낭비된다. +MAX_QUERY_ATTEMPTS = 4 + + +def normalize(text: str) -> str: + """상호 대조용 정규화. 공백·기호를 걷어내고 소문자로. + + ★ naver_place_lookup._normalize 와 같은 규칙을 쓴다 — 두 조회가 다른 기준으로 + '일치' 를 판정하면 한쪽만 붙는 업소가 생긴다. + """ + return re.sub(r"[\s,·.\-_'\"()&]", "", (text or "")).lower() + + +def _name_matches(query_name: str, candidate: str) -> bool: + """정규화 후 한쪽이 다른 쪽을 포함하면 같은 업소로 본다. + + TourAPI 표기가 우리 상호보다 길거나 짧은 경우가 흔하다 + (실측: '가재와곰' ↔ '가재와곰펜션', '롯데호텔 월드' ↔ '롯데호텔월드'). + ★ 다만 너무 짧은 상호는 포함 판정이 헐거워지므로 2자 이하면 완전 일치만 인정한다. + """ + a, b = normalize(query_name), normalize(candidate) + if not a or not b: + return False + if min(len(a), len(b)) <= 2: + return a == b + return a in b or b in a + + +def _distance_m(lat1: float, lng1: float, lat2: float, lng2: float) -> float: + """두 좌표의 거리(m). 국내 범위라 하버사인이면 충분하다.""" + r = 6_371_000 + p1, p2 = math.radians(lat1), math.radians(lat2) + dp, dl = math.radians(lat2 - lat1), math.radians(lng2 - lng1) + h = math.sin(dp / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2 + return 2 * r * math.asin(math.sqrt(h)) + + +def is_configured() -> bool: + return bool((external_api_config.tour_api_key or "").strip()) + + +def content_url(content_id: str) -> str: + """이 레코드를 가리키는 출처 주소(인증키 없음). 어댑터의 SOURCE_URL 과 같은 규칙이다.""" + return SOURCE_URL.format(content_id=content_id) + + +async def _search(client: httpx.AsyncClient, key: str, **params) -> list[dict]: + query = urlencode( + {"serviceKey": unquote(key), "MobileOS": "ETC", "MobileApp": "o2o-web4ai", + "_type": "json", "numOfRows": "20", "pageNo": "1", **params}, + safe="", + ) + res = await client.get(f"{BASE_URL}/searchKeyword2?{query}") + if res.status_code != 200: + raise RuntimeError(f"searchKeyword2 HTTP {res.status_code}") + try: + payload = res.json() + except ValueError: + raise RuntimeError(f"searchKeyword2 응답이 JSON 이 아니다: {res.text[:160]}") + + header = payload.get("response", {}).get("header", {}) + code = str(header.get("resultCode") or "") + if code not in ("0000", "00"): + raise RuntimeError(f"searchKeyword2 실패 [{code}] {header.get('resultMsg')}") + + items = (payload.get("response", {}).get("body", {}).get("items") or {}).get("item") + if isinstance(items, dict): + return [items] + return items or [] + + +def _query_candidates(name: str) -> list[str]: + """검색어 후보 — 전체 상호부터 시작해 **뒤 토큰을 하나씩 떼며** 짧게 만든다. + + ★ 왜 필요한가 (2026-08-31 실측) + searchKeyword2 는 토큰을 AND 로 묶는 것처럼 동작한다. 그래서 우리 상호가 등록명보다 + 길면 **0건**이 나온다: + "그래비티 조선 서울 판교 오토그래프 컬렉션" → 0건 + "그래비티 조선" → 1건 (등록명 '그래비티 조선 서울 판교') + 브랜드 수식어(오토그래프 컬렉션·컬렉션 바이 …)가 뒤에 붙는 호텔에서 늘 생기는 문제라 + 한 번 실패하고 마는 대신 짧혀가며 다시 묻는다. + + ★ 짧아질수록 남의 가게가 걸릴 위험이 커지지만, 최종 판정은 여전히 + 상호 일치 + 좌표 게이트가 한다. 여기서는 후보를 넓히기만 한다. + """ + tokens = [t for t in re.split(r"\s+", (name or "").strip()) if t] + if not tokens: + return [] + out: list[str] = [] + for end in range(len(tokens), 0, -1): + q = " ".join(tokens[:end]) + if len(normalize(q)) >= 2 and q not in out: + out.append(q) + if len(out) >= MAX_QUERY_ATTEMPTS: + break + return out + + +_TYPE_LABEL = {"32": "숙박", "39": "음식점·카페", "12": "관광지", "14": "문화시설", "28": "레포츠", "38": "쇼핑"} + + +async def _warn_if_other_content_type(key: str, name: str, expected: str) -> None: + """같은 상호가 **다른 콘텐츠 타입**으로 등록돼 있으면 로그로 알린다. + + ★ 조회 결과를 바꾸지 않는다. 업종이 다르면 스키마도 달라서, 숙박 fact 를 카페 사업장에 + 밀어 넣어봐야 대부분 스키마 밖 key 로 거부된다(실측: 3건 중 1건만 저장됐다). + 고쳐야 할 것은 조회가 아니라 **사업장 업종 등록**이므로, 사람이 볼 수 있게 남기기만 한다. + """ + try: + async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client: + for query in _query_candidates(name): + found = await _search(client, key, keyword=query) + for item in found: + other = str(item.get("contenttypeid") or "") + if other and other != expected and _name_matches(name, str(item.get("title") or "")): + LOG.w( + f"[tour_lookup] ★ 업종 불일치 — '{name}' 은 TourAPI 에 " + f"{_TYPE_LABEL.get(other, other)}({other}) 로 등록돼 있는데 " + f"이 사업장은 {_TYPE_LABEL.get(expected, expected)}({expected}) 로 조회했다. " + f"사업장 업종 등록을 확인하세요." + ) + return + if found: + return + except (httpx.HTTPError, RuntimeError): + return # 진단용이라 실패해도 조용히 넘어간다 + + +async def find_content_id( + name: str, + category: PlaceCategory, + *, + latitude: Optional[float] = None, + longitude: Optional[float] = None, +) -> Optional[tuple[str, str]]: + """(contentId, contentTypeId) 또는 None. + + ★ 상호가 일치하지 않거나 좌표가 멀면 **찾지 못한 것으로 처리한다.** + 틀린 업소를 붙이느니 안 붙이는 편이 낫다 — 사장님이 직접 주소를 넣는 경로가 살아 있다. + """ + key = (external_api_config.tour_api_key or "").strip() + if not key: + return None + content_type = CATEGORY_TO_CONTENT_TYPE.get(category) + if not content_type: + return None + + items: list[dict] = [] + try: + async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client: + for query in _query_candidates(name): + items = await _search(client, key, keyword=query, contentTypeId=content_type) + if items: + if query != name: + LOG.i(f"[tour_lookup] '{name}' 0건 → '{query}' 로 축약해 {len(items)}건") + break + except httpx.HTTPError as ex: + LOG.w(f"[tour_lookup] 조회 실패(계속): {type(ex).__name__}: {ex}") + return None + except RuntimeError as ex: + LOG.w(f"[tour_lookup] 조회 실패(계속): {ex}") + return None + + best: Optional[tuple[float, dict]] = None + for item in items: + title = str(item.get("title") or "") + if not _name_matches(name, title): + continue + + distance = 0.0 + if latitude is not None and longitude is not None: + try: + distance = _distance_m(latitude, longitude, float(item["mapy"]), float(item["mapx"])) + except (KeyError, TypeError, ValueError): + # 좌표가 없는 항목은 거리로 거를 수 없다 — 상호만 맞으면 후순위 후보로 둔다. + distance = float(MAX_DISTANCE_M) + if distance > MAX_DISTANCE_M: + LOG.i(f"[tour_lookup] '{title}' 상호는 맞지만 {distance:.0f}m 떨어져 있어 제외") + continue + if best is None or distance < best[0]: + best = (distance, item) + + if best is None: + # ★ 타입을 안 걸고 한 번 더 본다 — 업종을 잘못 등록하면 여기서만 알 수 있다. + # 실측(2026-08-31): 같은 호텔을 '카페' 로 등록했더니 39(음식점)로 조회돼 0건이었다. + # TourAPI 에는 32(숙박)로 있었다. 조용히 '없음' 으로 끝내면 원인을 못 찾는다. + await _warn_if_other_content_type(key, name, content_type) + LOG.i(f"[tour_lookup] '{name}' 일치하는 TourAPI 콘텐츠 없음 (후보 {len(items)}건)") + return None + + item = best[1] + LOG.i( + f"[tour_lookup] '{name}' → contentId={item['contentid']} " + f"({item.get('title')}, {best[0]:.0f}m)" + ) + return str(item["contentid"]), str(item.get("contenttypeid") or content_type) diff --git a/backend/services/fact_service.py b/backend/services/fact_service.py new file mode 100644 index 0000000..cfd8b8b --- /dev/null +++ b/backend/services/fact_service.py @@ -0,0 +1,475 @@ +import uuid + +from fastapi import Depends + +from common.category_schema import CategorySchemaError, get_schema +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import facts, places, units +from common.enums import ( + FACT_STATUS_TRANSITIONS, + PUBLISHABLE_FACT_STATUSES, + DBWRType, + ErrorType, + FactStatus, + FactWriteOutcome, + PlaceCategory, + SourceType, +) +from common.logger import LOG +from common.models.gmodel import UserInfo +from common.utils.gtime import GTime +from crud.fact_crud import FactCRUD, IFactCRUD +from crud.place_crud import PlaceCRUD +from router.v1.fact.protocol import ( + FactData, + FieldSpecData, + Req_TransitionFact, + Req_UpsertFact, + Res_CategorySchema, + Res_ExtractedFact, + Res_ExtractFacts, + Res_Fact, + Res_FactList, +) +from services.external.gemini_extract import extract_facts +from services.llm.gemini import GeminiError, GeminiNotConfigured + +# 사장님이 붙여넣은 원문의 출처 표기. ★ 실제 URL 이 아니라 경로 식별자다 — +# fact 는 출처가 비면 거부되는데(FACT_SOURCE_REQUIRED), 이 값은 웹 주소가 없다. +# '어디서 왔는가' 는 여전히 명확하다: 사장님이 화면에 직접 붙여넣었다. +OWNER_PASTE_SOURCE = "owner:paste" + +# 자동 수집 출처 — 노출값을 직접 바꾸지 못하고 후보로만 들어간다. +_AUTO_SOURCES = (SourceType.API, SourceType.CRAWL, SourceType.LLM) + + +class FactService: + """fact 기록 + 검증 상태 전이. + + ── 세 갈래 프로세스 ──────────────────────────────────────────────── + 생성 : 자동 수집 → 후보(UNVERIFIED) → 사람이 승인 → 노출값(VERIFIED) → 사이트 빌드 + 업데이트: 재수집 → 값이 같으면 검증 유지(REFRESHED) + 값이 다르면 **노출값은 그대로 두고** 후보(PENDING_OWNER)로 적재 + → 사람이 승인해야 노출값이 교체된다 + 수정 : 사람이 직접 입력 → 노출값 즉시 교체. 정정(CORRECTED)은 잠금 표시가 붙는다 + + 핵심은 재수집이 노출 중인 사실을 밀어내지 않는다는 것이다. 밀어내면 사이트에서 + 체크인 시간 같은 항목이 사라지고, 그 사이 방문자는 정보를 못 본다. + + 지켜야 하는 규칙: + 1. key 는 사업장 업종 스키마에 있는 것만 (FACT_INVALID_KEY) + 2. owner 가 아닌 출처는 source_url 필수 (FACT_SOURCE_REQUIRED) + 3. LLM 은 스키마가 허용한 문장 필드에만 쓴다 (절대규칙 7) + 4. 자동 수집은 노출값을 직접 못 바꾼다 — 후보로만 (절대규칙 1·6) + 5. 상태 전이는 FACT_STATUS_TRANSITIONS 에 있는 것만 + """ + + def __init__(self, crud: IFactCRUD = Depends(FactCRUD), place_crud: PlaceCRUD = Depends(PlaceCRUD)): + self.crud = crud + self.place_crud = place_crud + + # ---- 사업장 로드(회사 스코프) ---- + async def _load_place(self, user_info: UserInfo, place_id: str): + err_type, place = await DB_SESSION_MNG.execute_lambda( + places.DBType(), + DBWRType.DB_READ.value, + lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)), + ) + if err_type != ErrorType.SUCCESS: + return ErrorType.PLACE_NOT_FOUND, None + return ErrorType.SUCCESS, place + + async def _mark_content_updated(self, place_id: str, ts): + """★ 노출값이 실제로 바뀌었다 — 이 사업장만 다시 빌드하면 된다는 표시. + 부가 효과라 실패해도 본 흐름을 막지 않는다(다음 변경 때 다시 찍힌다).""" + err = await DB_SESSION_MNG.execute_lambda_run( + [places.DBType()], + [lambda s: self._touch(s, place_id, ts)], + ) + if err != ErrorType.SUCCESS: + LOG.e_no_callstack(f"[fact] content_updated_at 갱신 실패 place={place_id}") + + async def _touch(self, s, place_id: str, ts): + from sqlalchemy import update + + query = update(places).where(places.place_id == uuid.UUID(place_id)).values(content_updated_at=ts, updated_at=ts) + return await DB_SESSION_MNG.add(s, query) + + # ---- 업종 스키마 노출(관리 화면 폼 생성용) ---- + async def get_category_schema(self, user_info: UserInfo, place_id: str) -> Res_CategorySchema: + res = Res_CategorySchema() + err_type, place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + try: + schema = get_schema(PlaceCategory(place.category)) + except (CategorySchemaError, ValueError): + res.result.SetResult(ErrorType.PLACE_INVALID_CATEGORY) + return res + res.category = schema.name + res.label = schema.label + res.fields = [FieldSpecData(**spec.to_dict()) for spec in schema.fields.values()] + return res + + # ---- 조회 ---- + async def list_facts(self, user_info: UserInfo, place_id: str, unit_id=None, publishable_only: bool = False) -> Res_FactList: + res = Res_FactList() + err_type, _place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + list_err, rows = await DB_SESSION_MNG.execute_lambda( + facts.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.list_facts(s, uuid.UUID(place_id), unit_id, None, publishable_only, True), + ) + if list_err != ErrorType.SUCCESS: + res.result.SetResult(list_err) + return res + res.facts = [FactData.model_validate(r) for r in rows] + # ★ 사이트에 나갈 수 있는 건수. 발행 게이트가 보는 숫자와 같은 기준이다. + res.publishable = sum(1 for r in rows if FactStatus(r.status) in PUBLISHABLE_FACT_STATUSES) + # 재수집이 올려놓은 확인 대기 건수 — 관리 화면의 '검토할 것' 배지. + res.pending_review = sum(1 for r in rows if FactStatus(r.status) == FactStatus.PENDING_OWNER) + return res + + # ---- 기록 ---- + async def extract_from_text(self, user_info: UserInfo, place_id: str, text: str) -> Res_ExtractFacts: + """사장님이 붙여넣은 원문 → fact 후보. + + ★ 폴백 3단계의 2번이다. TourAPI 에 없고 네이버에도 요금표뿐인 업소 + (실측: 조이모텔)는 이 입구가 없으면 발행 근거가 영영 안 찬다. + + ★ 안전장치는 두 겹이다. + ① services/grounding/extract.py 가 **모델이 적은 근거 문장이 원문에 실제로 있는지** + 대조한다. 없으면 버린다(지어낸 값 차단). + ② 통과한 값도 여기서 upsert_fact 를 그대로 탄다 — 스키마 검사·CORRECTED 잠금 등 + 기존 관문을 우회하는 뒷문을 만들지 않는다. + + ★ source_type 은 CRAWL 이 아니라 **OWNER 가 아니다**. 사장님이 붙여넣긴 했지만 + 값을 고른 것은 모델이므로 LLM 으로 남긴다 — 출처를 사람으로 위장하면 + "사장님이 확인한 값" 과 구분이 사라진다. + """ + res = Res_ExtractFacts() + err_type, place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + try: + schema = get_schema(PlaceCategory(place.category)) + except (CategorySchemaError, ValueError): + res.result.SetResult(ErrorType.PLACE_INVALID_CATEGORY) + return res + + try: + extracted = await extract_facts( + place.name, PlaceCategory(place.category), text, + source_url=OWNER_PASTE_SOURCE, + ) + except GeminiNotConfigured: + res.result.SetResult(ErrorType.GENERATOR_NOT_CONFIGURED) + return res + except GeminiError as ex: + LOG.w(f"[fact] 붙여넣기 추출 실패: {type(ex).__name__}: {ex}") + res.result.SetResult(ErrorType.GENERATOR_CALL_FAILED) + return res + + res.rejections = [[label, why] for label, why in extracted.rejected] + res.rejected = len(extracted.rejected) + + # 단위(객실·메뉴) 이름을 실제 unit 으로 매핑한다. 없는 단위는 만들지 않는다 — + # 단위 생성은 수집 파이프라인(ensure_units)의 일이라 여기서 늘리지 않는다. + unit_map = await self._unit_map(place_id) + + for fact in extracted.facts: + spec = schema.get(fact.key) + row = Res_ExtractedFact( + key=fact.key, + label=(spec.label if spec else fact.key), + value=str(fact.value or ""), + unit_name=fact.unit_name, + ) + unit_id = unit_map.get(fact.unit_name) if fact.unit_name else None + if fact.unit_name and unit_id is None: + row.reason = f"'{fact.unit_name}' 단위가 아직 없다 — 수집으로 객실·메뉴가 먼저 만들어져야 한다" + res.facts.append(row) + res.rejected += 1 + continue + + write = await self.upsert_fact(user_info, place_id, Req_UpsertFact( + key=fact.key, + value=fact.value, + unit_id=unit_id, + source_type=SourceType.LLM, + source_url=OWNER_PASTE_SOURCE, + )) + if write.result.result == ErrorType.SUCCESS.value: + row.stored = True + res.stored += 1 + else: + row.reason = write.result.desc or "저장 실패" + res.rejected += 1 + res.facts.append(row) + + LOG.i(f"[fact] 붙여넣기 추출 — 저장 {res.stored}건 · 반려 {res.rejected}건 (place={place_id})") + return res + + async def _unit_map(self, place_id: str) -> dict: + """단위 이름 → unit_id. 붙여넣기 값이 어느 객실 것인지 잇는 데만 쓴다.""" + err, rows = await DB_SESSION_MNG.execute_lambda( + units.DBType(), + DBWRType.DB_READ.value, + lambda s: self.place_crud.list_units(s, uuid.UUID(place_id)), + ) + if err != ErrorType.SUCCESS: + return {} + return {r.name: r.unit_id for r in (rows or []) if r.name} + + + async def upsert_fact(self, user_info: UserInfo, place_id: str, req: Req_UpsertFact) -> Res_Fact: + """fact 를 기록한다. 출처에 따라 경로가 갈린다. + + 사람(owner) → 노출값을 직접 교체한다(수정 프로세스) + 자동 수집 → 노출값과 같으면 확인 시각만 갱신, 다르면 후보로 적재(업데이트 프로세스) + """ + res = Res_Fact() + err_type, place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + # 규칙 1 — 업종 스키마에 있는 key 만 + try: + schema = get_schema(PlaceCategory(place.category)) + except (CategorySchemaError, ValueError): + res.result.SetResult(ErrorType.PLACE_INVALID_CATEGORY) + return res + spec = schema.get(req.key) + if spec is None: + res.result.SetResult(ErrorType.FACT_INVALID_KEY) + return res + + # 규칙 2 — owner 가 아니면 출처 URL 필수 + if req.source_type != SourceType.OWNER and not (req.source_url or "").strip(): + res.result.SetResult(ErrorType.FACT_SOURCE_REQUIRED) + return res + + # 규칙 3 — ★ LLM 은 사실을 만들지 않는다. 스키마가 허용한 문장 필드에만 쓸 수 있다. + if req.source_type == SourceType.LLM and not spec.allow_llm: + res.result.SetResult(ErrorType.FACT_INVALID_KEY) + return res + + pid = uuid.UUID(place_id) + pub_err, published = await DB_SESSION_MNG.execute_lambda( + facts.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.get_published_fact(s, pid, req.unit_id, req.key), + ) + if pub_err != ErrorType.SUCCESS: + res.result.SetResult(pub_err) + return res + + now = GTime.UTC() + same_value = published is not None and (published.value or "") == (req.value or "") + + # ── 값이 그대로다 — 검증을 초기화하지 않고 '언제 다시 확인했는지'만 갱신 ── + if same_value: + run_err, _rc = await DB_SESSION_MNG.execute_lambda_claim( + facts.DBType(), + lambda s: self.crud.refresh_collected(s, published.fact_id, req.source_type.value, req.source_url, now), + ) + if run_err != ErrorType.SUCCESS: + res.result.SetResult(run_err) + return res + res.outcome = FactWriteOutcome.REFRESHED + return await self._reload(res, pid, published.fact_id) + + if req.source_type in _AUTO_SOURCES: + return await self._write_candidate(res, pid, req, published, now, spec) + return await self._replace_published(res, place_id, pid, req, published, now, spec, user_info) + + async def _write_candidate(self, res, pid, req, published, now, spec): + """자동 수집 — 노출값은 건드리지 않고 후보로 적재한다. + + ★ 이게 업데이트 프로세스의 핵심이다. 노출값을 밀어내면 사이트에서 사실이 사라진다. + 노출값이 이미 있으면 PENDING_OWNER(사람 확인 대기), 없으면 UNVERIFIED.""" + target_status = FactStatus.PENDING_OWNER if published is not None else FactStatus.UNVERIFIED + + cand_err, candidate = await DB_SESSION_MNG.execute_lambda( + facts.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.get_candidate(s, pid, req.unit_id, req.key, req.source_type.value), + ) + if cand_err != ErrorType.SUCCESS: + res.result.SetResult(cand_err) + return res + + # 같은 출처가 이미 올려둔 후보가 있으면 갱신한다(같은 후보가 계속 쌓이지 않게). + if candidate is not None: + run_err, _rc = await DB_SESSION_MNG.execute_lambda_claim( + facts.DBType(), + lambda s: self.crud.update_candidate( + s, candidate.fact_id, req.value, req.source_url, target_status.value, now + ), + ) + if run_err != ErrorType.SUCCESS: + res.result.SetResult(run_err) + return res + res.outcome = FactWriteOutcome.CANDIDATE_UPDATED + return await self._reload(res, pid, candidate.fact_id) + + fact = facts( + place_id=pid, + unit_id=req.unit_id, + key=req.key, + value=req.value, + unit=spec.unit, + source_type=req.source_type.value, + source_url=(req.source_url or None), + collected_at=now, + status=target_status.value, + expires_at=req.expires_at, + ) + run_err = await DB_SESSION_MNG.execute_lambda_run( + [facts.DBType()], + [lambda s: self.crud.add_fact(s, fact)], + ) + if run_err != ErrorType.SUCCESS: + res.result.SetResult(run_err) + return res + res.outcome = FactWriteOutcome.CANDIDATE_CREATED + res.fact = FactData.model_validate(fact) + return res + + async def _replace_published(self, res, place_id, pid, req, published, now, spec, user_info): + """사람이 직접 입력 — 노출값을 즉시 교체한다(수정 프로세스). + + 사람이 넣은 값은 그 사람이 곧 출처이자 책임 주체라 별도 확인 단계를 두지 않는다. + 기존 노출값은 지우지 않고 EXPIRED 이력으로 남긴다.""" + fact = facts( + place_id=pid, + unit_id=req.unit_id, + key=req.key, + value=req.value, + unit=spec.unit, + source_type=req.source_type.value, + source_url=(req.source_url or None), + collected_at=now, + verified_by=uuid.UUID(user_info.user_id), + verified_at=now, + status=FactStatus.VERIFIED.value, + expires_at=req.expires_at, + ) + run_err = await DB_SESSION_MNG.execute_lambda_run( + [facts.DBType()], + [ + lambda s: self._expire_then_ok(s, pid, req, now), + lambda s: self.crud.add_fact(s, fact), + ], + ) + if run_err != ErrorType.SUCCESS: + res.result.SetResult(run_err) + return res + + # ★ 노출값이 바뀌었다 → 이 사업장만 재빌드 대상이 된다. + await self._mark_content_updated(place_id, now) + res.outcome = FactWriteOutcome.PUBLISHED_REPLACED if published is not None else FactWriteOutcome.PUBLISHED_CREATED + res.fact = FactData.model_validate(fact) + return res + + async def _expire_then_ok(self, s, pid, req, now): + """execute_lambda_run 은 각 람다가 ErrorType 을 돌려주길 요구한다 — rowcount 는 버린다.""" + err_type, _rowcount = await self.crud.expire_published(s, pid, req.unit_id, req.key, now) + return err_type + + async def _reload(self, res, pid, fact_id): + _e, row = await DB_SESSION_MNG.execute_lambda( + facts.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.get_fact(s, pid, fact_id), + ) + res.fact = FactData.model_validate(row) if row is not None else None + return res + + # ---- 검증 상태 전이 ---- + async def transition(self, user_info: UserInfo, place_id: str, fact_id: str, req: Req_TransitionFact) -> Res_Fact: + """검증 상태를 바꾼다. 허용 전이는 FACT_STATUS_TRANSITIONS 가 유일한 소스다. + + 후보를 노출 상태로 승격시키면 **기존 노출값을 EXPIRED 로 내리고 남은 후보를 정리**한다 — + 이게 업데이트 프로세스의 마지막 단계(사람의 승인)다.""" + res = Res_Fact() + err_type, _place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + pid = uuid.UUID(place_id) + fid = uuid.UUID(fact_id) + get_err, fact = await DB_SESSION_MNG.execute_lambda( + facts.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.get_fact(s, pid, fid), + ) + if get_err != ErrorType.SUCCESS: + res.result.SetResult(ErrorType.FACT_NOT_FOUND) + return res + + current = FactStatus(fact.status) + target = req.status + if target not in FACT_STATUS_TRANSITIONS.get(current, set()): + res.result.SetResult(ErrorType.FACT_INVALID_TRANSITION) + return res + + now = GTime.UTC() + data: dict = {} + if target in PUBLISHABLE_FACT_STATUSES: + data["verified_by"] = uuid.UUID(user_info.user_id) + data["verified_at"] = now + if target == FactStatus.CORRECTED: + if req.value is None: + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + return res + # 사람이 고친 값 — 출처가 owner 로 바뀌고 자동 수집은 이후 후보로만 도전할 수 있다. + data["value"] = req.value + data["source_type"] = SourceType.OWNER.value + + promoting = target in PUBLISHABLE_FACT_STATUSES and current not in PUBLISHABLE_FACT_STATUSES + funcs = [] + if promoting: + # 승격 전에 자리를 비운다 — 노출값 유니크(1건) 때문에 순서가 중요하다. + funcs.append(lambda s: self._expire_published_ok(s, pid, fact, now)) + funcs.append(lambda s: self._transition_ok(s, fid, current, target, data)) + if promoting: + funcs.append(lambda s: self._reject_others_ok(s, pid, fact, now, fid)) + + run_err = await DB_SESSION_MNG.execute_lambda_run([facts.DBType()], funcs) + if run_err != ErrorType.SUCCESS: + res.result.SetResult( + ErrorType.FACT_INVALID_TRANSITION if run_err == ErrorType.DB_EMPTY_DATA else run_err + ) + return res + + # 노출값이 바뀌는 전이(승격 / 정정 / 노출값 내림)면 재빌드 대상으로 표시한다. + if promoting or current in PUBLISHABLE_FACT_STATUSES: + await self._mark_content_updated(place_id, now) + + res.outcome = FactWriteOutcome.PUBLISHED_REPLACED if promoting else None + return await self._reload(res, pid, fid) + + async def _expire_published_ok(self, s, pid, fact, now): + err_type, _rc = await self.crud.expire_published(s, pid, fact.unit_id, fact.key, now, except_fact_id=fact.fact_id) + return err_type + + async def _reject_others_ok(self, s, pid, fact, now, keep_fact_id): + err_type, _rc = await self.crud.reject_candidates(s, pid, fact.unit_id, fact.key, now, except_fact_id=keep_fact_id) + return err_type + + async def _transition_ok(self, s, fid, current, target, data): + """전이가 0행이면 그 사이 다른 사람이 상태를 바꿨다는 뜻 — 트랜잭션을 중단시킨다.""" + err_type, rowcount = await self.crud.transition(s, fid, (current.value,), target.value, data) + if err_type != ErrorType.SUCCESS: + return err_type + return ErrorType.SUCCESS if rowcount else ErrorType.DB_EMPTY_DATA diff --git a/backend/services/faq_service.py b/backend/services/faq_service.py new file mode 100644 index 0000000..c4c2efa --- /dev/null +++ b/backend/services/faq_service.py @@ -0,0 +1,214 @@ +"""FAQ 조회 + 승인(검증 상태 전이). + +COPY 잡이 faqs 를 UNVERIFIED 로 쌓아두지만, 절대규칙 1 때문에 확인 전에는 사이트에 나가지 못한다 +(snapshot 이 PUBLISHABLE 만 싣는다). 즉 **승인 창구가 없으면 FAQPage JSON-LD 는 영영 안 나간다** — +이 서비스가 그 창구다. + +fact 와 같은 규칙을 따른다(다른 표를 쓰면 두 도메인의 승인 의미가 갈라진다): + 1. 회사 스코프는 사업장 조회로 강제 — 남의 회사 place 의 FAQ 는 보이지도 만져지지도 않는다 + 2. 상태 전이는 FACT_STATUS_TRANSITIONS 에 있는 것만 (FACT_INVALID_TRANSITION) + 3. CORRECTED 는 잠긴 종착 상태(LOCKED_FACT_STATUSES) — 재생성이 사장님 문구를 덮어쓰지 못한다 + 4. 사람이 직접 쓴 FAQ 는 바로 노출값이다 — 사람이 곧 출처이자 책임 주체다 +""" +import uuid + +from fastapi import Depends + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import faqs, places +from common.enums import ( + CANDIDATE_FACT_STATUSES, + FACT_STATUS_TRANSITIONS, + PUBLISHABLE_FACT_STATUSES, + DBWRType, + ErrorType, + FactStatus, + SourceType, +) +from common.logger import LOG +from common.models.gmodel import UserInfo +from common.utils.gtime import GTime +from crud.faq_crud import FaqCRUD, IFaqCRUD +from crud.place_crud import PlaceCRUD +from router.v1.faq.protocol import FaqData, Req_CreateFaq, Req_TransitionFaq, Res_Faq, Res_FaqList + + +class FaqService: + def __init__(self, crud: IFaqCRUD = Depends(FaqCRUD), place_crud: PlaceCRUD = Depends(PlaceCRUD)): + self.crud = crud + self.place_crud = place_crud + + # ---- 사업장 로드(회사 스코프) ---- + async def _load_place(self, user_info: UserInfo, place_id: str): + """company_id 를 WHERE 에 걸어 조회한다 — 남의 회사 place_id 를 넣으면 PLACE_NOT_FOUND. + '없다'와 '권한 없다'를 구분해 주지 않는 것도 의도다(존재 여부를 흘리지 않는다).""" + err_type, place = await DB_SESSION_MNG.execute_lambda( + places.DBType(), + DBWRType.DB_READ.value, + lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)), + ) + if err_type != ErrorType.SUCCESS: + return ErrorType.PLACE_NOT_FOUND, None + return ErrorType.SUCCESS, place + + async def _mark_content_updated(self, place_id: str, ts): + """★ 사이트에 나가는 내용이 바뀌었다 — 이 사업장만 다시 빌드하면 된다는 표시. + FAQ 도 페이지에 렌더되고 FAQPage JSON-LD 로 나가므로 fact 와 같은 취급이다. + 부가 효과라 실패해도 본 흐름을 막지 않는다(다음 변경 때 다시 찍힌다).""" + err = await DB_SESSION_MNG.execute_lambda_run([places.DBType()], [lambda s: self._touch(s, place_id, ts)]) + if err != ErrorType.SUCCESS: + LOG.e_no_callstack(f"[faq] content_updated_at 갱신 실패 place={place_id}") + + async def _touch(self, s, place_id: str, ts): + from sqlalchemy import update + + query = update(places).where(places.place_id == uuid.UUID(place_id)).values(content_updated_at=ts, updated_at=ts) + return await DB_SESSION_MNG.add(s, query) + + async def _reload(self, res: Res_Faq, pid, faq_id) -> Res_Faq: + _e, row = await DB_SESSION_MNG.execute_lambda( + faqs.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.get_faq(s, pid, faq_id), + ) + res.faq = FaqData.model_validate(row) if row is not None else None + return res + + # ---- 조회 ---- + async def list_faqs(self, user_info: UserInfo, place_id: str, publishable_only: bool = False) -> Res_FaqList: + """publishable_only=True → ★ 사이트에 나갈 수 있는 것만(빌드가 보는 것과 같은 집합). + 기본(False)은 승인 대기까지 함께 준다 — 관리 화면이 승인할 대상을 봐야 하기 때문이다.""" + res = Res_FaqList() + err_type, _place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + pid = uuid.UUID(place_id) + list_err, rows = await DB_SESSION_MNG.execute_lambda( + faqs.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.list_faqs(s, pid, publishable_only), + ) + if list_err != ErrorType.SUCCESS: + res.result.SetResult(list_err) + return res + + res.faqs = [FaqData.model_validate(r) for r in rows] + res.publishable = sum(1 for r in rows if FactStatus(r.status) in PUBLISHABLE_FACT_STATUSES) + res.pending_review = sum(1 for r in rows if FactStatus(r.status) in CANDIDATE_FACT_STATUSES) + return res + + # ---- 직접 추가 ---- + async def create_faq(self, user_info: UserInfo, place_id: str, req: Req_CreateFaq) -> Res_Faq: + """사장님이 직접 쓴 FAQ 를 넣는다 — fact 의 owner 입력과 같은 철학으로 바로 노출값(VERIFIED)이 된다. + + 근거 fact(source_fact_ids)를 요구하지 않는 것도 그래서다. 근거를 요구하는 이유는 + LLM 이 지어냈는지 확인하기 위해서인데, 여기서는 사람 본인이 출처다.""" + res = Res_Faq() + err_type, _place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + question = (req.question or "").strip() + answer = (req.answer or "").strip() + if not question or not answer: + # 빈 문답은 사이트에 렌더도 안 되고 고유 콘텐츠로도 안 세진다 — 애초에 받지 않는다. + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + return res + + pid = uuid.UUID(place_id) + sort_order = req.sort_order + if sort_order is None: + # 순서를 안 주면 맨 뒤에 붙인다 — 기존 FAQ 사이에 끼어들어 순서를 흔들지 않게. + _e, rows = await DB_SESSION_MNG.execute_lambda( + faqs.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.list_faqs(s, pid, False), + ) + sort_order = max((r.sort_order for r in rows), default=-1) + 1 + + row = faqs( + place_id=pid, + question=question, + answer=answer, + generated_by=SourceType.OWNER.value, + status=FactStatus.VERIFIED.value, + sort_order=sort_order, + ) + run_err = await DB_SESSION_MNG.execute_lambda_run([faqs.DBType()], [lambda s: self.crud.add_faq(s, row)]) + if run_err != ErrorType.SUCCESS: + res.result.SetResult(run_err) + return res + + # 바로 노출 대상이 늘었다 → 재빌드 대상 표시. + await self._mark_content_updated(place_id, GTime.UTC()) + return await self._reload(res, pid, row.faq_id) + + # ---- 검증 상태 전이(승인 · 정정 · 반려) ---- + async def transition(self, user_info: UserInfo, place_id: str, faq_id: str, req: Req_TransitionFaq) -> Res_Faq: + """생성된 FAQ 를 승인하거나, 문구를 고쳐 승인하거나, 반려한다. + + 고쳐서 승인하면 CORRECTED — ★ 잠긴 상태다. 이후 재생성(expire_generated)은 미확인 FAQ 만 + 건드리므로 사장님이 고친 문구는 살아남는다. generated_by 도 OWNER 로 바꿔 둔다: + 문장의 책임 주체가 LLM 에서 사람으로 넘어왔다는 기록이다.""" + res = Res_Faq() + err_type, _place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + pid = uuid.UUID(place_id) + fid = uuid.UUID(faq_id) + get_err, faq = await DB_SESSION_MNG.execute_lambda( + faqs.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.get_faq(s, pid, fid), + ) + if get_err != ErrorType.SUCCESS: + res.result.SetResult(ErrorType.FAQ_NOT_FOUND) + return res + + current = FactStatus(faq.status) + target = req.status + if target not in FACT_STATUS_TRANSITIONS.get(current, set()): + res.result.SetResult(ErrorType.FACT_INVALID_TRANSITION) + return res + + data: dict = {} + if target == FactStatus.CORRECTED: + question = (req.question or "").strip() + answer = (req.answer or "").strip() + if not question and not answer: + # '정정'인데 고친 문구가 없으면 그냥 승인(VERIFIED)이어야 한다 — 잠금만 얻는 길을 막는다. + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + return res + if question: + data["question"] = question + if answer: + data["answer"] = answer + data["generated_by"] = SourceType.OWNER.value + + now = GTime.UTC() + run_err = await DB_SESSION_MNG.execute_lambda_run( + [faqs.DBType()], + [lambda s: self._transition_ok(s, fid, current, target, data)], + ) + if run_err != ErrorType.SUCCESS: + # 적용행수 0 = 그 사이 다른 사람이 상태를 바꿨다 — 요청한 전이는 더 이상 유효하지 않다. + res.result.SetResult(ErrorType.FACT_INVALID_TRANSITION if run_err == ErrorType.DB_EMPTY_DATA else run_err) + return res + + # 노출 집합이 바뀌는 전이(승격 / 정정 / 노출값 내림)면 재빌드 대상으로 표시한다. + if target in PUBLISHABLE_FACT_STATUSES or current in PUBLISHABLE_FACT_STATUSES: + await self._mark_content_updated(place_id, now) + return await self._reload(res, pid, fid) + + async def _transition_ok(self, s, fid, current: FactStatus, target: FactStatus, data: dict): + """출발 상태를 WHERE 에 걸어 조건부로만 바꾼다(동시 처리 가드). + execute_lambda_run 은 ErrorType 만 받으므로 적용행수 0 을 DB_EMPTY_DATA 로 바꿔 트랜잭션을 중단시킨다.""" + err_type, rowcount = await self.crud.transition(s, fid, (current.value,), target.value, data) + if err_type != ErrorType.SUCCESS: + return err_type + return ErrorType.SUCCESS if rowcount else ErrorType.DB_EMPTY_DATA diff --git a/backend/services/grounding/__init__.py b/backend/services/grounding/__init__.py new file mode 100644 index 0000000..705015f --- /dev/null +++ b/backend/services/grounding/__init__.py @@ -0,0 +1,13 @@ +"""LLM 이 내놓은 답을 믿어도 되는지 판정하는 자리. + +★ 여기에는 외부 호출이 없다. 전부 순수 함수다 — + 입력(생성된 문장 + 근거)만 주면 같은 답이 나오므로, 실호출 없이 테스트할 수 있다. + +★ 왜 따로 두나 + "지어내지 마라" 는 프롬프트로 막히지 않는다. 모델은 종종 어기고, 그 문장이 그대로 + 사장님 사이트에 실리면 틀린 요금·없는 시설이 손님에게 나간다. 그래서 프롬프트를 + 1차 방어로 두고, 실제 방어는 여기서 코드로 한다. + + 호출·재시도 코드와 섞여 있으면 "멀쩡한 답이 왜 반려되지" 를 고치러 갈 때 + HTTP 코드를 헤치고 들어가야 한다. 그래서 겹을 갈랐다(services/llm/__init__.py 참조). +""" diff --git a/backend/services/grounding/channels.py b/backend/services/grounding/channels.py new file mode 100644 index 0000000..5d8fbbc --- /dev/null +++ b/backend/services/grounding/channels.py @@ -0,0 +1,241 @@ +"""채널 URL 후보를 믿어도 되는지 판정하는 자리. + +Perplexity 가 돌려준 URL 목록에서 **상세 페이지가 아닌 것과 후기 블로그를 걸러낸다.** +외부 호출이 없는 순수 함수라 실호출 없이 테스트할 수 있다. + +★ 왜 호출 코드에서 떼어냈나 + "왜 이 URL 이 빠졌나 / 왜 이 쓰레기가 남았나" 는 필터 규칙 문제지 HTTP 문제가 아니다. + 규칙만 따로 읽고 따로 고칠 수 있어야 한다(services/llm/__init__.py 의 겹 설명 참조). + +★ 조용히 버리지 않는다. 걸러낸 것은 전부 (url, 사유) 로 돌려주고, 호출측이 로그와 + 운영 화면에 싣는다 — 필터가 과해서 진짜 채널을 버렸는지 사람이 판단할 수 있어야 한다. +""" +import json +from dataclasses import dataclass +from urllib.parse import urlparse + +from common.enums import LinkChannel +from common.logger import LOG + +# 검토할 오탐 후보가 과도하게 늘지 않도록 제한한다. +MAX_LINKS = 6 +MAX_LINKS_PER_CHANNEL = 3 + + +# URL 호스트 → 채널 코드. 접미사 매칭이라 서브도메인(place.naver.com 등)도 잡힌다. +_HOST_CHANNEL = ( + ("yanolja.com", LinkChannel.YANOLJA), + ("goodchoice.kr", LinkChannel.GOODCHOICE), + ("yeogi.com", LinkChannel.GOODCHOICE), + ("place.naver.com", LinkChannel.NAVER_PLACE), + ("naver.me", LinkChannel.NAVER_PLACE), + ("m.place.naver.com", LinkChannel.NAVER_PLACE), + # 사람이 실제로 공유하는 주소가 이 호스트다(map.naver.com/p/entry/place/...). + # 블로그·카페는 위 _NAVER_BLOG_HOSTS 가 먼저 걸러내므로 여기 넣어도 후기가 섞이지 않는다. + ("map.naver.com", LinkChannel.NAVER_PLACE), + ("instagram.com", LinkChannel.INSTAGRAM), +) + +# 네이버 도메인 중 블로그·카페는 플레이스가 아니다 — 채널 판정을 분리한다. +_NAVER_BLOG_HOSTS = ( + # ★ 안내·도움말 페이지. 가게 채널이 아니다 — 실측으로 '도플로' 수집에 + # pages.map.naver.com/useful-tips 가 유일한 네이버 링크로 등록돼 사진 0장이 됐다. + "pages.map.naver.com", "help.naver.com", "guide.naver.com", + "blog.naver.com", "cafe.naver.com", "m.blog.naver.com", "m.cafe.naver.com", + "post.naver.com", "m.post.naver.com", "in.naver.com", +) + + +# ── 상세 페이지 판정 ────────────────────────────────────────────────────── +# ★ 실측(2026-08-27 '핑크비치펜션', 발견 15건)에서 확인된 쓰레기 유형: +# https://nol.yanolja.com/ 루트 — 이 가게와 무관 +# https://www.goodchoice.kr/ 루트 +# https://nol.yanolja.com/sub-home/pension 카테고리(업종 목록) +# https://nol.yanolja.com/programmatic/... SEO 랜딩 +# https://blog.naver.com/... 후기 4건 +# 이런 URL 을 확정 대기 목록에 남기면 사람이 15건을 일일이 봐야 한다. + +# 상세 페이지일 수 없는 경로 첫 조각. 숫자 ID 가 뒤에 붙어도 상세가 아니다(SEO 랜딩·목록). +_NON_DETAIL_PREFIXES = frozenset({ + "sub-home", "sub_home", "programmatic", "search", "event", "promotion", + "category", "theme", "curation", "magazine", "notice", "help", "login", "signup", +}) + +# 상세 URL 이 숫자 ID 를 갖지 않는 예외 호스트(단축 링크·지도). +_ID_OPTIONAL_HOSTS = ("naver.me", "map.naver.com", "instagram.com") + +# 상세 판정에 숫자 ID 를 요구하는 채널. OTA 상세는 항상 숫자 ID 를 갖는다. +_ID_REQUIRED_CHANNELS = (LinkChannel.YANOLJA, LinkChannel.GOODCHOICE, LinkChannel.NAVER_PLACE) + +# 탈락 사유 코드 — 운영자가 "왜 빠졌나"를 보는 값이라 문자열을 고정한다. +REASON_NON_HTTP = "non_http" +REASON_DUPLICATE = "duplicate" +REASON_BLOG = "blog" +REASON_ROOT = "root" +REASON_CATEGORY = "category" +REASON_OVERFLOW = "overflow" # 상한 초과로 잘림 — 버린 게 아니라 순위가 밀린 것 + + + +@dataclass(frozen=True) +class DiscoveredLink: + """발견된 채널 URL 1건. **사실이 아니라 '여기를 보라'는 포인터다.**""" + + url: str + channel: LinkChannel + title: str | None = None + + +def classify_url(url: str) -> LinkChannel: + """URL → 채널 코드. 모르는 도메인은 ETC 로 떨어뜨린다(버리지 않는다).""" + try: + host = (urlparse(url).hostname or "").lower() + except (ValueError, AttributeError): + return LinkChannel.ETC + if not host: + return LinkChannel.ETC + + # 블로그·카페는 naver.com 접미사에 걸리기 전에 먼저 걸러낸다. + if any(host == h or host.endswith("." + h) for h in _NAVER_BLOG_HOSTS): + return LinkChannel.BLOG + + for suffix, channel in _HOST_CHANNEL: + if host == suffix or host.endswith("." + suffix): + return channel + return LinkChannel.ETC + + +def _path_segments(url: str) -> list[str]: + """URL 경로를 조각으로 나눈다. 빈 조각은 버린다.""" + try: + path = urlparse(url).path or "" + except (ValueError, AttributeError): + return [] + return [seg for seg in path.split("/") if seg] + + +def _detail_reject_reason(url: str, channel: LinkChannel) -> str | None: + """이 URL 이 '이 가게의 상세 페이지' 인가. 아니면 탈락 사유를, 맞으면 None 을 돌려준다. + + ★ 판정을 못 하겠으면 통과시킨다(사람이 확정 단계에서 본다). 여기서 과하게 버리면 + 진짜 채널을 잃는데, 그건 필터가 없는 것보다 나쁘다. + """ + segments = _path_segments(url) + + # 루트('/' 또는 경로 없음)는 업소와 무관한 서비스 첫 화면이다. + if not segments: + return REASON_ROOT + + # SEO 랜딩·목록 경로는 숫자 ID 가 뒤에 붙어도 상세가 아니다. + if segments[0].lower() in _NON_DETAIL_PREFIXES: + return REASON_CATEGORY + + try: + host = (urlparse(url).hostname or "").lower() + except (ValueError, AttributeError): + host = "" + # 단축 링크(naver.me)·지도·인스타 프로필은 숫자 ID 를 갖지 않는다 — 경로만 있으면 통과. + if any(host == h or host.endswith("." + h) for h in _ID_OPTIONAL_HOSTS): + return None + + # OTA 상세 URL 은 항상 숫자 ID 를 갖는다. 없으면 목록·카테고리다. + if channel in _ID_REQUIRED_CHANNELS: + if not any(seg.isdigit() for seg in segments): + return REASON_CATEGORY + + return None + + +def filter_links(links: list[DiscoveredLink], include_blogs: bool) -> tuple[list[DiscoveredLink], list[tuple[str, str]]]: + """발견된 URL 을 '이 가게의 상세 페이지' 인 것만 남긴다. + + ★ 전부 걸러지면 빈 목록을 돌려준다. 억지로 하나 남기지 않는다 — + '못 찾음'은 정상 결과이고, 사장님 직접 입력으로 폴백한다. + """ + kept: list[DiscoveredLink] = [] + dropped: list[tuple[str, str]] = [] + per_channel: dict[LinkChannel, int] = {} + for link in links: + # 블로그·카페는 채널이 아니라 후기다. 크롤링해도 이 가게의 공식 정보가 아니다. + if link.channel is LinkChannel.BLOG and not include_blogs: + dropped.append((link.url, REASON_BLOG)) + continue + reason = _detail_reject_reason(link.url, link.channel) + if reason: + dropped.append((link.url, reason)) + continue + # ★ 상한 — 같은 채널에서 서로 다른 업소가 우수수 딸려오는 것을 막는다. + # links 는 '모델이 고른 것 → search_results' 순으로 들어오므로 앞쪽이 더 믿을 만하다. + used = per_channel.get(link.channel, 0) + if used >= MAX_LINKS_PER_CHANNEL or len(kept) >= MAX_LINKS: + dropped.append((link.url, REASON_OVERFLOW)) + continue + per_channel[link.channel] = used + 1 + kept.append(link) + return kept, dropped + + +def _parse_content_links(content: str) -> list[dict]: + """구조화 출력(JSON) 본문에서 links 배열을 꺼낸다. 깨져 있으면 빈 목록.""" + if not content: + return [] + try: + doc = json.loads(content) + except (json.JSONDecodeError, TypeError): + LOG.w("[perplexity] 구조화 출력 파싱 실패 — search_results 만 사용한다") + return [] + links = doc.get("links") + return links if isinstance(links, list) else [] + + +def collect_links(payload: dict) -> tuple[list[DiscoveredLink], list[tuple[str, str]]]: + """모델이 고른 links + search_results(실제 검색 출처)를 합쳐 URL 목록을 만든다. + + search_results 를 함께 쓰는 이유: 모델 답변은 환각이 섞이지만 search_results 는 + 실제로 조회된 URL 이라 더 믿을 만하다. 어차피 다음 단계(동일 업소 검증)가 걸러낸다. + + 반환: (URL 목록, [(버린 URL, 사유), ...]). 중복·비 http 도 사유로 남긴다.""" + seen: set[str] = set() + out: list[DiscoveredLink] = [] + dropped: list[tuple[str, str]] = [] + + def _add(url, title): + if not isinstance(url, str): + return + url = url.strip() + if not url: + return + if url in seen: + dropped.append((url, REASON_DUPLICATE)) + return + if not url.lower().startswith(("http://", "https://")): + dropped.append((url, REASON_NON_HTTP)) + return + seen.add(url) + out.append(DiscoveredLink(url=url, channel=classify_url(url), title=(title or None))) + + choices = payload.get("choices") or [] + content = "" + if choices and isinstance(choices[0], dict): + content = ((choices[0].get("message") or {}).get("content")) or "" + for row in _parse_content_links(content): + if isinstance(row, dict): + _add(row.get("url"), row.get("title")) + + for row in payload.get("search_results") or []: + if isinstance(row, dict): + _add(row.get("url"), row.get("title")) + + return out, dropped + + +def search_count(payload: dict) -> int: + """이번 호출의 검색 횟수. usage 에 없으면 search_results 개수로 대체한다.""" + usage = payload.get("usage") or {} + for key in ("num_search_queries", "search_queries", "num_searches"): + value = usage.get(key) + if isinstance(value, int): + return value + results = payload.get("search_results") + return len(results) if isinstance(results, list) else 0 + diff --git a/backend/services/grounding/copy.py b/backend/services/grounding/copy.py new file mode 100644 index 0000000..edc9e5e --- /dev/null +++ b/backend/services/grounding/copy.py @@ -0,0 +1,255 @@ +"""소개문·FAQ 의 근거 검증 — LLM 이 지어낸 문장을 걸러내는 규칙. + +★ 왜 코드로 또 검사하나 + 프롬프트에 "주어진 사실만 써라" 를 몇 번이나 못박아도 모델은 종종 어긴다. + 프롬프트는 1차 방어일 뿐이고, 실제로 손님에게 나갈 문장을 지키는 건 여기다. + 틀린 요금·없는 시설이 사이트에 실리면 그건 그대로 예약 클레임이 된다. + +★ 왜 호출 코드에서 떼어냈나 + 한때 이 규칙이 Gemini HTTP 호출과 같은 파일에 500줄로 뭉쳐 있었다. + "FAQ 가 멀쩡한데 반려된다" 를 고치려면 호출·재시도 코드를 헤치고 들어가야 했다. + 검증 규칙은 외부 호출이 전혀 없는 순수 함수라 여기서 따로 읽고 따로 테스트한다. + + 프롬프트를 고치려면 services/prompts/copy.py, 호출을 고치려면 services/llm/gemini.py 다. +""" +import re +from dataclasses import dataclass +from typing import Optional + +# ── 시설 어휘 사전 ──────────────────────────────────────────────────────── +# 문장에 이 낱말이 나오면 대응 fact key 중 하나가 **반드시** 있어야 한다. +# 어느 업종 스키마에도 없는 key(pool/sauna/elevator …)로 매핑된 낱말은 언제나 반려된다 — +# 그게 바로 "fact 에 없는 시설을 지어낸" 경우다. +_FACILITY_VOCAB: dict[str, tuple[str, ...]] = { + # 실제로 스키마에 있는 것 + "바비큐": ("bbq_available", "bbq_fee"), + "BBQ": ("bbq_available", "bbq_fee"), + "주차": ("parking", "parking_capacity", "parking_free_hours"), + "와이파이": ("wifi",), + "wifi": ("wifi",), + "Wi-Fi": ("wifi",), + "인터넷": ("wifi",), + "조식": ("breakfast",), + "아침 식사": ("breakfast",), + "반려동물": ("pet_allowed",), + "애완": ("pet_allowed",), + "취사": ("cooking_allowed", "has_kitchen"), + "조리": ("cooking_allowed", "has_kitchen"), + "주방": ("has_kitchen", "cooking_allowed"), + "흡연": ("smoking",), + "픽업": ("pickup_service",), + "유아용품": ("baby_amenities",), + "에어컨": ("has_aircon",), + "냉방": ("has_aircon",), + "테라스": ("terrace",), + "야외석": ("terrace",), + "콘센트": ("power_outlet",), + "배달": ("delivery",), + "포장": ("takeout",), + "테이크아웃": ("takeout",), + "휠체어": ("wheelchair_accessible",), + "물품보관함": ("locker_available",), + "락커": ("locker_available",), + "샤워": ("shower_available",), + "콜키지": ("corkage",), + "단체석": ("group_seat_max",), + "노키즈": ("kids_allowed",), + "예약 필수": ("reservation_required",), + # 어느 스키마에도 없는 시설 — 언급되면 무조건 근거 없음 + "수영장": ("pool",), + "온수풀": ("pool",), + "스파": ("spa",), + "사우나": ("sauna",), + "찜질": ("sauna",), + "엘리베이터": ("elevator",), + "헬스": ("gym",), + "피트니스": ("gym",), + "노래방": ("karaoke",), + "당구": ("billiard",), + "족구": ("sports_court",), + "카라반": ("caravan",), + "글램핑": ("glamping",), + "루프탑": ("rooftop",), + "정원": ("garden",), + "오션뷰": ("view",), + "조식뷔페": ("breakfast",), +} + +# 값이 '아니다'를 뜻하는 표기. 이 값인데 문장이 긍정으로 쓰면 반려한다. +_FALSY = {"false", "0", "no", "n", "불가", "불가능", "없음", "미제공", "제공안함", "안됨", "없습니다"} + +# 부정 표현. 시설 낱말 뒤 이 범위 안에 있으면 '없다'고 말한 것으로 본다. +_NEGATION = ("불가", "안 됩", "안됩", "안 돼", "안돼", "없습니다", "없음", "않습니다", "않으", "제한", "금지", "미제공", "어렵습니다") +_NEGATION_WINDOW = 24 + +# 문장 분리용. 의문문은 '주장' 이 아니라서 값 반대 판정(3번)에서 제외한다 — +# "반려동물 동반이 가능한가요?" 는 사실을 주장하는 게 아니라 묻는 것이다(실호출에서 오탐 확인). +_SENT_SPLIT = re.compile(r"(?<=[.!?。])\s*|\n+") + +# 홍보성·과장 표현. fact 값에 그대로 들어있지 않으면 반려한다. +# (객실명이 "프리미엄 스위트" 라면 fact 값에 있으므로 통과한다.) +_PROMOTIONAL = ( + "최고", "최상", "최적", "최대한", "완벽", "국내 최", "업계 1위", "1위", "명품", "럭셔리", + "최고급", "독보적", "비교불가", "단연", "손꼽히는", "자랑하는", "환상적", "황홀", "잊지 못할", + "특별한 추억", "아름다운", "쾌적한", "넓고", "저렴한", "합리적인 가격", +) + +# 숫자 뒤 한글 자릿수. "2만원" 을 20000 으로도 본다. +_SCALE = {"만": 10_000, "천": 1_000, "억": 100_000_000} + +_NUM_RE = re.compile(r"(\d[\d,]*)\s*([만천억])?") + + +@dataclass +class FactInput: + """생성 근거로 넘기는 확보된 fact 1건. 검증도 이 목록으로만 한다.""" + + key: str + label: str + value: str + unit: Optional[str] = None + + +# ── 근거 검증 ───────────────────────────────────────────────────────────── +def _number_occurrences(text: str) -> list[tuple[str, set[str]]]: + """문자열의 숫자를 **등장 단위로** 뽑는다. (표기, 같은 값으로 볼 수 있는 후보들) + + "2만원" → ("2만", {"2", "20000"}) ← 둘 중 하나만 fact 에 있으면 근거가 있는 것이다 + "20,000" → ("20,000", {"20000"}) + "15:00" → ("15", {"15"}), ("00", {"0"}) + + 등장 단위로 묶는 이유: "2만원" 을 {"2","20000"} 로 평평하게 펴면 + fact 에 20000 이 있어도 "2" 가 근거 없다며 반려된다.""" + out: list[tuple[str, set[str]]] = [] + for raw, scale in _NUM_RE.findall(text or ""): + digits = raw.replace(",", "") + if not digits: + continue + alts = {digits.lstrip("0") or "0"} + if scale: + try: + alts.add(str(int(digits) * _SCALE[scale])) + except ValueError: + pass + out.append((raw + (scale or ""), alts)) + return out + + +def _fact_number_tokens(facts: list[FactInput]) -> set[str]: + """fact 값에 등장하는 모든 숫자 표현. 여기서는 평평하게 펴도 된다(대조 대상이라서).""" + tokens: set[str] = set() + for f in facts: + for _raw, alts in _number_occurrences(f.value or ""): + tokens |= alts + return tokens + + +def _fact_key_map(facts: list[FactInput]) -> dict[str, FactInput]: + return {f.key: f for f in facts} + + +def _is_falsy(value: str) -> bool: + v = (value or "").strip().lower() + return v in _FALSY + + +def _negated_near(text: str, pos: int, word_len: int) -> bool: + """시설 낱말 바로 뒤에 부정 표현이 있는지 — '반려동물 동반 불가' 를 긍정 주장으로 보지 않게.""" + window = text[pos + word_len: pos + word_len + _NEGATION_WINDOW] + return any(n in window for n in _NEGATION) + + +def _is_question_at(text: str, pos: int) -> bool: + """그 위치가 의문문 안인지. 의문문은 사실을 주장하지 않는다. + + FAQ 의 질문("반려동물 동반이 가능한가요?")을 긍정 주장으로 오해하면 + 멀쩡한 문답이 통째로 버려진다 — 실호출에서 실제로 겪은 오탐이다.""" + start = 0 + for match in _SENT_SPLIT.finditer(text): + if match.start() > pos: + break + start = match.end() + end = len(text) + for match in _SENT_SPLIT.finditer(text, pos): + end = match.start() + break + sentence = text[start:end] + return sentence.rstrip().endswith("?") or "나요" in sentence or "까요" in sentence + + +def faq_polarity_ok(question: str, answer: str, facts: list[FactInput]) -> tuple[bool, list[str]]: + """FAQ 전용 — 질문이 '불가한 시설' 을 물었으면 **답변이 반드시 부정해야** 한다. + + 질문은 주장이 아니라 ground_check 의 값-반대 판정에서 빠진다. 그 빈틈을 여기서 막는다: + pet_allowed=false 인데 "가능한가요?" 라 묻고 "네, 가능합니다" 라 답하면 잡아야 한다.""" + key_map = _fact_key_map(facts) + reasons: list[str] = [] + lowered_q = (question or "").lower() + for word, keys in _FACILITY_VOCAB.items(): + if lowered_q.find(word.lower()) < 0: + continue + falsy = [k for k in keys if k in key_map and _is_falsy(key_map[k].value)] + if not falsy: + continue + if not any(n in (answer or "") for n in _NEGATION): + reasons.append(f"'{word}' 은 {falsy[0]}='{key_map[falsy[0]].value}' 인데 답변이 부정하지 않는다") + return (not reasons), reasons + + +def ground_check(text: str, facts: list[FactInput]) -> tuple[bool, list[str]]: + """생성된 문장이 fact 로 뒷받침되는지 검사한다. + + ★ 이게 이 모듈의 핵심이다. 프롬프트로 "지어내지 마라" 라고 해도 모델은 종종 지어낸다. + 그래서 결과를 코드로 검증하고, 통과 못 하면 문장을 버린다. + + 잡아내는 것: + 1. 문장에 나온 숫자·시각·금액이 fact 값에 없다 → 근거 없는 수치 + 2. fact 에 없는 시설을 언급했다 (수영장·사우나·엘리베이터 …) + 3. fact 값이 '불가/없음' 인데 긍정문으로 썼다 (pet_allowed=false 인데 "반려동물 동반 가능") + 4. 홍보성 과장 표현 ("국내 최고의", "완벽한") + + 반환: (통과 여부, 사유 목록) + """ + if not (text or "").strip(): + return False, ["빈 문장"] + + reasons: list[str] = [] + key_map = _fact_key_map(facts) + fact_values = " ".join((f.value or "") for f in facts) + fact_numbers = _fact_number_tokens(facts) + + # 1. 근거 없는 수치 — 등장마다 후보 중 하나라도 fact 에 있으면 통과 + seen_bad: set[str] = set() + for raw, alts in _number_occurrences(text): + if not (alts & fact_numbers) and raw not in seen_bad: + seen_bad.add(raw) + reasons.append(f"근거 없는 수치 '{raw}' — fact 값에 없다") + + # 2·3. 시설 언급 + lowered = text.lower() + for word, keys in _FACILITY_VOCAB.items(): + pos = lowered.find(word.lower()) + if pos < 0: + continue + if word in fact_values: # fact 값에 그 낱말이 그대로 있으면 근거가 있다 + continue + present = [k for k in keys if k in key_map] + if not present: + reasons.append(f"근거 없는 시설 언급 '{word}' — 해당 fact 가 없다") + continue + # 값이 '아니다'인데 부정 없이 **주장**했다 → 반대로 말한 것. + # 의문문은 주장이 아니므로 제외한다(FAQ 질문이 통째로 버려지는 것을 막는다). + if ( + all(_is_falsy(key_map[k].value) for k in present) + and not _negated_near(text, pos, len(word)) + and not _is_question_at(text, pos) + ): + reasons.append(f"사실과 반대 '{word}' — {present[0]} 값이 '{key_map[present[0]].value}' 다") + + # 4. 홍보성 과장 + for phrase in _PROMOTIONAL: + if phrase in text and phrase not in fact_values: + reasons.append(f"홍보성 표현 '{phrase}'") + + return (not reasons), reasons + diff --git a/backend/services/grounding/extract.py b/backend/services/grounding/extract.py new file mode 100644 index 0000000..7347f83 --- /dev/null +++ b/backend/services/grounding/extract.py @@ -0,0 +1,164 @@ +"""추출 결과 검증 — "AI 가 원문에서 찾아온 것인가, 지어낸 것인가" 를 코드로 가른다. + +★ 이 파일이 없으면 URL·붙여넣기 추출은 쓸 수 없다. + 프롬프트로 "지어내지 마라" 를 아무리 적어도 그건 부탁이지 보장이 아니다. + 보장은 하나뿐이다 — **모델이 적어 낸 근거 문장이 원문에 실제로 있는지 대조하는 것.** + 없으면 그 항목을 버린다. 통과한 것만 fact 후보(UNVERIFIED)로 올라가고, + 그 다음 관문은 여전히 사장님 확인이다. + +★ 왜 '값' 이 아니라 '근거 문장' 을 대조하는가 + 값만 대조하면 "3" 같은 짧은 값이 원문 아무 데나 있다는 이유로 통과한다 + ("최대 3인" 을 못 찾아도 "3층" 이 있으면 통과해 버린다). + 근거 문장을 통째로 대조하면 그 값이 **그 맥락에서** 나왔다는 것까지 확인된다. +""" +import re + +from common.category_schema import CategorySchema + +# 원문 대조 전 정규화: 공백·따옴표·괄호 종류 차이로 어긋나는 것을 막는다. +# ★ 글자 자체는 지우지 않는다 — 지우기 시작하면 "불가" 가 사라져 부정이 긍정으로 뒤집힌다. +_WS = re.compile(r"\s+") +_QUOTES = str.maketrans({ + "“": '"', "”": '"', "‘": "'", "’": "'", """: '"', + "-": "-", "–": "-", "—": "-", "~": "~", "~": "~", + "(": "(", ")": ")", ":": ":", ",": ",", ".": ".", +}) + +# evidence 가 이보다 짧으면 대조가 의미 없다("3" 은 원문 어디에나 있다). +MIN_EVIDENCE = 6 +# 값이 evidence 안에 있는지까지 볼 필요가 없는 타입. +# bool 은 "true"/"false" 라 원문에 그 글자가 있을 리 없고, +# 부호 판정은 아래 _bool_ok 가 따로 본다. +_SKIP_VALUE_CHECK = {"bool"} + +_FALSE_WORDS = ("false", "불가", "없음", "없슴", "미제공", "제공하지", "안됨", "안 됨", "불가능", "금지", "않습니다", "제한") +_TRUE_WORDS = ("true", "가능", "있음", "제공", "완비", "무료", "구비") + +_NUMBER_OK = re.compile(r"^\d+(\.\d+)?$") + + +def normalize(text: str) -> str: + """대조용 정규화. 공백을 하나로, 특수 문장부호를 표준형으로.""" + return _WS.sub(" ", (text or "").translate(_QUOTES)).strip().lower() + + +def loose(text: str) -> str: + """값 대조 전용 — 공백과 자릿수 쉼표까지 지운다. + + ★ 왜 따로 두는가 (실측) + number 필드는 규칙상 "19000" 으로 오는데 원문 표기는 "19,000원" 이다. + normalize 만으로 대조하면 **모든 메뉴 가격이 '고쳐 쓴 값' 으로 반려된다** — + 속초항아리물회 홈페이지에서 가격 5건이 통째로 날아갔다. + 쉼표·공백은 같은 수를 다르게 적은 것일 뿐 값을 바꾸지 않으므로 여기서만 지운다. + ★ 글자는 여전히 지우지 않는다 — "불가" 가 사라지면 부호가 뒤집힌다. + """ + return normalize(text).replace(",", "").replace(" ", "") + + +def _bool_ok(value: str, evidence: str) -> tuple[bool, str]: + """bool 값의 부호가 근거 문장과 맞는가. + + ★ 부호가 뒤집히면 "반려동물 동반 불가" 가 "동반 가능" 이 된다 — + 숙박·음식점 모두 critical 항목이라 예약 클레임으로 직결된다. + """ + v = value.strip().lower() + if v not in ("true", "false"): + return False, f"bool 필드인데 값이 'true'/'false' 가 아니다: {value!r}" + + ev = evidence.lower() + has_false = any(w in ev for w in _FALSE_WORDS) + has_true = any(w in ev for w in _TRUE_WORDS) + + # 근거에 부정 표현이 있는데 true 로 올렸다면 뒤집힌 것이다. 그 반대도 같다. + if v == "true" and has_false and not has_true: + return False, "근거 문장은 부정인데 true 로 올렸다" + if v == "false" and has_true and not has_false: + return False, "근거 문장은 긍정인데 false 로 올렸다" + return True, "" + + +def verify( + rows: list[dict], + *, + source_text: str, + schema: CategorySchema, +) -> tuple[list[dict], list[tuple[str, str]]]: + """추출 결과를 걸러 (통과, 반려) 로 나눈다. + + 반려는 조용히 버리지 않고 (항목, 사유) 로 남긴다 — + 운영자가 "왜 이 값이 안 들어왔나" 를 이 목록으로 읽는다. + + 통과한 dict 는 {key, value, scope, unit_name, evidence} 형태다. + """ + haystack = normalize(source_text) + passed: list[dict] = [] + rejected: list[tuple[str, str]] = [] + seen: set[tuple[str, str]] = set() + + for row in rows: + key = str(row.get("key") or "").strip() + value = str(row.get("value") or "").strip() + unit_name = str(row.get("unit_name") or "").strip() + evidence = str(row.get("evidence") or "").strip() + label = f"{key}={value[:30]}" if key else "(key 없음)" + + # 1) 업종 스키마에 있는 key 인가. ★ 없는 key 는 fact 기록 단계에서도 거부되지만, + # 여기서 먼저 걸러야 반려 사유가 남는다. + spec = schema.get(key) + if spec is None: + rejected.append((label, f"업종 스키마에 없는 key: {key!r}")) + continue + if not value: + rejected.append((label, "값이 비었다")) + continue + + # 2) 스코프 계약. unit 스코프인데 이름이 없으면 어느 객실 것인지 알 수 없다. + if spec.scope == "unit" and not unit_name: + rejected.append((label, "unit 스코프인데 unit_name 이 없다")) + continue + if spec.scope == "place" and unit_name: + unit_name = "" # place 스코프에 이름이 붙어 온 것은 무시하고 진행한다 + + # 3) 근거 문장이 원문에 실제로 있는가. ★ 이 검사가 이 파일의 존재 이유다. + if len(evidence) < MIN_EVIDENCE: + rejected.append((label, f"근거 문장이 너무 짧다({len(evidence)}자) — 대조할 수 없다")) + continue + if normalize(evidence) not in haystack: + rejected.append((label, "근거 문장이 원문에 없다 — 지어낸 값으로 본다")) + continue + + # 4) 타입 계약. + if spec.type == "bool": + ok, why = _bool_ok(value, evidence) + if not ok: + rejected.append((label, why)) + continue + elif spec.type == "number": + if not _NUMBER_OK.match(value.replace(",", "")): + rejected.append((label, f"number 필드인데 숫자가 아니다: {value!r}")) + continue + value = value.replace(",", "") + + # 5) 값이 근거 안에 실제로 적혀 있는가(bool 제외). + # ★ 근거는 원문에서 가져왔는데 값이 그 안에 없다면, 값 쪽을 모델이 고쳐 쓴 것이다 + # — "오후 3시" 를 "15:00" 으로 환산한 경우가 여기서 걸린다. + if spec.type not in _SKIP_VALUE_CHECK and loose(value) not in loose(evidence): + rejected.append((label, "값이 근거 문장 안에 없다 — 원문 표기를 고쳐 쓴 것으로 본다")) + continue + + # 6) 같은 (key, unit) 중복은 첫 건만. + dedupe = (key, unit_name) + if dedupe in seen: + rejected.append((label, "같은 key 가 이미 들어왔다")) + continue + seen.add(dedupe) + + passed.append({ + "key": key, + "value": value, + "scope": spec.scope, + "unit_name": unit_name or None, + "evidence": evidence, + }) + + return passed, rejected diff --git a/backend/services/indexnow.py b/backend/services/indexnow.py new file mode 100644 index 0000000..69d7731 --- /dev/null +++ b/backend/services/indexnow.py @@ -0,0 +1,111 @@ +"""발행본 URL 을 IndexNow 로 알린다 — 크롤러가 찾아올 때까지 기다리지 않는다. + +★ 어디에 닿고 어디에 안 닿는지가 이 파일의 존재 이유다. + + 닿는다 네이버(2023-07 부터 지원) · Bing · Yandex · Seznam. + 네이버가 소상공인 검색 트래픽의 주력이라 여기가 핵심이고, + Bing 은 ChatGPT 검색의 상류라 AEO 로도 값이 있다. + + 안 닿는다 **구글**. 구글은 IndexNow 를 지원하지 않는다(2021 년부터 테스트만 하고 채택 안 함). + 구글 색인 요청 API(Indexing API)도 JobPosting·BroadcastEvent 전용이라 우리는 못 쓴다 — + URL 을 받아 200 을 주지만 그 밖의 타입은 그냥 버린다. + 구글 쪽은 Search Console 사이트맵 제출이 유일한 자동화 경로다. + +★ 보낼 URL 을 여기서 다시 계산하지 않는다. 사이트의 `sitemap.xml` 을 읽는다 — + 프리렌더가 실제로 구운 페이지 목록이 거기 있다. 라우트 규칙을 두 군데 두면 + 사이트맵에 없는 URL 을 통보하게 되고, 그건 404 통보라 신뢰만 깎는다. + +★ 실패해도 발행을 되돌리지 않는다. 색인 통보는 발행의 **부수 효과**다. + 여기서 예외를 올리면 정적 파일이 이미 올라간 뒤에 발행이 실패로 뒤집힌다. +""" + +import os +import xml.etree.ElementTree as ET +from pathlib import Path +from urllib.parse import urlsplit + +import httpx + +from common.logger import LOG + +ENDPOINT = "https://api.indexnow.org/indexnow" +SITEMAP_NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}" +TIMEOUT_SEC = 10.0 +# 규격 상한은 한 번에 10,000 개다. 사이트 하나는 수십 개라 넉넉하다. +MAX_URLS = 10_000 + + +def key() -> str: + return os.environ.get("INDEXNOW_KEY", "").strip() + + +def is_configured() -> bool: + return bool(key()) + + +def output_dir() -> Path: + return Path(os.environ.get("SITE_OUTPUT_DIR", "/app/out/sites")) + + +def site_urls(slug: str) -> list[str]: + """이 사이트가 실제로 발행한 URL 목록(사이트맵의 ``).""" + sitemap = output_dir() / "s" / slug / "sitemap.xml" + if not sitemap.is_file(): + return [] + try: + root = ET.parse(sitemap).getroot() + except ET.ParseError as ex: + LOG.w(f"[indexnow] 사이트맵을 읽지 못했다 — {sitemap}: {ex}") + return [] + urls = [(node.text or "").strip() for node in root.iter(f"{SITEMAP_NS}loc")] + return [url for url in urls if url][:MAX_URLS] + + +def _payload(urls: list[str]) -> dict | None: + """IndexNow 요청 본문. 호스트는 URL 에서 뽑는다(커스텀 도메인도 그대로 맞는다). + + 한 요청의 URL 은 전부 같은 호스트여야 한다(규격). 섞여 있으면 422 를 받으므로 + 첫 URL 의 호스트에 속한 것만 보낸다.""" + host = urlsplit(urls[0]).netloc + if not host: + return None + same_host = [url for url in urls if urlsplit(url).netloc == host] + return { + "host": host, + "key": key(), + # 키 파일은 오리진 루트에 있다(프리렌더가 굽고 azure_static 이 올린다). + "keyLocation": f"https://{host}/{key()}.txt", + "urlList": same_host, + } + + +async def submit(slug: str) -> dict | None: + """설정된 경우에만 통보한다. 실패는 로그로 남기고 삼킨다(발행을 되돌리지 않는다).""" + if not is_configured(): + return None + + urls = site_urls(slug) + if not urls: + LOG.w(f"[indexnow] 보낼 URL 이 없다 — 사이트맵이 없거나 비었다: {slug}") + return None + + body = _payload(urls) + if body is None: + LOG.w(f"[indexnow] URL 에서 호스트를 못 읽었다: {urls[0]}") + return None + + try: + async with httpx.AsyncClient(timeout=TIMEOUT_SEC) as client: + res = await client.post(ENDPOINT, json=body) + except httpx.HTTPError as ex: + LOG.w(f"[indexnow] 통보 실패 {slug}: {type(ex).__name__}: {ex}") + return {"ok": False, "error": f"{type(ex).__name__}: {ex}", "urls": len(body['urlList'])} + + # 200 OK · 202 Accepted 가 정상이다. 그 밖은 규격상 원인이 정해져 있다: + # 400 형식 · 403 키 불일치 · 422 호스트 불일치 · 429 과다 요청 + ok = res.status_code in (200, 202) + if ok: + LOG.i(f"[indexnow] {slug} — URL {len(body['urlList'])}개 통보 (HTTP {res.status_code})") + else: + LOG.w(f"[indexnow] {slug} 거절됨 HTTP {res.status_code}: {res.text[:200]}") + return {"ok": ok, "status": res.status_code, "urls": len(body["urlList"])} diff --git a/backend/services/job_service.py b/backend/services/job_service.py new file mode 100644 index 0000000..2ec6c3e --- /dev/null +++ b/backend/services/job_service.py @@ -0,0 +1,66 @@ +from fastapi import Depends + +from common.enums import ErrorType, JobType +from common.logger import LOG +from crud.job_crud import JobQueue +from router.v1.job.protocol import JobData, Res_Job, Res_JobOps + + +class JobService: + """작업 큐 조회·관리. 적재는 각 도메인 서비스가 JobQueue 로 직접 한다. + + 수집·비전분석·빌드는 몇 분 걸린다 — API 는 잡만 넣고 즉시 응답하고, + 클라이언트는 GET /v1/job/{id} 를 폴링한다.""" + + def __init__(self, queue: JobQueue = Depends(JobQueue)): + self.queue = queue + + async def get_job(self, job_id: str) -> Res_Job: + 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}) + return res + + async def ops(self) -> Res_JobOps: + snap = await self.queue.ops() + return Res_JobOps(**{k: v for k, v in snap.items() if k in Res_JobOps.model_fields}) + + async def requeue(self, job_id: str) -> Res_Job: + """DEAD 잡 재큐(운영자 액션).""" + try: + requeued = await self.queue.requeue(job_id) + except Exception as ex: + # 같은 dedupe_key 의 활성 잡이 이미 있으면 부분 유니크 위반. + LOG.w(f"[job] requeue 실패 {job_id}: {type(ex).__name__}") + res = Res_Job() + res.result.SetResult(ErrorType.JOB_ALREADY_QUEUED) + return res + if requeued is None: + res = Res_Job() + res.result.SetResult(ErrorType.JOB_NOT_DEAD) + return res + return await self.get_job(job_id) + + +async def enqueue_job( + queue: JobQueue, + job_type: JobType, + payload: dict, + dedupe_key: str | None = None, + priority: int = 100, +) -> tuple[str | None, bool]: + """도메인 서비스가 잡을 넣을 때 쓰는 공용 진입점. + + 반환: (job_id, 새로 만들었는가). 활성 중복이면 기존 잡의 id 와 False 를 돌려준다 — + 같은 사업장 수집을 두 번 눌러도 잡이 두 번 돌지 않는다.""" + job_id = await queue.enqueue(job_type.value, payload, priority=priority, dedupe_key=dedupe_key) + if job_id is not None: + return job_id, True + if dedupe_key: + existing = await queue.find_active(dedupe_key) + if existing: + return existing["job_id"], False + return None, False diff --git a/backend/services/llm/__init__.py b/backend/services/llm/__init__.py new file mode 100644 index 0000000..05dc9eb --- /dev/null +++ b/backend/services/llm/__init__.py @@ -0,0 +1,23 @@ +"""LLM 이 들어가는 자리. + +★ 규칙: **이 패키지 밖에서 LLM API 를 직접 부르지 않는다.** + `generativelanguage.googleapis.com` · `api.perplexity.ai` 같은 주소가 다른 파일에 + 나타나면 그건 이 규칙을 어긴 것이다. 한 곳에만 있어야 재시도·타임아웃·인증·비용을 + 한 번만 고치면 되고, "우리가 LLM 을 몇 번 부르는가"를 세는 자리도 하나가 된다. + + 실제로 한때 Gemini 호출 코드가 vision 용·copy 용 두 벌로 복사돼 있었다. + 타임아웃을 바꾸려면 두 곳을 찾아야 했고, 한쪽만 고치면 조용히 갈렸다. + +★ LLM 기능 하나는 네 겹으로 나뉜다. 고칠 것이 생기면 **그 겹으로 바로 간다**: + + 무엇을 묻는가 services/prompts/<기능>.py 프롬프트·응답 스키마 + 어떻게 부르는가 services/llm/<제공자>.py ← 여기 (HTTP·재시도·비용) + 답을 어떻게 믿는가 services/grounding/<기능>.py 근거 검증·필터 + 무엇을 돌려주는가 services/external/<기능>.py 위 셋을 엮어 결과를 만든다 + + 예) "FAQ 답이 이상하다" 는 물음은 이렇게 갈린다 — + 질문을 잘못 시켰나 → prompts/copy.py + 멀쩡한 답이 반려됐나 → grounding/copy.py + 호출이 실패·지연되나 → llm/gemini.py + 결과를 잘못 엮었나 → external/gemini_text.py +""" diff --git a/backend/services/llm/gemini.py b/backend/services/llm/gemini.py new file mode 100644 index 0000000..5c995bb --- /dev/null +++ b/backend/services/llm/gemini.py @@ -0,0 +1,123 @@ +"""Gemini 호출 — 이 프로젝트에서 Gemini 로 나가는 **유일한 통로**. + +사진 분석(services/external/gemini.py)도 소개문·FAQ 생성(services/external/gemini_text.py)도 +전부 여기를 통한다. 두 기능이 각자 HTTP 코드를 들고 있던 시절에는 `_post` 와 `_extract_text` 가 +글자 그대로 두 벌 복사돼 있었고, 타임아웃·재시도·인증 처리를 고치려면 두 곳을 다 찾아야 했다. + +여기가 책임지는 것: 주소·인증 헤더·재시도·응답 파싱·토큰 집계·비용 계산. +여기가 책임지지 않는 것: 무엇을 물을지(services/prompts/), 답을 믿을지(services/grounding/). +""" +import asyncio +from dataclasses import dataclass + +import httpx + +from config.server_configs import external_api_config + +_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/models" + +DEFAULT_MODEL = "gemini-3.7-flash" + +# 100만 토큰당 USD. 모르는 모델은 0 으로 잡는다 — 비용을 지어내느니 0 이 낫다(로그가 이상하면 눈에 띈다). +_PRICE_PER_1M_INPUT = {"gemini-3.7-flash": 0.75, "gemini-3.6-flash": 0.75, "gemini-2.5-flash": 0.30} +_PRICE_PER_1M_OUTPUT = {"gemini-3.7-flash": 3.75, "gemini-3.6-flash": 3.75, "gemini-2.5-flash": 2.50} + +# 일시적 장애만 재시도한다. 4xx 는 요청 자체가 잘못된 것이라 다시 보내도 같다. +_RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504} + + +class GeminiError(RuntimeError): + """Gemini 호출 실패 — 호출측은 ErrorType.GENERATOR_CALL_FAILED 로 매핑한다.""" + + +class GeminiNotConfigured(GeminiError): + """GEMINI_API_KEY 미설정 또는 인증 실패. + + ★ 서버 부팅은 막지 않는다 — 이 어댑터만 비활성이고 나머지 파이프라인은 돈다.""" + + +class GeminiInvalidOutput(GeminiError): + """응답이 기대한 모양이 아니다 — ErrorType.GENERATOR_INVALID_OUTPUT.""" + + +@dataclass +class Usage: + """호출 1회(또는 여러 회 합산)의 토큰 사용량. 비용 로그의 근거다.""" + + input_tokens: int = 0 + output_tokens: int = 0 + + +def is_configured() -> bool: + """키가 있는지 — 어댑터 등록/스킵 판단용. 예외를 던지지 않는다.""" + return bool(external_api_config.gemini_api_key) + + +async def call( + client: httpx.AsyncClient, + model: str, + body: dict, + max_retries: int = 2, +) -> dict: + """★ LLM 이 실제로 불리는 지점. generateContent 1회 + 지수 백오프 재시도. + + 재시도는 5xx·429·타임아웃만 한다. 401/403 은 키 문제이므로 GeminiNotConfigured 로 + 구분해 올린다 — 호출측이 "설정이 없어서 못 한 것"과 "불렀는데 실패한 것"을 다르게 다룬다. + + 응답 본문(dict)을 그대로 돌려준다. 해석은 부르는 쪽 몫이다 — 사진 분석과 문장 생성이 + 같은 응답 구조에서 서로 다른 것을 꺼내 쓰기 때문이다. + """ + url = f"{_BASE_URL}/{model}:generateContent" + headers = {"Content-Type": "application/json", "x-goog-api-key": external_api_config.gemini_api_key} + last = None + for attempt in range(max_retries + 1): + try: + resp = await client.post(url, json=body, headers=headers) + except (httpx.TimeoutException, httpx.TransportError) as ex: + last = f"{type(ex).__name__}: {ex}" + else: + if resp.status_code == 200: + try: + return resp.json() + except ValueError as ex: + raise GeminiInvalidOutput(f"JSON 이 아닌 응답: {ex}") from ex + if resp.status_code in (401, 403): + raise GeminiNotConfigured(f"인증 실패 status={resp.status_code} — API 키를 확인하세요") + if resp.status_code not in _RETRYABLE_STATUS: + raise GeminiError(f"status={resp.status_code} body={resp.text[:200]}") + last = f"status={resp.status_code}" + + if attempt < max_retries: + await asyncio.sleep(min(8.0, 1.0 * (2 ** attempt))) + raise GeminiError(f"{max_retries + 1}회 시도 실패: {last}") + + +def extract_text(payload: dict) -> str: + """응답에서 텍스트 파트만 이어붙인다. + + ★ 파트에 thoughtSignature 가 함께 실려 오므로(실호출에서 확인) text 키가 있는 것만 고른다. + 전부 이어붙이면 모델의 사고 흔적이 결과 문자열에 섞인다.""" + candidates = payload.get("candidates") or [] + if not candidates: + raise GeminiInvalidOutput("candidates 가 비었다(안전 필터 차단 가능)") + parts = (candidates[0].get("content") or {}).get("parts") or [] + text = "".join(p["text"] for p in parts if isinstance(p, dict) and "text" in p) + if not text.strip(): + raise GeminiInvalidOutput(f"텍스트 파트가 없다 finishReason={candidates[0].get('finishReason')}") + return text + + +def read_usage(payload: dict) -> Usage: + """응답의 usageMetadata → Usage. 없으면 0 이다(과금 안 된 호출도 있다).""" + meta = payload.get("usageMetadata") or {} + return Usage( + input_tokens=int(meta.get("promptTokenCount") or 0), + output_tokens=int(meta.get("candidatesTokenCount") or 0), + ) + + +def price(model: str, usage: Usage) -> float: + """USD. 로그에만 쓴다 — 과금 근거가 아니라 "이 잡이 얼마짜리였나"를 눈으로 보는 값이다.""" + inp = _PRICE_PER_1M_INPUT.get(model, 0.0) * usage.input_tokens / 1_000_000 + out = _PRICE_PER_1M_OUTPUT.get(model, 0.0) * usage.output_tokens / 1_000_000 + return round(inp + out, 4) diff --git a/backend/services/llm/perplexity.py b/backend/services/llm/perplexity.py new file mode 100644 index 0000000..1c6fc3e --- /dev/null +++ b/backend/services/llm/perplexity.py @@ -0,0 +1,74 @@ +"""Perplexity 호출 — 이 프로젝트에서 Perplexity 로 나가는 **유일한 통로**. + +여기가 책임지는 것: 주소·인증 헤더·타임아웃·응답 파싱. +여기가 책임지지 않는 것: 무엇을 물을지(services/prompts/channel_discovery.py), +답으로 받은 URL 을 믿을지(services/grounding/channels.py). + +★ Perplexity 답변을 **사실로 쓰지 않는다.** 이 어댑터의 산출물은 "여기를 보라"는 URL 포인터일 + 뿐이고, 실제 사실은 그 URL 을 크롤링해서 얻는다. 그래서 응답 원문(raw)을 통째로 박제해 + 나중에 환각을 추적할 수 있게 한다. +""" +import json + +import httpx + +from config.server_configs import external_api_config + +API_URL = "https://api.perplexity.ai/chat/completions" + +DEFAULT_MODEL = "sonar" + +# 첫 구조화 출력 요청은 스키마 준비에 10~30초가 걸린다 — 그 시간을 포함한 값이다. +DEFAULT_TIMEOUT = httpx.Timeout(90.0, connect=10.0) +DEFAULT_MAX_TOKENS = 2048 + + +class PerplexityError(RuntimeError): + """Perplexity 호출 실패. 호출측(collector)은 ErrorType.COLLECT_FETCH_FAILED 로 매핑한다.""" + + +class PerplexityNotConfigured(PerplexityError): + """PERPLEXITY_API_KEY 미설정 — 이 어댑터만 비활성. **서버 부팅을 막지 않는다.**""" + + +def is_configured() -> bool: + """키가 설정돼 있는지. 어댑터 등록 여부를 판단할 때 쓴다.""" + return bool((external_api_config.perplexity_api_key or "").strip()) + + +async def call(body: dict, *, client: httpx.AsyncClient | None = None) -> dict: + """★ LLM 이 실제로 불리는 지점. chat/completions 1회. + + Gemini 쪽(services/llm/gemini.py)과 달리 재시도하지 않는다 — 이 호출은 검색을 동반해 + 한 번이 비싸고 느리다. 실패하면 수집 파이프라인이 등록된 링크로 그냥 진행한다 + (services/collect_service.py 의 discover_links 참조). + + 응답 본문(dict)을 그대로 돌려준다. 해석은 부르는 쪽 몫이다. + """ + api_key = (external_api_config.perplexity_api_key or "").strip() + if not api_key: + raise PerplexityNotConfigured("PERPLEXITY_API_KEY 미설정 — 채널 발견을 건너뛴다") + + headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"} + owns_client = client is None + http = client or httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) + try: + resp = await http.post(API_URL, json=body, headers=headers) + except httpx.TimeoutException as ex: + raise PerplexityError(f"Perplexity 타임아웃: {ex}") from ex + except httpx.HTTPError as ex: + raise PerplexityError(f"Perplexity 호출 실패: {type(ex).__name__}: {ex}") from ex + finally: + if owns_client: + await http.aclose() + + if resp.status_code != 200: + raise PerplexityError(f"Perplexity 응답 오류: status={resp.status_code} body={resp.text[:200]}") + + try: + payload = resp.json() + except (json.JSONDecodeError, ValueError) as ex: + raise PerplexityError(f"Perplexity 응답 JSON 파싱 실패: {ex}") from ex + if not isinstance(payload, dict): + raise PerplexityError("Perplexity 응답이 객체가 아니다") + return payload diff --git a/backend/services/local_content_service.py b/backend/services/local_content_service.py new file mode 100644 index 0000000..071779d --- /dev/null +++ b/backend/services/local_content_service.py @@ -0,0 +1,148 @@ +from datetime import date, datetime, timedelta, timezone + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import local_contents +from common.enums import DBWRType, ErrorType, LocalContentStatus, LocalContentType, LocalSource +from crud.local_content_crud import LocalContentCRUD +from router.v1.local.protocol import ResLocalContentList, ResSyncFestivals, ResWeather, WeatherData +from services.external.open_meteo import OpenMeteoRequestFailed, fetch_current_weather +from services.external.tour_api import TourApiNotConfigured, TourApiRequestFailed, search_festivals + + +class LocalContentService: + def __init__(self): + self.crud = LocalContentCRUD() + + async def list(self, status=None, region_code=None): + res = ResLocalContentList() + err, rows = await DB_SESSION_MNG.execute_lambda( + local_contents.DBType(), DBWRType.DB_READ.value, lambda s: self.crud.list(s, status, region_code) + ) + res.result.SetResult(err) + res.contents = list(rows) if err == ErrorType.SUCCESS else [] + return res + + async def sync_festivals(self, req): + res = ResSyncFestivals() + try: + start = datetime.strptime(req.start_date, "%Y%m%d").date() if req.start_date else date.today() + items = await search_festivals(start_date=start, area_code=req.area_code) + except TourApiNotConfigured: + res.result.SetResult(ErrorType.LOCAL_NOT_CONFIGURED) + res.msg = "TOUR_API_KEY를 먼저 설정해주세요." + return res + except TourApiRequestFailed as ex: + res.result.SetResult(ErrorType.LOCAL_FETCH_FAILED) + res.msg = str(ex) + return res + + collected = skipped = 0 + for item in items: + external_id = str(item.get("contentid") or "") + if not external_id: + skipped += 1 + continue + _, existing = await DB_SESSION_MNG.execute_lambda( + local_contents.DBType(), DBWRType.DB_READ.value, + lambda s, eid=external_id: self.crud.get_by_external_id(s, req.region_code, eid), + ) + if existing: + skipped += 1 + continue + row = local_contents( + region_code=req.region_code, + content_type=LocalContentType.FESTIVAL.value, + source=LocalSource.TOUR_API.value, + external_id=external_id, + title=item.get("title"), + body=item, + status=LocalContentStatus.REVIEW.value, + collected_at=datetime.now(timezone.utc), + ) + err = await DB_SESSION_MNG.execute_lambda_run([row.DBType()], [lambda s, r=row: self.crud.insert(s, r)]) + collected += int(err == ErrorType.SUCCESS) + skipped += int(err != ErrorType.SUCCESS) + res.collected, res.skipped = collected, skipped + return res + + async def publish(self, ids, user_id): + res = ResLocalContentList() + err, _ = await DB_SESSION_MNG.execute_lambda_claim( + local_contents.DBType(), lambda s: self.crud.publish(s, ids, user_id) + ) + res.result.SetResult(err) + return res + + async def update(self, content_id, req): + res = ResLocalContentList() + data = req.model_dump(exclude_none=True) + start, end = data.get("display_start_at"), data.get("display_end_at") + if start and end and start >= end: + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + res.msg = "노출 종료는 시작보다 뒤여야 합니다." + return res + err, count = await DB_SESSION_MNG.execute_lambda_claim( + local_contents.DBType(), lambda s: self.crud.update(s, content_id, data) + ) + res.result.SetResult(err if count else ErrorType.DB_EMPTY_DATA) + return res + + async def end(self, content_id): + res = ResLocalContentList() + err, count = await DB_SESSION_MNG.execute_lambda_claim( + local_contents.DBType(), lambda s: self.crud.end(s, content_id) + ) + res.result.SetResult(err if count else ErrorType.DB_EMPTY_DATA) + return res + + async def get_weather(self, region_code: str, latitude: float, longitude: float): + """Cache-aside weather lookup; stale data survives upstream failures.""" + res = ResWeather() + err, cached = await DB_SESSION_MNG.execute_lambda( + local_contents.DBType(), DBWRType.DB_READ.value, + lambda s: self.crud.get_weather(s, region_code), + ) + if err != ErrorType.SUCCESS: + res.result.SetResult(err) + return res + + now = datetime.now(timezone.utc) + if cached and cached.expires_at and cached.expires_at > now: + res.weather = WeatherData.model_validate(cached.body) + res.cached = True + return res + + try: + weather = await fetch_current_weather(latitude, longitude) + except OpenMeteoRequestFailed as ex: + if cached: + res.weather = WeatherData.model_validate(cached.body) + res.cached = True + res.stale = True + res.msg = "최신 날씨를 가져오지 못해 직전 정보를 반환합니다." + return res + res.result.SetResult(ErrorType.LOCAL_FETCH_FAILED) + res.msg = str(ex) + return res + + expires_at = now + timedelta(hours=1) + values = { + "region_code": region_code, + "content_type": LocalContentType.WEATHER.value, + "source": LocalSource.OPEN_METEO.value, + "external_id": None, + "title": None, + "body": weather, + "status": LocalContentStatus.PUBLISHED.value, + "collected_at": now, + "expires_at": expires_at, + "updated_at": now, + } + write_err = await DB_SESSION_MNG.execute_lambda_run( + [local_contents.DBType()], [lambda s: self.crud.upsert_weather(s, values)] + ) + if write_err != ErrorType.SUCCESS: + res.result.SetResult(write_err) + return res + res.weather = WeatherData.model_validate(weather) + return res diff --git a/backend/services/media_service.py b/backend/services/media_service.py new file mode 100644 index 0000000..9a43007 --- /dev/null +++ b/backend/services/media_service.py @@ -0,0 +1,91 @@ +import uuid + +from fastapi import Depends + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import media, places +from common.enums import DBWRType, ErrorType, MediaStatus, SourceType +from common.models.gmodel import UserInfo +from crud.media_crud import IMediaCRUD, MediaCRUD +from crud.place_crud import PlaceCRUD +from router.v1.media.protocol import MediaData, Res_MediaList + + +def _is_publishable(row) -> bool: + """이 사진이 지금 사이트에 실릴 수 있는가. + + ★ 판단 기준을 services/snapshot.py 와 한 글자도 다르지 않게 맞춘다 — + 관리 화면이 '나간다'고 표시한 사진이 발행에서 빠지면 그게 제일 설명하기 어려운 버그다. + 승인(APPROVED)만으로는 부족하다. alt 가 빈 사진은 빌더가 렌더 자체를 하지 않는다.""" + return row.status == MediaStatus.APPROVED.value and bool((row.alt_text or "").strip()) and bool((row.url or "").strip()) + + +class MediaService: + """사진 조회. + + ★ 이 서비스가 지키는 규칙은 둘이다. + 1. 회사 스코프 — 사업장을 먼저 회사 스코프로 로드해서 남의 회사 사진에 닿지 못하게 한다. + (fact/site 와 같은 _load_place 패턴. 없는 것과 남의 것은 똑같이 PLACE_NOT_FOUND 로 답한다) + 2. 출처 보존 — source_type / origin_url 을 절대 응답에서 빼지 않는다. + 크롤링 이미지 재게시 권리가 미결이고(docs/DECISIONS.md 1-2), 결론이 '불가'면 + 발행에서 source_type = CRAWL 을 통째로 제외해야 한다. 그 필터를 화면이 미리 + 보여주려면 출처가 목록에 실려 있어야 한다. + """ + + def __init__(self, crud: IMediaCRUD = Depends(MediaCRUD), place_crud: PlaceCRUD = Depends(PlaceCRUD)): + self.crud = crud + self.place_crud = place_crud + + # ---- 사업장 로드(회사 스코프) ---- + async def _load_place(self, user_info: UserInfo, place_id: str): + err_type, place = await DB_SESSION_MNG.execute_lambda( + places.DBType(), + DBWRType.DB_READ.value, + lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)), + ) + if err_type != ErrorType.SUCCESS: + return ErrorType.PLACE_NOT_FOUND, None + return ErrorType.SUCCESS, place + + # ---- 조회 ---- + async def list_media(self, user_info: UserInfo, place_id: str, unit_id=None, publishable_only: bool = False) -> Res_MediaList: + """사진 목록. 관리자 빌더 캔버스와 사장님 확인 화면이 같은 엔드포인트를 쓴다. + + publishable_only=True 는 '발행하면 실제로 실릴 것'만 — 승인 + alt 있음. + alt 조건을 여기서 같이 거는 게 중요하다. 승인만 보고 목록을 그리면 캔버스에는 + 사진이 보이는데 발행된 사이트엔 없는 상태가 되고, 원인을 찾는 데 반나절이 든다. + + 사진이 0장인 것은 오류가 아니다 — 수집 전이거나 Vision 이 아직 안 돌았을 뿐이라 + 빈 배열을 그대로 돌려준다(호출자가 '수집을 돌리세요'를 띄울 수 있게).""" + res = Res_MediaList() + err_type, _place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + # publishable_only 의 승인 조건만 CRUD 에 넘기고, alt 조건은 목록 계산과 함께 아래에서 건다. + status = MediaStatus.APPROVED.value if publishable_only else None + list_err, rows = await DB_SESSION_MNG.execute_lambda( + media.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.list_media( + s, uuid.UUID(place_id), status, False, unit_id, publishable_only + ), + ) + if list_err != ErrorType.SUCCESS: + res.result.SetResult(list_err) + return res + + items = [] + for r in rows: + data = MediaData.model_validate(r) + data.publishable = _is_publishable(r) + items.append(data) + res.media = items + res.publishable = sum(1 for x in items if x.publishable) + # 사람 확인 큐에 남은 수 — 관리 화면의 '검토할 것' 배지. + res.pending_review = sum(1 for r in rows if r.status == MediaStatus.PENDING_REVIEW.value) + # ★ 재게시 권리(1-2)가 '불가'로 결론나면 통째로 빠질 사진 수. 미리 보여줘야 사장님이 + # 직접 올릴 사진을 몇 장 준비해야 하는지 안다. + res.crawled = sum(1 for r in rows if r.source_type == SourceType.CRAWL.value) + return res diff --git a/backend/services/place_service.py b/backend/services/place_service.py new file mode 100644 index 0000000..31afcd8 --- /dev/null +++ b/backend/services/place_service.py @@ -0,0 +1,724 @@ +import uuid + +from fastapi import Depends + +from common.category_schema import CategorySchemaError, get_schema +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import place_links, places, units +from common.enums import DBWRType, ErrorType, JobStatus, JobType, LinkChannel, PlaceCategory, PlaceStatus, SourceType +from common.logger import LOG +from common.models.gmodel import PageParams, UserInfo +from common.utils.gtime import GTime +from crud.job_crud import JobQueue +from crud.place_crud import IPlaceCRUD, PlaceCRUD +from router.v1.place.protocol import ( + Req_VerifyPlaceByUrl, + LinkData, + PlaceData, + UnitData, + Req_CreateLink, + Req_CreatePlace, + Req_CreateUnit, + Req_StartCollect, + Req_StartCopy, + Req_StartVision, + Req_UpdatePlace, + Req_VerifyPlace, + Res_Link, + Res_LinkList, + Res_Place, + Res_PlaceList, + Res_VerifyCandidates, + PlaceCandidate, + Res_StartCollect, + Res_StartCopy, + Res_StartVision, + Res_Unit, + Res_UnitList, +) +from router.v1.job.protocol import JobData, Res_Job +# 도로명주소 → 지역 캐시 키. 외부 장소 DB 는 행정구역 코드를 주지 않으므로 여기서 만든다. +from services.external.naver import region_key +from services.job_service import enqueue_job + + +class PlaceService: + """사업장 등록·조회·동일 업소 검증. + + ★ 이 서비스의 핵심 규칙: `verified_at` 이 NULL 인 사업장은 수집이 열리지 않는다. + 카카오 로컬로 동일 업소임을 확인하지 않으면 남의 가게 정보가 섞인다. + """ + + def __init__(self, crud: IPlaceCRUD = Depends(PlaceCRUD), queue: JobQueue = Depends(JobQueue)): + self.crud = crud + self.queue = queue + + # ---- 조회 ---- + async def list_places(self, user_info: UserInfo, pg: PageParams, search=None, category=None, status=None) -> Res_PlaceList: + res = Res_PlaceList(page=pg.page, size=pg.size) + cid = uuid.UUID(user_info.company_id) + err_type, rows, total = await DB_SESSION_MNG.execute_lambda( + places.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.list_places( + s, cid, search, + category.value if isinstance(category, PlaceCategory) else category, + status.value if isinstance(status, PlaceStatus) else status, + pg.skip, pg.size, + ), + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + res.places = [PlaceData.model_validate(r) for r in rows] + res.total = total + return res + + async def get_place(self, user_info: UserInfo, place_id: str) -> Res_Place: + res = Res_Place() + err_type, place = await self._load(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + res.place = PlaceData.model_validate(place) + return res + + async def _load(self, user_info: UserInfo, place_id: str): + """회사 스코프로 사업장 1건. 없으면 PLACE_NOT_FOUND(남의 회사 것도 '없음'으로 응답).""" + err_type, place = await DB_SESSION_MNG.execute_lambda( + places.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)), + ) + if err_type != ErrorType.SUCCESS: + return ErrorType.PLACE_NOT_FOUND, None + return ErrorType.SUCCESS, place + + # ---- 등록 ---- + async def create_place(self, user_info: UserInfo, req: Req_CreatePlace) -> Res_Place: + res = Res_Place() + if not req.name.strip(): + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + return res + # 업종 스키마가 없는 업종은 받지 않는다 — fact 를 하나도 쓸 수 없다. + try: + get_schema(req.category) + except CategorySchemaError: + res.result.SetResult(ErrorType.PLACE_INVALID_CATEGORY) + return res + + place = places( + company_id=uuid.UUID(user_info.company_id), + owner_user_id=req.owner_user_id, + name=req.name.strip(), + category=req.category.value, + status=PlaceStatus.DRAFT.value, + ) + err_type = await DB_SESSION_MNG.execute_lambda_run( + [places.DBType()], + [lambda s: self.crud.add_place(s, place)], + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + res.place = PlaceData.model_validate(place) + return res + + async def update_place(self, user_info: UserInfo, place_id: str, req: Req_UpdatePlace) -> Res_Place: + res = Res_Place() + data = req.model_dump(exclude_unset=True, exclude_none=True) + if "status" in data: + data["status"] = req.status.value + if "name" in data: + data["name"] = str(data["name"]).strip() + + if data: + err_type, rowcount = await DB_SESSION_MNG.execute_lambda_claim( + places.DBType(), + lambda s: self.crud.update_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id), data), + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + if rowcount == 0: + res.result.SetResult(ErrorType.PLACE_NOT_FOUND) + return res + return await self.get_place(user_info, place_id) + + async def delete_place(self, user_info: UserInfo, place_id: str) -> Res_Place: + res = Res_Place() + err_type, rowcount = await DB_SESSION_MNG.execute_lambda_claim( + places.DBType(), + lambda s: self.crud.delete_place( + s, uuid.UUID(user_info.company_id), uuid.UUID(place_id) + ), + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + elif rowcount == 0: + res.result.SetResult(ErrorType.PLACE_NOT_FOUND) + return res + + async def get_active_collect(self, user_info: UserInfo, place_id: str) -> Res_Job: + """재접속한 화면이 진행 중인 수집 잡에 다시 연결할 수 있게 한다.""" + res = Res_Job() + err_type, _place = await self._load(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + row = await self.queue.find_active(f"collect:{place_id}") + if row: + res.job = JobData(**row) + return res + + # ---- 동일 업소 검증 ---- + async def verify_place_by_url(self, user_info: UserInfo, place_id: str, req: Req_VerifyPlaceByUrl) -> Res_Place: + """네이버 플레이스 URL → 상호·주소·좌표를 읽어 동일 업소를 확정하고, 그 URL 을 수집 채널로 등록한다. + + ★ 한 번에 세 가지를 끝낸다: 신원 확정(verified_at) · 채널 등록 · 확정. + 쪼개 놓으면 사장님이 같은 판단을 세 번 하게 된다 — URL 을 붙여넣은 시점에 + "이 가게가 맞다"와 "이 채널이 내 것이다"가 동시에 확인된 것이다. + + ★ 실패는 조용히 넘기지 않는다. URL 이 잘못됐거나 네이버가 막으면 그대로 알려야 + 사장님이 다른 주소를 넣는다 — 빈 사이트를 만들어 놓고 나중에 발견하면 늦다. + """ + from decimal import Decimal + + from common.enums import ExternalPlaceSource, LinkChannel, SourceType + from services.collector.naver_place_adapter import NaverPlaceAdapter + + res = Res_Place() + err_type, place = await self._load(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + url = (req.url or "").strip() + adapter = NaverPlaceAdapter() + if not url or not adapter.can_handle(url): + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + res.msg = "네이버 플레이스 주소가 아닙니다." + return res + + try: + naver_id = await adapter._resolve_place_id(url) + state = await adapter._load_state(naver_id) + except Exception as ex: + LOG.w(f"[verify_by_url] 상세를 읽지 못했다: {ex}") + res.result.SetResult(ErrorType.PLACE_VERIFY_NO_CANDIDATE) + res.msg = "이 주소에서 가게 정보를 읽지 못했습니다. 주소를 다시 확인해 주세요." + return res + + base = state.get(f"PlaceDetailBase:{naver_id}") or next( + (v for k, v in state.items() if k.startswith("PlaceDetailBase")), None + ) + if not base or not str(base.get("name") or "").strip(): + res.result.SetResult(ErrorType.PLACE_VERIFY_NO_CANDIDATE) + res.msg = "이 주소에서 상호를 찾지 못했습니다." + return res + + coord = base.get("coordinate") or {} + verify_req = Req_VerifyPlace( + source=ExternalPlaceSource.NAVER, + external_place_id=str(naver_id), + road_address=base.get("roadAddress") or None, + address=base.get("address") or None, + phone=base.get("phone") or base.get("virtualPhone") or None, + latitude=Decimal(str(coord.get("y"))) if coord.get("y") else None, + longitude=Decimal(str(coord.get("x"))) if coord.get("x") else None, + ) + verified = await self.verify_place(user_info, place_id, verify_req) + if not verified.result.success: + return verified + + # 상호도 네이버 표기로 맞춘다 — 사장님이 검색창에 친 이름과 실제 등록 상호가 다를 수 있다. + official = str(base.get("name")).strip() + if official and official != place.name: + await DB_SESSION_MNG.execute_lambda_claim( + places.DBType(), + lambda s: self.crud.update_place( + s, uuid.UUID(user_info.company_id), uuid.UUID(place_id), {"name": official} + ), + ) + if verified.place: + verified.place.name = official + + # 붙여넣은 URL 을 채널로 등록·확정한다. 사장님이 직접 가져온 주소라 추가 확인이 필요 없다. + canonical = f"https://m.place.naver.com/place/{naver_id}/home" + await self.create_link( + user_info, place_id, + Req_CreateLink(channel=LinkChannel.NAVER_PLACE, url=canonical, + title=f"{official} 네이버 플레이스", discovered_by=SourceType.OWNER), + ) + await DB_SESSION_MNG.execute_lambda_claim( + place_links.DBType(), + lambda s: self.crud.confirm_link_by_url( + s, uuid.UUID(place_id), canonical, uuid.UUID(user_info.user_id), GTime.UTC() + ), + ) + LOG.i(f"[verify_by_url] '{official}' 확정 + 채널 등록 — naver place {naver_id}") + return verified + + async def verify_place(self, user_info: UserInfo, place_id: str, req: Req_VerifyPlace) -> Res_Place: + """외부 장소 DB(카카오/네이버) 조회 결과를 박제해 동일 업소를 확정한다. + + ★ 이걸 통과해야 수집이 열린다(verified_at). + + 식별 근거가 하나도 없으면 확정하지 않는다 — 외부 고유 id(카카오) 또는 도로명주소(네이버) + 중 하나는 있어야 '이 가게가 그 가게'라고 말할 수 있다.""" + res = Res_Place() + external_id = req.external_place_id.strip() + road_address = (req.road_address or "").strip() + if not external_id and not road_address: + res.result.SetResult(ErrorType.PLACE_VERIFY_NO_CANDIDATE) + return res + + err_type, place = await self._load(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + cid = uuid.UUID(user_info.company_id) + now = GTime.UTC() + data = { + "external_source": req.source.value, + "external_place_id": external_id or None, + "road_address": road_address or None, + "address": req.address, + "phone": req.phone, + "latitude": req.latitude, + "longitude": req.longitude, + # ★ 지역 코드는 **서버가 유도한다**. 외부 장소 DB(카카오·네이버)는 행정구역 코드를 + # 주지 않으므로 후보에도 없고, 그래서 프론트가 보낼 수가 없다 — 클라이언트가 + # 못 채우는 값을 클라이언트에 맡겨 두면 영원히 NULL 로 남는다(실측: 모든 사업장). + # + # region_code 가 비면 지역 정보 캐시를 찾을 키가 없어서 + # 날씨·축제·주변 관광지가 통째로 빈다(local_contents 의 키가 이 값이다). + # 발행본에는 날씨 섹션이 아무것도 그리지 않고, 하이드레이션 뒤 실시간 조회도 + # 막힌다(use-live-weather 가 regionCode 없이는 fetch 하지 않는다). + # + # ★ 지어내지 않는다. 도로명주소에서 '시도 + 시군구' 를 뽑는 것뿐이고, + # 주소가 없거나 형식이 다르면 None 이다(그때는 지역 정보가 비는 게 맞다). + # 요청이 값을 실어 보냈으면 그쪽이 이긴다. + "region_code": req.region_code or region_key(road_address), + "verified_at": now, + "verified_by": uuid.UUID(user_info.user_id), + } + err_type, rowcount = await DB_SESSION_MNG.execute_lambda_claim( + places.DBType(), + lambda s: self.crud.update_place(s, cid, uuid.UUID(place_id), data), + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + if rowcount == 0: + res.result.SetResult(ErrorType.PLACE_NOT_FOUND) + return res + + # 외부 장소 DB 가 준 업체 홈페이지를 공식 홈페이지 채널로 등록해 둔다. + # 실측상 Perplexity 는 이 채널을 잘 못 찾는다 — 검증 단계에서 건지는 게 확실하다. + # 등록만 하고 확정하지는 않는다(확정은 수집 잡이 어댑터 유무를 보고 판단). + if (req.place_url or "").strip(): + link = place_links( + place_id=uuid.UUID(place_id), + channel=LinkChannel.OFFICIAL_SITE.value, + url=req.place_url.strip(), + title=place.name, + discovered_by=SourceType.API.value, + discovered_at=now, + ) + await DB_SESSION_MNG.execute_lambda_run( + [place_links.DBType()], + [lambda s: self.crud.add_link(s, link)], + ) + return await self.get_place(user_info, place_id) + + # ---- 하위 단위(객실·메뉴·프로그램) ---- + async def list_units(self, user_info: UserInfo, place_id: str) -> Res_UnitList: + res = Res_UnitList() + err_type, _place = await self._load(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + list_err, rows = await DB_SESSION_MNG.execute_lambda( + units.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.list_units(s, uuid.UUID(place_id)), + ) + if list_err != ErrorType.SUCCESS: + res.result.SetResult(list_err) + return res + res.units = [UnitData.model_validate(r) for r in rows] + return res + + async def create_unit(self, user_info: UserInfo, place_id: str, req: Req_CreateUnit) -> Res_Unit: + res = Res_Unit() + if not req.name.strip(): + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + return res + err_type, _place = await self._load(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + unit = units(place_id=uuid.UUID(place_id), name=req.name.strip(), sort_order=req.sort_order) + run_err = await DB_SESSION_MNG.execute_lambda_run( + [units.DBType()], + [lambda s: self.crud.add_unit(s, unit)], + ) + if run_err != ErrorType.SUCCESS: + res.result.SetResult(run_err) + return res + res.unit = UnitData.model_validate(unit) + return res + + # ---- 채널 링크 ---- + async def list_links(self, user_info: UserInfo, place_id: str, confirmed_only: bool = False) -> Res_LinkList: + res = Res_LinkList() + err_type, _place = await self._load(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + list_err, rows = await DB_SESSION_MNG.execute_lambda( + place_links.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.list_links(s, uuid.UUID(place_id), confirmed_only), + ) + if list_err != ErrorType.SUCCESS: + res.result.SetResult(list_err) + return res + res.links = [LinkData.model_validate(r) for r in rows] + res.confirmed = sum(1 for r in rows if r.confirmed_at is not None) + return res + + async def create_link(self, user_info: UserInfo, place_id: str, req: Req_CreateLink) -> Res_Link: + """채널 URL 등록. Perplexity 가 발견한 것도, 사장님이 직접 붙여넣은 것도 여기로 들어온다. + + ★ 확정(confirmed_at)은 별도 액션이다 — 등록만으로 크롤링 대상이 되지 않는다.""" + res = Res_Link() + if not req.url.strip(): + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + return res + err_type, _place = await self._load(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + link = place_links( + place_id=uuid.UUID(place_id), + channel=req.channel.value, + url=req.url.strip(), + title=req.title, + discovered_by=req.discovered_by.value, + discovered_at=GTime.UTC(), + ) + run_err = await DB_SESSION_MNG.execute_lambda_run( + [place_links.DBType()], + [lambda s: self.crud.add_link(s, link)], + ) + if run_err != ErrorType.SUCCESS: + res.result.SetResult(run_err) + return res + res.link = LinkData.model_validate(link) + return res + + async def confirm_link(self, user_info: UserInfo, place_id: str, link_id: str) -> Res_Link: + """★ 동일 업소로 확인된 URL 만 크롤링 대상이 된다. 사업장 검증이 끝나야 확정할 수 있다.""" + res = Res_Link() + err_type, place = await self._load(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + if place.verified_at is None: + res.result.SetResult(ErrorType.PLACE_NOT_VERIFIED) + return res + + run_err, rowcount = await DB_SESSION_MNG.execute_lambda_claim( + place_links.DBType(), + lambda s: self.crud.confirm_link( + s, uuid.UUID(place_id), uuid.UUID(link_id), uuid.UUID(user_info.user_id), GTime.UTC() + ), + ) + if run_err != ErrorType.SUCCESS: + res.result.SetResult(run_err) + return res + if rowcount == 0: + # 없거나 이미 확정됨 — 어느 쪽이든 이 호출로 바뀐 건 없다. + res.result.SetResult(ErrorType.LINK_NOT_FOUND) + return res + + links = await self.list_links(user_info, place_id) + res.link = next((x for x in links.links if str(x.link_id) == str(link_id)), None) + return res + + # ---- 수집 시작 ---- + async def start_collect(self, user_info: UserInfo, place_id: str, req: Req_StartCollect) -> Res_StartCollect: + """수집 파이프라인을 큐에 넣고 즉시 응답한다. + + 한 건에 몇 분(Perplexity 10~30s + 크롤링 + Vision 사진 배치)이라 동기로 처리할 수 없다. + 클라이언트는 돌려받은 job_id 로 GET /v1/job/{job_id} 를 폴링한다. + + ★ 진입 게이트는 하나 — 동일 업소 검증(verified_at). 검증 없이 긁으면 남의 가게가 섞인다. + 채널 URL 발견(Perplexity)과 확정은 잡 안에서 순서대로 일어난다: + Perplexity URL 발견 → 확정 → 확정된 URL 만 크롤링 → fact/사진 후보 적재 + """ + res = Res_StartCollect() + err_type, place = await self._load(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + if place.verified_at is None: + res.result.SetResult(ErrorType.PLACE_NOT_VERIFIED) + return res + + # 채널 URL 발견(Perplexity)은 **잡의 첫 단계**다 — 링크가 하나도 없어도 수집을 시작할 수 있다. + # 여기서는 이미 확정된 링크 수만 세어 응답에 실어준다(진행 상황 표시용). + link_err, links = await DB_SESSION_MNG.execute_lambda( + place_links.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.list_links(s, uuid.UUID(place_id), True), + ) + if link_err != ErrorType.SUCCESS: + res.result.SetResult(link_err) + return res + + wanted = {str(x) for x in req.link_ids} + targets = [x for x in links if not wanted or str(x.link_id) in wanted] + res.confirmed_links = len(targets) + + # link_ids 를 콕 집었는데 그중 확정된 게 없으면 시작할 이유가 없다(재크롤 요청 경로). + if wanted and not targets: + res.result.SetResult(ErrorType.LINK_NOT_CONFIRMED) + return res + + payload = { + "place_id": place_id, + "company_id": user_info.company_id, + "category": place.category, + # 명시적으로 고른 링크가 있을 때만 대상을 제한한다. 기본 요청에서 현재 + # 확정 링크를 복사하면, 잡의 discover 단계가 새로 확정한 네이버 링크가 + # wanted 필터에서 빠져 사진·정보 수집이 0건으로 끝난다. + "link_ids": [str(x) for x in req.link_ids], + "force": req.force, + # 유료 검색은 요청자가 선택한 한 회차에만 실행한다. 이후 확정 링크 크롤링이나 + # 재수집이 이 값을 암묵적으로 물려받으면 같은 URL 을 찾는 데 계속 과금된다. + "discover_channels": req.discover_channels, + "requested_by": user_info.user_id, + } + # 사업장당 활성 수집 잡 1건 — 버튼을 두 번 눌러도 두 번 돌지 않는다. + job_id, created = await enqueue_job( + self.queue, JobType.COLLECT, payload, dedupe_key=f"collect:{place_id}" + ) + if job_id is None: + res.result.SetResult(ErrorType.COLLECT_ALREADY_RUNNING) + return res + + res.job_id = uuid.UUID(job_id) + res.status = JobStatus.PENDING + res.created = created + + # 수집 진행 중임을 사업장 상태에 반영(관리 화면 배지). 실패해도 잡은 이미 들어갔다. + if created and place.status == PlaceStatus.DRAFT.value: + await DB_SESSION_MNG.execute_lambda_claim( + places.DBType(), + lambda s: self.crud.update_place( + s, uuid.UUID(user_info.company_id), uuid.UUID(place_id), + {"status": PlaceStatus.COLLECTING.value}, + ), + ) + return res + + # ---- 사진 분석 시작 ---- + async def start_vision(self, user_info: UserInfo, place_id: str, req: Req_StartVision) -> Res_StartVision: + """Gemini Vision 사진 분석을 큐에 넣고 즉시 응답한다. + + 수집이 사진을 저장하면 자동으로 걸리지만, 사장님이 사진을 직접 올린 뒤 다시 돌리거나 + force 로 재분석할 때 이 엔드포인트를 쓴다.""" + from sqlalchemy import func, select + + from common.database.model.models import media + from services.external import gemini + + res = Res_StartVision() + err_type, _place = await self._load(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + if not gemini.is_configured(): + res.result.SetResult(ErrorType.GENERATOR_NOT_CONFIGURED) + return res + + conds = [media.place_id == uuid.UUID(place_id), media.deleted == False] # noqa: E712 + if not req.force: + # ★ 미분석 기준은 alt_text 다 — label 은 수집 어댑터가 페이지 캡션으로 채운다. + # label 로 세면 캡션 있는 사진이 전부 '분석됨'으로 빠져 pending 0 이 된다 + # (crud/media_crud.list_media 의 같은 주석 참고). + from sqlalchemy import func as sa_func + from sqlalchemy import or_ as sa_or + conds.append(sa_or(media.alt_text.is_(None), sa_func.btrim(media.alt_text) == "")) + cnt_err, rows = await DB_SESSION_MNG.execute_lambda( + media.DBType(), + DBWRType.DB_READ.value, + lambda s: DB_SESSION_MNG.execute(s, select(func.count()).select_from(media).where(*conds)), + ) + res.pending_media = int(rows[0] or 0) if cnt_err == ErrorType.SUCCESS and rows else 0 + if res.pending_media == 0: + res.result.SetResult(ErrorType.MEDIA_NOT_FOUND) + return res + + job_id, created = await enqueue_job( + self.queue, JobType.VISION, + {"place_id": place_id, "company_id": user_info.company_id, "force": req.force}, + dedupe_key=f"vision:{place_id}", + ) + if job_id is None: + res.result.SetResult(ErrorType.COLLECT_ALREADY_RUNNING) + return res + res.job_id = uuid.UUID(job_id) + res.status = JobStatus.PENDING + res.created = created + return res + + # ---- 동일 업소 후보 조회 (UI 가 사람에게 고르게 한다) ---- + async def find_candidates(self, user_info: UserInfo, place_id: str, query: str | None = None) -> Res_VerifyCandidates: + """외부 장소 DB 에서 이 상호명의 후보를 찾아 그대로 내려준다. + + ★ 서버가 자동으로 확정하지 않는다. outcome 이 MATCHED 여도 후보 전체를 돌려줘 + UI 가 사람에게 보여주고 고르게 한다 — 남의 가게를 붙이는 게 이 서비스에서 제일 비싼 실수다. + 자동 판정은 'UI 가 한 번만 물어봐도 되는가'(auto_selectable)를 알려주는 힌트일 뿐이다. + """ + from common.enums import ExternalPlaceSource + from services.external import kakao as kakao_client + from services.external import naver as naver_client + + res = Res_VerifyCandidates() + err_type, place = await self._load(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + # ★ 검색어와 판정용 상호명은 다른 값이다. + # 화면은 '상호명 + 위치'를 합쳐 query 로 보낸다(후보를 좁히려고). 그런데 판정 + # (pick_match)은 후보 상호명과 **정확일치**를 보므로, 지역이 붙은 문자열을 그대로 + # 넘기면 정확일치가 영영 성립하지 않는다 — 실측(2026-08-28) 10건 전부 + # AMBIGUOUS(name_no_exact) 였고, 후보가 1건뿐인 경우까지 그랬다. + # 상호명은 places.name 이 들고 있다(위저드가 검색 직전에 상호만 PATCH 한다). + search_query = (query or place.name or "").strip() + name = (place.name or "").strip() or search_query + if not search_query: + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + return res + + # 카카오 키가 있으면 카카오(전화번호·고유 id 가 있어 판정이 강하다), 없으면 네이버. + kakao = kakao_client.KakaoLocalClient() + try: + if kakao.enabled: + res.source = ExternalPlaceSource.KAKAO + match = await kakao.verify_place(name, search_query=search_query) + await kakao.aclose() + else: + client = naver_client.NaverLocalClient() + if not client.enabled: + res.result.SetResult(ErrorType.LOCAL_NOT_CONFIGURED) + return res + res.source = ExternalPlaceSource.NAVER + match = await client.verify_place( + name, address_hint=place.road_address, search_query=search_query + ) + await client.aclose() + except (kakao_client.KakaoNotConfigured, naver_client.NaverNotConfigured): + res.result.SetResult(ErrorType.LOCAL_NOT_CONFIGURED) + return res + except (kakao_client.KakaoRequestFailed, naver_client.NaverRequestFailed) as ex: + LOG.w(f"[verify] 후보 조회 실패 place={place_id}: {type(ex).__name__}: {ex}") + res.result.SetResult(ErrorType.LOCAL_FETCH_FAILED) + return res + + res.outcome = match.outcome.value if hasattr(match.outcome, "value") else str(match.outcome) + res.reason = match.reason + res.auto_selectable = bool(match.is_matched) + + # MATCHED 여도 후보를 전부 내려보낸다 — 사람이 다른 걸 고를 수 있어야 한다. + rows = match.candidates or ([match.place] if match.place else []) + # 지역검색 API는 네이버 Place ID를 주지 않는다. 후보를 보여주기 전에 모바일 통합검색에서 + # 상호가 정확히 일치하는 ID를 한 번 찾아, 화면이 "지역 후보 발견"과 "플레이스 발견"을 + # 구분할 수 있게 한다. 실패는 정상적인 fallback이므로 후보 조회 자체는 실패시키지 않는다. + from services.external import naver_place_lookup + + try: + # ★ 여기는 **넓은 검색어**를 쓴다. 통합검색은 한 번만 부르고(5번 부르면 429) 그 + # 한 페이지 안에서 후보들의 id 를 찾는 구조라, 지역이 붙어 결과가 그 동네로 + # 좁혀질수록 찾을 확률이 올라간다. 판정(pick_match)과는 요구가 정반대다. + naver_ids = await naver_place_lookup.find_place_ids(search_query, [c.name for c in rows]) + except Exception as ex: # noqa: BLE001 — 지도 URL 직접 입력으로 이어진다 + LOG.w(f"[verify] 네이버 플레이스 자동 발견 실패(후보는 유지): {type(ex).__name__}: {ex}") + naver_ids = {} + res.candidates = [ + PlaceCandidate( + external_place_id=getattr(c, "kakao_place_id", None) or getattr(c, "naver_place_id", None), + name=c.name, + road_address=c.road_address, + address=c.address, + phone=c.phone, + latitude=c.latitude, + longitude=c.longitude, + category_name=c.category_name, + place_url=c.place_url, + naver_place_url=( + naver_place_lookup.place_url(naver_ids[c.name]) if c.name in naver_ids else None + ), + ) + for c in rows + ] + if not res.candidates: + res.result.SetResult(ErrorType.PLACE_VERIFY_NO_CANDIDATE) + return res + + # ---- 소개문·FAQ 생성 시작 ---- + async def start_copy(self, user_info: UserInfo, place_id: str, req: Req_StartCopy) -> Res_StartCopy: + """소개문·FAQ 생성을 큐에 넣는다. + + ★ 근거로 쓸 확인된 fact 가 없으면 잡을 만들지 않는다 — + 근거 없이 문장을 쓰면 그게 환각이고, 유료 호출만 낭비된다.""" + from common.database.model.models import facts as facts_model + from crud.fact_crud import FactCRUD + from services.external import gemini_text + + res = Res_StartCopy() + err_type, _place = await self._load(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + if not gemini_text.is_configured(): + res.result.SetResult(ErrorType.GENERATOR_NOT_CONFIGURED) + return res + + crud = FactCRUD() + f_err, rows = await DB_SESSION_MNG.execute_lambda( + facts_model.DBType(), + DBWRType.DB_READ.value, + lambda s: crud.list_facts(s, uuid.UUID(place_id), None, None, True, True), + ) + if f_err != ErrorType.SUCCESS: + res.result.SetResult(f_err) + return res + res.grounded_facts = sum(1 for r in rows if r.unit_id is None and (r.value or "").strip()) + if res.grounded_facts == 0: + res.result.SetResult(ErrorType.FAQ_UNGROUNDED) + return res + + job_id, created = await enqueue_job( + self.queue, JobType.COPY, + {"place_id": place_id, "company_id": user_info.company_id, "requested_by": user_info.user_id}, + dedupe_key=f"copy:{place_id}", + ) + if job_id is None: + res.result.SetResult(ErrorType.COLLECT_ALREADY_RUNNING) + return res + res.job_id = uuid.UUID(job_id) + res.status = JobStatus.PENDING + res.created = created + return res diff --git a/backend/services/prompts/__init__.py b/backend/services/prompts/__init__.py new file mode 100644 index 0000000..32fbada --- /dev/null +++ b/backend/services/prompts/__init__.py @@ -0,0 +1 @@ +"""LLM prompts and structured-output schemas.""" diff --git a/backend/services/prompts/channel_discovery.py b/backend/services/prompts/channel_discovery.py new file mode 100644 index 0000000..89403c1 --- /dev/null +++ b/backend/services/prompts/channel_discovery.py @@ -0,0 +1,46 @@ +"""Prompt contract for public channel URL discovery.""" + +SYSTEM_PROMPT = ( + "너는 URL 수집기다. 업소의 채널 페이지 URL만 찾는다. " + "정보를 요약하거나 지어내지 않는다." +) + +RESPONSE_SCHEMA = { + "type": "json_schema", + "json_schema": { + "schema": { + "type": "object", + "properties": { + "links": { + "type": "array", + "items": { + "type": "object", + "properties": {"url": {"type": "string"}, "title": {"type": "string"}}, + "required": ["url"], + }, + } + }, + "required": ["links"], + } + }, +} + + +def build_prompt(name: str, address: str | None, category_hint: str | None) -> str: + identity = [f"상호명: {name}"] + if address: + identity.append(f"주소(참고): {address}") + if category_hint: + identity.append(f"업종(참고): {category_hint}") + + return "\n".join([ + " / ".join(identity), + "", + "이 업소의 상세 페이지 URL을 찾아라. 야놀자·여기어때·네이버 플레이스를 우선한다.", + "- URL만 반환하고 영업시간·가격·주소는 쓰지 마라.", + "- 확인한 URL만 사용하며 URL을 추측해 만들지 않는다.", + "- 채널당 상세 페이지는 1개만 반환한다.", + "- 서비스 첫 화면, 목록, 블로그·카페 후기는 제외한다.", + "- 동명 업소이거나 확실하지 않으면 제외한다.", + "- 최대 4건이며, 없으면 links를 빈 배열로 둔다.", + ]) diff --git a/backend/services/prompts/copy.py b/backend/services/prompts/copy.py new file mode 100644 index 0000000..9cd4cdd --- /dev/null +++ b/backend/services/prompts/copy.py @@ -0,0 +1,82 @@ +"""Prompt contract for grounded homepage copy.""" + +from typing import Optional, Protocol, Sequence + +from common.enums import PlaceCategory + + +class FactLike(Protocol): + key: str + label: str + value: str + unit: Optional[str] + + +RESPONSE_SCHEMA = { + "type": "object", + "properties": { + "intro": {"type": "string"}, + "intro_fact_keys": {"type": "array", "items": {"type": "string"}}, + "meta_description": {"type": "string"}, + "faqs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "question": {"type": "string"}, + "answer": {"type": "string"}, + "fact_keys": {"type": "array", "items": {"type": "string"}}, + }, + "required": ["question", "answer", "fact_keys"], + }, + }, + }, + "required": ["intro", "intro_fact_keys", "meta_description", "faqs"], +} + +_CATEGORY_LABEL = { + PlaceCategory.LODGING: "숙박업소", + PlaceCategory.CAFE: "카페", + PlaceCategory.RESTAURANT: "음식점", + PlaceCategory.TOUR_ACTIVITY: "관광·체험 시설", +} + + +def _fact_lines(facts: Sequence[FactLike]) -> str: + return "\n".join( + f"- {fact.key} ({fact.label}) = {fact.value}" + (f" {fact.unit}" if fact.unit else "") + for fact in facts + ) + + +def build_prompt( + place_name: str, + category: PlaceCategory, + facts: Sequence[FactLike], + max_faqs: int, + unit_facts: Optional[Sequence[FactLike]] = None, +) -> str: + sections = [ + f"'{place_name}'({_CATEGORY_LABEL.get(category, '사업장')})의 공식 홈페이지 문구를 작성한다.", + "", + "확인된 사업장 사실:", + _fact_lines(facts) if facts else "- 없음", + ] + if unit_facts: + sections.extend(["", "확인된 객실·메뉴 사실:", _fact_lines(unit_facts)]) + sections.extend([ + "", + "출력:", + "- intro: 소개문 100~250자", + "- intro_fact_keys: 소개문의 근거 key", + "- meta_description: 검색 요약 50~120자", + f"- faqs: 최대 {max_faqs}개, 각 항목에 근거 fact_keys 포함", + "", + "규칙:", + "- 위 사실에 없는 숫자·시설·지역 정보를 지어내지 마라.", + "- false·불가·없음 값을 가능하다고 표현하지 않는다.", + "- 홍보성·평가성 표현을 쓰지 않는다.", + "- 근거 없는 FAQ는 만들지 않는다.", + "- 한국어 존댓말을 사용한다.", + ]) + return "\n".join(sections) diff --git a/backend/services/prompts/extract.py b/backend/services/prompts/extract.py new file mode 100644 index 0000000..2899d40 --- /dev/null +++ b/backend/services/prompts/extract.py @@ -0,0 +1,110 @@ +"""원문 텍스트 → 업종 스키마 fact 추출 프롬프트·응답 스키마. + + 무엇을 묻는가 여기 + 어떻게 부르는가 services/llm/gemini.py + 답을 믿을 것인가 services/grounding/extract.py evidence 대조 + 무엇을 돌려주는가 services/external/gemini_extract.py + +★ 왜 사이트별 파서 대신 이걸 쓰는가 + 사장님 홈페이지는 카페24·아임웹·워드프레스·수제 HTML 이 전부 제각각이고 + JSON-LD 가 있는 곳이 드물다. 도메인마다 파서를 짜는 것은 끝이 없다. + 대신 **원문에서 찾아 오게 하고, 찾았다는 근거를 원문과 대조**한다. + +★ 이 프롬프트의 유일한 임무는 "옮겨 적기" 다. 생성이 아니다. + 값을 추론·환산·보정하지 못하게 막는 문장이 규칙의 대부분인 이유다. + 실제 안전장치는 프롬프트가 아니라 evidence 대조 코드에 있다(grounding/extract.py). +""" +from common.category_schema import get_schema +from common.enums import PlaceCategory + +# Gemini responseSchema(OpenAPI subset). ★ evidence 는 required 다 — +# 근거를 못 적는 값은 애초에 받지 않는다. +RESPONSE_SCHEMA = { + "type": "object", + "properties": { + "facts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "key": {"type": "string", "description": "아래 필드 목록의 key 중 하나. 목록에 없는 key 는 절대 쓰지 않는다"}, + "value": {"type": "string", "description": "원문 표기 그대로. bool 필드는 'true' 또는 'false'"}, + "unit_name": {"type": "string", "description": "scope=unit 필드일 때 어느 객실·메뉴·프로그램인지. place 스코프면 빈 문자열"}, + "evidence": {"type": "string", "description": "이 값의 근거가 된 원문 문장을 **글자 그대로** 복사. 요약·수정 금지"}, + }, + "required": ["key", "value", "evidence"], + }, + } + }, + "required": ["facts"], +} + +_RULES = """규칙 +1. 아래 [필드 목록]에 있는 key 만 쓴다. 목록에 없는 key 는 버린다. +2. value 는 원문 표기를 **그대로** 옮긴다. 단위 환산·반올림·요약·번역을 하지 않는다. + - "오후 3시" 를 "15:00" 으로 바꾸지 않는다. 원문이 "오후 3시" 면 "오후 3시" 다. +3. evidence 에는 그 값이 적힌 **원문 문장을 글자 그대로 복사**한다. + - 원문에 없는 문장을 쓰면 그 항목은 버려진다. + - 여러 문장에 걸쳐 있으면 값이 실제로 적힌 한 문장만 고른다. +4. 원문에 없는 것은 만들지 않는다. 모르면 그 key 를 빼면 된다. 빈 값으로 채우지 않는다. + - "보통 펜션은 3시 체크인" 같은 일반 상식으로 채우지 않는다. +5. type=bool 필드는 value 를 "true" 또는 "false" 로만 쓴다. + - 원문에 "반려동물 동반 불가" 라고 있으면 pet_allowed = "false" 다. 부정 표현을 놓치지 않는다. + - 원문에 언급이 아예 없으면 그 key 를 **쓰지 않는다**. "없다"고 단정하지 않는다. +6. type=number 필드는 숫자만 쓴다(단위·쉼표 없이). 원문이 "최대 4인" 이면 "4" 다. +7. scope=unit 필드는 unit_name 을 반드시 채운다. 같은 객실·메뉴의 항목은 unit_name 을 똑같이 쓴다. + - unit_name 은 원문에 적힌 이름 그대로. "A동", "커플룸", "김치찌개". +8. 홍보 문구·후기·다른 업소 이야기는 근거로 쓰지 않는다. + - "최고의 전망", "인생 맛집" 같은 표현은 사실이 아니다. +9. 같은 key 가 원문에서 여러 번 다르게 적혀 있으면, 가장 구체적이고 최신인 한 건만 고른다. +""" + + +def _field_lines(category: PlaceCategory) -> str: + """업종 스키마를 그대로 프롬프트에 편다. + + ★ 여기서 목록을 따로 관리하지 않는다 — resources/*.json 이 유일한 출처다. + 업종 필드가 늘면 프롬프트도 자동으로 같이 는다. + """ + schema = get_schema(category) + lines = [] + for spec in schema.fields.values(): + # ★ allow_llm 필드(소개문 등)는 목록에 넣지 않는다 — LLM 이 **쓰는** 칸이지 + # 원문에서 옮겨 담는 사실이 아니다. 여기에 원문을 채우면 발행본의 소개가 + # 수집 원문으로 덮인다(2026-08-31 사고, tests/test_collector.py 참고). + if spec.allow_llm: + continue + bits = [f"- {spec.key} ({spec.label})", f"type={spec.type}", f"scope={spec.scope}"] + if spec.unit: + bits.append(f"단위={spec.unit}") + if spec.critical: + # ★ 틀리면 예약 클레임이 나는 항목. 애매하면 비우라고 명시한다. + bits.append("※중요-확실할 때만") + lines.append(" · ".join(bits)) + return "\n".join(lines) + + +def build_prompt(place_name: str, category: PlaceCategory, source_text: str, *, max_chars: int = 30000) -> str: + """추출 프롬프트. + + source_text 는 앞에서 잘라 넣는다 — 사장님 홈페이지 한 페이지 본문은 대개 이 안에 들어오고, + 넘치면 뒤쪽은 대개 푸터·저작권·다른 페이지 링크라 fact 가 거의 없다. + """ + schema = get_schema(category) + text = (source_text or "").strip()[:max_chars] + + return f"""너는 사업장 정보를 **원문에서 찾아 옮겨 적는** 추출기다. 글을 쓰는 것이 아니다. + +[사업장] {place_name} (업종: {schema.label}) + +{_RULES} + +[필드 목록] +{_field_lines(category)} + +[원문] +\"\"\" +{text} +\"\"\" + +원문에서 찾은 항목만 facts 배열에 담아라. 찾은 게 없으면 빈 배열을 반환한다.""" diff --git a/backend/services/prompts/vision.py b/backend/services/prompts/vision.py new file mode 100644 index 0000000..f9bd1b2 --- /dev/null +++ b/backend/services/prompts/vision.py @@ -0,0 +1,51 @@ +"""Prompt contract for image classification and accessible alt text.""" + +from typing import Optional + +from common.enums import PlaceCategory + +_LABELS = { + PlaceCategory.LODGING: ["외관", "침실", "거실", "욕실", "주방", "수영장", "바비큐장", "주차장", "전망", "부대시설"], + PlaceCategory.CAFE: ["외관", "내부", "좌석", "메뉴", "디저트", "음료", "테라스", "주차장"], + PlaceCategory.RESTAURANT: ["외관", "내부", "좌석", "메뉴", "음식", "룸", "주차장"], + PlaceCategory.TOUR_ACTIVITY: ["외관", "시설", "장비", "활동", "안전장비", "주차장", "매표소"], +} +_DEFAULT_LABELS = ["외관", "내부", "시설", "기타"] + +RESPONSE_SCHEMA = { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "ref": {"type": "string"}, + "label": {"type": "string"}, + "alt_text": {"type": "string"}, + "confidence": {"type": "number", "minimum": 0, "maximum": 1}, + }, + "required": ["ref", "label", "alt_text", "confidence"], + }, + } + }, + "required": ["items"], +} + + +def build_prompt( + category: Optional[PlaceCategory], unit_names: Optional[list[str]], refs: list[str] +) -> str: + lines = [ + "소상공인 홈페이지에 사용할 사진을 분류한다.", + f"사진 {len(refs)}장의 각 [ref]에 대해 아래 값을 만든다.", + f"- label: {' / '.join(_LABELS.get(category, _DEFAULT_LABELS))} 중 하나", + "- alt_text: 화면에 보이는 것만 한국어 20~60자로 작성", + "- confidence: 불명확할수록 0에 가깝게 지정", + "- 가격·면적·인원·시설을 지어내지 마라.", + "- '아름다운' 같은 홍보성 또는 평가성 표현을 쓰지 않는다.", + ] + if unit_names: + lines.append(f"- 관련된 경우 객실·프로그램 이름을 label에 붙일 수 있다: {', '.join(unit_names)}") + lines.append(f"모든 ref를 빠짐없이 반환한다: {', '.join(refs)}") + return "\n".join(lines) diff --git a/backend/services/publish_gate.py b/backend/services/publish_gate.py new file mode 100644 index 0000000..78b50a0 --- /dev/null +++ b/backend/services/publish_gate.py @@ -0,0 +1,109 @@ +"""발행 검수 게이트 — 사이트가 나가기 전에 반드시 통과해야 하는 검사. + +이 파일이 절대규칙 1~3 을 코드로 강제하는 유일한 자리다. 여기를 우회하는 발행 경로를 만들면 안 된다. + + ★ 규칙 1 미검증 fact 는 응답에 포함하지 않는다. + 특히 체크인·취사·반려동물·취소 규정 — 틀린 채로 발행되면 실제 예약 클레임이 난다. + ★ 규칙 2 고유 콘텐츠가 1건도 없으면 발행 API 가 거부한다. 같은 템플릿 대량 생성은 스팸 판정 대상. + ★ 규칙 3 구조화 데이터(JSON-LD) 값 = 화면에 보이는 값. 불일치 시 빌드 실패. + + 업종 스키마의 required 필드가 비면 발행하지 않는다(빈 껍데기 페이지 방지). + +게이트는 **판정만** 한다. 스냅샷을 만들거나 빌드하지 않는다 — 그래야 테스트가 쉽고, +빌드 경로가 바뀌어도 규칙은 한 곳에 남는다. +""" +from dataclasses import dataclass, field + +from common.category_schema import get_schema +from common.enums import PUBLISHABLE_FACT_STATUSES, FactStatus, PlaceCategory, PublishRejectReason + + +@dataclass +class GateResult: + """검수 결과. passed 가 False 면 reason 과 detail 이 publish_logs 에 그대로 실린다.""" + + passed: bool + reason: PublishRejectReason | None = None + detail: dict = field(default_factory=dict) + + def as_log(self) -> dict: + return {"reason": self.reason.name if self.reason else None, **self.detail} + + +def check_facts_verified(facts: list) -> GateResult: + """★ 규칙 1 — 노출 대상 fact 가 전부 검증됐는가. + + facts 는 '사이트에 실을 예정인' fact 행 목록이다. 하나라도 VERIFIED/CORRECTED 가 아니면 거부한다. + 호출측이 이미 필터링했더라도 여기서 다시 본다 — 필터를 빠뜨린 경로가 생겨도 여기서 막힌다.""" + bad = [ + {"key": f["key"] if isinstance(f, dict) else f.key, + "status": FactStatus(f["status"] if isinstance(f, dict) else f.status).name} + for f in facts + if FactStatus(f["status"] if isinstance(f, dict) else f.status) not in PUBLISHABLE_FACT_STATUSES + ] + if bad: + return GateResult(False, PublishRejectReason.UNVERIFIED_FACT, {"unverified": bad[:20], "count": len(bad)}) + return GateResult(True) + + +def check_required_fields(category: PlaceCategory, facts: list) -> GateResult: + """업종 스키마의 required 필드가 다 있는가. 없으면 빈 껍데기 페이지가 된다.""" + schema = get_schema(category) + required = set(schema.required_keys("place")) + have = { + (f["key"] if isinstance(f, dict) else f.key) + for f in facts + if str(f["value"] if isinstance(f, dict) else f.value or "").strip() + } + missing = sorted(required - have) + if missing: + return GateResult( + False, PublishRejectReason.REQUIRED_FACT_MISSING, + {"missing": missing, "labels": [schema.get(k).label for k in missing if schema.get(k)]}, + ) + return GateResult(True) + + +def check_unique_content(unique_content_count: int) -> GateResult: + """고유 콘텐츠 품질 진단용. 발행 게이트에서는 더 이상 호출하지 않는다. + + 이 가게에만 있는 것(소개문·FAQ·객실 설명·사진 alt·템플릿 아닌 fact 값)이 0이면 + 같은 템플릿 대량 생성으로 보인다. 그건 스팸 판정 대상이고, 판정되면 사이트가 통째로 무의미해진다.""" + if unique_content_count <= 0: + return GateResult(False, PublishRejectReason.NO_UNIQUE_CONTENT, {"unique_content_count": unique_content_count}) + return GateResult(True) + + +def check_jsonld_matches(mismatches: list) -> GateResult: + """★ 규칙 3 — 구조화 데이터 값이 화면 값과 같은가. + + JSON-LD 는 AI 검색이 읽는 값이고 화면은 사람이 읽는 값이다. 둘이 다르면 + '검색엔진에만 다른 말을 하는' 상태가 된다 — 클로킹으로 취급될 수 있고, 무엇보다 거짓이다.""" + if mismatches: + return GateResult(False, PublishRejectReason.JSONLD_MISMATCH, {"mismatches": list(mismatches)[:20]}) + return GateResult(True) + + +def evaluate(category: PlaceCategory, facts: list, unique_content_count: int, mismatches: list) -> GateResult: + """게이트 전체. **처음 걸린 것에서 멈춘다** — 운영자가 하나씩 고치게 사유를 하나만 준다. + + 순서는 심각도 순: 미검증(클레임) → JSON-LD 불일치(거짓). + + ★ 업종 필수 항목 누락은 **막지 않는다**(2026-08-27 결정). + 막아야 할 것은 "틀린 정보가 나가는 것"이지 "정보가 덜 찬 것"이 아니다. + 영업시간이 비어 있어도 주소·전화가 확인된 페이지는 그 자체로 쓸모가 있고, + 사장님은 발행 뒤에 언제든 채워 넣을 수 있다(채우면 재빌드된다). + 대신 무엇이 비었는지는 계속 알려준다 — warnings 로 내려보내 화면이 띄운다. + """ + for result in ( + check_facts_verified(facts), + check_jsonld_matches(mismatches), + ): + if not result.passed: + return result + + # 통과했지만 비어 있는 필수 항목은 경고로 실어 보낸다(발행은 진행된다). + required = check_required_fields(category, facts) + if not required.passed: + return GateResult(True, None, {"warning": PublishRejectReason.REQUIRED_FACT_MISSING.name, + **(required.detail or {})}) + return GateResult(True) diff --git a/backend/services/render_report.py b/backend/services/render_report.py new file mode 100644 index 0000000..b9844b9 --- /dev/null +++ b/backend/services/render_report.py @@ -0,0 +1,106 @@ +"""렌더 보고서 — SSG 가 실제로 페이지를 구웠는지 확인하는 창구. + +★ 왜 필요한가 + 발행 잡은 payload JSON 을 쓰는 것까지가 끝이고, 방문자가 볼 HTML 은 프론트의 SSG 가 굽는다. + 그 사이가 끊겨 있었다. 프리렌더가 깨져도 DB 에는 "발행됨"으로 남고, 페이지는 없는데 + 아무도 그걸 모른다 — 사장님이 [사이트 열기] 를 눌러야 404 로 발견된다. + + 이제 프리렌더가 사이트마다 결과를 `/.status/.json` 에 쓴다. + 백엔드에 마운트된 디렉토리가 payload 디렉토리뿐이라 보고서도 그 안에 둔다. + +★ 여기서 하는 두 가지 + 1. 렌더 상태 — 구워졌는가, 언제, 실패했으면 왜 (사이트 조회 API 가 그대로 내보낸다) + 2. 발행 대기 — BUILD 잡이 이 버전의 보고서를 기다렸다가, 그 결과로 발행 여부를 정한다 + (wait_for). 게이트는 **실제로 나갈 HTML** 을 보고 판정해야 한다. + +★ 읽기 전용이다. 보고서가 없거나 깨져 있어도 예외를 밖으로 내보내지 않는다 — + 사이트 조회가 부수 산출물 때문에 실패하면 안 된다. +""" +import asyncio +import json +from pathlib import Path + +from common.logger import LOG +from services.site_payload import payload_dir + +# 프리렌더가 쓰는 보고서 스키마 버전. 모양이 바뀌면 prerender.ts 와 같이 올린다. +REPORT_SCHEMA_VERSION = 1 + +# 보고서 디렉토리 이름. prerender.ts 의 writeReport 와 맞춰야 한다. +STATUS_DIR = ".status" + +def report_path(slug: str) -> Path: + """`/.status/.json`.""" + return payload_dir() / STATUS_DIR / f"{slug}.json" + + +def read_report(slug: str) -> dict | None: + """렌더 보고서를 읽는다. 없거나 깨졌으면 None. + + ★ 없는 것과 깨진 것을 구분하지 않는다. 호출측이 할 일은 같다 — '아직 못 구웠다'로 본다.""" + if not slug: + return None + path = report_path(slug) + try: + if not path.is_file(): + return None + report = json.loads(path.read_text(encoding="utf-8")) + except Exception as ex: # noqa: BLE001 — 부수 산출물이 사이트 조회를 깨뜨리면 안 된다 + LOG.w(f"[render] 보고서 읽기 실패 slug={slug}: {type(ex).__name__}: {ex}") + return None + + if not isinstance(report, dict): + return None + if report.get("schemaVersion") != REPORT_SCHEMA_VERSION: + # 모르는 버전을 반쯤 해석해 "정상"이라고 답하는 게 최악이다. + LOG.w(f"[render] 모르는 보고서 버전 slug={slug}: {report.get('schemaVersion')}") + return None + return report + + +async def wait_for(slug: str, site_version: int, timeout_sec: float, poll_sec: float = 1.0) -> dict | None: + """이 버전의 렌더 보고서가 나올 때까지 기다린다. 시간 안에 안 나오면 None. + + ★ 왜 기다리나 + 발행 게이트는 **실제로 나갈 HTML** 을 보고 판정해야 한다. 그 HTML 은 프론트 렌더러가 + 굽고, 렌더러는 payload 파일을 보고 도는 별도 프로세스다. 그래서 잡이 payload 를 쓴 뒤 + 보고서가 올 때까지 기다렸다가, 그 결과로 발행 여부를 정한다. + + ★ 버전이 맞는 보고서만 받는다. 직전 버전 보고서를 보고 통과시키면 이번에 바뀐 값은 + 아무도 검사하지 않은 채로 발행된다. + + ★ BUILD 잡은 heartbeat 로 lease 를 갱신하므로 여기서 기다려도 reaper 에 회수되지 않는다.""" + deadline = asyncio.get_running_loop().time() + timeout_sec + while True: + report = read_report(slug) + if report is not None and report.get("siteVersion") == site_version: + return report + if asyncio.get_running_loop().time() >= deadline: + LOG.w(f"[render] 보고서 대기 시간 초과 slug={slug} v{site_version} ({timeout_sec}초)") + return None + await asyncio.sleep(poll_sec) + + +def render_status(slug: str, site_version: int | None = None) -> dict: + """사이트 조회 API 가 그대로 내보내는 렌더 상태. + + state PENDING 아직 안 구웠다(보고서 없음) + STALE 구웠지만 지금 버전이 아니다(발행 후 프리렌더 대기 중) + OK 현재 버전이 구워져 있다 + FAILED 프리렌더가 실패했다 — 페이지가 없거나 낡았다 + """ + report = read_report(slug) + if report is None: + return {"state": "PENDING", "rendered_at": None, "error": None, "rendered_version": None} + + rendered_version = report.get("siteVersion") + base = { + "rendered_at": report.get("renderedAt"), + "error": report.get("error"), + "rendered_version": rendered_version, + } + if not report.get("ok"): + return {"state": "FAILED", **base} + if site_version is not None and rendered_version != site_version: + return {"state": "STALE", **base} + return {"state": "OK", **base} diff --git a/backend/services/seo_audit.py b/backend/services/seo_audit.py new file mode 100644 index 0000000..9b4604d --- /dev/null +++ b/backend/services/seo_audit.py @@ -0,0 +1,108 @@ +"""발행 사이트 SEO/AEO 준비도 채점. + +점수는 검색 순위를 보장하는 외부 공인 점수가 아니라, 우리 빌더가 통제할 수 있는 신호의 +완성도다. 같은 입력은 언제나 같은 결과를 내도록 순수 함수로 두어 UI와 발행 흐름이 서로 +다른 기준을 말하지 않게 한다. +""" +from dataclasses import dataclass + + +@dataclass(frozen=True) +class AuditCheck: + id: str + group: str + label: str + points: int + earned: int + status: str + detail: str + recommendation: str | None = None + + def as_dict(self) -> dict: + return self.__dict__.copy() + + +def _check(id, group, label, points, passed, detail, recommendation=None, partial=0): + earned = points if passed else min(points, max(0, partial)) + status = "pass" if earned == points else ("warn" if earned > 0 else "fail") + return AuditCheck(id, group, label, points, earned, status, detail, recommendation) + + +def evaluate(snapshot: dict, *, verified: bool, site=None, version=None, ai_checks: list | None = None) -> dict: + place = snapshot.get("place") or {} + facts = snapshot.get("facts") or [] + faqs = snapshot.get("faqs") or [] + media = snapshot.get("media") or [] + built = bool(version and getattr(version, "built_at", None)) + unique_count = int(getattr(version, "unique_content_count", 0) or 0) if version else 0 + domain = (getattr(site, "domain", None) or "").strip() if site else "" + fact_count = len([f for f in facts if str(f.get("value") or "").strip()]) + sourced = len([f for f in facts if f.get("source_url") or f.get("verified_at")]) + image_with_alt = len([m for m in media if str(m.get("alt_text") or "").strip()]) + + seo = [ + _check("built", "기술 SEO", "정적 HTML 빌드", 15, built, + "크롤러가 자바스크립트 없이 읽을 수 있는 발행본이 있습니다." if built else "아직 빌드된 정적 발행본이 없습니다.", + "사이트를 빌드·발행하세요."), + _check("domain", "기술 SEO", "고유 주소와 canonical", 10, bool(domain), + f"고유 주소 {domain}이 canonical 기준이 됩니다." if domain else "고유 사이트 주소가 정해지지 않았습니다.", + "발행 전 사이트 주소를 확정하세요."), + _check("machine_files", "기술 SEO", "robots·sitemap·구조화 데이터", 15, built, + "robots.txt, sitemap.xml, JSON-LD가 발행본에 포함됩니다." if built else "기계용 파일은 빌드 시 생성됩니다.", + "빌드를 완료해 기계용 파일을 생성하세요."), + _check("address", "콘텐츠 SEO", "주소", 8, bool(place.get("road_address") or place.get("address")), + "지역 검색에 사용할 주소가 있습니다." if place.get("road_address") or place.get("address") else "주소가 없습니다.", + "도로명 주소를 확인하세요."), + _check("phone", "콘텐츠 SEO", "전화번호", 7, bool(place.get("phone")), + "전화 문의 답변에 사용할 번호가 있습니다." if place.get("phone") else "전화번호가 없습니다.", + "공식 전화번호를 등록하세요."), + _check("facts", "콘텐츠 SEO", "고유 정보량", 15, fact_count >= 8, + f"확인된 사업장 정보가 {fact_count}건입니다.", "영업시간·가격·시설 등 확인된 정보를 8건 이상 채우세요.", + partial=min(10, fact_count)), + _check("images", "콘텐츠 SEO", "설명 있는 이미지", 10, image_with_alt >= 3, + f"alt 설명이 있는 이미지가 {image_with_alt}장입니다.", "대표·내부·상품 사진을 3장 이상 승인하세요.", + partial=min(6, image_with_alt * 2)), + _check("unique", "신뢰·품질", "고유 콘텐츠", 10, unique_count > 0, + f"최근 빌드의 고유 콘텐츠 판정은 {unique_count}건입니다." if version else "고유 콘텐츠를 판정할 빌드가 없습니다.", + "복제 문구가 아닌 사업장 고유 소개·FAQ·사진을 추가하세요."), + _check("verified", "신뢰·품질", "동일 업소 검증", 10, verified, + "공식 사업장으로 검증되었습니다." if verified else "동일 업소 검증 전입니다.", "사업장 검증을 완료하세요."), + ] + + aeo = [ + _check("entity", "엔티티", "사업장 엔티티 식별", 20, verified and bool(place.get("road_address") or place.get("address")), + "상호와 검증된 주소로 사업장을 명확히 식별합니다." if verified else "사업장 정체성 신호가 부족합니다.", + "사업장을 검증하고 공식 주소를 채우세요."), + _check("geo", "엔티티", "좌표와 지역 문맥", 10, place.get("latitude") is not None and place.get("longitude") is not None, + "좌표를 구조화 데이터에 제공할 수 있습니다." if place.get("latitude") is not None else "좌표가 없습니다.", + "검증된 위도·경도를 등록하세요."), + _check("answers", "답변 가능성", "확인된 사실", 20, fact_count >= 8, + f"AI가 답변에 사용할 확인된 사실이 {fact_count}건입니다.", "고객이 자주 묻는 영업·이용 정보를 보강하세요.", + partial=min(15, fact_count * 2)), + _check("faq", "답변 가능성", "질문형 FAQ", 20, len(faqs) >= 3, + f"발행 가능한 FAQ가 {len(faqs)}건입니다.", "실제 고객 질문과 짧고 단정적인 답변을 3건 이상 승인하세요.", + partial=min(12, len(faqs) * 4)), + _check("llms", "기계 가독성", "JSON-LD·llms.txt", 15, built, + "구조화 데이터와 llms.txt가 생성되었습니다." if built else "빌드 전이라 기계용 요약이 없습니다.", + "사이트를 빌드해 JSON-LD와 llms.txt를 생성하세요."), + _check("sources", "신뢰성", "출처와 검증 시각", 10, fact_count > 0 and sourced == fact_count, + f"확인된 정보 {fact_count}건 중 {sourced}건에 출처 또는 검증 시각이 있습니다.", + "출처가 없는 정보는 사장님 확인을 거쳐 검증 시각을 남기세요.", partial=5 if sourced else 0), + _check("freshness", "신뢰성", "최신 발행본", 5, built, + "최근 빌드 시각을 검색엔진에 제공합니다." if built else "발행 시각 신호가 없습니다.", "변경 내용을 다시 빌드하세요."), + ] + + ai_checks = ai_checks or [] + cited = sum(1 for row in ai_checks if getattr(row, "is_own_site_cited", False)) + return { + "seo_score": sum(c.earned for c in seo), + "aeo_score": sum(c.earned for c in aeo), + "overall_score": round((sum(c.earned for c in seo) + sum(c.earned for c in aeo)) / 2), + "checks": [c.as_dict() for c in (*seo, *aeo)], + "summary": { + "facts": fact_count, "faqs": len(faqs), "images_with_alt": image_with_alt, + "built": built, "domain": domain or None, + }, + "visibility": {"checks": len(ai_checks), "own_site_cited": cited}, + "disclaimer": "준비도 점수이며 검색 순위나 AI 인용을 보장하지 않습니다.", + } diff --git a/backend/services/site_payload.py b/backend/services/site_payload.py new file mode 100644 index 0000000..7773eb0 --- /dev/null +++ b/backend/services/site_payload.py @@ -0,0 +1,773 @@ +"""발행 payload — 정적 렌더러(frontend/site)가 먹는 유일한 입력 JSON. + +★ 왜 필요한가 + 빌드 잡은 지금까지 HTML 을 굽고 그 **길이만** 재고 버렸다(발행 기록은 남는데 페이지가 없었다). + 실제로 방문자에게 보여줄 페이지는 frontend/site 의 SSG 가 굽는다. 그 렌더러의 유일한 입력이 + 이 payload 이므로, 빌드 잡이 이 JSON 만 파일로 떨어뜨리면 발행이 실제 페이지로 이어진다. + +★ 스키마는 frontend/shared/src/types/site-payload.ts 의 `SitePayload` 다. + 필드명이 camelCase 인 이유는 그쪽이 원본이기 때문이다 — 여기서 스네이크로 바꾸면 렌더러가 못 읽는다. + 스키마가 바뀌면 schemaVersion 을 올린다(렌더러는 모르는 버전을 조용히 반쪽 렌더하지 않고 실패한다). + +★ DB 를 여기서 다시 읽지 않는다. + 입력은 이미 박제된 스냅샷(site_versions.snapshot)과 그 빌드가 만든 행들뿐이다. + 스냅샷이 정적 빌드의 경계다 — 여기서 DB 를 한 번 더 읽으면 '스냅샷과 다른 페이지'가 나올 수 있다. + (channel 링크만 스냅샷에 없어서 호출측이 읽어 넘긴다.) +""" +import json +import os +import unicodedata +from datetime import datetime, timezone +from pathlib import Path + +from common.category_schema import get_schema +from common.enums import ( + FactStatus, + LinkChannel, + LocalContentType, + PlaceCategory, + SiteStatus, + SourceType, +) +from common.logger import LOG + +# 렌더러가 확인하는 스키마 버전. 모양이 바뀌면 여기와 site-payload.ts 를 같이 올린다. +SCHEMA_VERSION = 1 + +# 출력 디렉토리. 컨테이너 밖(볼륨·오브젝트 스토리지)으로 빼기 쉬우라고 env 로 둔다. +PAYLOAD_DIR_ENV = "SITE_PAYLOAD_DIR" +DEFAULT_PAYLOAD_DIR = "/app/out/payloads" + +# 커스텀 도메인이 없을 때 쓰는 기본 호스트. sites.domain 이 채워지면 그 값이 이긴다. +# +# ★ env 로 뺀 이유: 이 값이 canonical·og:url·사이트맵·IndexNow 통보에 **전부** 들어간다. +# 상수로 박아 두면 스테이징에 올릴 때마다 코드를 고쳐야 하고, 안 고치면 발행은 성공하는데 +# 검색엔진에는 열리지도 않는 주소가 등록된다(조용히 틀린다 — 아무도 눈치채지 못한다). +# 프론트도 같은 이유로 VITE_PUBLISH_HOST 를 쓴다. 두 값은 **같아야 한다**. +SITE_HOST_ENV = "SITE_PUBLIC_HOST" +DEFAULT_HOST = os.environ.get(SITE_HOST_ENV, "").strip() or "w4ai.o2o.kr" + +# 링크 제목이 비었을 때 채우는 채널 이름. 없는 채널명을 지어내지 않기 위한 고정 표다. +_CHANNEL_TITLE = { + LinkChannel.YANOLJA.value: "야놀자", + LinkChannel.GOODCHOICE.value: "여기어때", + LinkChannel.NAVER_PLACE.value: "네이버 플레이스", + LinkChannel.INSTAGRAM.value: "인스타그램", + LinkChannel.OFFICIAL_SITE.value: "공식 홈페이지", + LinkChannel.BLOG.value: "블로그", + LinkChannel.ETC.value: "기타 채널", +} + +# 업종별 **기본 디자인**. 사장님이 아직 아무것도 고르지 않았을 때 쓰는 폴백이다. +# ★ 이제 여섯 가지가 모두 저장되는 자리를 갖는다: +# templateId ← sites.template_id (POST /v1/place/{id}/site/template) +# 색·서체·섹션 on/off·순서·배리에이션 ← sites.theme (POST /v1/place/{id}/site/theme) +# 저장된 값이 있으면 **그게 이긴다**. 이 표는 저장값이 없을 때만 쓰인다 — +# 고르지 않은 값을 고른 것처럼 굽지 않는다. +# ★ 이 표의 섹션 목록은 에디터의 업종별 기본 목록 +# (admin `src/data/industryData.ts` 의 `sections`)과 **id·순서·이름·잠금이 1:1로 같아야 한다.** +# 여기가 에디터보다 적으면, 사장님이 에디터에서 본 섹션이 발행본에서 통째로 사라진다 — +# 저장값이 없는 사업장은 이 표가 곧 발행본이기 때문이다(실측: 날씨·실시간 예약·대관 문의). +# 에디터에 섹션을 늘릴 때는 이 표도 같이 늘린다. 어긋나면 tests/test_site_theme.py 가 잡는다. +# ★ 이 표가 여전히 필요한 이유: 위저드를 끝까지 돌지 않은 사업장, 그리고 sections 의 +# locked 판정 근거다(아래 _theme 주석 참조). 표의 세 번째 값이 locked 다. +_DEFAULT_THEME = { + PlaceCategory.LODGING.value: { + "templateId": "stay-o2o-editorial", + "fontStyle": "Modern Editorial", + "colors": {"primary": "#18181b", "secondary": "#52525b", "bg": "#ffffff", + "card": "#fafafa", "text": "#09090b", "accent": "#2563eb"}, + "sections": [ + ("hero", "히어로", True), ("intro", "소개", False), ("rooms", "객실 안내", False), + ("info", "기본 정보", True), ("rules", "이용 규정", False), ("booking", "실시간 예약", False), + ("photos", "사진 갤러리", False), ("map", "오시는 길", True), ("weather", "날씨", False), + ("local", "지역 정보", False), ("faq", "자주 묻는 질문", False), + ], + }, + PlaceCategory.CAFE.value: { + "templateId": "cafe-modern-espresso", + "fontStyle": "Sleek Roast", + "colors": {"primary": "#1c1917", "secondary": "#78716c", "bg": "#ffffff", + "card": "#fafaf9", "text": "#0c0a09", "accent": "#b45309"}, + "sections": [ + ("hero", "히어로", True), ("intro", "소개", False), ("menu", "시그니처 메뉴", False), + ("info", "기본 정보", True), ("space", "공간 · 좌석 안내", False), ("photos", "사진 갤러리", False), + ("inquiry", "대관 및 단체 문의", False), ("map", "오시는 길", True), ("weather", "날씨", False), + ("local", "주변 나들이", False), ("faq", "자주 묻는 질문", False), + ], + }, + PlaceCategory.RESTAURANT.value: { + "templateId": "rest-neat-table", + "fontStyle": "Sophisticated Table", + "colors": {"primary": "#1c1917", "secondary": "#57534e", "bg": "#ffffff", + "card": "#fafaf9", "text": "#0c0a09", "accent": "#b45309"}, + "sections": [ + ("hero", "히어로", True), ("intro", "소개", False), ("menu", "코스 및 메뉴", False), + ("info", "기본 정보", True), ("booking", "예약 · 포장 안내", False), ("photos", "사진 갤러리", False), + ("inquiry", "단체 행사 문의", False), ("map", "오시는 길", True), ("weather", "날씨", False), + ("local", "주변 안내", False), ("faq", "자주 묻는 질문", False), + ], + }, + PlaceCategory.TOUR_ACTIVITY.value: { + "templateId": "tour-visual-tour", + "fontStyle": "Visual Journey", + "colors": {"primary": "#0f172a", "secondary": "#475569", "bg": "#ffffff", + "card": "#f8fafc", "text": "#020617", "accent": "#0284c7"}, + "sections": [ + ("hero", "히어로", True), ("intro", "소개", False), ("programs", "체험 프로그램", False), + ("info", "기본 정보", True), ("exhibition", "관람 및 갤러리 안내", False), ("photos", "사진 갤러리", False), + ("inquiry", "단체 및 출강 문의", False), ("map", "오시는 길", True), ("weather", "날씨", False), + ("local", "주변 관광 코스", False), ("faq", "자주 묻는 질문", False), + ], + }, +} + + +# ── 값 변환 헬퍼 ────────────────────────────────────────────────────────── +def _get(row, key, default=None): + """ORM 행이든 dict 든 같은 방식으로 읽는다(테스트가 가짜 행을 넣기 쉬우라고).""" + if isinstance(row, dict): + return row.get(key, default) + return getattr(row, key, default) + + +def _text(value) -> str: + return str(value).strip() if value is not None else "" + + +def _iso(value) -> str | None: + """ISO8601 문자열. ★ 화면·JSON-LD 의 dateModified 로 나가는 값이라 시간대를 명시한다. + + DB 의 timestamptz 는 여기서 naive UTC 로 올라오므로(GTime 규약) UTC 를 붙인다. + naive 로 내보내면 렌더러·검색엔진이 로컬시각으로 오해한다.""" + if value is None: + return None + if isinstance(value, str): + return value + if isinstance(value, datetime): + if value.tzinfo is None: + value = value.replace(tzinfo=timezone.utc) + return value.isoformat() + return str(value) + + +def slugify(text: str) -> str: + """frontend/shared 의 toSlug 와 같은 규칙(로마자 음차하지 않는다). + + ★ 한글을 음차하면 같은 가게가 두 주소를 갖는다. 한글은 그대로 두고 퍼센트 인코딩에 맡긴다. + NFC 로 정규화하는 이유: macOS 가 준 NFD 문자열이 그대로 디렉토리명이 되면 + 같은 이름이 서로 다른 경로로 갈린다.""" + normalized = unicodedata.normalize("NFC", str(text or "")).strip().lower() + out = [] + for ch in normalized: + if ch.isalnum() or ch == "-": + out.append(ch) + elif ch.isspace() or ch == "_": + out.append("-") + # 나머지(쉼표·괄호·따옴표…)는 버린다. + slug = "".join(out) + while "--" in slug: + slug = slug.replace("--", "-") + return slug.strip("-") + + +# ── 주소 구성요소 ────────────────────────────────────────────── +# 시·도 이름 → ISO 3166-2:KR 코드. `geo.region` 메타에 쓰인다(네이버·다음이 읽는 자리). +# 약칭과 정식명을 둘 다 적는다 — 외부 장소 API 가 둘을 섞어 준다("경기" / "경기도"). +_SIDO_ISO = { + "서울": "KR-11", "서울특별시": "KR-11", + "부산": "KR-26", "부산광역시": "KR-26", + "대구": "KR-27", "대구광역시": "KR-27", + "인천": "KR-28", "인천광역시": "KR-28", + "광주": "KR-29", "광주광역시": "KR-29", + "대전": "KR-30", "대전광역시": "KR-30", + "울산": "KR-31", "울산광역시": "KR-31", + "세종": "KR-50", "세종시": "KR-50", "세종특별자치시": "KR-50", + "경기": "KR-41", "경기도": "KR-41", + "강원": "KR-42", "강원도": "KR-42", "강원특별자치도": "KR-42", + "충북": "KR-43", "충청북도": "KR-43", + "충남": "KR-44", "충청남도": "KR-44", + "전북": "KR-45", "전라북도": "KR-45", "전북특별자치도": "KR-45", + "전남": "KR-46", "전라남도": "KR-46", + "경북": "KR-47", "경상북도": "KR-47", + "경남": "KR-48", "경상남도": "KR-48", + "제주": "KR-49", "제주도": "KR-49", "제주특별자치도": "KR-49", +} + + +def _parse_address_parts(*addresses: str | None) -> dict: + """주소 문자열에서 시·도 / 시·군·구 / 읍·면 을 뽑는다. + + ★ **원문에 있는 조각을 그대로만 쓴다.** "경기" 를 "경기도" 로 펴지 않는다. + addressRegion·addressLocality 는 JSON-LD 로 나가고, JSON-LD 는 화면 텍스트와 + 대조된다(frontend/site/src/seo/verify.ts). 화면에는 원문 주소가 그대로 찍히므로 + 정식명으로 펴는 순간 '화면에 없는 값'이 되어 발행 게이트가 막는다. + 정규화가 필요한 곳은 ISO 코드 하나뿐이고, 그건 화면 대조 대상이 아니다. + + ★ 첫 토큰이 아는 시·도가 아니면 **아무것도 돌려주지 않는다** — 추측해서 채우지 않는다. + + 도로명 주소를 먼저 보고, 못 읽으면 지번 주소로 넘어간다. + """ + for raw in addresses: + tokens = str(raw or "").split() + if len(tokens) < 2 or tokens[0] not in _SIDO_ISO: + continue + + region = tokens[0] + rest = tokens[1:] + + # 시·군 → (있으면) 그 아래 구. 광역시·특별시는 구가 바로 온다. + locality: list[str] = [] + i = 0 + while i < len(rest): + token = rest[i] + if not locality and token.endswith(("시", "군")): + locality.append(token) + elif token.endswith("구") and (not locality or locality[-1].endswith("시")): + locality.append(token) + else: + break + i += 1 + + # 읍·면 — "애월 스테이" 처럼 실제 검색어가 되는 자리라 따로 들고 있는다. + sub = rest[i] if i < len(rest) and rest[i].endswith(("읍", "면")) else None + + return { + "addressRegion": region, + "addressLocality": " ".join(locality) or None, + "addressSubLocality": sub, + "addressRegionCode": _SIDO_ISO[region], + } + + return {} + + +def _fact_entry(spec, row: dict) -> dict: + """스냅샷 fact 1건 → FactEntry. + + label/type/unit/critical/required 는 업종 스키마가 유일한 소스다 — + 스냅샷에 라벨이 박제돼 있어도 스키마가 있으면 스키마를 따른다(라벨 오탈자 수정이 재빌드로 반영된다).""" + key = row.get("key") + return { + "key": key, + "label": (spec.label if spec else row.get("label") or key), + "value": row.get("value"), + "unit": row.get("unit") or (spec.unit if spec else None), + "type": (spec.type if spec else "text"), + "scope": row.get("scope") or (spec.scope if spec else "place"), + # ★ status 를 그대로 싣는다. 렌더러가 selectPublishable() 로 한 번 더 거른다(2중 방어). + "status": row.get("status") or FactStatus.VERIFIED.value, + # facts.source_type 은 NOT NULL 이라 여기 기본값은 옛 스냅샷용 안전망이다. + "sourceType": row.get("source_type") or SourceType.OWNER.value, + "sourceUrl": row.get("source_url"), + "critical": bool(spec.critical) if spec else False, + "required": bool(spec.required) if spec else False, + "unitId": row.get("unit_id"), + "collectedAt": row.get("collected_at"), + "verifiedAt": row.get("verified_at"), + } + + +def _theme(site, theme_spec: dict) -> dict: + """SiteTheme — 저장된 디자인이 이기고, 없는 것만 업종 기본으로 떨어진다. + + ★ 저장값 우선이 이 함수의 존재 이유다. 예전에는 이 자리가 업종 기본 표를 그대로 굽고 + enabled 를 True 로 박아 넣었다 — 사장님이 섹션을 끄고 순서를 바꿔도 발행본은 언제나 + 업종 기본 모양이었다. 저장할 자리(sites.theme)가 생겼으니 여기서 읽는다. + + ★ 서버는 값을 해석하지 않는다. 섹션 id 도 배리에이션 키도 색 토큰도 프론트가 소유하므로 + 모르는 값이 와도 그대로 싣는다 — 렌더러가 모르는 키를 만나면 자기 기본으로 떨어진다. + + ★ 딱 하나 서버가 우기는 것이 locked 다. 아래 _sections 주석 참조.""" + saved = _get(site, "theme") + if not isinstance(saved, dict): + saved = {} + + # 색: 저장값이 이기되 **업종 기본 위에 덮는다**. + # ★ 렌더러 타입(SiteTheme.colors)은 6개 키를 모두 요구한다. 저장값이 일부만 담고 있을 때 + # 그것만 실으면 나머지 색이 undefined 로 나가 화면이 깨진다 — 빠진 자리는 업종 기본이 메운다. + colors = dict(theme_spec["colors"]) + for key, value in (saved.get("colors") or {}).items(): + if isinstance(value, str) and value.strip(): + colors[key] = value.strip() + + font_style = _text(saved.get("fontStyle")) or theme_spec["fontStyle"] + + # ★ colorPaletteId 는 여기 싣지 않는다. 에디터 복원 전용 값이고 발행 계약(SiteTheme)에 없다 — + # 계약에 없는 필드를 payload 에 흘리면 렌더러가 모르는 것이 발행본에 섞인다. + return { + # 저장된 템플릿이 있으면 그것으로 굽는다(sites.template_id). 비어 있으면 업종 기본이다. + # 여기서 안 읽으면 사장님이 고른 디자인과 실제 발행본이 갈린다(그게 이 컬럼이 생긴 이유다). + "templateId": _text(_get(site, "template_id")) or theme_spec["templateId"], + "colors": colors, + "fontStyle": font_style, + "sections": _sections(saved.get("sections"), theme_spec["sections"]), + } + + +def _sections(saved_sections, default_spec) -> list: + """섹션 목록 — 저장된 **배열 순서**가 곧 발행본의 섹션 순서다. + + ★ locked 는 서버가 우긴다. 잠긴 섹션(히어로·기본 정보·오시는 길)은 SEO·필수 마크업 때문에 + 잠긴 것이라, 저장값이 껐다고 해도 켜서 내보낸다. 그리고 잠금 판정은 **업종 기본 표**가 하고 + 저장값의 locked 는 잠그는 방향으로만 더한다 — 저장값의 locked:false 를 그대로 믿으면 + 클라이언트가 locked 를 내려 보내는 것만으로 필수 섹션을 끌 수 있어 잠금 자체가 무의미해진다. + + ★ 저장값에 없는 기본 섹션은 **켜서** 목록 끝에 덧붙인다. + + 한때 잠기지 않은 섹션은 꺼서 붙였다 — "사장님이 목록에서 뺐다 = 안 쓰겠다는 뜻"이라고 봤다. + 그 전제가 틀렸다. 에디터에는 섹션을 **빼는 기능이 없다**(toggleSection·reorderSection 뿐, + admin/src/stores/builder.ts). 그러니 저장값에 없다는 건 "뺐다"가 아니라 + **저장할 당시 그 섹션이 아직 없었다**는 뜻이다 — 우리가 나중에 추가한 섹션이다. + + 꺼서 붙이면 새 섹션은 기존 사업장에 영원히 나오지 않는다. 에디터에는 보이는데 + 발행본에는 없는 상태가 되고(실측: 날씨 섹션), 사장님은 켠 적도 끈 적도 없는 것이 + 안 나온다고 본다. 저장값이 아예 없을 때 전부 켜서 내보내는 것과 같은 규칙으로 맞춘다. + + ★ 통째로 버리지는 않는다 — 렌더러가 섹션 이름을 알아야 에디터에서 껐을 때 같은 이름으로 + 붙고, 무엇이 꺼져 있는지도 payload 만 보고 알 수 있다. + + ★ 저장값에만 있고 업종 기본에 없는 섹션(프론트가 새로 추가한 것)은 그대로 싣는다. + 섹션 목록은 프론트가 소유한다 — 서버가 모른다고 버리면 새 섹션이 발행되지 않는다.""" + defaults = {sid: (label, locked) for sid, label, locked in default_spec} + + # 저장값이 없으면(아직 아무것도 고르지 않았다) 업종 기본을 전부 켜서 내보낸다. + if not isinstance(saved_sections, list) or not saved_sections: + return [ + {"id": sid, "name": label, "enabled": True, "locked": locked} + for sid, label, locked in default_spec + ] + + out = [] + used = set() + for item in saved_sections: + if not isinstance(item, dict): + continue + sid = _text(item.get("id")) + if not sid or sid in used: + continue + used.add(sid) + default_label, default_locked = defaults.get(sid, ("", False)) + # 서버가 아는 잠금(업종 기본)이 항상 이긴다. 저장값은 잠그는 방향으로만 보탠다. + locked = bool(default_locked) or bool(item.get("locked")) + entry = { + "id": sid, + # 사장님이 붙인 제목이 있으면 그게 발행본의 소제목이다. 없으면 업종 기본 이름, 그것도 없으면 id. + "name": _text(item.get("name")) or default_label or sid, + # ★ 잠긴 섹션은 꺼진 채로 나갈 수 없다. + "enabled": bool(item.get("enabled", True)) or locked, + "locked": locked, + } + # ★ 고른 배리에이션이 있을 때만 키를 붙인다. 서버는 이 값을 해석하지 않는다 — + # 비어 있으면 렌더러가 그 섹션의 기본 레이아웃으로 떨어진다(null 을 실으면 타입이 안 맞는다). + variant_id = _text(item.get("variantId")) + if variant_id: + entry["variantId"] = variant_id + out.append(entry) + + for sid, label, locked in default_spec: + if sid in used: + continue + # ★ 켜서 붙인다. 저장값에 없는 건 사장님이 뺀 게 아니라 저장 당시 없던 섹션이다(위 주석). + out.append({"id": sid, "name": label, "enabled": True, "locked": bool(locked)}) + return out + + +# WMO weather code → 한 줄 날씨. ★ frontend/site/src/lib/use-live-weather.ts 의 condition() 과 +# **같은 구간**이어야 한다. 렌더러는 프리렌더된 이 값으로 그리다가 하이드레이션 뒤 최신 캐시로 덮어쓰는데, +# 두 곳이 다른 표를 쓰면 같은 날씨인데 화면 문구가 바뀐다(사장님 눈에는 버그로 보인다). +def _weather_condition(code) -> str: + try: + value = int(code) + except (TypeError, ValueError): + return "흐림" + if value == 0: + return "맑음" + if 1 <= value <= 3: + return "구름많음" + if 50 <= value <= 69: + return "비" + if 70 <= value <= 79: + return "눈" + return "흐림" + + +def _weather(row: dict): + """WeatherSnapshot. 값이 없으면 None — 없는 날씨를 지어내지 않는다.""" + body = row.get("body") or {} + temperature = _as_float(body.get("temperature")) + observed_at = _text(body.get("observed_at")) + if temperature is None or not observed_at: + return None + return { + "temperature": temperature, + "condition": _weather_condition(body.get("weather_code")), + # note 는 LLM 이 쓰는 안내 문구다. 지금 그걸 만드는 경로가 없으므로 넣지 않는다(지어내지 않는다). + "observedAt": observed_at, + } + + +def _yyyymmdd(value) -> str: + digits = "".join(ch for ch in _text(value) if ch.isdigit()) + return digits if len(digits) == 8 else "" + + +def _festival(row: dict): + """FestivalEntry. 이름이 없으면 버린다 — 이름 없는 행사는 화면에 걸 수 없다.""" + body = row.get("body") or {} + name = _text(row.get("title")) or _text(body.get("title")) + if not name: + return None + + start, end = _yyyymmdd(body.get("eventstartdate")), _yyyymmdd(body.get("eventenddate")) + # month 는 화면의 배지다(예: "10월"). 시작일이 없으면 만들지 않는다. + month = f"{int(start[4:6])}월" if start else "" + if start and end and start != end: + period = f"{start[:4]}.{start[4:6]}.{start[6:]} ~ {end[:4]}.{end[4:6]}.{end[6:]}" + elif start: + period = f"{start[:4]}.{start[4:6]}.{start[6:]}" + else: + period = "" + + homepage = _text(body.get("homepage")) + entry = { + "name": name, + "month": month, + # ★ searchQuery 만 있고 우리가 URL 을 지어내지 않는다 — 틀린 링크는 방문자를 엉뚱한 데로 보내고 + # 그 책임을 이 홈페이지가 진다(렌더러 LocalGuideSection 주석과 같은 규칙). + "searchQuery": name, + } + if period: + entry["period"] = period + location = _text(body.get("addr1")) + if location: + entry["location"] = location + description = _text(body.get("overview")) + if description: + entry["description"] = description + # 공식 홈페이지는 출처가 준 값일 때만 싣는다. 형식이 URL 이 아니면 링크로 걸지 않는다. + if homepage.startswith("http://") or homepage.startswith("https://"): + entry["officialUrl"] = homepage + return entry + + +def _local_place(row: dict, category: str): + """LocalPlace(주변 명소·맛집). + + ★ title 컬럼만 믿는다. 이 두 종류(ATTRACTION·RESTAURANT)를 채우는 수집기가 아직 없어서 + body 의 모양이 정해지지 않았다 — 있지도 않은 키를 가정해 파싱하면 수집기가 붙는 날 + 조용히 빈 값이 나간다. 지금은 테이블 스키마가 보장하는 것(title)만 쓰고, + 설명·거리는 실제 수집기가 붙을 때 그 모양을 보고 채운다.""" + name = _text(row.get("title")) + if not name: + return None + return {"name": name, "category": category, "searchQuery": name} + + +def _local(snapshot_local: dict) -> tuple[dict, str | None]: + """스냅샷의 지역 정보 → LocalContents. + + ★ 스냅샷이 이미 걸렀다(PUBLISHED + 노출 기간 안). 여기서 더 거르지 않고 모양만 바꾼다 — + fact·사진과 같은 분업이다. + ★ 예전에는 이 자리가 무조건 빈 배열이었다. local_contents 에 검수·발행된 지역 정보가 있어도 + payload 경계에서 통째로 버려져, 모든 발행 사이트의 지역 정보 섹션이 영구히 안 나왔다.""" + contents = (snapshot_local or {}).get("contents") or [] + local = {"attractions": [], "restaurants": [], "festivals": []} + synced_at = None + + for row in contents: + if not isinstance(row, dict): + continue + collected_at = _text(row.get("collected_at")) + # syncedAt 은 화면에 "○○ 갱신"으로 그대로 노출된다 — 가장 최근 수집 시각을 쓴다. + # ★ 오래된 정보를 숨기지 않는다(렌더러 타입 주석). 그래서 최신값이 아니라 '실제 최신 수집 시각'이다. + if collected_at and (synced_at is None or collected_at > synced_at): + synced_at = collected_at + + content_type = row.get("content_type") + if content_type == LocalContentType.WEATHER.value: + weather = _weather(row) + # 지역당 1행이지만 방어적으로 첫 유효값만 쓴다. + if weather and "weather" not in local: + local["weather"] = weather + elif content_type == LocalContentType.FESTIVAL.value: + entry = _festival(row) + if entry: + local["festivals"].append(entry) + elif content_type == LocalContentType.ATTRACTION.value: + entry = _local_place(row, "관광지") + if entry: + local["attractions"].append(entry) + elif content_type == LocalContentType.RESTAURANT.value: + entry = _local_place(row, "맛집") + if entry: + local["restaurants"].append(entry) + # 그 밖의 content_type 은 버린다 — 렌더러 타입에 담을 자리가 없다. + + return local, synced_at + + +def _publish_target(site, place_id: str, name: str) -> dict: + """발행 주소(origin/basePath/slug). + + ★ sites.domain 이 있으면 그게 사장님이 고른 주소다. 없으면 **임시값**이다 — + 상호명은 유일하지 않으므로 place_id 앞자리를 붙여 사이트끼리 겹치지 않게 한다. + + ★ **언제나 경로형**(`https:///s/`)이다. 서브도메인을 쓰지 않는 이유는 + 사이트가 하나 늘 때마다 DNS 레코드와 TLS 인증서를 새로 만들어야 해서다 — + 발행 시점에 그걸 대신 만들어 줄 방법이 없으니 서브도메인 주소는 화면에만 있고 + 실제로는 열리지 않는다. shared/lib/slug.ts 의 publishUrl 과 **같은 규칙**이어야 + 화면이 보여준 주소와 발행본의 주소가 갈리지 않는다.""" + domain = _text(_get(site, "domain")) + + if domain: + # domain 컬럼에는 slug 만 들어온다(site_slug 가 검증한 값). 옛 데이터가 호스트 형태로 + # 남아 있을 수 있어 첫 라벨만 취한다. + slug = slugify(domain.split(".")[0]) or slugify(name) or place_id + else: + name_slug = slugify(name) + slug = f"{name_slug}-{place_id[:8]}" if name_slug else f"place-{place_id[:8]}" + + return {"origin": f"https://{DEFAULT_HOST}", "basePath": f"/s/{slug}", "slug": slug} + + +def publish_slug(place, site) -> str: + """이 사업장 사이트의 발행 슬러그. + + ★ 렌더 보고서(payloads/.status/.json)를 찾으려면 payload 를 만들 때와 **같은 규칙**으로 + 슬러그를 구해야 한다. 그래서 여기 한 곳에서만 계산하고 밖에서는 이 함수를 부른다 — + 규칙을 두 군데 두면 보고서를 못 찾아 "아직 안 구워졌다"고 잘못 답하게 된다.""" + return _publish_target(site, str(_get(place, "place_id") or ""), _text(_get(place, "name")))["slug"] + + +# ── payload 조립 ────────────────────────────────────────────────────────── +def to_site_payload(place, snapshot: dict, site, version, links) -> dict: + """스냅샷 + 사이트/버전 행 + 채널 링크 → SitePayload(dict). + + 순수 변환 함수다. DB 도 파일도 건드리지 않는다 — 그래야 테스트가 쉽고, + 같은 입력이면 언제나 같은 payload 가 나온다.""" + snapshot = snapshot or {} + snap_place = snapshot.get("place") or {} + place_id = str(_get(place, "place_id")) + category = int(snap_place.get("category") or _get(place, "category")) + schema = get_schema(category) + name = _text(snap_place.get("name") or _get(place, "name")) + + target = _publish_target(site, place_id, name) + + # ── fact ───────────────────────────────────────────── + all_facts = [_fact_entry(schema.get(r.get("key")), r) for r in (snapshot.get("facts") or [])] + place_facts = [f for f in all_facts if not f["unitId"]] + unit_facts: dict[str, list] = {} + for entry in all_facts: + if entry["unitId"]: + unit_facts.setdefault(str(entry["unitId"]), []).append(entry) + + # ── 사진 ───────────────────────────────────────────── + # ★ 스냅샷이 이미 걸렀다(APPROVED + alt 있음). 여기서 더 거르지 않고 모양만 바꾼다. + # ★ sourceType/originUrl 을 반드시 싣는다 — 크롤링 이미지 재게시 권리가 미결이라(DECISIONS 1-2) + # 결론이 나면 출처로 걸러낼 수 있어야 한다. 출처를 버리면 그때 다시 수집해야 한다. + media = [] + primary_done = False + for index, row in enumerate(snapshot.get("media") or []): + unit_id = row.get("unit_id") + # 대표 이미지(og:image)는 객실 전용 사진이 아닌 첫 장으로 한다. + is_primary = not unit_id and not primary_done + primary_done = primary_done or is_primary + media.append({ + "mediaId": str(row.get("media_id") or f"m-{index}"), + "url": row.get("url"), + "alt": _text(row.get("alt_text")), + "category": row.get("label"), + "width": row.get("width"), + "height": row.get("height"), + "isPrimary": is_primary, + # 출처가 없는 건 옛 스냅샷뿐이다(media.source_type 은 NOT NULL). 그때는 CRAWL 로 본다 — + # 재게시 권리가 결론 나면 걸러져야 할 쪽으로 기울이는 게 안전하다. + "sourceType": row.get("source_type") or SourceType.CRAWL.value, + "originUrl": row.get("origin_url"), + "unitId": unit_id, + }) + media_by_unit: dict[str, list] = {} + for item in media: + if item["unitId"]: + media_by_unit.setdefault(str(item["unitId"]), []).append(item["mediaId"]) + + # ── 하위 단위(객실·메뉴·프로그램) ───────────────────── + units = [] + for index, row in enumerate(snapshot.get("units") or []): + unit_id = str(row.get("unit_id")) + unit_name = _text(row.get("name")) + units.append({ + "unitId": unit_id, + "name": unit_name, + # slug 가 URL 이 된다. 이름이 비거나 기호뿐이면 순번으로 떨어뜨린다(빈 경로를 만들지 않는다). + "slug": slugify(unit_name) or f"unit-{index + 1}", + "sortOrder": int(row.get("sort_order") or index), + "facts": unit_facts.get(unit_id, []), + "mediaIds": media_by_unit.get(unit_id, []), + }) + + # ── FAQ ────────────────────────────────────────────── + faqs = [] + for index, row in enumerate(snapshot.get("faqs") or []): + faqs.append({ + "faqId": str(row.get("faq_id") or f"faq-{index + 1}"), + "question": _text(row.get("question")), + "answer": _text(row.get("answer")), + "status": row.get("status") or FactStatus.VERIFIED.value, + "sourceType": row.get("generated_by") or SourceType.LLM.value, + "sortOrder": int(row.get("sort_order") or index), + }) + + # ── 채널 링크 ──────────────────────────────────────── + # 확정(confirmed_at)되지 않은 링크도 실어 보낸다 — 렌더러가 confirmed 로 한 번 더 거른다. + # 여기서 미리 빼면 "왜 안 나오는지"가 payload 만 봐서는 안 보인다. + channel_links = [] + for row in links or []: + channel = _get(row, "channel") + url = _text(_get(row, "url")) + if not url or channel is None: + continue + channel_links.append({ + "channel": int(channel), + "url": url, + "title": _text(_get(row, "title")) or _CHANNEL_TITLE.get(int(channel), "채널"), + "confirmed": _get(row, "confirmed_at") is not None, + }) + + # ── 소개문 ─────────────────────────────────────────── + # ★ 여기서 문장을 지어내지 않는다. intro fact(allow_llm=true 필드)에 있는 것만 옮긴다. + # heroHeadline·tagline 은 저장되는 자리가 없어서 비운다 — 비면 렌더러가 상호명으로 대체한다. + intro = _text(next((f["value"] for f in place_facts if f["key"] == "intro" and f["value"]), "")) + paragraphs = [p.strip() for p in intro.split("\n") if p.strip()] if intro else [] + narrative = { + "about": paragraphs, + # 요약은 첫 문단을 그대로 쓴다(요약문을 새로 생성하지 않는다). + "summary": paragraphs[0] if paragraphs else None, + } + + theme_spec = _DEFAULT_THEME.get(category) or _DEFAULT_THEME[PlaceCategory.LODGING.value] + theme = _theme(site, theme_spec) + + # ── 지역 정보 ──────────────────────────────────────── + # ★ 스냅샷에서 읽는다 — 여기서 DB 를 다시 읽으면 '스냅샷과 다른 페이지'가 나온다(파일 상단 원칙). + # 지역 정보를 스냅샷에 담는 필터링은 services/snapshot._local_contents 가 한다. + # 옛 스냅샷에는 "local" 키가 없다. 그때는 빈 채로 나가고, 다음 빌드에서 채워진다. + local, local_synced_at = _local(snapshot.get("local") or {}) + if local_synced_at: + local["syncedAt"] = local_synced_at + + published_at = _iso(_get(site, "published_at")) + updated_at = ( + _iso(_get(version, "built_at")) + or _iso(_get(place, "content_updated_at")) + or published_at + or _iso(datetime.now(timezone.utc)) + ) + + external_source = _get(place, "external_source") + kakao_place_id = _text(_get(place, "external_place_id")) if external_source == 1 else "" + + return { + "schemaVersion": SCHEMA_VERSION, + "site": { + "siteId": str(_get(site, "site_id") or ""), + "placeId": place_id, + "status": int(_get(site, "status") or SiteStatus.DRAFT.value), + "origin": target["origin"], + "basePath": target["basePath"], + "slug": target["slug"], + "publishedAt": published_at or updated_at, + "updatedAt": updated_at, + "version": int(_get(version, "version") or 1), + }, + "place": { + "name": name, + "category": category, + "roadAddress": snap_place.get("road_address") or None, + "address": snap_place.get("address") or None, + # 시·도 / 시·군·구 / 읍·면. PostalAddress 의 지역 필드와 title·geo 메타가 이걸 쓴다 — + # 없으면 지역 질의("성남 소금빵")에 걸릴 자리를 통째로 버리게 된다. + **_parse_address_parts(snap_place.get("road_address"), snap_place.get("address")), + "phone": snap_place.get("phone") or None, + # 스냅샷은 좌표를 문자열로 박제한다(Numeric 직렬화). 렌더러 타입은 number 라 여기서 되돌린다. + "latitude": _as_float(snap_place.get("latitude")), + "longitude": _as_float(snap_place.get("longitude")), + # ★ 스냅샷이 실제로 쓴 지역 키가 이긴다. places.region_code 가 비어 있어도 + # 스냅샷이 주소에서 유도했으면(services/snapshot._local_contents) 그 값이 여기 실려야 + # 렌더러의 실시간 날씨 조회가 산다 — use-live-weather 는 regionCode 없이는 fetch 하지 않고, + # 그러면 날씨 섹션이 통째로 사라진다(에디터에는 보이는데 사이트에는 없는 그 자리). + "regionCode": ( + _text((snapshot.get("local") or {}).get("region_code")) + or _text(_get(place, "region_code")) + or None + ), + "kakaoPlaceId": kakao_place_id or None, + }, + "facts": place_facts, + "units": units, + "media": media, + "faqs": faqs, + "links": channel_links, + "local": local, + # ★ 가는 길(routes)은 비어 있다. local.routes 테이블에 행이 0이고, 그 테이블에 쓰는 코드 경로가 + # 아직 어디에도 없다(모델과 DDL 만 있고 수집기·입력 API 가 없다). 여기서 조회 배선을 만들어 봐야 + # 영원히 빈 결과를 도는 코드가 되고, 실제 수집기가 붙는 날 그 모양에 맞을지도 알 수 없다. + # ★ 없는 것을 지어내지 않는다 — 틀린 경로 안내는 방문자에게 헛걸음을 만든다(모델 주석). + # 렌더러는 비면 해당 섹션을 그리지 않는다. + "routes": [], + "narrative": narrative, + "theme": theme, + } + + +def _as_float(value): + try: + return float(value) if value not in (None, "") else None + except (TypeError, ValueError): + return None + + +# ── 파일 출력 ───────────────────────────────────────────────────────────── +def payload_dir() -> Path: + """payload 출력 디렉토리. 컨테이너 밖 볼륨을 붙이기 쉬우라고 env 로 뺀다.""" + return Path(os.environ.get(PAYLOAD_DIR_ENV) or DEFAULT_PAYLOAD_DIR) + + +def write_payload(payload: dict) -> str: + """payload 를 `.json` 으로 쓴다. 경로를 돌려준다. + + ★ 임시파일에 쓰고 rename 한다 — 렌더러가 디렉토리를 통째로 읽는 구조라 + 반쯤 쓰인 JSON 을 집어 빌드가 깨지는 일이 없어야 한다(rename 은 같은 파일시스템에서 원자적).""" + directory = payload_dir() + directory.mkdir(parents=True, exist_ok=True) + + site = payload.get("site") or {} + # slug 는 slugify 를 거쳐 경로 구분자가 남을 수 없지만, 파일명은 마지막 한 겹을 더 막는다. + stem = os.path.basename(_text(site.get("slug")) or _text(site.get("placeId")) or "site") + path = directory / f"{stem}.json" + tmp = directory / f".{stem}.json.tmp" + tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") + tmp.replace(path) + return str(path) + + +def emit_payload(place, snapshot: dict, site, version, links) -> str | None: + """payload 조립 + 파일 쓰기. 실패해도 예외를 밖으로 내보내지 않는다. + + ★ 발행 자체를 실패시키면 안 된다 — 게이트를 통과해 DB 에 남은 발행 기록은 이미 정확하고, + payload 는 그것을 화면으로 옮기는 부수 산출물이다. 디스크가 없거나 권한이 없어서 + 발행이 되돌려지는 게 더 나쁘다. 대신 경고 로그로 반드시 드러낸다.""" + try: + payload = to_site_payload(place, snapshot, site, version, links) + path = write_payload(payload) + LOG.i( + f"[payload] {payload['site']['slug']} → {path} " + f"(fact {len(payload['facts'])} · 단위 {len(payload['units'])} · " + f"사진 {len(payload['media'])} · FAQ {len(payload['faqs'])} · 링크 {len(payload['links'])})" + ) + return path + except Exception as ex: # noqa: BLE001 — 어떤 이유로도 발행을 되돌리지 않는다 + LOG.w(f"[payload] 생성 실패(발행은 그대로 진행): {type(ex).__name__}: {ex}") + return None diff --git a/backend/services/site_service.py b/backend/services/site_service.py new file mode 100644 index 0000000..5b1e89e --- /dev/null +++ b/backend/services/site_service.py @@ -0,0 +1,593 @@ +import json +import uuid + +from fastapi import Depends + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import ai_check_results, places, publish_logs, site_versions, sites +from common.enums import ( + BuildStatus, + DBWRType, + ErrorType, + JobStatus, + JobType, + PublishAction, + PublishResult, + SiteStatus, +) +from common.logger import LOG +from common.models.gmodel import UserInfo +from common.utils.gtime import GTime +from crud.job_crud import JobQueue +from crud.place_crud import PlaceCRUD +from crud.site_crud import ISiteCRUD, SiteCRUD +from router.v1.site.protocol import ( + PublishLogData, + RenderStatusData, + Req_SiteSlug, + Req_SiteStatus, + Req_SiteTemplate, + Req_SiteTheme, + Req_StartBuild, + Res_PublishLogs, + Res_Site, + Res_SeoAudit, + Res_SiteSlug, + Res_SiteVersions, + Res_SlugCheck, + Res_StartBuild, + SiteData, + SiteVersionData, +) +from services import render_report, site_payload, site_slug +from services.job_service import enqueue_job + +# 주소 저장을 거부할 때 쓰는 결과 코드. 사유(reason)는 응답에 따로 실어 프론트가 문구를 고르게 한다. +_ERROR_BY_SLUG_REASON = { + site_slug.REASON_LENGTH: ErrorType.INVALID_REQUEST_DATA, + site_slug.REASON_FORMAT: ErrorType.INVALID_REQUEST_DATA, + site_slug.REASON_RESERVED: ErrorType.INVALID_REQUEST_DATA, + site_slug.REASON_TAKEN: ErrorType.DB_ALREADY_SAME_KEY, + site_slug.REASON_LOCKED: ErrorType.SITE_SLUG_LOCKED, +} + +# 템플릿 키 길이 상한. sites.template_id 가 varchar(100) 이라 여기서 막지 않으면 DB 가 트랜잭션째로 튕긴다. +# ★ 값 자체(무슨 템플릿인가)는 검증하지 않는다 — 목록은 프론트가 소유한다(protocol.Req_SiteTemplate 주석). +_TEMPLATE_ID_MAX = 100 + +# 테마 JSON 직렬화 크기 상한(64KB). +# ★ 왜 상한만 두는가: 테마의 내용(섹션 id·배리에이션 키·색 토큰)은 프론트가 소유하므로 서버가 +# 해석하지 않는다. 해석하지 않는다는 건 무엇이든 들어올 수 있다는 뜻이라, 크기까지 놓으면 +# jsonb 컬럼 하나가 DB 를 부풀리고 그대로 site_versions.snapshot 을 타고 빌드까지 번진다. +# ★ 왜 64KB 인가: 섹션은 업종당 10개 남짓이고 한 섹션이 200바이트를 넘기 어렵다 — 실제 테마는 3KB 안쪽이다. +# 64KB 면 정상 값의 20배쯤 되는 여유라 프론트가 항목을 늘려도 걸리지 않고, +# 그걸 넘는 건 '디자인 설정'이 아니라 다른 것이 흘러든 것이다. +# ★ 필드 개수가 아니라 직렬화 바이트로 잰다. 개수로 재면 값 하나가 긴 경우를 못 막는다. +_THEME_MAX_BYTES = 64 * 1024 + +# ★ theme 안에 들어와도 저장하지 않는 키. sites.template_id 컬럼이 소유하는 값이라 +# theme 에 같이 담기면 어느 쪽이 진짜인지 갈리고, payload 가 읽는 쪽과 화면이 보는 쪽이 어긋난다. +# 화이트리스트가 아니라 '이 한 개만 뺀다'는 블랙리스트다 — 나머지는 전부 그대로 보관한다. +_THEME_OWNED_ELSEWHERE = ("templateId", "template_id") + +# '거부' 표식. None 은 '빈 값 → NULL 로 되돌린다'는 정상 결과라서, 거부를 None 으로 표현하면 +# 잘못된 요청이 조용히 '디자인 초기화'로 처리된다 — 둘을 반드시 구분한다. +_THEME_REJECTED = object() + +# 상태 전이만으로 처리하는 액션 — ★ 물리 삭제 경로는 만들지 않는다. +_STATUS_BY_ACTION = { + PublishAction.SUSPEND: SiteStatus.SUSPENDED, + PublishAction.RESUME: SiteStatus.PUBLISHED, + PublishAction.UNPUBLISH: SiteStatus.UNPUBLISHED, +} + + +class SiteService: + """사이트 조회 · 빌드 트리거 · 발행 상태 전이. + + 빌드와 발행 판정은 BUILD 잡(services/build_service)이 한다 — 여기는 조회와 상태 전이만. + """ + + def __init__( + self, + crud: ISiteCRUD = Depends(SiteCRUD), + place_crud: PlaceCRUD = Depends(PlaceCRUD), + queue: JobQueue = Depends(JobQueue), + ): + self.crud = crud + self.place_crud = place_crud + self.queue = queue + + async def _load_place(self, user_info: UserInfo, place_id: str): + err_type, place = await DB_SESSION_MNG.execute_lambda( + places.DBType(), + DBWRType.DB_READ.value, + lambda s: self.place_crud.get_place(s, uuid.UUID(user_info.company_id), uuid.UUID(place_id)), + ) + if err_type != ErrorType.SUCCESS: + return ErrorType.PLACE_NOT_FOUND, None + return ErrorType.SUCCESS, place + + async def _get_site(self, place_id: str): + """사업장의 사이트 행. 없으면 None.""" + pid = uuid.UUID(place_id) + err_type, site = await DB_SESSION_MNG.execute_lambda( + sites.DBType(), DBWRType.DB_READ.value, lambda s: self.crud.get_site_by_place(s, pid) + ) + return site if err_type == ErrorType.SUCCESS else None + + async def get_seo_audit(self, user_info: UserInfo, place_id: str) -> Res_SeoAudit: + """현재 저장값 기준 SEO/AEO 준비도. 조회할 때마다 계산해 오래된 점수를 보여주지 않는다.""" + from sqlalchemy import select + from services.seo_audit import evaluate + from services.snapshot import build_snapshot + + res = Res_SeoAudit() + 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) + version = None + if site is not None and site.current_version_id: + v_err, version = await DB_SESSION_MNG.execute_lambda( + site_versions.DBType(), DBWRType.DB_READ.value, + lambda s: self.crud.get_version(s, site.site_id, site.current_version_id), + ) + if v_err != ErrorType.SUCCESS: + version = None + + _ai_err, ai_rows = await DB_SESSION_MNG.execute_lambda( + ai_check_results.DBType(), DBWRType.DB_READ.value, + lambda s: DB_SESSION_MNG.execute( + s, select(ai_check_results).where( + ai_check_results.place_id == uuid.UUID(place_id), + ai_check_results.deleted == False, # noqa: E712 + ).order_by(ai_check_results.checked_at.desc()).limit(20), + raise_error=False, + ), + ) + report = evaluate( + await build_snapshot(place), verified=place.verified_at is not None, + site=site, version=version, ai_checks=list(ai_rows or []), + ) + return Res_SeoAudit(**report) + + # ---- 사이트 주소(네임스페이스) --------------------------------------- + # 규칙(정규식·예약어)은 services/site_slug 한 곳에만 있다. 확인과 저장이 그것을 같이 쓴다. + + async def _domain_owner(self, slug: str): + """이 주소를 이미 쓰는 사업장 id. 아무도 안 쓰면 None.""" + err_type, site = await DB_SESSION_MNG.execute_lambda( + sites.DBType(), DBWRType.DB_READ.value, lambda s: self.crud.get_site_by_domain(s, slug) + ) + if err_type != ErrorType.SUCCESS or site is None: + return None + return str(site.place_id) + + async def _suggest(self, slug: str): + """`-2`, `-3` … 중 실제로 비어 있는 것 하나. 없으면 None.""" + candidates = site_slug.suggestions(slug) + if not candidates: + return None + err_type, taken = await DB_SESSION_MNG.execute_lambda( + sites.DBType(), DBWRType.DB_READ.value, lambda s: self.crud.taken_domains(s, candidates) + ) + if err_type != ErrorType.SUCCESS: + return None + return next((c for c in candidates if c not in taken), None) + + async def _judge_slug(self, place_id: str, slug: str): + """(불가 사유, 대안)을 돌려준다. 쓸 수 있으면 (None, None). + + ★ 확인(check)과 저장(POST)이 이 하나를 같이 쓴다 — 판정이 갈리면 + "된다고 해놓고 저장에서 튕기는" 화면이 나온다.""" + reason = site_slug.validate_slug(slug) + if reason in (site_slug.REASON_LENGTH, site_slug.REASON_FORMAT): + # 형식이 깨진 값에 -2 를 붙여 봐야 여전히 못 쓴다. 사유만 돌려준다. + return reason, None + + value = (slug or "").strip() + if reason is None: + owner = await self._domain_owner(value) + # ★ 이미 자기 주소면 쓸 수 있다 — 저장해 둔 화면을 다시 열었을 때 '중복'이라고 하면 안 된다. + if owner is None or owner == str(uuid.UUID(place_id)): + return None, None + reason = site_slug.REASON_TAKEN + return reason, await self._suggest(value) + + async def check_slug(self, user_info: UserInfo, place_id: str, slug: str) -> Res_SlugCheck: + """주소를 쓸 수 있는지 미리 본다. + + ★ 서버가 상호명으로 자동 확정하지 않는다 — 사람이 고르고, 겹치면 고르기 전에 알려 준다.""" + 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 + + reason, suggestion = await self._judge_slug(place_id, slug) + res.available = reason is None + res.reason = reason + res.suggestion = suggestion + return res + + async def set_slug(self, user_info: UserInfo, place_id: str, req: Req_SiteSlug) -> Res_SiteSlug: + """주소를 확정해 sites.domain 에 저장한다. 사이트 행이 없으면 만든다.""" + # 사이트 생성은 빌드와 같은 경로를 쓴다(사업장당 1개 보장) — 지역 import 로 빌드 스택을 웹에 얹지 않는다. + from services.build_service import BuildAborted, ensure_site + + res = Res_SiteSlug() + err_type, _place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + value = (req.slug or "").strip() + site = await self._get_site(place_id) + + # ★ 이미 발행된 사이트의 주소는 바꾸지 않는다. + # 색인된 주소가 바뀌면 AI 검색이 잡아 둔 페이지가 404 가 되고, 그 자리를 다시 OTA 가 채운다 — + # '해지는 상태 전이지 삭제가 아니다' 와 정확히 같은 이유다. + # 한 번이라도 발행된 적 있으면(published_at) 중지·내림 상태여도 같다. 색인은 그 주소로 남아 있다. + if site is not None and (site.published_at is not None or site.status == SiteStatus.PUBLISHED.value): + if (site.domain or "") != value: + res.result.SetResult(ErrorType.SITE_SLUG_LOCKED) + res.reason = site_slug.REASON_LOCKED + return res + # 같은 값을 다시 보낸 건 변경이 아니다 — 재전송을 에러로 만들지 않는다. + res.site = SiteData.model_validate(site) + return res + + # ★ 클라이언트 검증을 믿지 않는다. check 와 같은 규칙으로 서버가 다시 본다. + reason, suggestion = await self._judge_slug(place_id, value) + if reason is not None: + res.result.SetResult(_ERROR_BY_SLUG_REASON.get(reason, ErrorType.INVALID_REQUEST_DATA)) + res.reason = reason + res.suggestion = suggestion + return res + + if site is None: + # 빌드 전에도 주소를 먼저 잡아둘 수 있어야 한다 — 주소를 고르는 건 발행보다 앞선 결정이다. + try: + site = await ensure_site(place_id) + except BuildAborted as ex: + LOG.e_no_callstack(ex) + res.result.SetResult(ErrorType.DB_RUN_FAILED) + return res + + u_err, _rowcount = await DB_SESSION_MNG.execute_lambda_claim( + sites.DBType(), lambda s: self.crud.update_site(s, site.site_id, {"domain": value}) + ) + if u_err != ErrorType.SUCCESS: + # uq_sites_domain 이 막았다면 확인과 저장 사이에 남이 먼저 가져간 것이다 — 대안까지 같이 준다. + res.result.SetResult(u_err) + if u_err == ErrorType.DB_ALREADY_SAME_KEY: + res.reason = site_slug.REASON_TAKEN + res.suggestion = await self._suggest(value) + return res + + saved = await self._get_site(place_id) + res.site = SiteData.model_validate(saved if saved is not None else site) + return res + + # ---- 템플릿(디자인) --------------------------------------------------- + + async def _mark_content_updated(self, place_id: str, ts): + """★ 발행본과 달라졌다 — 이 사업장만 다시 빌드하면 된다는 표시. + fact/faq 가 노출값이 바뀔 때 찍는 것과 같은 자리를 같은 이유로 쓴다(services/faq_service). + 부가 효과라 실패해도 본 흐름을 막지 않는다(다음 변경 때 다시 찍힌다).""" + err = await DB_SESSION_MNG.execute_lambda_run([places.DBType()], [lambda s: self._touch(s, place_id, ts)]) + if err != ErrorType.SUCCESS: + LOG.e_no_callstack(f"[site] content_updated_at 갱신 실패 place={place_id}") + + async def _touch(self, s, place_id: str, ts): + from sqlalchemy import update + + query = update(places).where(places.place_id == uuid.UUID(place_id)).values(content_updated_at=ts, updated_at=ts) + return await DB_SESSION_MNG.add(s, query) + + async def set_template(self, user_info: UserInfo, place_id: str, req: Req_SiteTemplate) -> Res_Site: + """사장님이 고른 템플릿을 sites.template_id 에 저장한다. 사이트 행이 없으면 만든다. + + ★ 왜 서버에 저장하나: 위저드가 고른 값이 브라우저에만 남으면 발행 잡이 읽을 곳이 없어 + 업종 기본 템플릿으로 굽는다 — 고른 디자인과 실제 발행본이 갈린다. + ★ 슬러그와 달리 발행 뒤에도 바꿀 수 있다. 주소는 AI 검색이 색인한 영구 식별자라 잠그지만, + 디자인은 바뀌어도 URL 이 그대로다(색인이 깨지지 않는다).""" + # 사이트 생성은 빌드와 같은 경로를 쓴다(사업장당 1개 보장) — 지역 import 로 빌드 스택을 웹에 얹지 않는다. + from services.build_service import BuildAborted, ensure_site + + res = Res_Site() + err_type, _place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + value = (req.template_id or "").strip() + # 길이만 본다. 모르는 키가 들어와도 발행 잡이 업종 기본으로 떨어뜨리므로 화면이 깨지지 않는다. + if len(value) > _TEMPLATE_ID_MAX: + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + return res + + site = await self._get_site(place_id) + if site is None: + # 빌드 전에도 템플릿을 먼저 잡아둘 수 있어야 한다 — 고르는 건 발행보다 앞선 결정이다. + try: + site = await ensure_site(place_id) + except BuildAborted as ex: + LOG.e_no_callstack(ex) + res.result.SetResult(ErrorType.DB_RUN_FAILED) + return res + + before = site.template_id or None + # ★ 빈 문자열은 '고르지 않음'이다 — NULL 로 되돌려 업종 기본 템플릿으로 떨어뜨린다. + # 빈 문자열을 그대로 두면 payload 가 '있는데 이름이 없는 템플릿'을 만나 기본값으로도 못 간다. + after = value or None + u_err, _rowcount = await DB_SESSION_MNG.execute_lambda_claim( + sites.DBType(), lambda s: self.crud.update_site(s, site.site_id, {"template_id": after}) + ) + if u_err != ErrorType.SUCCESS: + res.result.SetResult(u_err) + return res + + # 한 번이라도 구워진 사이트에서 디자인이 바뀌었다면 지금 나가 있는 페이지와 달라졌다 — + # 재빌드 대상으로 표시한다. 값이 그대로면 찍지 않는다(재전송이 재빌드를 만들지 않게). + if before != after and (site.published_at is not None or site.current_version_id is not None): + await self._mark_content_updated(place_id, GTime.UTC()) + + return await self.get_site(user_info, place_id) + + # ---- 테마(색·서체·섹션) ----------------------------------------------- + + async def set_theme(self, user_info: UserInfo, place_id: str, req: Req_SiteTheme) -> Res_Site: + """에디터가 정한 디자인을 sites.theme 에 저장한다. 사이트 행이 없으면 만든다. + + ★ 왜 서버에 저장하나: template_id 와 정확히 같은 이유다. 섹션 on/off·순서·배리에이션·색·서체가 + 브라우저 메모리에만 있으면 새로고침에 사라지고, 발행 잡은 읽을 곳이 없어 업종 기본 모양을 굽는다 — + 사장님이 섹션을 끄고 순서를 바꿔도 발행본은 언제나 업종 기본으로 나갔다. + + ★ 값은 해석하지 않는다. 섹션 목록·배리에이션 키·색 토큰 이름은 프론트가 소유하므로 + 검증하면 프론트에 항목이 하나 늘 때마다 백엔드를 같이 고쳐야 한다(protocol.Req_SiteTheme). + 막는 것은 크기 하나뿐이다. + + ★ 템플릿과 마찬가지로 발행 뒤에도 바꿀 수 있다 — 디자인이 바뀌어도 URL 은 그대로라 색인이 안 깨진다.""" + # 사이트 생성은 빌드와 같은 경로를 쓴다(사업장당 1개 보장) — 지역 import 로 빌드 스택을 웹에 얹지 않는다. + from services.build_service import BuildAborted, ensure_site + + res = Res_Site() + err_type, _place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + after = self._clean_theme(req.theme) + if after is _THEME_REJECTED: + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + return res + + site = await self._get_site(place_id) + if site is None: + # 빌드 전에도 디자인을 먼저 잡아둘 수 있어야 한다 — 고르는 건 발행보다 앞선 결정이다. + try: + site = await ensure_site(place_id) + except BuildAborted as ex: + LOG.e_no_callstack(ex) + res.result.SetResult(ErrorType.DB_RUN_FAILED) + return res + + before = site.theme or None + u_err, _rowcount = await DB_SESSION_MNG.execute_lambda_claim( + sites.DBType(), lambda s: self.crud.update_site(s, site.site_id, {"theme": after}) + ) + if u_err != ErrorType.SUCCESS: + res.result.SetResult(u_err) + return res + + # 한 번이라도 구워진 사이트에서 디자인이 바뀌었다면 지금 나가 있는 페이지와 달라졌다 — + # 재빌드 대상으로 표시한다. 값이 그대로면 찍지 않는다(재전송이 재빌드를 만들지 않게). + if before != after and (site.published_at is not None or site.current_version_id is not None): + await self._mark_content_updated(place_id, GTime.UTC()) + + return await self.get_site(user_info, place_id) + + @staticmethod + def _clean_theme(theme): + """저장할 theme 값을 만든다. 거부해야 하면 _THEME_REJECTED 를 돌려준다. + + ★ 하는 일이 셋뿐인 게 의도다 — 서버는 이 값을 해석하지 않는다. + 1) 빈 값이면 NULL 로 되돌린다. 빈 dict 를 그대로 두면 payload 가 '있는데 아무것도 없는 테마'를 + 만나 업종 기본으로도 못 간다(template_id 의 빈 문자열과 같은 함정이다). + 2) templateId 는 뺀다 — sites.template_id 컬럼이 소유하는 값이다(중복 보관 금지). + 3) 직렬화 크기 상한을 넘으면 거부한다. + 그 외의 키(colorPaletteId 처럼 에디터 복원 전용인 것 포함)는 전부 그대로 보관한다.""" + if not isinstance(theme, dict) or not theme: + return None + + cleaned = {k: v for k, v in theme.items() if k not in _THEME_OWNED_ELSEWHERE} + if not cleaned: + return None + + try: + size = len(json.dumps(cleaned, ensure_ascii=False).encode("utf-8")) + except (TypeError, ValueError): + # jsonb 컬럼에 넣을 수 없는 값이 섞였다는 뜻이다. DB 가 트랜잭션째로 튕기기 전에 여기서 막는다. + return _THEME_REJECTED + if size > _THEME_MAX_BYTES: + return _THEME_REJECTED + return cleaned + + async def get_site(self, user_info: UserInfo, place_id: str) -> Res_Site: + res = Res_Site() + err_type, place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + pid = uuid.UUID(place_id) + s_err, site = await DB_SESSION_MNG.execute_lambda( + sites.DBType(), DBWRType.DB_READ.value, lambda s: self.crud.get_site_by_place(s, pid) + ) + if s_err != ErrorType.SUCCESS or site is None: + res.result.SetResult(ErrorType.SITE_NOT_FOUND) + return res + res.site = SiteData.model_validate(site) + + if site.current_version_id: + v_err, version = await DB_SESSION_MNG.execute_lambda( + site_versions.DBType(), + DBWRType.DB_READ.value, + lambda s: self.crud.get_version(s, site.site_id, site.current_version_id), + ) + if v_err == ErrorType.SUCCESS and version is not None: + res.current_version = SiteVersionData.model_validate(version) + # ★ 개별 재빌드 판별: 노출값이 바뀐 시각이 마지막 빌드보다 나중이면 다시 빌드해야 한다. + built = version.built_at + changed = place.content_updated_at + res.needs_rebuild = bool(changed and (built is None or changed > built)) + res.render = self._render_status(place, site, version) + else: + res.needs_rebuild = bool(place.content_updated_at) + res.render = self._render_status(place, site, None) + return res + + @staticmethod + def _render_status(place, site, version) -> RenderStatusData: + """정적 페이지가 실제로 구워졌는지 + 두 렌더러가 어긋나지 않았는지. + + ★ 빌드(DB)와 렌더(정적 파일)는 다른 단계다. 빌드가 BUILT 라고 페이지가 있는 게 아니다. + 프리렌더가 남긴 보고서를 읽어 그 간극을 드러낸다. + ★ 버전이 맞는 보고서만 OK 로 본다 — 낡은 렌더를 현재 것처럼 답하면 안 된다.""" + # ★ payload 를 쓸 때와 같은 규칙으로 슬러그를 구한다(site_payload 가 소유). + slug = site_payload.publish_slug(place, site) + if not slug: + return RenderStatusData() + + status = render_report.render_status(slug, getattr(version, "version", None)) + return RenderStatusData( + state=status["state"], + rendered_at=status["rendered_at"], + rendered_version=status["rendered_version"], + error=status["error"], + ) + + async def start_build(self, user_info: UserInfo, place_id: str, req: Req_StartBuild) -> Res_StartBuild: + """빌드를 큐에 넣는다. 빌드는 몇 십 초 걸린다 — 동기로 처리하지 않는다.""" + res = Res_StartBuild() + err_type, place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + # 검증 안 된 사업장은 빌드하지 않는다 — 주소·좌표가 없으면 JSON-LD 가 성립하지 않는다. + if place.verified_at is None: + res.result.SetResult(ErrorType.PLACE_NOT_VERIFIED) + return res + + job_id, created = await enqueue_job( + self.queue, JobType.BUILD, + { + "place_id": place_id, "company_id": user_info.company_id, + "publish": req.publish, "requested_by": user_info.user_id, + }, + dedupe_key=f"build:{place_id}", + ) + if job_id is None: + res.result.SetResult(ErrorType.COLLECT_ALREADY_RUNNING) + return res + res.job_id = uuid.UUID(job_id) + res.status = JobStatus.PENDING + res.created = created + return res + + async def list_versions(self, user_info: UserInfo, place_id: str) -> Res_SiteVersions: + from sqlalchemy import select + + res = Res_SiteVersions() + err_type, _place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + pid = uuid.UUID(place_id) + s_err, site = await DB_SESSION_MNG.execute_lambda( + sites.DBType(), DBWRType.DB_READ.value, lambda s: self.crud.get_site_by_place(s, pid) + ) + if s_err != ErrorType.SUCCESS or site is None: + res.result.SetResult(ErrorType.SITE_NOT_FOUND) + return res + + query = ( + select(site_versions) + .where(site_versions.site_id == site.site_id, site_versions.deleted == False) # noqa: E712 + .order_by(site_versions.version.desc()) + .limit(50) + ) + v_err, rows = await DB_SESSION_MNG.execute_lambda( + site_versions.DBType(), + DBWRType.DB_READ.value, + lambda s: DB_SESSION_MNG.execute(s, query), + ) + if v_err == ErrorType.SUCCESS: + res.versions = [SiteVersionData.model_validate(r) for r in rows] + return res + + async def list_logs(self, user_info: UserInfo, place_id: str) -> Res_PublishLogs: + res = Res_PublishLogs() + err_type, _place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + pid = uuid.UUID(place_id) + s_err, site = await DB_SESSION_MNG.execute_lambda( + sites.DBType(), DBWRType.DB_READ.value, lambda s: self.crud.get_site_by_place(s, pid) + ) + if s_err != ErrorType.SUCCESS or site is None: + res.result.SetResult(ErrorType.SITE_NOT_FOUND) + return res + l_err, rows = await DB_SESSION_MNG.execute_lambda( + publish_logs.DBType(), DBWRType.DB_READ.value, lambda s: self.crud.list_logs(s, site.site_id, 50) + ) + if l_err == ErrorType.SUCCESS: + res.logs = [PublishLogData.model_validate(r) for r in rows] + return res + + async def change_status(self, user_info: UserInfo, place_id: str, req: Req_SiteStatus) -> Res_Site: + """발행 상태를 전이한다(중지·재개·내림). + + ★ 해지는 물리 삭제가 아니다. 색인된 페이지를 갑자기 404 로 만들면 + AI 검색이 그 자리를 다시 OTA 로 채운다 — 이 서비스가 하려던 것의 정반대가 된다.""" + res = Res_Site() + err_type, _place = await self._load_place(user_info, place_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + target = _STATUS_BY_ACTION.get(req.action) + if target is None: + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + return res + + pid = uuid.UUID(place_id) + s_err, site = await DB_SESSION_MNG.execute_lambda( + sites.DBType(), DBWRType.DB_READ.value, lambda s: self.crud.get_site_by_place(s, pid) + ) + if s_err != ErrorType.SUCCESS or site is None: + res.result.SetResult(ErrorType.SITE_NOT_FOUND) + return res + # 한 번도 발행한 적 없는 사이트는 재개할 것이 없다. + if req.action == PublishAction.RESUME and site.current_version_id is None: + res.result.SetResult(ErrorType.SITE_VERSION_NOT_FOUND) + return res + + now = GTime.UTC() + await DB_SESSION_MNG.execute_lambda_claim( + sites.DBType(), lambda s: self.crud.update_site(s, site.site_id, {"status": target.value}) + ) + log = publish_logs( + site_id=site.site_id, + site_version_id=site.current_version_id, + action=req.action.value, + result=PublishResult.SUCCESS.value, + actor_user_id=uuid.UUID(user_info.user_id), + ) + await DB_SESSION_MNG.execute_lambda_run([publish_logs.DBType()], [lambda s: self.crud.add_log(s, log)]) + return await self.get_site(user_info, place_id) diff --git a/backend/services/site_slug.py b/backend/services/site_slug.py new file mode 100644 index 0000000..08c0424 --- /dev/null +++ b/backend/services/site_slug.py @@ -0,0 +1,86 @@ +"""사이트 주소(네임스페이스) 규칙 — 확인(check)과 저장(POST)이 함께 쓰는 단 하나의 정의. + +★ 주소는 한 번 정하면 AI 검색이 색인하는 영구 식별자다. 그래서 + - 규칙은 이 파일 한 곳에만 둔다. 확인과 저장이 서로 다른 규칙을 쓰면 + "쓸 수 있다고 해놓고 저장에서 튕기는" 최악의 화면이 나온다. + - 클라이언트 검증은 믿지 않는다. 저장 직전에 서버가 이 규칙으로 다시 본다. + +★ ASCII 소문자·숫자·하이픈만 받는다. + 한글 상호를 그대로 주소로 쓰면 경로는 퍼센트 인코딩(/s/%EC%8A%A4%ED%85%8C%EC%9D%B4), + 서브도메인은 퓨니코드(xn--…)가 된다 — 사장님이 전화로 불러줄 수도, 명함에 적을 수도 없는 주소다. + (프론트 `shared/src/lib/slug.ts` 의 publishUrl 이 ASCII 슬러그면 서브도메인으로 낸다.) +""" +import re +from typing import Optional + +# 3~50자. 처음과 끝은 영문 소문자·숫자여야 하고, 하이픈은 가운데에만 올 수 있다. +# (1 + 1~48 + 1 = 3~50자) +SLUG_PATTERN = re.compile(r"^[a-z0-9](?:[a-z0-9-]{1,48}[a-z0-9])$") +SLUG_MIN_LEN = 3 +SLUG_MAX_LEN = 50 + +# 불가 사유 코드. 응답의 reason 으로 그대로 나가고, 프론트가 문구를 고른다. +REASON_LENGTH = "INVALID_LENGTH" # 3~50자를 벗어남 +REASON_FORMAT = "INVALID_FORMAT" # 한글·대문자·언더스코어·연속 하이픈·양끝 하이픈 +REASON_RESERVED = "RESERVED" # 서비스가 선점한 이름 +REASON_TAKEN = "TAKEN" # 다른 사업장이 이미 쓰는 주소 +REASON_LOCKED = "LOCKED" # ★ 이미 발행됨 — 색인된 주소는 바꾸지 않는다 + +# 예약어. 두 부류가 섞여 있다. +# 1) 서비스가 실제로 쓰는 경로·서브도메인(/s, /healthz, api. …) — 내주면 사이트가 서로를 가린다. +# 2) 관용적으로 시스템을 뜻하는 이름(admin, root, www …) — 사장님 사이트가 이 주소를 갖고 있으면 +# 방문자도 크롤러도 공식 홈페이지로 읽지 않는다. +RESERVED_SLUGS = frozenset({ + # 서비스 경로 / 인프라 서브도메인 + "s", "site", "sites", "api", "app", "admin", "www", "www2", "static", "assets", "cdn", "media", + "img", "images", "css", "js", "files", "download", "downloads", "public", "dev", "stage", "staging", + "test", "demo", "local", "localhost", "mail", "smtp", "imap", "pop", "ftp", "ns", "ns1", "ns2", "mx", + "webmail", "vpn", "proxy", "gateway", "internal", "console", "dashboard", "manage", "management", + # 서버가 실제로 서비스하는 엔드포인트 + "health", "healthz", "healthcheck", "status", "metrics", "robots", "sitemap", "llms", "favicon", + "manifest", "feed", "rss", "opensearch", "well-known", "v1", "v2", "graphql", "openapi", "docs", "swagger", + # 계정 / 정책 페이지 + "login", "logout", "signin", "signup", "register", "join", "auth", "oauth", "account", "accounts", + "user", "users", "me", "my", "owner", "root", "system", "support", "help", "contact", "about", + "terms", "privacy", "policy", "legal", "security", "billing", "payment", "pay", "order", "orders", + # 도메인 리소스 이름 — 관리 API 경로와 같아 헷갈린다 + "place", "places", "fact", "facts", "faq", "faqs", "job", "jobs", "report", "reports", "unit", "units", + "search", "index", "home", "main", "new", "edit", "delete", "create", "update", + # 값이 비었을 때 프론트가 문자열로 흘려보내는 것들 — 주소로 들어오면 버그의 흔적이다 + "null", "undefined", "none", "nan", "true", "false", +}) + + +def validate_slug(slug: Optional[str]) -> Optional[str]: + """형식·예약어만 본다(중복은 DB 를 봐야 하므로 서비스가 판단한다). + + 쓸 수 있으면 None, 아니면 REASON_* 를 돌려준다.""" + value = (slug or "").strip() + if len(value) < SLUG_MIN_LEN or len(value) > SLUG_MAX_LEN: + return REASON_LENGTH + # 하이픈 연속은 정규식으로 막지 않는다(가운데 문자 집합이라 통과한다) — 여기서 따로 거른다. + # a--b 는 퓨니코드 접두(xn--)와 모양이 겹쳐서 서브도메인으로 냈을 때 오해를 산다. + if "--" in value: + return REASON_FORMAT + if not SLUG_PATTERN.fullmatch(value): + return REASON_FORMAT + if value in RESERVED_SLUGS: + return REASON_RESERVED + return None + + +def suggestions(slug: Optional[str], count: int = 9) -> list[str]: + """`-2`, `-3` … 을 붙인 대안 후보. 실제로 쓸 수 있는지(중복)는 서비스가 DB 로 거른다. + + ★ 음차하거나 상호를 마음대로 줄이지 않는다 — 서버가 고른 주소는 사장님이 기억하지 못한다. + 사장님이 적어낸 이름을 그대로 두고 뒤에 숫자만 붙인다.""" + value = (slug or "").strip() + result: list[str] = [] + for n in range(2, 2 + max(count, 0)): + suffix = f"-{n}" + # 50자 상한을 넘기지 않도록 앞을 자른다. 자른 끝이 하이픈이면 `a--2` 가 되므로 떼어낸다. + base = value[: SLUG_MAX_LEN - len(suffix)].rstrip("-") + candidate = f"{base}{suffix}" + if validate_slug(candidate) is None: + result.append(candidate) + return result diff --git a/backend/services/snapshot.py b/backend/services/snapshot.py new file mode 100644 index 0000000..baa02bd --- /dev/null +++ b/backend/services/snapshot.py @@ -0,0 +1,257 @@ +"""빌드 스냅샷 조립 — DB 에서 '사이트에 나갈 것만' 골라 빌더 입력을 만든다. + +★ 정적 빌드의 경계다. DB 는 **빌드 시점에만** 읽고, 방문자는 DB 와 만나지 않는다. + 여기서 만든 스냅샷이 site_versions.snapshot 에 박제되고, 그 뒤로는 그것만 렌더된다. + +★ 필터링이 여기 한 곳에만 있다: + fact — VERIFIED / CORRECTED 만 + 사진 — APPROVED 만 (Vision 신뢰도 미달은 PENDING_REVIEW 로 남아 여기서 빠진다) + FAQ — VERIFIED / CORRECTED 만 + 지역 — PUBLISHED 만 + 노출 기간 안에 있는 것만 (운영자가 검수해 발행한 것만 나간다) + 게이트(publish_gate)가 뒤에서 한 번 더 보지만, 애초에 미검증 값이 스냅샷에 들어오면 안 된다. + +★ 지역 정보가 왜 여기서 읽히나(services/site_payload 가 아니라). + site_payload 는 "DB 를 다시 읽지 않는다 — 입력은 박제된 스냅샷뿐"이 원칙이다. 거기서 지역 캐시를 + 읽으면 발행 시점과 렌더 시점 사이에 지역 정보가 바뀌었을 때 '스냅샷과 다른 페이지'가 나온다. + 그래서 지역 정보도 다른 재료와 똑같이 여기서 걸러 스냅샷에 박제하고, site_payload 는 모양만 바꾼다. +""" +import uuid +from datetime import datetime, timezone + +from sqlalchemy import or_, select + +from common.category_schema import get_schema +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import facts, faqs, local_contents, media, units +from common.enums import ( + PUBLISHABLE_FACT_STATUSES, + DBWRType, + ErrorType, + FactStatus, + LocalContentStatus, + MediaStatus, + PlaceCategory, +) +from common.logger import LOG +from services.external.naver import region_key + +_PUBLISHABLE = tuple(s.value for s in PUBLISHABLE_FACT_STATUSES) + +# 지역 정보를 종류별로 몇 건까지 박제할지. +# ★ 스냅샷은 site_versions.snapshot 에 통째로 들어간다. 지역 캐시는 region_code 단위 공용이라 +# 한 지역에 수백 건이 쌓일 수 있고, 그걸 다 박제하면 버전 행마다 그만큼이 복사된다. +# 화면(LocalGuideSection)도 그만큼 보여주지 않는다 — 최근 수집분 위주로 자른다. +_LOCAL_MAX_PER_TYPE = 20 + +# 지역 원문(body)에서 스냅샷으로 옮기지 않는 키. +# ★ TourAPI 원본을 통째로 담은 필드라 정규화된 값과 100% 중복이고, 축제 1건의 크기를 두 배로 만든다. +# site_payload 는 정규화된 키만 읽는다. +_LOCAL_BODY_DROP = ("raw",) + + +async def build_snapshot(place) -> dict: + """사업장 1건의 빌드 스냅샷을 만든다. 노출 가능한 것만 담는다.""" + pid = place.place_id if isinstance(place.place_id, uuid.UUID) else uuid.UUID(str(place.place_id)) + category = PlaceCategory(place.category) + schema = get_schema(category) + + fact_rows = await _select( + select(facts).where( + facts.place_id == pid, + facts.deleted == False, # noqa: E712 + facts.status.in_(_PUBLISHABLE), + ) + ) + unit_rows = await _select( + select(units).where(units.place_id == pid, units.deleted == False) # noqa: E712 + .order_by(units.sort_order.asc()) + ) + faq_rows = await _select( + select(faqs).where( + faqs.place_id == pid, + faqs.deleted == False, # noqa: E712 + faqs.status.in_(_PUBLISHABLE), + ).order_by(faqs.sort_order.asc()) + ) + # ★ 승인된 사진만. Vision 신뢰도가 낮아 확인 큐에 남은 사진은 사이트에 안 나간다. + media_rows = await _select( + select(media).where( + media.place_id == pid, + media.deleted == False, # noqa: E712 + media.status == MediaStatus.APPROVED.value, + ).order_by(media.sort_order.asc()) + ) + + local_rows = await _local_contents(place) + + snapshot = { + "place": { + "name": place.name, + "category": category.value, + "category_name": schema.label, + "road_address": place.road_address, + "address": place.address, + "phone": place.phone, + "latitude": str(place.latitude) if place.latitude is not None else None, + "longitude": str(place.longitude) if place.longitude is not None else None, + }, + "facts": [ + { + "key": r.key, + "label": (schema.get(r.key).label if schema.get(r.key) else r.key), + "value": r.value, + "unit": r.unit, + "scope": (schema.get(r.key).scope if schema.get(r.key) else "place"), + "unit_id": str(r.unit_id) if r.unit_id else None, + # 게이트가 다시 볼 수 있게 상태를 함께 싣는다(스냅샷은 감사 기록이기도 하다). + "status": r.status, + # ★ 출처와 확인 시각도 박제한다. 발행 payload(FactEntry)가 이 값을 그대로 싣고, + # 화면은 "언제 무엇으로 확인된 값인지"를 보여준다 — 출처 없는 사실은 우리 규칙 위반이다. + "source_type": r.source_type, + "source_url": r.source_url, + "collected_at": _iso(r.collected_at), + "verified_at": _iso(r.verified_at), + } + for r in fact_rows + ], + # sort_order 를 함께 싣는다 — 객실·메뉴 순서는 사장님이 정한 것이고, 발행본도 그 순서를 따른다. + "units": [{"unit_id": str(r.unit_id), "name": r.name, "sort_order": r.sort_order} for r in unit_rows], + "faqs": [ + { + "faq_id": str(r.faq_id), + "question": r.question, + "answer": r.answer, + # 렌더러가 노출 필터를 한 번 더 걸 수 있게 상태·출처를 싣는다(fact 와 같은 규칙). + "status": r.status, + "generated_by": r.generated_by, + "sort_order": r.sort_order, + } + for r in faq_rows + ], + # ★ alt 가 없는 사진은 넣지 않는다 — 빌더가 렌더하지 않고, 접근성·AI 검색 신호도 잃는다. + # ★ source_type/origin_url 을 반드시 남긴다 — 크롤링 이미지의 재게시 권리가 미결이라 + # (docs/DECISIONS.md 1-2) 결론이 나면 출처로 걸러내야 한다. 여기서 버리면 재수집밖에 답이 없다. + "media": [ + { + "media_id": str(r.media_id), + "url": r.url, + "origin_url": r.origin_url, + "source_type": r.source_type, + "label": r.label, + "alt_text": r.alt_text, + "width": r.width, + "height": r.height, + "sort_order": r.sort_order, + "unit_id": str(r.unit_id) if r.unit_id else None, + } + for r in media_rows + if (r.alt_text or "").strip() + ], + # ★ 지역 정보. 캐시 키가 place_id 가 아니라 region_code 라 사업장의 지역 코드로 찾는다 + # (같은 지역 사이트 50개여도 외부 조회는 1회 — 그게 이 테이블이 region_code 로 묶인 이유다). + # region_code 가 비어 있으면 조회할 키가 없으므로 빈 목록이다. 그 경우 지어내지 않는다 — + # 지역 코드는 수집 파이프라인이 채우는 값이고, 없으면 아직 지역을 특정하지 못한 사업장이다. + # ★ 원문(body)을 거의 그대로 싣는다. 렌더러 타입으로의 변환은 site_payload 가 한다 — + # fact·사진과 같은 분업이다(여기는 '무엇이 나갈 수 있는가', 거기는 '어떤 모양으로 나가는가'). + "local": local_rows, + } + LOG.i( + f"[snapshot] place={pid} fact {len(snapshot['facts'])} · 객실 {len(snapshot['units'])} · " + f"FAQ {len(snapshot['faqs'])} · 사진 {len(snapshot['media'])} · " + f"지역 {len(snapshot['local']['contents'])}" + ) + return snapshot + + +async def _local_contents(place) -> dict: + """사업장 지역의 노출 가능한 지역 정보. {"region_code", "contents":[...]} + + ★ 노출 가능 = PUBLISHED + 노출 기간 안. + local_contents.status 는 운영 관리자의 검수 결과다(REVIEW=1 · PUBLISHED=2 · ENDED=3). + REVIEW 는 아직 사람이 확인하지 않은 외부 API 원문이고, ENDED 는 내린 것이다. + 둘 중 하나라도 사이트로 새면 '미검증 값 노출 금지'가 깨진다 — fact 를 VERIFIED/CORRECTED 로, + 사진을 APPROVED 로 거르는 것과 같은 규칙을 같은 이유로 적용한다. + display_start_at/display_end_at 은 운영자가 정한 노출 창이다. 기간이 지난 축제를 + "이번 주말 행사"로 걸어두는 것도 틀린 정보라 여기서 함께 막는다. + + ★ expires_at 은 보지 않는다. 모델 주석대로 그건 '갱신 대상'이라는 표시지 '못 쓰는 값'이 아니다 + (외부 API 가 죽어도 직전 값을 유지하는 게 이 캐시의 규약이다). 게다가 날씨는 렌더러가 + 하이드레이션 뒤 최신값으로 덮어쓴다(frontend/site/src/lib/use-live-weather.ts). + """ + # ★ getattr 로 읽는다 — 이 함수는 ORM 행뿐 아니라 테스트의 가짜 place 객체도 받는다. + region_code = str(getattr(place, "region_code", None) or "").strip() + if not region_code: + # ★ 저장된 값이 없으면 도로명주소에서 즉석에서 유도한다. + # places.region_code 를 채우는 곳은 신원 확정(place_service.verify) 한 곳뿐이라, + # 그 코드가 생기기 전에 만들어진 사업장은 영영 NULL 로 남는다(실측: 28곳 중 25곳). + # 그 사업장은 날씨·축제·주변 관광지가 통째로 비고, 발행본에서 날씨 섹션이 아예 + # 사라진다 — 에디터에는 보이는데(폴백값을 그리므로) 사이트에는 없는 그 자리다. + # 여기서 유도하면 신원을 다시 확정하지 않아도 다음 발행부터 지역 정보가 붙는다. + # ★ 지어내지 않는 규칙은 그대로다. region_key 는 주소에서 뽑을 뿐이고, + # 주소가 없거나 형식이 다르면 None 이다(그때는 비는 게 맞다). + region_code = region_key( + str(getattr(place, "road_address", None) or getattr(place, "address", None) or "") + ) or "" + if not region_code: + return {"region_code": None, "contents": []} + + now = datetime.now(timezone.utc) + query = ( + select(local_contents) + .where( + local_contents.region_code == region_code, + local_contents.deleted == False, # noqa: E712 + local_contents.status == LocalContentStatus.PUBLISHED.value, + or_(local_contents.display_start_at.is_(None), local_contents.display_start_at <= now), + or_(local_contents.display_end_at.is_(None), local_contents.display_end_at > now), + ) + .order_by(local_contents.content_type.asc(), local_contents.collected_at.desc()) + ) + err, rows = await DB_SESSION_MNG.execute_lambda( + local_contents.DBType(), DBWRType.DB_READ.value, lambda s: DB_SESSION_MNG.execute(s, query) + ) + if err != ErrorType.SUCCESS: + # ★ 지역 정보가 없다고 발행을 막지 않는다 — 사업장의 사실이 아니라 곁들이는 정보다. + # 빈 채로 나가면 렌더러가 그 섹션을 아예 그리지 않는다. + LOG.w(f"[snapshot] 지역 정보 조회 실패 region={region_code}: {err.name}") + return {"region_code": region_code, "contents": []} + + seen: dict[int, int] = {} + contents = [] + for row in rows or []: + content_type = int(row.content_type) + # 종류별 상한. 위 order_by 가 collected_at 내림차순이라 최근 수집분이 남는다. + taken = seen.get(content_type, 0) + if taken >= _LOCAL_MAX_PER_TYPE: + continue + seen[content_type] = taken + 1 + body = row.body if isinstance(row.body, dict) else {} + contents.append({ + "content_type": content_type, + "source": row.source, + "title": row.title, + "body": {k: v for k, v in body.items() if k not in _LOCAL_BODY_DROP}, + "collected_at": _iso(row.collected_at), + }) + return {"region_code": region_code, "contents": contents} + + +def _iso(value) -> str | None: + """datetime → ISO8601 문자열. + + ★ 스냅샷은 JSONB 컬럼에 그대로 들어간다 — datetime 을 그대로 넣으면 직렬화에서 터진다. + DB 의 timestamptz 는 naive UTC 로 올라오므로(GTime 규약) UTC 를 명시해 둔다.""" + if value is None: + return None + if value.tzinfo is None: + value = value.replace(tzinfo=timezone.utc) + return value.isoformat() + + +async def _select(query) -> list: + err, rows = await DB_SESSION_MNG.execute_lambda( + facts.DBType(), + DBWRType.DB_READ.value, + lambda s: DB_SESSION_MNG.execute(s, query), + ) + return list(rows) if err == ErrorType.SUCCESS else [] diff --git a/backend/services/vision_service.py b/backend/services/vision_service.py new file mode 100644 index 0000000..9f7e4a8 --- /dev/null +++ b/backend/services/vision_service.py @@ -0,0 +1,116 @@ +"""사진 분류 + alt 생성 — VISION 잡이 하는 일. + +수집된 사진을 Gemini Vision 에 넘겨 분류 라벨과 alt 텍스트를 받아 media 에 반영한다. + +★ 신뢰도가 낮은 항목은 자동 반영하지 않는다. 라벨·alt 는 저장하되(사람이 보고 고칠 재료) + status 는 PENDING_REVIEW 로 남겨 사람 확인 큐에 둔다. 임계값은 설정값 하나로만 판단한다. +★ 사진 20~50장을 한 번에 처리하므로 배치·재시도·부분 실패는 클라이언트가 담당한다. + 여기서는 "결과를 어떻게 반영할 것인가"만 판단한다. +""" +import uuid + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import media, places +from common.enums import DBWRType, ErrorType, MediaStatus, PlaceCategory +from common.logger import LOG +from common.utils.gtime import GTime +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 + +_media_crud = MediaCRUD() +_place_crud = PlaceCRUD() + + +class VisionAborted(RuntimeError): + """재시도해도 소용없는 중단 — 잡의 last_error 로 남는다.""" + + +async def run_vision(job: dict) -> dict: + """VISION 잡 핸들러. payload: {place_id, company_id, force?}""" + payload = job["payload"] + place_id = payload["place_id"] + company_id = payload["company_id"] + force = bool(payload.get("force")) + + if not gemini.is_configured(): + raise VisionAborted("GEMINI_API_KEY 미설정 — 사진 분석을 할 수 없다") + + err, place = await DB_SESSION_MNG.execute_lambda( + places.DBType(), + DBWRType.DB_READ.value, + lambda s: _place_crud.get_place(s, uuid.UUID(company_id), uuid.UUID(place_id)), + ) + if err != ErrorType.SUCCESS or place is None: + raise VisionAborted(f"사업장을 찾을 수 없다: {place_id}") + + # force 가 아니면 아직 분석 안 된 사진만 — 같은 사진을 다시 태우면 요금만 나간다. + list_err, rows = await DB_SESSION_MNG.execute_lambda( + media.DBType(), + DBWRType.DB_READ.value, + lambda s: _media_crud.list_media(s, uuid.UUID(place_id), unlabeled_only=not force), + ) + if list_err != ErrorType.SUCCESS: + raise VisionAborted(f"사진 조회 실패: {list_err.name}") + if not rows: + return {"place_id": place_id, "analyzed": 0, "note": "분석할 사진이 없다"} + + # 객실·메뉴 이름을 힌트로 준다 — 라벨이 units 와 같은 어휘로 나오면 매칭이 쉬워진다. + unit_err, unit_rows = await DB_SESSION_MNG.execute_lambda( + media.DBType(), + DBWRType.DB_READ.value, + lambda s: _place_crud.list_units(s, uuid.UUID(place_id)), + ) + unit_names = [u.name for u in (unit_rows or [])] if unit_err == ErrorType.SUCCESS else [] + unit_by_id = {u.unit_id: u.name for u in (unit_rows or [])} if unit_err == ErrorType.SUCCESS else {} + + images = [ + gemini.ImageInput( + origin_url=r.origin_url or r.url, + fetch_url=r.url, + unit_name_hint=unit_by_id.get(r.unit_id), + ) + for r in rows + ] + by_key = {(r.origin_url or r.url): r for r in rows} + + threshold = external_api_config.vision_confidence_threshold + try: + results = await gemini.analyze_images( + images, + category=PlaceCategory(place.category), + unit_names=unit_names, + model=external_api_config.gemini_vision_model, + confidence_threshold=threshold, + ) + except gemini.GeminiNotConfigured as ex: + raise VisionAborted(str(ex)) from ex + + now = GTime.UTC() + stat = {"place_id": place_id, "analyzed": len(rows), "approved": 0, "needs_review": 0, "failed": 0} + for result in results: + row = by_key.get(result.origin_url) + if row is None: + continue + if not result.ok: + # 분석 실패 — 사진은 그대로 두고 사람 확인 큐에 남긴다. 잡을 실패시키지 않는다. + stat["failed"] += 1 + continue + # ★ 신뢰도 미달이면 라벨은 저장하되 승인 상태로 올리지 않는다. + approved = not result.needs_review + status = MediaStatus.APPROVED.value if approved else MediaStatus.PENDING_REVIEW.value + run_err, _rc = await DB_SESSION_MNG.execute_lambda_claim( + media.DBType(), + lambda s, r=result, st=status: _media_crud.apply_vision( + s, by_key[r.origin_url].media_id, r.label, r.alt_text, r.confidence, st, now + ), + ) + if run_err != ErrorType.SUCCESS: + stat["failed"] += 1 + continue + stat["approved" if approved else "needs_review"] += 1 + + LOG.i(f"[vision] place={place_id} {stat['analyzed']}장 → 자동반영 {stat['approved']} · " + f"확인필요 {stat['needs_review']} · 실패 {stat['failed']} (임계값 {threshold})") + return stat diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py new file mode 100644 index 0000000..6724205 --- /dev/null +++ b/backend/tests/test_auth.py @@ -0,0 +1,43 @@ +"""auth 도메인 e2e — 로그인 / 내정보 / 인증거부 흐름. + +유저 시드/로그인은 auth_headers 픽스처. +""" + + +async def test_login_and_me_flow(auth_headers, client, company_id): + """검증: 시드된 유저가 로그인해 받은 토큰으로 /me 호출. + 기대결과: 200, 본인 id·name·소속사(company_id)가 그대로 반환.""" + h = await auth_headers("user1", name="홍길동") + + r = await client.get("/v1/auth/me", headers=h) + assert r.status_code == 200 + me = r.json() + assert me["id"] == "user1" + assert me["name"] == "홍길동" + assert me["company"]["company_id"] == company_id + + +async def test_login_with_wrong_password(auth_headers, client): + """검증: 존재하는 계정에 '틀린 비밀번호'로 로그인. + 기대결과: 로그인 실패 — success=False, code=1100(ACCOUNT_INVALID_INFO), 토큰 빈 문자열.""" + await auth_headers("user2") # pw1234 로 시드 + + r = await client.post("/v1/auth/login", json={"id": "user2", "password": "wrong"}) + body = r.json() + assert body["result"]["success"] is False + assert body["result"]["code"] == 1100 + assert body.get("access_token", "") == "" + + +async def test_login_nonexistent_account(client): + """검증: 존재하지 않는 계정으로 로그인. + 기대결과: 실패 — success=False (계정 유무를 '틀린 비번'과 구분해 흘리지 않음).""" + r = await client.post("/v1/auth/login", json={"id": "ghost", "password": "whatever"}) + assert r.json()["result"]["success"] is False + + +async def test_me_without_token_is_rejected(client): + """검증: 토큰 없이 보호 엔드포인트 /me 호출. + 기대결과: 인증 단계에서 거부 — HTTP 401 또는 403.""" + r = await client.get("/v1/auth/me") + assert r.status_code in (401, 403) diff --git a/backend/tests/test_azure_static.py b/backend/tests/test_azure_static.py new file mode 100644 index 0000000..b19b361 --- /dev/null +++ b/backend/tests/test_azure_static.py @@ -0,0 +1,86 @@ +from pathlib import Path +from types import SimpleNamespace + +from services import azure_static + + +class FakeContainer: + def __init__(self): + self.uploads = {} + self.existing = [] + self.deleted = [] + + def upload_blob(self, name, data, **options): + self.uploads[name] = {"body": data.read(), **options} + + def list_blobs(self, name_starts_with): + return [SimpleNamespace(name=name) for name in self.existing if name.startswith(name_starts_with)] + + def delete_blob(self, name): + self.deleted.append(name) + + +def test_설정없으면_로컬발행만_유지(monkeypatch): + monkeypatch.delenv("AZURE_STORAGE_CONNECTION_STRING", raising=False) + assert azure_static.is_configured() is False + + +def test_ai_for_web_아래에_사이트와_공용산출물을_업로드(tmp_path, monkeypatch): + (tmp_path / "assets").mkdir() + (tmp_path / "assets" / "index-abc.js").write_text("console.log(1)") + (tmp_path / "fonts").mkdir() + (tmp_path / "fonts" / "Pretendard.woff2").write_bytes(b"font") + # ★ 오리진 루트 파일 — 크롤러가 robots.txt 를 읽는 유일한 자리다(RFC 9309). + (tmp_path / "robots.txt").write_text("User-agent: *\nAllow: /\n") + (tmp_path / "sitemap.xml").write_text("") + site_dir = tmp_path / "s" / "butter" + (site_dir / "about").mkdir(parents=True) + (site_dir / "index.html").write_text("

Butter

") + (site_dir / "about" / "index.html").write_text("

About

") + # 다른 사업장의 발행본. 이번 발행 대상이 아니므로 올라가면 안 된다. + (tmp_path / "s" / "joy").mkdir(parents=True) + (tmp_path / "s" / "joy" / "index.html").write_text("

Joy

") + + container = FakeContainer() + container.existing = [ + "ai-for-web/s/butter/index.html", + "ai-for-web/s/butter/old/index.html", + ] + service = SimpleNamespace(get_container_client=lambda name: container) + monkeypatch.setattr( + azure_static.BlobServiceClient, + "from_connection_string", + lambda value: service, + ) + monkeypatch.setattr(azure_static, "output_dir", lambda: Path(tmp_path)) + monkeypatch.setenv("AZURE_STORAGE_CONNECTION_STRING", "UseDevelopmentStorage=true") + monkeypatch.delenv("AZURE_STORAGE_PREFIX", raising=False) + + result = azure_static._publish_sync("butter") + + assert set(container.uploads) == { + "ai-for-web/assets/index-abc.js", + "ai-for-web/fonts/Pretendard.woff2", + "ai-for-web/robots.txt", + "ai-for-web/sitemap.xml", + "ai-for-web/s/butter/index.html", + "ai-for-web/s/butter/about/index.html", + } + assert container.deleted == ["ai-for-web/s/butter/old/index.html"] + assert result == { + "container": "$web", + "prefix": "ai-for-web", + "shared_files": 4, + "site_files": 2, + "removed_stale": 1, + } + + +def test_루트_robots_와_사이트맵은_짧게_캐시된다(): + # 해시가 박힌 번들만 영구 캐시다. robots·사이트맵이 길게 캐시되면 + # 새 사업장이 사이트맵 인덱스에 들어가도 크롤러가 옛 파일을 계속 본다. + assert "immutable" in azure_static._cache_control(Path("assets/index-abc.js")) + assert azure_static._cache_control(Path("robots.txt")) == "public, max-age=60, must-revalidate" + assert azure_static._cache_control(Path("sitemap.xml")) == "public, max-age=60, must-revalidate" + assert azure_static._cache_control(Path("s/butter/index.html")) == "public, max-age=60, must-revalidate" + assert azure_static._cache_control(Path("fonts/Pretendard.woff2")) == "public, max-age=604800" diff --git a/backend/tests/test_build_publish.py b/backend/tests/test_build_publish.py new file mode 100644 index 0000000..4453272 --- /dev/null +++ b/backend/tests/test_build_publish.py @@ -0,0 +1,353 @@ +"""정적 빌드 + 발행 — 상호명에서 발행까지 한 바퀴. + +★ 이 경로가 절대 하면 안 되는 것: + - 미검증 fact 를 실은 사이트를 발행하는 것 + - 고유 콘텐츠 0건짜리 템플릿 페이지를 발행하는 것 + - JSON-LD 와 화면이 다른 사이트를 발행하는 것 + - 렌더 결과를 확인하지 않고 "발행됨" 으로 남기는 것 (페이지 없는 발행) + - 해지를 물리 삭제로 처리하는 것 + +★ 게이트는 이제 **렌더러가 실제로 구운 결과**를 보고 판정한다. 여기서는 그 보고서를 + 백엔드가 어떻게 처리하는지를 본다 — 구조화 데이터 ↔ 화면 값 대조 자체는 + 렌더러 쪽 테스트가 본다(frontend/site/src/seo/verify.test.ts). +""" +import uuid + +from sqlalchemy import text + +from common.enums import ( + BuildStatus, + ErrorType, + FactStatus, + JobStatus, + MediaStatus, + PublishAction, + PublishRejectReason, + SiteStatus, + SourceType, +) +from crud.job_crud import JobQueue +from worker.handlers import build_handler +from worker.runner import Worker + +REQUIRED = { + "check_in_time": "15:00", "check_out_time": "11:00", + "cancel_policy": "이용 7일 전 100% 환불, 3일 전 50% 환불", + "cooking_allowed": "true", "pet_allowed": "false", +} + + +async def _run(): + assert await Worker("w", JobQueue(), build_handler(), job_deadline_sec=60).process_one() is True + + +async def _place(client, h, name="빌드펜션"): + pid = (await client.post("/v1/place", headers=h, json={"name": name, "category": 1})).json()["place"]["place_id"] + await client.post(f"/v1/place/{pid}/verify", headers=h, json={ + "source": 2, "road_address": f"강원특별자치도 양양군 현북면 하조대3길 {uuid.uuid4().hex[:3]}", + "phone": "033-672-0000", "latitude": "38.0219217", "longitude": "128.7221449", + }) + return pid + + +async def _verified_facts(client, h, pid, extra=None): + """필수 항목을 넣고 전부 승인 상태로 만든다(사람이 직접 입력 = 즉시 노출값).""" + for k, v in {**REQUIRED, **(extra or {})}.items(): + await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v}) + + +async def _approved_media(db_engine, pid, alt="2층 목조 건물 외관"): + async with db_engine.begin() as c: + await c.execute( + text("INSERT INTO media (media_id, place_id, url, origin_url, source_type, status, alt_text, label, sort_order) " + "VALUES (:m,:p,:u,:u,:s,:st,:a,:l,0)"), + {"m": uuid.uuid4(), "p": uuid.UUID(pid), "u": f"https://cdn.test/{uuid.uuid4().hex[:6]}.jpg", + "s": SourceType.CRAWL.value, "st": MediaStatus.APPROVED.value, "a": alt, "l": "외관"}, + ) + + +async def test_full_build_and_publish(auth_headers, client, db_engine): + """검증: 필수 fact + 승인 사진이 갖춰진 사업장을 빌드·발행한다. + 기대결과: 게이트 통과 → BUILT → PUBLISHED. 버전과 발행 기록이 남는다.""" + h = await auth_headers("u1") + pid = await _place(client, h) + await _verified_facts(client, h, pid, {"intro": "하조대 해변 도보 3분 거리의 펜션입니다."}) + await _approved_media(db_engine, pid) + + job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})).json()["job_id"] + await _run() + + job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"] + assert job["status"] == JobStatus.DONE.value, job.get("last_error") + r = job["result"] + assert r["gate"]["passed"] is True, r["gate"] + assert r["build_status"] == "BUILT" + assert r["published"] is True + assert r["unique_content_count"] > 0 + # ★ 백엔드는 HTML 을 굽지 않는다. payload 를 쓰고, 렌더러가 굽은 결과를 받아 판정한다. + assert r["payload_path"], "렌더러에 넘길 payload 가 없다" + assert r["routes"] > 0, "렌더러가 페이지를 하나도 굽지 않았다" + + site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json() + assert site["site"]["status"] == SiteStatus.PUBLISHED.value + assert site["current_version"]["build_status"] == BuildStatus.BUILT.value + + +async def test_unverified_fact_blocks_publish(auth_headers, client, db_engine): + """검증: 미검증 fact 가 섞인 채로 빌드한다. + + 기대결과: ★ 스냅샷에서 전부 걸러져 페이지에 남는 내용이 없다 — NO_UNIQUE_CONTENT 로 막힌다. + (필수 항목 누락은 2026-08-27 부터 막지 않는다. 그래서 여기서 걸리는 사유가 바뀌었다.)""" + h = await auth_headers("u1") + pid = await _place(client, h, "미검증펜션") + # 크롤링으로만 들어온 값 = 후보 상태 + for k, v in REQUIRED.items(): + await client.post(f"/v1/place/{pid}/fact", headers=h, json={ + "key": k, "value": v, "source_type": SourceType.CRAWL.value, "source_url": "https://ota.test/1"}) + + job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})).json()["job_id"] + await _run() + + r = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]["result"] + assert r["gate"]["passed"] is False + assert r["gate"]["reason"] == PublishRejectReason.NO_UNIQUE_CONTENT.name + assert r["build_status"] == "FAILED" + assert r.get("published") is None + + site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json() + assert site["site"]["status"] == SiteStatus.DRAFT.value, "★ 게이트를 막았는데 발행됐다" + + +async def test_no_unique_content_blocks_publish(auth_headers, client): + """검증: 필수 항목은 다 채웠지만 값이 전부 짧은 정형값이고 소개문·FAQ·사진이 없다. + 기대결과: ★ NO_UNIQUE_CONTENT — 이 가게를 구분할 문장이 하나도 없으면 + 같은 템플릿 대량 생성으로 보인다(스팸 판정 대상).""" + h = await auth_headers("u1") + pid = await _place(client, h, "빈껍데기펜션") + # 취소 규정을 한 글자로 — 형식은 갖췄지만 이 가게만의 내용이 없다. + for k, v in {**REQUIRED, "cancel_policy": "X"}.items(): + await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v}) + + job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})).json()["job_id"] + await _run() + + r = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]["result"] + assert r["gate"]["passed"] is False + assert r["gate"]["reason"] == PublishRejectReason.NO_UNIQUE_CONTENT.name + + +async def test_missing_required_field_warns_but_publishes(auth_headers, client, db_engine): + """검증: 취소 규정 없이 빌드한다. + + 기대결과: ★ **발행된다.** 막아야 할 것은 "틀린 정보가 나가는 것"이지 "덜 찬 것"이 아니다 + (2026-08-27 결정). 대신 무엇이 비었는지는 경고로 알려줘야 한다 — 사장님이 나중에 + 채우면 재빌드된다. 여기서 막으면 주소·전화가 확인된 쓸모 있는 페이지조차 못 낸다.""" + h = await auth_headers("u1") + pid = await _place(client, h, "규정없는펜션") + partial = {k: v for k, v in REQUIRED.items() if k != "cancel_policy"} + for k, v in partial.items(): + await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v}) + await _approved_media(db_engine, pid) + + job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})).json()["job_id"] + await _run() + + r = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]["result"] + assert r["gate"]["passed"] is True, "필수 항목 누락은 더 이상 발행을 막지 않는다" + assert r["gate"]["warning"] == PublishRejectReason.REQUIRED_FACT_MISSING.name + assert "cancel_policy" in r["gate"]["missing"], "무엇이 비었는지는 계속 알려줘야 한다" + assert r["build_status"] == "BUILT" + + site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json() + assert site["site"]["status"] == SiteStatus.PUBLISHED.value + + +async def test_rejected_build_is_logged_with_reason(auth_headers, client): + """검증: 게이트가 막은 뒤 발행 기록. + 기대결과: REJECTED 로 남고 사유가 detail 에 있다 — 운영자가 뭘 고칠지 안다.""" + h = await auth_headers("u1") + pid = await _place(client, h, "기록펜션") + for k, v in {**REQUIRED, "cancel_policy": "X"}.items(): + await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": v}) + await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True}) + await _run() + + logs = (await client.get(f"/v1/place/{pid}/site/log/list", headers=h)).json()["logs"] + assert logs + assert logs[0]["reject_reason"] == PublishRejectReason.NO_UNIQUE_CONTENT.value + assert logs[0]["detail"]["reason"] == "NO_UNIQUE_CONTENT" + + +async def test_build_requires_verified_place(auth_headers, client): + """검증: 동일 업소 검증 전에 빌드한다. + 기대결과: PLACE_NOT_VERIFIED — 주소·좌표가 없으면 JSON-LD 가 성립하지 않는다.""" + h = await auth_headers("u1") + pid = (await client.post("/v1/place", headers=h, json={"name": "미검증", "category": 1})).json()["place"]["place_id"] + r = await client.post(f"/v1/place/{pid}/site/build", headers=h, json={}) + assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_VERIFIED.value + + +async def test_needs_rebuild_after_content_change(auth_headers, client, db_engine): + """검증: 발행 후 노출값을 바꾼다. + 기대결과: ★ needs_rebuild=true — 이 사업장만 재빌드하면 된다(전체 재빌드 금지).""" + h = await auth_headers("u1") + pid = await _place(client, h, "재빌드펜션") + await _verified_facts(client, h, pid, {"intro": "조용한 펜션입니다."}) + await _approved_media(db_engine, pid) + await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True}) + await _run() + + assert (await client.get(f"/v1/place/{pid}/site", headers=h)).json()["needs_rebuild"] is False + + await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": "check_in_time", "value": "16:00"}) + assert (await client.get(f"/v1/place/{pid}/site", headers=h)).json()["needs_rebuild"] is True + + +async def test_suspend_is_state_transition_not_delete(auth_headers, client, db_engine): + """검증: 발행된 사이트를 중지하고 다시 재개한다. + 기대결과: ★ 상태만 바뀌고 버전·행은 그대로 — 해지를 삭제로 처리하지 않는다.""" + h = await auth_headers("u1") + pid = await _place(client, h, "해지펜션") + await _verified_facts(client, h, pid, {"intro": "펜션 소개문입니다."}) + await _approved_media(db_engine, pid) + await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True}) + await _run() + version_id = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()["current_version"]["site_version_id"] + + body = (await client.post(f"/v1/place/{pid}/site/status", headers=h, + json={"action": PublishAction.SUSPEND.value})).json() + assert body["site"]["status"] == SiteStatus.SUSPENDED.value + assert body["current_version"]["site_version_id"] == version_id, "★ 중지가 버전을 지웠다" + + body = (await client.post(f"/v1/place/{pid}/site/status", headers=h, + json={"action": PublishAction.RESUME.value})).json() + assert body["site"]["status"] == SiteStatus.PUBLISHED.value + + +async def test_versions_accumulate(auth_headers, client, db_engine): + """검증: 두 번 빌드한다. + 기대결과: 버전이 1, 2 로 쌓인다 — 예전에 뭐가 나갔는지 추적할 수 있다.""" + h = await auth_headers("u1") + pid = await _place(client, h, "버전펜션") + await _verified_facts(client, h, pid, {"intro": "펜션 소개문입니다."}) + await _approved_media(db_engine, pid) + + await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True}) + await _run() + await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True}) + await _run() + + versions = (await client.get(f"/v1/place/{pid}/site/version/list", headers=h)).json()["versions"] + assert [v["version"] for v in versions] == [2, 1] + + +async def test_site_is_scoped_to_company(auth_headers, client, other_company_id): + """검증: 다른 회사 계정으로 남의 사이트를 본다. + 기대결과: PLACE_NOT_FOUND.""" + h1 = await auth_headers("o1") + pid = await _place(client, h1, "스코프펜션") + h2 = await auth_headers("o2", other_company_id) + r = await client.get(f"/v1/place/{pid}/site", headers=h2) + assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value + + +# ── 렌더 결과 기반 게이트 ──────────────────────────────────────────────────── +async def _built_place(client, h, db_engine): + pid = await _place(client, h) + await _verified_facts(client, h, pid, {"intro": "하조대 해변 도보 3분 거리의 펜션입니다."}) + await _approved_media(db_engine, pid) + return pid + + +async def _build(client, h, pid, publish=True): + job_id = (await client.post(f"/v1/place/{pid}/site/build", headers=h, + json={"publish": publish})).json()["job_id"] + await _run() + return (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]["result"] + + +async def test_렌더가_실패하면_발행하지_않는다(auth_headers, client, db_engine, monkeypatch): + """검증: 렌더러가 페이지를 굽지 못했다고 보고한다. + 기대결과: ★ FAILED. 페이지가 없는데 "발행됨"으로 남으면 사장님은 404 를 눌러야 안다.""" + from services import render_report + + async def _broken(slug, site_version, timeout_sec, poll_sec=1.0): + return {"schemaVersion": 1, "slug": slug, "siteId": "", "placeId": "", + "siteVersion": site_version, "ok": False, "renderedAt": "2026-01-01T00:00:00Z", + "routes": 0, "bundle": "t.js", "uniqueContentCount": 5, "jsonld": [], + "mismatches": [], "error": "번들이 없다"} + + h = await auth_headers("u1") + pid = await _built_place(client, h, db_engine) + monkeypatch.setattr(render_report, "wait_for", _broken) + + r = await _build(client, h, pid) + assert r["build_status"] == "FAILED" + assert r.get("published") is not True + assert "번들이 없다" in r["error"] + + site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json() + assert site["site"]["status"] != SiteStatus.PUBLISHED.value + + +async def test_구조화데이터가_화면과_다르면_발행하지_않는다(auth_headers, client, db_engine, monkeypatch): + """검증: 렌더러가 JSON-LD 불일치를 보고한다. + 기대결과: ★ JSONLD_MISMATCH — 검색엔진에만 다른 말을 하는 페이지는 나가면 안 된다.""" + from services import render_report + + async def _mismatch(slug, site_version, timeout_sec, poll_sec=1.0): + return {"schemaVersion": 1, "slug": slug, "siteId": "", "placeId": "", + "siteVersion": site_version, "ok": False, "renderedAt": "2026-01-01T00:00:00Z", + "routes": 0, "bundle": "t.js", "uniqueContentCount": 5, "jsonld": [], + "mismatches": ["telephone: '02-0000-0000' 이 화면에 없다"], + "error": "구조화 데이터가 화면 값과 다릅니다(1건)"} + + h = await auth_headers("u1") + pid = await _built_place(client, h, db_engine) + monkeypatch.setattr(render_report, "wait_for", _mismatch) + + r = await _build(client, h, pid) + assert r["build_status"] == "FAILED" + # ★ 사유가 "렌더 실패"로 뭉뚱그려지면 운영자가 손댈 곳을 알 수 없다. + assert r["gate"]["reason"] == PublishRejectReason.JSONLD_MISMATCH.name + assert r["mismatches"] + + +async def test_렌더_결과가_안_오면_발행하지_않는다(auth_headers, client, db_engine, monkeypatch): + """검증: 렌더러가 죽어 보고서가 오지 않는다(타임아웃). + 기대결과: ★ FAILED. 확인하지 못한 것을 발행됨으로 남기지 않는다.""" + from services import render_report + + async def _timeout(slug, site_version, timeout_sec, poll_sec=1.0): + return None + + h = await auth_headers("u1") + pid = await _built_place(client, h, db_engine) + monkeypatch.setattr(render_report, "wait_for", _timeout) + + r = await _build(client, h, pid) + assert r["build_status"] == "FAILED" + assert r.get("published") is not True + assert "렌더 결과" in r["error"] + + +async def test_렌더_보고서의_값이_그대로_박제된다(auth_headers, client, db_engine): + """검증: site_versions 에 남는 jsonld·고유콘텐츠 수의 출처. + 기대결과: ★ 렌더러가 실제로 내보낸 값이다 — 백엔드가 따로 계산하지 않는다. + (따로 계산하던 시절엔 게이트가 통과시킨 근거와 실제 페이지가 어긋날 수 있었다.)""" + h = await auth_headers("u1") + pid = await _built_place(client, h, db_engine) + r = await _build(client, h, pid) + + assert r["build_status"] == "BUILT" + + async with db_engine.begin() as c: + row = (await c.execute( + text("SELECT jsonld, unique_content_count FROM site.site_versions WHERE site_version_id = :v"), + {"v": uuid.UUID(r["site_version_id"])}, + )).mappings().first() + + assert row["unique_content_count"] == r["unique_content_count"] + assert row["jsonld"], "렌더러가 내보낸 JSON-LD 가 박제되지 않았다" + # 렌더러 대역이 내보낸 노드가 그대로 들어와야 한다(백엔드가 다시 만들지 않는다). + assert row["jsonld"][0]["@type"] == "LodgingBusiness" diff --git a/backend/tests/test_category_schema.py b/backend/tests/test_category_schema.py new file mode 100644 index 0000000..3fd3c20 --- /dev/null +++ b/backend/tests/test_category_schema.py @@ -0,0 +1,78 @@ +"""업종 스키마 — 4개 업종 파일이 규약대로 로드되는지. + +업종 추가 = resources/ 에 JSON 1개 + PlaceCategory 코드 1줄. 이 테스트는 그 규약이 깨지면 잡는다. +""" +import pytest + +from common.category_schema import CategorySchemaError, all_schemas, get_schema, is_valid_key +from common.enums import PlaceCategory + + +def test_all_categories_have_schema(): + """검증: PlaceCategory 의 모든 업종에 스키마 파일이 있는지. + 기대결과: 4개 업종(숙박·카페·음식점·관광체험)이 모두 로드되고 code 가 1:1로 맞는다.""" + schemas = all_schemas() + assert set(schemas) == {c.value for c in PlaceCategory} + for code, schema in schemas.items(): + assert schema.code == code + assert schema.category == PlaceCategory(code) + assert schema.fields, f"{schema.name}: 필드가 비었다" + + +def test_keys_unique_within_category(): + """검증: 업종 안에서 fact key 가 유일한지. + 기대결과: 중복 없음 (facts 의 (place,unit,key) 유니크가 의미를 가지려면 필수).""" + for schema in all_schemas().values(): + keys = list(schema.fields) + assert len(keys) == len(set(keys)), f"{schema.name}: key 중복" + + +def test_place_and_unit_scopes_exist(): + """검증: 업종마다 place 스코프 필드가 있는지. + 기대결과: 전 업종에 place 필드 존재. unit 필드는 업종별로 있을 수도 없을 수도 있다.""" + for schema in all_schemas().values(): + assert schema.keys_by_scope("place"), f"{schema.name}: place 스코프 필드가 없다" + + +def test_lodging_has_claim_critical_fields(): + """검증: 숙박 업종에 예약 클레임 직결 항목이 critical 로 잡혀 있는지. + 기대결과: 체크인·체크아웃·취사·반려동물·취소규정이 모두 critical=True 이고 LLM 이 못 쓴다.""" + schema = get_schema(PlaceCategory.LODGING) + for key in ("check_in_time", "check_out_time", "cooking_allowed", "pet_allowed", "cancel_policy"): + spec = schema.get(key) + assert spec is not None, f"숙박 스키마에 {key} 가 없다" + assert spec.critical is True, f"{key} 는 critical 이어야 한다" + assert spec.allow_llm is False, f"{key} 는 LLM 이 값을 만들면 안 된다" + + +def test_llm_writable_fields_are_sentences_only(): + """검증: LLM 이 값을 만들 수 있는 필드가 '문장' 필드뿐인지 (절대규칙 7 — LLM 은 사실을 만들지 않는다). + 기대결과: allow_llm=True 인 필드는 전부 type=text 이고 critical 이 아니다.""" + for schema in all_schemas().values(): + for key in schema.llm_writable_keys(): + spec = schema.get(key) + assert spec.type == "text", f"{schema.name}.{key}: LLM 이 쓸 수 있는 필드는 text 여야 한다" + assert spec.critical is False, f"{schema.name}.{key}: critical 필드를 LLM 이 쓰면 안 된다" + + +def test_required_fields_are_never_llm_written(): + """검증: 발행 필수 항목을 LLM 이 채우지 못하는지. + 기대결과: required=True 인 필드는 전부 allow_llm=False.""" + for schema in all_schemas().values(): + for key in schema.required_keys(): + assert schema.get(key).allow_llm is False, f"{schema.name}.{key}: 필수 항목을 LLM 이 채우면 안 된다" + + +def test_is_valid_key_rejects_cross_category_key(): + """검증: 업종에 없는 key 를 걸러내는지 (facts 쓰기 전 FACT_INVALID_KEY 판정). + 기대결과: 숙박의 check_in_time 은 카페 스키마에서 거부된다.""" + assert is_valid_key(PlaceCategory.LODGING, "check_in_time") is True + assert is_valid_key(PlaceCategory.CAFE, "check_in_time") is False + assert is_valid_key(PlaceCategory.CAFE, "break_time") is True + + +def test_unknown_category_raises(): + """검증: 지원하지 않는 업종 코드 조회. + 기대결과: CategorySchemaError.""" + with pytest.raises(CategorySchemaError): + get_schema(99) diff --git a/backend/tests/test_collect_api.py b/backend/tests/test_collect_api.py new file mode 100644 index 0000000..c2716e2 --- /dev/null +++ b/backend/tests/test_collect_api.py @@ -0,0 +1,168 @@ +"""수집 시작 e2e — 비동기 잡 적재와 진입 게이트. + +수집은 한 건에 몇 분(Perplexity 10~30s + 크롤링 + Vision 사진 배치)이라 동기로 못 한다. +API 는 잡만 넣고 즉시 응답하고, 클라이언트는 job_id 로 폴링한다. + +★ 진입 게이트는 하나 — 동일 업소 검증. 검증 없이 긁으면 남의 가게가 섞인다. + 채널 URL 발견(Perplexity)과 확정은 잡 안에서 일어나므로, 링크가 없어도 수집은 시작된다. +""" +from common.enums import ErrorType, JobStatus, JobType, LinkChannel, SourceType + +OTA = "https://www.yanolja.com/pension/1" + + +async def _place(client, h, kakao=None, name="테스트펜션"): + pid = (await client.post("/v1/place", headers=h, json={"name": name, "category": 1})).json()["place"]["place_id"] + if kakao: + await client.post(f"/v1/place/{pid}/verify", headers=h, json={"external_place_id": kakao}) + return pid + + +async def _confirmed_link(client, h, pid, url=OTA): + lid = (await client.post(f"/v1/place/{pid}/link", headers=h, json={ + "channel": LinkChannel.YANOLJA.value, "url": url, "discovered_by": SourceType.API.value, + })).json()["link"]["link_id"] + await client.post(f"/v1/place/{pid}/link/{lid}/confirm", headers=h) + return lid + + +async def test_collect_requires_verified_place(auth_headers, client): + """검증: 동일 업소 검증 전에 수집을 시작한다. + 기대결과: PLACE_NOT_VERIFIED — ★ 검증 없이는 크롤링이 열리지 않는다.""" + h = await auth_headers("u1") + pid = await _place(client, h) + + r = await client.post(f"/v1/place/{pid}/collect", headers=h, json={}) + assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_VERIFIED.value + + +async def test_collect_starts_without_any_link(auth_headers, client): + """검증: 링크가 하나도 없는 검증된 사업장에서 수집을 시작한다. + 기대결과: 시작된다 — 채널 URL 발견(Perplexity)이 잡의 첫 단계이기 때문.""" + h = await auth_headers("u1") + pid = await _place(client, h, kakao="c1") + + body = (await client.post(f"/v1/place/{pid}/collect", headers=h, json={})).json() + assert body["result"]["success"] is True + assert body["job_id"] + assert body["confirmed_links"] == 0 + + +async def test_targeted_recrawl_needs_confirmed_link(auth_headers, client): + """검증: link_ids 로 특정 링크만 재크롤하라고 했는데 그게 확정 상태가 아니다. + 기대결과: LINK_NOT_CONFIRMED — 콕 집은 대상이 없으면 시작할 이유가 없다.""" + import uuid as _uuid + + h = await auth_headers("u1") + pid = await _place(client, h, kakao="c2") + lid = (await client.post(f"/v1/place/{pid}/link", headers=h, json={"channel": 1, "url": OTA})).json()["link"]["link_id"] + + r = await client.post(f"/v1/place/{pid}/collect", headers=h, json={"link_ids": [lid]}) + assert r.json()["result"]["code"] == ErrorType.LINK_NOT_CONFIRMED.value + + +async def test_collect_enqueues_job_and_returns_immediately(auth_headers, client): + """검증: 검증 + 링크 확정이 끝난 뒤 수집을 시작한다. + 기대결과: job_id 를 즉시 돌려주고 잡은 PENDING — 요청이 몇 분을 기다리지 않는다.""" + h = await auth_headers("u1") + pid = await _place(client, h, kakao="c3") + await _confirmed_link(client, h, pid) + + body = (await client.post(f"/v1/place/{pid}/collect", headers=h, json={})).json() + assert body["result"]["success"] is True + assert body["job_id"] + assert body["status"] == JobStatus.PENDING.value + assert body["created"] is True + assert body["confirmed_links"] == 1 + + job = (await client.get(f"/v1/job/{body['job_id']}", headers=h)).json() + assert job["job"]["job_type"] == JobType.COLLECT.value + assert job["job"]["status"] == JobStatus.PENDING.value + + +async def test_collect_marks_place_as_collecting(auth_headers, client): + """검증: 수집을 시작한 뒤 사업장 상태. + 기대결과: DRAFT → COLLECTING (관리 화면 배지).""" + h = await auth_headers("u1") + pid = await _place(client, h, kakao="c4") + await _confirmed_link(client, h, pid) + + await client.post(f"/v1/place/{pid}/collect", headers=h, json={}) + place = (await client.get(f"/v1/place/{pid}", headers=h)).json()["place"] + assert place["status"] == 2 # PlaceStatus.COLLECTING + + +async def test_double_click_does_not_run_twice(auth_headers, client): + """검증: 수집 버튼을 두 번 누른다. + 기대결과: 같은 job_id 를 돌려주고 created=False — dedupe_key 로 활성 중복이 막힌다.""" + h = await auth_headers("u1") + pid = await _place(client, h, kakao="c5") + await _confirmed_link(client, h, pid) + + first = (await client.post(f"/v1/place/{pid}/collect", headers=h, json={})).json() + second = (await client.post(f"/v1/place/{pid}/collect", headers=h, json={})).json() + + assert second["result"]["success"] is True + assert second["job_id"] == first["job_id"] + assert second["created"] is False + + +async def test_default_collect_payload_does_not_freeze_existing_links(auth_headers, client): + """기본 수집은 잡 안에서 새로 발견·확정되는 링크도 대상으로 삼는다.""" + h = await auth_headers("u1") + pid = await _place(client, h, kakao="c6") + confirmed = await _confirmed_link(client, h, pid, "https://www.yanolja.com/pension/ok") + await client.post(f"/v1/place/{pid}/link", headers=h, json={"channel": 3, "url": "https://place.naver.com/nope"}) + + body = (await client.post(f"/v1/place/{pid}/collect", headers=h, json={})).json() + assert body["confirmed_links"] == 1 + + from crud.job_crud import JobQueue + + job = await JobQueue().get(body["job_id"]) + assert job["payload"]["link_ids"] == [] + assert job["payload"]["place_id"] == pid + assert job["payload"]["discover_channels"] is False + + +async def test_collect_payload_carries_explicit_channel_discovery_option(auth_headers, client): + """Perplexity URL 발견은 사용자가 선택한 수집 회차에만 잡 payload 로 전달한다.""" + h = await auth_headers("u1") + pid = await _place(client, h, kakao="c6-discovery") + + body = (await client.post( + f"/v1/place/{pid}/collect", headers=h, json={"discover_channels": True} + )).json() + + from crud.job_crud import JobQueue + + job = await JobQueue().get(body["job_id"]) + assert job["payload"]["discover_channels"] is True + + +async def test_targeted_collect_payload_carries_requested_confirmed_link(auth_headers, client): + """사용자가 특정 링크를 고른 재수집만 그 링크로 제한한다.""" + h = await auth_headers("u1") + pid = await _place(client, h, kakao="c6-targeted") + confirmed = await _confirmed_link(client, h, pid, "https://www.yanolja.com/pension/target") + + body = (await client.post( + f"/v1/place/{pid}/collect", headers=h, json={"link_ids": [confirmed]} + )).json() + + from crud.job_crud import JobQueue + + job = await JobQueue().get(body["job_id"]) + assert job["payload"]["link_ids"] == [confirmed] + + +async def test_collect_is_scoped_to_company(auth_headers, client, other_company_id): + """검증: 다른 회사 계정으로 남의 사업장 수집을 시작한다. + 기대결과: PLACE_NOT_FOUND — 사업장이 안 보이니 수집도 못 건다.""" + h1 = await auth_headers("o1") + pid = await _place(client, h1, kakao="c7") + await _confirmed_link(client, h1, pid) + + h2 = await auth_headers("o2", other_company_id) + r = await client.post(f"/v1/place/{pid}/collect", headers=h2, json={}) + assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value diff --git a/backend/tests/test_collect_pipeline.py b/backend/tests/test_collect_pipeline.py new file mode 100644 index 0000000..4b5d9d7 --- /dev/null +++ b/backend/tests/test_collect_pipeline.py @@ -0,0 +1,231 @@ +"""수집 파이프라인 e2e — 잡이 실제로 돌아 fact·사진이 후보로 쌓이는지. + + 상호명 → (URL 발견) → 확정 → 크롤링 → fact/사진 적재 + +★ 이 파이프라인이 절대 하면 안 되는 것: + - 검증 안 된 사업장을 긁는 것 + - 수집값을 바로 사이트에 노출시키는 것 (전부 후보로 들어가야 한다) + - 사장님 정정본을 덮어쓰는 것 +""" +import uuid + +from common.enums import FactStatus, JobStatus, JobType, LinkChannel, MediaStatus, PlaceCategory, SourceType +from crud.job_crud import JobQueue +from services.collector import MockAdapter +from worker.handlers import build_handler +from worker.runner import Worker + + +async def _ready_place(client, h, category=PlaceCategory.LODGING, kakao="k1"): + """검증까지 끝나고 MockAdapter 가 처리할 수 있는 링크가 확정된 사업장.""" + pid = (await client.post("/v1/place", headers=h, json={"name": "하조대펜션", "category": category.value})).json()["place"]["place_id"] + await client.post(f"/v1/place/{pid}/verify", headers=h, json={ + "external_place_id": kakao, "road_address": "강원 양양군 현북면 하조대해안길 3", "region_code": "4283025"}) + url = MockAdapter.url_for(category, pid, channel="yanolja") + lid = (await client.post(f"/v1/place/{pid}/link", headers=h, json={ + "channel": LinkChannel.YANOLJA.value, "url": url, "discovered_by": SourceType.API.value})).json()["link"]["link_id"] + await client.post(f"/v1/place/{pid}/link/{lid}/confirm", headers=h) + return pid + + +async def _run_worker(job_id=None): + """워커 1틱 — 큐에서 잡을 집어 실제 파이프라인을 돌린다.""" + worker = Worker("test-worker", JobQueue(), build_handler(), job_deadline_sec=60) + assert await worker.process_one() is True, "워커가 집을 잡이 없다" + + +async def test_pipeline_stores_facts_as_candidates(auth_headers, client): + """검증: 수집 잡을 끝까지 돌린다. + 기대결과: fact 가 쌓이되 **전부 후보(UNVERIFIED)** — ★ 크롤링 값은 사이트에 안 나간다.""" + h = await auth_headers("u1") + pid = await _ready_place(client, h) + + job_id = (await client.post(f"/v1/place/{pid}/collect", headers=h, json={})).json()["job_id"] + await _run_worker() + + 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"]["facts"]["stored"] > 0 + + listed = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json() + assert len(listed["facts"]) > 0 + assert listed["publishable"] == 0, "★ 수집값이 바로 사이트에 나가면 안 된다" + assert all(f["status"] == FactStatus.UNVERIFIED.value for f in listed["facts"]) + + +async def test_pipeline_records_source_on_every_fact(auth_headers, client): + """검증: 수집된 fact 의 출처. + 기대결과: 전부 source_type=crawl + source_url 이 붙어 있다 — 출처 없는 사실은 없다.""" + h = await auth_headers("u1") + pid = await _ready_place(client, h, kakao="k2") + await client.post(f"/v1/place/{pid}/collect", headers=h, json={}) + await _run_worker() + + facts = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()["facts"] + for f in facts: + assert f["source_type"] == SourceType.CRAWL.value + assert f["source_url"], f"출처 없는 fact: {f['key']}" + + +async def test_pipeline_creates_units_and_unit_scoped_facts(auth_headers, client): + """검증: 숙박 수집 결과의 객실 단위 fact. + 기대결과: units 가 생기고 객실별 fact 가 각자 붙는다(A동·B동이 각자 기준인원을 갖는다).""" + h = await auth_headers("u1") + pid = await _ready_place(client, h, kakao="k3") + await client.post(f"/v1/place/{pid}/collect", headers=h, json={}) + await _run_worker() + + units = (await client.get(f"/v1/place/{pid}/unit/list", headers=h)).json()["units"] + assert len(units) >= 2 + + facts = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()["facts"] + unit_facts = [f for f in facts if f.get("unit_id")] + assert unit_facts, "객실 단위 fact 가 하나도 없다" + capacities = [f for f in unit_facts if f["key"] == "standard_capacity"] + assert len({f["unit_id"] for f in capacities}) >= 2, "객실별로 따로 붙어야 한다" + + +async def test_pipeline_stores_media_with_origin_and_pending_review(auth_headers, client): + """검증: 수집된 사진. + 기대결과: origin_url·source_type=crawl 이 남고 PENDING_REVIEW 다 — + ★ 재게시 권리 결론에 따라 통째로 걸러낼 수 있어야 하고, Vision 전이라 사람 확인 큐다.""" + from sqlalchemy import text + + h = await auth_headers("u1") + pid = await _ready_place(client, h, kakao="k4") + job_id = (await client.post(f"/v1/place/{pid}/collect", headers=h, json={})).json()["job_id"] + await _run_worker() + + job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"] + assert job["result"]["media"]["stored"] > 0 + + +async def test_recollect_skips_crawl_when_already_enough(auth_headers, client): + """검증: 필수 항목이 이미 다 찬 사업장에 다시 수집을 건다. + 기대결과: ★ 크롤링을 아예 하지 않는다 — 사이트를 만들 정보가 충분하면 여분의 크롤링은 낭비다.""" + h = await auth_headers("u1") + pid = await _ready_place(client, h, kakao="k5") + + await client.post(f"/v1/place/{pid}/collect", headers=h, json={}) + await _run_worker() + first = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json() + + job_id = (await client.post(f"/v1/place/{pid}/collect", headers=h, json={})).json()["job_id"] + await _run_worker() + job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"] + + assert job["result"]["coverage"]["enough"] is True + assert "크롤링 생략" in job["result"].get("note", "") + assert "fetch" not in job["result"], "충분한데 크롤링을 시도했다" + + second = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json() + assert len(second["facts"]) == len(first["facts"]), "재수집이 fact 를 중복 생성했다" + + +async def test_forced_recollect_is_idempotent(auth_headers, client): + """검증: force=true 로 강제 재수집한다(항목이 이미 차 있어도). + 기대결과: 다시 긁되 fact 는 REFRESHED, 사진은 중복 스킵 — 데이터가 부풀지 않는다.""" + h = await auth_headers("u1") + pid = await _ready_place(client, h, kakao="k5f") + + await client.post(f"/v1/place/{pid}/collect", headers=h, json={}) + await _run_worker() + first = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json() + + job_id = (await client.post(f"/v1/place/{pid}/collect", headers=h, json={"force": True})).json()["job_id"] + await _run_worker() + job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"] + + assert job["result"]["fetch"]["fetched"] == 1, "force 인데 크롤링을 안 했다" + assert job["result"]["media"]["stored"] == 0 + assert job["result"]["media"]["skipped_duplicate"] > 0 + + second = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json() + assert len(second["facts"]) == len(first["facts"]), "재수집이 fact 를 중복 생성했다" + + +async def test_coverage_reports_missing_required_fields(auth_headers, client): + """검증: 수집 후 필수 항목 충족도. + 기대결과: coverage 에 required/covered/missing 이 담긴다 — UI 가 '뭐가 비었나'를 보여줄 수 있다.""" + h = await auth_headers("u1") + pid = await _ready_place(client, h, kakao="k5c") + + job_id = (await client.post(f"/v1/place/{pid}/collect", headers=h, json={})).json()["job_id"] + await _run_worker() + cov = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]["result"]["coverage"] + + assert cov["total"] > 0 + assert cov["covered"] == cov["total"] + assert cov["missing"] == [] + assert "check_in_time" in cov["required"] + + +async def test_recollect_does_not_touch_verified_value(auth_headers, client): + """검증: 수집값을 사람이 승인한 뒤 다시 수집한다. + 기대결과: 값이 같으므로 REFRESHED — ★ 사이트에 나가던 사실이 사라지지 않는다.""" + h = await auth_headers("u1") + pid = await _ready_place(client, h, kakao="k6") + await client.post(f"/v1/place/{pid}/collect", headers=h, json={}) + await _run_worker() + + facts = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()["facts"] + target = next(f for f in facts if f["key"] == "check_in_time") + await client.post(f"/v1/place/{pid}/fact/{target['fact_id']}/transition", headers=h, + json={"status": FactStatus.VERIFIED.value}) + assert (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()["publishable"] == 1 + + await client.post(f"/v1/place/{pid}/collect", headers=h, json={}) + await _run_worker() + + after = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json() + assert after["publishable"] == 1, "★ 재수집이 확인된 값을 밀어냈다" + check_in = [f for f in after["facts"] if f["key"] == "check_in_time"] + assert len(check_in) == 1 and check_in[0]["status"] == FactStatus.VERIFIED.value + + +async def test_recollect_cannot_overwrite_corrected_value(auth_headers, client): + """검증: 사장님이 정정한 값에 재수집이 다른 값을 들고 온다. + 기대결과: 노출값은 정정본 그대로, 크롤링 값은 후보로만 남는다 — ★ 절대규칙 6.""" + h = await auth_headers("u1") + pid = await _ready_place(client, h, kakao="k7") + await client.post(f"/v1/place/{pid}/collect", headers=h, json={}) + await _run_worker() + + facts = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json()["facts"] + target = next(f for f in facts if f["key"] == "check_in_time") + fid = target["fact_id"] + await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h, json={"status": FactStatus.VERIFIED.value}) + await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h, + json={"status": FactStatus.CORRECTED.value, "value": "16:30"}) + + await client.post(f"/v1/place/{pid}/collect", headers=h, json={}) + await _run_worker() + + published = (await client.get(f"/v1/place/{pid}/fact/list", headers=h, params={"publishable_only": True})).json()["facts"] + check_in = [f for f in published if f["key"] == "check_in_time"] + assert len(check_in) == 1 + assert check_in[0]["value"] == "16:30", "★ 자동 수집이 사장님 정정본을 덮어썼다" + assert check_in[0]["status"] == FactStatus.CORRECTED.value + + +async def test_pipeline_refuses_unverified_place(db_engine, company_id): + """검증: 검증 안 된 사업장의 수집 잡이 큐에 직접 들어간 경우(잡 적재 후 검증이 취소된 상황). + 기대결과: 잡이 실패한다 — ★ 잡 실행 시점에도 게이트를 다시 확인한다.""" + from sqlalchemy import text + + pid = uuid.uuid4() + async with db_engine.begin() as conn: + await conn.execute( + text("INSERT INTO places (place_id, company_id, name, category, status) " + "VALUES (:pid, :cid, :n, 1, 1)"), + {"pid": pid, "cid": uuid.UUID(company_id), "n": "미검증펜션"}, + ) + + q = JobQueue() + job_id = await q.enqueue(JobType.COLLECT.value, {"place_id": str(pid), "company_id": company_id}, max_attempts=1) + worker = Worker("test-worker", q, build_handler(), backoff_fn=lambda _a: 0) + await worker.process_one() + + row = await q.get(job_id) + assert row["status"] == JobStatus.DEAD.value + assert "동일 업소 검증" in row["last_error"] diff --git a/backend/tests/test_collector.py b/backend/tests/test_collector.py new file mode 100644 index 0000000..bb5fb04 --- /dev/null +++ b/backend/tests/test_collector.py @@ -0,0 +1,352 @@ +"""수집 어댑터 계약 — 어디서 긁어오든 결과 모양이 같은지, 그리고 법무 게이트가 코드로 지켜지는지. + +가장 중요한 것 두 개: + 1. 목데이터의 fact key 가 전부 업종 스키마에 있는가 + — 없는 key 는 FACT_INVALID_KEY 로 전부 거부되므로, 어긋나면 목데이터가 파이프라인을 하나도 검증하지 못한다 + 2. Phase 1 에 실제 크롤 어댑터가 등록돼 있지 않은가 + — 법적 검토 결론 전까지 크롤이 돌면 안 된다(docs/DECISIONS.md 1-1) + +DB 를 쓰지 않는 순수 단위 테스트다. +""" +import pytest + +from common.category_schema import get_schema +from common.enums import LinkChannel, PlaceCategory +from services.collector import ( + AdapterDisabled, + AdapterNotFound, + AdapterRegistry, + CollectedFact, + CollectedMedia, + CollectError, + MockAdapter, + RawSource, + adapter_ids, + get_adapter, +) +from services.collector.registry import REGISTRY + +# 어떤 어댑터도 처리하면 안 되는 URL — 조용히 빈 결과를 주지 않고 AdapterNotFound 로 끊어야 한다. +# ★ 네이버 플레이스는 2026-08-27 부터 naver_place 어댑터가 처리하므로 여기서 뺐다. +# ★ 일반 도메인(example.co.kr)도 2026-08-28 부터 static_html 이 처리하므로 뺐다. +# 여기 남은 것은 **수집 불가 결론이 난 곳**이다(docs/DATA_SOURCE_RESEARCH.md): +# 야놀자·여기어때는 403 + Cloudflare 로 막혀 있고 민사 10억 선례가 있다. +# 카카오맵은 내부 API 406. 인스타는 Graph API(사장님 OAuth)로만 간다. +_REAL_URLS = ( + "https://www.yanolja.com/pension/1000", + "https://www.goodchoice.kr/product/detail/1000", + "https://place.map.kakao.com/26338954", + "https://www.instagram.com/some_cafe", +) + + +# ── 목데이터 ↔ 업종 스키마 정합성 (제일 중요) ──────────────────────────── +@pytest.mark.parametrize("category", list(PlaceCategory)) +async def test_mock_fact_keys_exist_in_category_schema(category): + """검증: MockAdapter 가 뱉는 fact key 를 업종 스키마와 대조한다. + 기대결과: 전부 스키마에 존재한다 — 없는 key 는 fact 기록에서 전부 거부돼 목데이터가 무의미해진다.""" + schema = get_schema(category) + source = await MockAdapter().fetch(MockAdapter.url_for(category)) + + assert source.ok is True + assert source.facts, f"{schema.name}: 목데이터 fact 가 비었다" + for fact in source.facts: + assert schema.has(fact.key), f"{schema.name} 스키마에 없는 key={fact.key}" + + +@pytest.mark.parametrize("category", list(PlaceCategory)) +async def test_mock_fact_scope_matches_schema(category): + """검증: fact 의 scope 가 스키마 정의와 같은지. + 기대결과: place 필드는 place 로, unit 필드는 unit(+단위 이름)으로 수집된다. + scope 가 어긋나면 객실별 값이 사업장 값으로 뭉개진다.""" + schema = get_schema(category) + source = await MockAdapter().fetch(MockAdapter.url_for(category)) + + for fact in source.facts: + assert fact.scope == schema.get(fact.key).scope, f"{schema.name}.{fact.key}: scope 불일치" + if fact.scope == "unit": + assert fact.unit_name, f"{schema.name}.{fact.key}: unit 스코프인데 단위 이름이 없다" + + +@pytest.mark.parametrize("category", list(PlaceCategory)) +async def test_mock_does_not_collect_llm_written_fields(category): + """검증: 수집물에 소개문 계열(allow_llm=True) 필드가 섞이는지. + 기대결과: 없다 — 소개문은 수집하는 사실이 아니라 generator 가 쓰는 문장이다(절대규칙 7).""" + schema = get_schema(category) + source = await MockAdapter().fetch(MockAdapter.url_for(category)) + + llm_keys = set(schema.llm_writable_keys()) + collected = {f.key for f in source.facts} + assert not (collected & llm_keys), f"{schema.name}: 수집물에 LLM 작성 필드가 섞였다 — {collected & llm_keys}" + + +@pytest.mark.parametrize("category", list(PlaceCategory)) +async def test_mock_returns_three_to_five_photos(category): + """검증: 사진 수집 결과. + 기대결과: 3~5장. Gemini Vision 배치 처리를 물려볼 수 있는 최소량이다.""" + source = await MockAdapter().fetch(MockAdapter.url_for(category)) + assert 3 <= len(source.media) <= 5, f"사진 {len(source.media)}장" + for item in source.media: + assert item.origin_url.startswith("http") + + +async def test_mock_is_deterministic(): + """검증: 같은 URL 로 두 번 수집한다. + 기대결과: fact·사진이 동일하다 — 목데이터가 흔들리면 파이프라인 테스트가 못 믿을 게 된다.""" + adapter = MockAdapter() + url = MockAdapter.url_for(PlaceCategory.LODGING) + first, second = await adapter.fetch(url), await adapter.fetch(url) + + assert [(f.key, f.value, f.unit_name) for f in first.facts] == [(f.key, f.value, f.unit_name) for f in second.facts] + assert [m.origin_url for m in first.media] == [m.origin_url for m in second.media] + + +async def test_mock_reads_category_and_channel_from_url(): + """검증: URL 에서 업종·채널을 읽는지. + 기대결과: 업종별로 다른 목데이터가 나오고, ?channel= 로 채널이 지정된다.""" + adapter = MockAdapter() + lodging = await adapter.fetch("mock://lodging/p1") + cafe = await adapter.fetch("mock://cafe/c1?channel=naver_place") + + assert "check_in_time" in lodging.fact_map() + assert "break_time" in cafe.fact_map() + assert lodging.channel is LinkChannel.ETC + assert cafe.channel is LinkChannel.NAVER_PLACE + + +async def test_mock_unknown_category_fails_softly(): + """검증: 업종을 못 읽는 mock URL. + 기대결과: 예외가 아니라 ok=False 결과 — 채널 하나가 이상해도 나머지 수집이 멈추면 안 된다.""" + source = await MockAdapter().fetch("mock://unknown/x1") + assert source.ok is False + assert source.error and "업종" in source.error + assert source.facts == [] + + +# ── can_handle / 레지스트리 ────────────────────────────────────────────── +def test_can_handle_accepts_mock_urls_only(): + """검증: MockAdapter 의 처리 범위. + 기대결과: mock:// 와 mock.test 만 받고 실제 사이트 URL 은 거부한다.""" + adapter = MockAdapter() + assert adapter.can_handle("mock://lodging/1") is True + assert adapter.can_handle("https://mock.test/cafe/1") is True + for url in _REAL_URLS: + assert adapter.can_handle(url) is False, f"MockAdapter 가 실제 URL 을 처리하려 한다: {url}" + assert adapter.can_handle("") is False + + +def test_registry_resolves_mock_url(): + """검증: 레지스트리로 어댑터를 찾는다. + 기대결과: mock URL 은 MockAdapter 로 해결된다.""" + assert get_adapter("mock://lodging/1").id == "mock" + + +@pytest.mark.parametrize("url", _REAL_URLS) +def test_registry_raises_for_unhandled_url(url): + """검증: 등록된 어댑터가 처리 못 하는 URL 을 조회한다. + 기대결과: AdapterNotFound — 조용히 빈 결과를 돌려주지 않는다.""" + with pytest.raises(AdapterNotFound): + get_adapter(url) + + +def test_registry_rejects_duplicate_adapter_id(): + """검증: 같은 id 의 어댑터를 두 번 등록한다. + 기대결과: ValueError — 어느 쪽이 쓰이는지 모르는 상태를 만들지 않는다.""" + registry = AdapterRegistry() + registry.register(MockAdapter()) + with pytest.raises(ValueError): + registry.register(MockAdapter()) + + +def test_disabled_adapter_is_blocked(): + """검증: 등록은 됐지만 ENABLED 목록에 없는 어댑터를 조회한다. + 기대결과: AdapterDisabled — 등록과 사용 허가를 분리해 실수로 켜지지 않게 한다.""" + registry = AdapterRegistry(enabled=frozenset()) + registry.register(MockAdapter()) + with pytest.raises(AdapterDisabled): + registry.get_adapter("mock://lodging/1") + assert registry.can_handle("mock://lodging/1") is False + + +# ── 법무 게이트 (Phase 1) ──────────────────────────────────────────────── +def test_registers_only_reviewed_adapters(): + """검증: 기본 레지스트리에 등록된 어댑터 목록. + + 기대결과: 검토를 거쳐 명시적으로 승인한 것만 있다. 이 목록이 늘어나는 것은 + **의도된 결정이어야** 하므로, 코드가 몰래 늘어나면 여기서 깨진다.""" + assert adapter_ids() == ["naver_place", "tour_api", "mock", "static_html"], ( + f"예상 밖 어댑터가 등록됐다: {adapter_ids()} — 승인 없이 수집 대상을 늘리지 않는다" + ) + + +def test_static_html_is_registered_last(): + """검증: 넓은 어댑터(static_html)가 좁은 어댑터보다 뒤에 있는가. + + 기대결과: 목록의 맨 끝. 앞에 있으면 http(s) 를 통째로 받는 static_html 이 + 네이버 플레이스 URL 까지 가로채 naver_place 가 영영 안 불린다.""" + assert adapter_ids()[-1] == "static_html", ( + f"static_html 은 맨 뒤여야 한다: {adapter_ids()}" + ) + + +def test_static_html_never_touches_blocked_platforms(): + """검증: 수집 불가 결론이 난 플랫폼 URL 을 static_html 에 직접 물어본다. + + 기대결과: 전부 False. static_html 의 정당성은 '사장님이 확정한 자기 홈페이지만 본다' 에서 + 나오므로, 플랫폼 URL 이 흘러들어오면 정당성이 통째로 깨진다. 운영자가 실수로 넣어도 + 구조적으로 막혀야 한다(docs/DATA_SOURCE_RESEARCH.md).""" + from services.collector.static_html_adapter import StaticHtmlAdapter + + adapter = StaticHtmlAdapter() + for url in ( + "https://www.yanolja.com/pension/1000", # 403 + 민사 10억 선례 + "https://nol.yanolja.com/hotels/1", + "https://www.goodchoice.kr/product/detail?ano=1", + "https://m.place.naver.com/restaurant/1/home", # robots Disallow: / · 전용 어댑터 있음 + "https://blog.naver.com/somepension", + "https://place.map.kakao.com/26338954", # 내부 API 406 + "https://www.instagram.com/some_cafe", # Graph API(OAuth)로만 + "https://app.catchtable.co.kr/ct/shop/x", + ): + assert adapter.can_handle(url) is False, f"건드리면 안 되는 URL 을 받았다: {url}" + + +def test_static_html_takes_owner_domains(): + """검증: 사장님 자체 홈페이지로 보이는 평범한 도메인. + + 기대결과: static_html 이 받는다. 숙박 표본의 76%가 자체 도메인을 쓰므로 + 여기서 놓치면 숙박 수집이 통째로 비어버린다.""" + for url in ("https://gangmunstay.kr/rooms", "https://offinghouse.com/", "https://www.mulhoe.co.kr/"): + assert get_adapter(url).id == "static_html", f"static_html 이 받지 않는다: {url}" + + +def test_adapters_do_not_collect_llm_written_fields(): + """검증: **등록된 모든 어댑터**가 만드는 fact key 에 allow_llm=True 필드가 섞이는지. + + 기대결과: 없다. 소개문 계열은 수집하는 사실이 아니라 generator 가 쓰는 문장이다(절대규칙 7). + + ★ 실측 사고 (2026-08-31) — 이 테스트가 MockAdapter 만 보고 있어서 놓쳤다. + tour_api·naver_place 가 `intro` 를 수집했고, TourAPI overview 457자가 그대로 + VERIFIED 로 들어가 사장님 사이트의 '숙소 소개' 를 차지했다. Gemini 가 쓴 162자 + 소개문은 PENDING_OWNER 로 뒤에 밀려 영영 안 보였다. + 원문 그대로 싣는 것은 GEO 에서도 복제 콘텐츠라 손해다. + + 그래서 소스를 훑어 확인한다 — 어댑터가 늘어나도 같은 실수를 반복할 수 없게.""" + from pathlib import Path + + banned = set() + for category in PlaceCategory: + banned |= set(get_schema(category).llm_writable_keys()) + assert banned, "allow_llm 필드가 하나도 없다 — 스키마 로딩이 잘못됐다" + + package = Path(__file__).resolve().parents[1] / "services" / "collector" + for path in package.glob("*_adapter.py"): + body = path.read_text(encoding="utf-8") + for key in banned: + for pattern in (f'key="{key}"', f'("{key}",'): + for line in body.splitlines(): + stripped = line.strip() + if pattern in stripped and not stripped.startswith("#"): + raise AssertionError( + f"{path.name}: LLM 작성 필드 '{key}' 를 수집한다 — {stripped[:80]}" + ) + + +@pytest.mark.parametrize("url", _REAL_URLS) +def test_unregistered_sites_are_not_reachable(url): + """검증: 어댑터가 없는 사이트 URL 로 수집을 시도한다. + 기대결과: can_handle 이 False — 확정 링크 거르기 단계에서 크롤링 대상에 오르지 않는다.""" + assert REGISTRY.can_handle(url) is False + + +def test_naver_place_hosts_are_handled(): + """검증: 사람이 실제로 공유하는 네이버 플레이스 주소들. + + 기대결과: 전부 naver_place 가 받는다. 하나라도 빠지면 사장님이 붙여넣은 주소가 + '어댑터없음' 으로 조용히 버려진다 — 실제로 map.naver.com 이 빠져서 그랬다.""" + for url in ( + "https://map.naver.com/p/entry/place/1133638931", + "https://m.place.naver.com/accommodation/1133638931/home", + "https://pcmap.place.naver.com/accommodation/1133638931/home", + "https://naver.me/xxxxxxx", + ): + assert REGISTRY.can_handle(url) is True, f"처리하지 못한다: {url}" + + +def test_no_evasion_code_in_collector_package(): + """검증: 수집 패키지에 우회 코드가 들어왔는지 소스를 훑는다. + 기대결과: 캡차 우회·봇 탐지 우회·IP 회전 흔적이 없다(영구 금지, 검토 결과와 무관).""" + from pathlib import Path + + banned = ("captcha", "solve_captcha", "rotate_ip", "proxy_rotate", "stealth", "undetected") + package = Path(__file__).resolve().parents[1] / "services" / "collector" + for path in package.glob("*.py"): + body = path.read_text(encoding="utf-8").lower() + for token in banned: + # 금지 사실을 적어둔 주석은 허용한다 — 실제 식별자로 쓰였는지만 본다. + for line in body.splitlines(): + stripped = line.strip() + if token in stripped and not stripped.startswith("#"): + raise AssertionError(f"{path.name}: 금지된 우회 코드 흔적 '{token}' — {stripped[:80]}") + + +# ── 출처 강제 ──────────────────────────────────────────────────────────── +async def test_every_fact_and_media_carries_source_url(): + """검증: 수집 결과의 모든 fact·사진이 출처를 들고 있는지. + 기대결과: 전부 RawSource.url 과 같다 — 출처 없는 값은 fact 기록에서 거부된다.""" + url = MockAdapter.url_for(PlaceCategory.LODGING, "pension-9") + source = await MockAdapter().fetch(url) + + assert source.source_url == url + for item in (*source.facts, *source.media): + assert item.source_url == url, f"출처 없이 흘러가는 항목: {item}" + + +def test_raw_source_stamps_source_url_on_bare_items(): + """검증: source_url 을 비운 채 항목을 넣어 RawSource 를 만든다. + 기대결과: 생성 시점에 출처가 찍힌다 — 어댑터가 깜빡해도 구조가 막는다.""" + source = RawSource( + url="mock://lodging/x", + adapter_id="mock", + facts=[CollectedFact(key="wifi", value="true")], + media=[CollectedMedia(origin_url="https://mock.test/img/1.jpg")], + ) + assert source.facts[0].source_url == "mock://lodging/x" + assert source.media[0].source_url == "mock://lodging/x" + + +def test_raw_source_requires_url(): + """검증: url 없이 RawSource 를 만든다. + 기대결과: CollectError — 출처 없는 수집 결과는 존재할 수 없다.""" + with pytest.raises(CollectError): + RawSource(url="", adapter_id="mock") + + +def test_collected_media_requires_origin_url(): + """검증: origin_url 없이 사진을 담는다. + 기대결과: CollectError — 재게시 권리 판단(docs/DECISIONS.md 1-2)에 원본 URL 이 필요하다.""" + with pytest.raises(CollectError): + CollectedMedia(origin_url=" ") + + +def test_unit_scoped_fact_requires_unit_name(): + """검증: 단위 이름 없이 unit 스코프 fact 를 만든다. + 기대결과: CollectError — 어느 객실 값인지 모르면 저장할 수 없다.""" + with pytest.raises(CollectError): + CollectedFact(key="standard_capacity", value="2", scope="unit") + + +async def test_unit_names_are_listed_in_order(): + """검증: 수집된 단위 이름 목록. + 기대결과: 등록 순서대로 중복 없이 나온다 — place.units 시드에 그대로 쓴다.""" + source = await MockAdapter().fetch(MockAdapter.url_for(PlaceCategory.LODGING)) + assert source.unit_names() == ["A동 스탠다드", "B동 복층"] + + +async def test_failure_result_has_no_facts(): + """검증: 실패 결과(RawSource.failure)의 모양. + 기대결과: ok=False, error 존재, fact·사진 없음 — 실패를 성공으로 오인할 수 없다.""" + source = RawSource.failure("mock://lodging/1", "mock", "타임아웃") + assert source.ok is False and source.error == "타임아웃" + assert source.facts == [] and source.media == [] + assert source.source_url == "mock://lodging/1" diff --git a/backend/tests/test_config.py b/backend/tests/test_config.py new file mode 100644 index 0000000..87899bb --- /dev/null +++ b/backend/tests/test_config.py @@ -0,0 +1,22 @@ +"""설정 로딩 — 우선순위와 테스트 격리. + +우선순위: 실제 환경변수 > 레포 최상위 .env > config.{APP_ENV}.toml +.env 에 APP_ENV=local 이 들어 있어도 테스트는 반드시 test DB 를 봐야 한다 — +그 규칙이 깨지면 db_engine 픽스처의 TRUNCATE 가 dev DB 를 지운다. +""" +from config.server_configs import APP_ENV, external_api_config, main_db_config + + +def test_tests_run_against_test_db(): + """검증: 테스트 실행 시 바라보는 DB. + 기대결과: APP_ENV=test, DB 이름에 'test' 포함 — .env 의 APP_ENV=local 에 끌려가지 않는다.""" + assert APP_ENV == "test", f"테스트가 APP_ENV={APP_ENV} 로 돈다 — .env 나 실행 환경을 확인할 것" + assert "test" in main_db_config.name, f"테스트가 비-test DB('{main_db_config.name}')를 가리킨다" + + +def test_external_api_keys_are_absent_in_tests(): + """검증: 테스트 환경의 외부 API 키. + 기대결과: 전부 빈 값 — 테스트가 실제 외부 API 를 때리지 않는다(수집 경로는 MockAdapter 로 검증).""" + for name in ("perplexity_api_key", "kakao_rest_api_key", "gemini_api_key", "tour_api_key"): + # 값 자체는 출력하지 않는다(실키가 로그·CI 에 남지 않게). + assert not getattr(external_api_config, name), f"{name} 이 테스트 환경에 설정돼 있다 — .env 가 새어 들어왔다" diff --git a/backend/tests/test_copy_api.py b/backend/tests/test_copy_api.py new file mode 100644 index 0000000..03f1586 --- /dev/null +++ b/backend/tests/test_copy_api.py @@ -0,0 +1,177 @@ +"""소개문·FAQ 생성 — ★ LLM 은 사실을 만들지 않는다. + +이 잡이 절대 하면 안 되는 것: + - 미검증 fact 를 근거로 문장을 쓰는 것 (그 문장도 미검증이 된다) + - 근거 없이 생성하는 것 (그게 환각이다) + - 생성물을 바로 사이트에 노출하는 것 (사람 승인이 있어야 한다) + - 사람이 확인한 FAQ 를 재생성이 덮어쓰는 것 +""" +import uuid + +from sqlalchemy import text + +from common.enums import ErrorType, FactStatus, JobStatus, SourceType +from crud.job_crud import JobQueue +from services.external import gemini_text +from worker.handlers import build_handler +from worker.runner import Worker + + +def _copy(intro="조용한 숙소입니다.", faqs=None, rejected=None): + return gemini_text.GeneratedCopy( + intro=intro, + intro_fact_keys=["check_in_time"], + meta_description="양양 하조대 펜션", + faqs=faqs if faqs is not None else [ + gemini_text.GeneratedFaq("체크인은 몇 시인가요?", "15시입니다.", ["check_in_time"]), + ], + rejected=rejected or [], + ) + + +def _patch(monkeypatch, copy): + monkeypatch.setattr(gemini_text, "is_configured", lambda: True) + + async def _gen(place_name, category, facts, **kw): + return copy + + monkeypatch.setattr(gemini_text, "generate_copy", _gen) + + +async def _place_with_facts(client, h, n_verified=5): + 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": f"주소{uuid.uuid4().hex[:6]}"}) + keys = ["check_in_time", "check_out_time", "cancel_policy", "cooking_allowed", "pet_allowed"][:n_verified] + for k in keys: + await client.post(f"/v1/place/{pid}/fact", headers=h, json={"key": k, "value": "15:00"}) + return pid + + +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 faqs WHERE place_id = :p ORDER BY sort_order"), + {"p": uuid.UUID(pid)}, + )).all() + + +async def test_copy_generates_intro_and_faq_as_candidates(auth_headers, client, db_engine, monkeypatch): + """검증: 소개문·FAQ 를 생성한다. + 기대결과: 생성되지만 ★ 전부 미검증 — 사람이 승인해야 사이트에 나간다.""" + _patch(monkeypatch, _copy()) + h = await auth_headers("u1") + pid = await _place_with_facts(client, h) + + body = (await client.post(f"/v1/place/{pid}/copy", headers=h, json={})).json() + assert body["result"]["success"] is True + assert body["grounded_facts"] == 5 + + await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).process_one() + 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"]["intro"] is True + assert job["result"]["faqs"] == 1 + + rows = await _faq_rows(db_engine, pid) + assert rows[0][3] == FactStatus.UNVERIFIED.value, "★ 생성된 FAQ 가 바로 노출 상태면 안 된다" + assert rows[0][2] == ["check_in_time"], "근거 fact 가 기록돼야 한다" + + # 소개문도 fact 로 들어가되 미검증 후보다 + facts = (await client.get(f"/v1/place/{pid}/fact/list", headers=h)).json() + intro = [f for f in facts["facts"] if f["key"] == "intro"] + assert intro and intro[0]["status"] == FactStatus.UNVERIFIED.value + assert intro[0]["source_type"] == SourceType.LLM.value + + +async def test_copy_refuses_without_verified_facts(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": "빈주소"}) + + 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 — 미검증 값으로 쓴 문장도 미검증이다.""" + 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": "미검증주소"}) + await client.post(f"/v1/place/{pid}/fact", headers=h, json={ + "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 + + +async def test_faq_without_grounding_is_dropped(auth_headers, client, db_engine, monkeypatch): + """검증: 근거 fact 가 비어 있는 FAQ 가 생성물에 섞여 온다. + 기대결과: 저장하지 않고 반려 목록에 남는다.""" + _patch(monkeypatch, _copy(faqs=[ + gemini_text.GeneratedFaq("체크인은?", "15시입니다.", ["check_in_time"]), + gemini_text.GeneratedFaq("수영장 있나요?", "네 있습니다.", []), + ])) + h = await auth_headers("u1") + pid = await _place_with_facts(client, h) + 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).process_one() + + 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 + + +async def test_rejected_sentences_are_reported(auth_headers, client, monkeypatch): + """검증: 클라이언트가 반려한 문장이 있다. + 기대결과: 잡 result 에 사유와 함께 실린다 — 소개문이 왜 안 나왔는지 알 수 있어야 한다.""" + _patch(monkeypatch, _copy(intro=None, rejected=[("수영장을 갖추고 있습니다", "fact 에 없는 시설 '수영장'")])) + h = await auth_headers("u1") + pid = await _place_with_facts(client, h) + 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).process_one() + + job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"] + assert job["result"]["intro"] is False + assert any("수영장" in str(r) for r in job["result"]["rejected"]) + + +async def test_regeneration_keeps_human_approved_faq(auth_headers, client, db_engine, monkeypatch): + """검증: 사람이 승인한 FAQ 가 있는 상태에서 재생성한다. + 기대결과: ★ 승인된 FAQ 는 남는다 — 재생성이 사람의 판단을 덮어쓰면 안 된다.""" + _patch(monkeypatch, _copy()) + h = await auth_headers("u1") + pid = await _place_with_facts(client, h) + await client.post(f"/v1/place/{pid}/copy", headers=h, json={}) + await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).process_one() + + # 사람이 승인 + async with db_engine.begin() as c: + await c.execute( + text("UPDATE faqs SET status = :s WHERE place_id = :p"), + {"s": FactStatus.VERIFIED.value, "p": uuid.UUID(pid)}, + ) + + _patch(monkeypatch, _copy(faqs=[gemini_text.GeneratedFaq("새 질문?", "새 답변", ["check_in_time"])])) + await client.post(f"/v1/place/{pid}/copy", headers=h, json={}) + await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).process_one() + + rows = await _faq_rows(db_engine, pid) + approved = [r for r in rows if r[3] == FactStatus.VERIFIED.value] + assert approved and approved[0][0] == "체크인은 몇 시인가요?", "★ 승인된 FAQ 가 재생성에 밀려났다" + + +async def test_copy_requires_api_key(auth_headers, client, monkeypatch): + """검증: GEMINI_API_KEY 없이 생성을 시도한다. + 기대결과: GENERATOR_NOT_CONFIGURED — 잡을 만들지 않는다.""" + monkeypatch.setattr(gemini_text, "is_configured", lambda: False) + h = await auth_headers("u1") + pid = await _place_with_facts(client, h) + r = await client.post(f"/v1/place/{pid}/copy", headers=h, json={}) + assert r.json()["result"]["code"] == ErrorType.GENERATOR_NOT_CONFIGURED.value diff --git a/backend/tests/test_cost.py b/backend/tests/test_cost.py new file mode 100644 index 0000000..af1f057 --- /dev/null +++ b/backend/tests/test_cost.py @@ -0,0 +1,96 @@ +"""사이트 1건 원가 미터 — $1 예산이 실제로 호출을 막는지. + +★ 이 테스트가 지키는 제품 제약: 업소 1곳의 사이트 생성 외부 API 비용 <= $1(1,400원). + 예산이 "문서에 적힌 목표" 로만 남지 않게, 가드가 실제로 예외를 던지는지 확인한다. +""" +import pytest + +from common.cost import ( + RATES, + SITE_BUDGET_KRW, + USD_KRW, + BudgetExceeded, + CostMeter, + Provider, + UnconfirmedRate, + assert_rates_confirmed, + estimate_krw, +) + + +def test_budget_is_one_dollar(): + """검증: 예산 상한값. + 기대결과: 1,400원 = $1 — 환율 상수와 예산 상수가 어긋나지 않는다.""" + assert SITE_BUDGET_KRW == USD_KRW + assert CostMeter().budget_krw == SITE_BUDGET_KRW + + +def test_kakao_keyword_search_is_2won(): + """검증: 레포에 확정된 카카오 단가. + 기대결과: 키워드 검색 2원/건, 좌표 변환 0.5원/건 — 좌표가 4배 싸다.""" + assert estimate_krw(Provider.KAKAO, calls=1) == 2.0 + assert estimate_krw(Provider.KAKAO, kakao_coord_calls=1) == 0.5 + assert estimate_krw(Provider.KAKAO, calls=10) == 20.0 + + +def test_free_providers_cost_nothing(): + """검증: 무료 API. + 기대결과: TourAPI·Open-Meteo 는 아무리 불러도 0원.""" + assert estimate_krw(Provider.TOUR_API, calls=100) == 0.0 + assert estimate_krw(Provider.OPEN_METEO, calls=100) == 0.0 + + +def test_guard_blocks_before_the_call(): + """검증: 예산을 넘기는 호출을 '하기 전' 에 막는가. + 기대결과: guard 가 BudgetExceeded — 호출측은 이 호출을 하지 않는다.""" + meter = CostMeter(place_id=1) + meter.charge(Provider.KAKAO, calls=699) # 1,398원 — 상한 코앞 + assert meter.remaining_krw == pytest.approx(2.0) + + meter.guard(Provider.KAKAO, calls=1) # 2원 — 딱 맞으므로 통과 + with pytest.raises(BudgetExceeded): + meter.guard(Provider.KAKAO, calls=2) # 4원 — 넘으므로 차단 + + # ★ guard 는 확인만 한다. 막혔다고 이미 쓴 금액이 변하면 안 된다. + assert meter.spent_krw == pytest.approx(1398.0) + + +def test_charge_raises_after_exceeding_to_stop_the_next_call(): + """검증: 실측을 적었더니 예산을 넘긴 경우. + 기대결과: 금액은 그대로 누적하되 BudgetExceeded — 이미 나간 호출은 못 되돌리고 다음을 막는다.""" + meter = CostMeter(place_id=2) + with pytest.raises(BudgetExceeded): + meter.charge(Provider.KAKAO, calls=1000) # 2,000원 — 한 번에 초과 + assert meter.spent_krw == pytest.approx(2000.0) # 실제로 나간 돈은 그대로 기록된다 + assert meter.remaining_krw == 0.0 + + +def test_meter_tracks_spend_per_provider(): + """검증: 공급자별 누적. + 기대결과: 합계와 공급자별 금액이 일치하고, $ 환산이 맞는다.""" + meter = CostMeter(place_id=3) + meter.charge(Provider.KAKAO, calls=5) # 10원 + meter.charge(Provider.PERPLEXITY, calls=1, tokens=3000) # 7 + 4.2 = 11.2원 + assert meter.by_provider["kakao"] == pytest.approx(10.0) + assert meter.by_provider["perplexity"] == pytest.approx(11.2) + assert meter.spent_krw == pytest.approx(21.2) + assert meter.spent_usd == pytest.approx(21.2 / USD_KRW) + assert meter.calls == 2 + + +def test_unconfirmed_rates_block_a_real_batch(): + """검증: 추정 단가로 실배치를 돌리려 할 때. + 기대결과: UnconfirmedRate — 추정치 위에 세운 '예산 안' 결론을 막는다.""" + assert_rates_confirmed( + Provider.KAKAO, Provider.PERPLEXITY, Provider.TOUR_API, Provider.OPEN_METEO + ) # 확정분은 통과 + with pytest.raises(UnconfirmedRate): + assert_rates_confirmed() # 전체 — 미확인이 섞여 있으므로 막힌다 + + +def test_rate_table_declares_its_source(): + """검증: 단가표의 출처 표기. + 기대결과: 확정 단가에는 출처가 적혀 있다 — 어디서 온 숫자인지 추적 가능해야 한다.""" + for provider, rate in RATES.items(): + if rate.confirmed: + assert rate.source, f"{provider.value} 단가가 확정인데 출처가 비어 있다" diff --git a/backend/tests/test_extract_grounding.py b/backend/tests/test_extract_grounding.py new file mode 100644 index 0000000..2ce0304 --- /dev/null +++ b/backend/tests/test_extract_grounding.py @@ -0,0 +1,206 @@ +"""추출 검증 게이트 — "AI 가 원문에서 찾아온 것인가, 지어낸 것인가". + +URL·붙여넣기 추출(services/external/gemini_extract.py)의 안전장치는 프롬프트가 아니라 +services/grounding/extract.py 의 evidence 대조다. 프롬프트로 "지어내지 마라" 를 아무리 적어도 +그건 부탁이지 보장이 아니다. + +**이 파일이 깨지면 추출 경로를 끄는 것이 맞다.** 통과 못 한 값이 fact 후보로 올라가면 +사장님이 확인 화면에서 "네" 를 누르는 순간 환각이 발행본에 실린다. + +DB 도 네트워크도 쓰지 않는 순수 단위 테스트다. +""" +import pytest + +from common.category_schema import get_schema +from common.enums import PlaceCategory +from services.grounding.extract import MIN_EVIDENCE, loose, normalize, verify + +_LODGING = get_schema(PlaceCategory.LODGING) +_RESTAURANT = get_schema(PlaceCategory.RESTAURANT) + +_SOURCE = ( + "강문스테이는 강릉 경포해변 도보 3분 거리에 있는 독채 펜션입니다. " + "체크인은 오후 3시, 체크아웃은 오전 11시입니다. " + "전 객실 무료 주차가 가능하며, 무선인터넷을 제공합니다. " + "반려동물 동반은 불가합니다. " + "바비큐장은 별도 요금 20,000원으로 이용하실 수 있습니다. " + "오션뷰룸은 기준 2인, 최대 4인까지 이용 가능합니다." +) + + +def _one(row: dict, *, source: str = _SOURCE, schema=_LODGING): + passed, rejected = verify([row], source_text=source, schema=schema) + return passed, rejected + + +# ── 통과해야 하는 것 ────────────────────────────────────────────────────── +def test_accepts_value_copied_verbatim(): + """검증: 원문 표기 그대로 옮긴 값. + 기대결과: 통과. 이게 추출의 정상 경로다.""" + passed, rejected = _one({ + "key": "check_in_time", "value": "오후 3시", + "evidence": "체크인은 오후 3시, 체크아웃은 오전 11시입니다.", + }) + assert not rejected + assert passed[0]["value"] == "오후 3시" + assert passed[0]["scope"] == "place" + + +def test_accepts_number_written_with_comma_in_source(): + """검증: 원문은 "20,000원" 인데 number 필드라 값은 "20000" 으로 온다. + + 기대결과: 통과. ★ 실측 회귀 — loose() 가 없던 때 속초항아리물회 홈페이지에서 + 메뉴 가격 5건이 통째로 '고쳐 쓴 값' 으로 반려됐다. 쉼표는 같은 수를 다르게 적은 것뿐이다.""" + passed, rejected = _one({ + "key": "bbq_fee", "value": "20000", + "evidence": "바비큐장은 별도 요금 20,000원으로 이용하실 수 있습니다.", + }) + assert not rejected, rejected + assert passed[0]["value"] == "20000" + + +def test_accepts_unit_scope_with_name(): + """검증: 객실 단위 fact 가 unit_name 을 달고 온다. + 기대결과: 통과하고 scope/unit_name 이 보존된다 — ensure_units 가 이걸로 객실을 만든다.""" + passed, rejected = _one({ + "key": "standard_capacity", "value": "2", "unit_name": "오션뷰룸", + "evidence": "오션뷰룸은 기준 2인, 최대 4인까지 이용 가능합니다.", + }) + assert not rejected + assert passed[0]["scope"] == "unit" and passed[0]["unit_name"] == "오션뷰룸" + + +def test_accepts_negative_bool_when_source_is_negative(): + """검증: 원문이 "불가" 이고 값도 false. + 기대결과: 통과. '없다' 도 사실이다 — 명시된 부정은 담는다.""" + passed, rejected = _one({ + "key": "pet_allowed", "value": "false", + "evidence": "반려동물 동반은 불가합니다.", + }) + assert not rejected + assert passed[0]["value"] == "false" + + +# ── 막아야 하는 것 (여기가 본론) ────────────────────────────────────────── +def test_blocks_evidence_not_in_source(): + """검증: 원문에 없는 문장을 근거로 들이민다(순수 환각). + 기대결과: 반려. **이 검사가 이 게이트의 존재 이유다.**""" + passed, rejected = _one({ + "key": "breakfast", "value": "true", + "evidence": "조식은 오전 8시부터 제공됩니다.", + }) + assert not passed + assert "원문에 없다" in rejected[0][1] + + +def test_blocks_flipped_bool_polarity(): + """검증: 근거는 "불가" 인데 값을 true 로 올린다. + + 기대결과: 반려. ★ 부호가 뒤집히면 "반려동물 동반 불가" 가 "동반 가능" 이 된다 — + critical 항목이라 그대로 예약 클레임이다.""" + passed, rejected = _one({ + "key": "pet_allowed", "value": "true", + "evidence": "반려동물 동반은 불가합니다.", + }) + assert not passed + assert "부정인데 true" in rejected[0][1] + + +def test_blocks_converted_value(): + """검증: 원문은 "오후 3시" 인데 값을 "15:00" 으로 환산해 올린다. + + 기대결과: 반려. 환산은 옮겨 적기가 아니다 — 한 번 허용하면 단위·통화·시간대까지 + 모델이 손대기 시작하고, 그 오차는 원문 대조로 잡히지 않는다.""" + passed, rejected = _one({ + "key": "check_in_time", "value": "15:00", + "evidence": "체크인은 오후 3시, 체크아웃은 오전 11시입니다.", + }) + assert not passed + assert "근거 문장 안에 없다" in rejected[0][1] + + +def test_blocks_key_outside_category_schema(): + """검증: 업종 스키마에 없는 key. + 기대결과: 반려. fact 기록 단계에서도 거부되지만, 여기서 걸러야 반려 사유가 남는다.""" + passed, rejected = _one({ + "key": "michelin_star", "value": "2", + "evidence": "강문스테이는 강릉 경포해변 도보 3분 거리에 있는 독채 펜션입니다.", + }) + assert not passed + assert "스키마에 없는 key" in rejected[0][1] + + +def test_blocks_unit_fact_without_unit_name(): + """검증: unit 스코프 필드인데 unit_name 이 비었다. + 기대결과: 반려. 어느 객실 것인지 모르는 값은 화면에 붙일 자리가 없다.""" + passed, rejected = _one({ + "key": "max_capacity", "value": "4", + "evidence": "오션뷰룸은 기준 2인, 최대 4인까지 이용 가능합니다.", + }) + assert not passed + assert "unit_name" in rejected[0][1] + + +def test_blocks_non_numeric_value_in_number_field(): + """검증: number 필드에 "최대 4인" 같은 문장이 들어온다. + 기대결과: 반려. 화면·JSON-LD 가 숫자로 다루는 자리라 문자열이 섞이면 렌더가 깨진다.""" + passed, rejected = _one({ + "key": "max_capacity", "value": "최대 4인", "unit_name": "오션뷰룸", + "evidence": "오션뷰룸은 기준 2인, 최대 4인까지 이용 가능합니다.", + }) + assert not passed + assert "숫자가 아니다" in rejected[0][1] + + +@pytest.mark.parametrize("evidence", ["", "3", "펜션"]) +def test_blocks_evidence_too_short_to_verify(evidence): + """검증: 근거가 너무 짧아 원문 어디에나 있는 경우. + + 기대결과: 반려. "3" 은 원문 아무 데나 있으므로 대조가 통과해도 아무것도 보장하지 못한다.""" + passed, rejected = _one({"key": "check_in_time", "value": "오후 3시", "evidence": evidence}) + assert not passed + assert len(evidence) < MIN_EVIDENCE + + +def test_blocks_duplicate_key_for_same_unit(): + """검증: 같은 (key, unit) 이 두 번 온다. + 기대결과: 첫 건만 통과. 같은 자리에 두 값이 들어가면 어느 쪽이 발행될지 알 수 없다.""" + rows = [ + {"key": "check_in_time", "value": "오후 3시", "evidence": "체크인은 오후 3시, 체크아웃은 오전 11시입니다."}, + {"key": "check_in_time", "value": "오전 11시", "evidence": "체크인은 오후 3시, 체크아웃은 오전 11시입니다."}, + ] + passed, rejected = verify(rows, source_text=_SOURCE, schema=_LODGING) + assert len(passed) == 1 and passed[0]["value"] == "오후 3시" + assert "이미 들어왔다" in rejected[0][1] + + +# ── 정규화가 부호를 지우지 않는가 ───────────────────────────────────────── +def test_normalization_never_drops_negation_words(): + """검증: 대조용 정규화가 "불가" 같은 부정어를 지우지 않는가. + + 기대결과: 남아 있다. ★ 정규화가 글자를 지우기 시작하면 부정이 긍정으로 뒤집힌다 — + normalize/loose 는 공백·문장부호·쉼표만 건드려야 한다.""" + for text in ("반려동물 동반은 불가합니다.", "취사 불가능", "주차 없음"): + for fn in (normalize, loose): + out = fn(text) + assert any(w in out for w in ("불가", "없음")), f"{fn.__name__} 이 부정어를 지웠다: {out}" + + +def test_loose_only_strips_commas_and_spaces(): + """검증: loose() 가 쉼표·공백 외의 글자를 건드리지 않는가. + 기대결과: 숫자와 단위가 그대로 남는다.""" + assert loose("20,000 원") == "20000원" + assert loose("최대 4인") == "최대4인" + + +# ── 업종이 다르면 통과 여부도 달라야 한다 ───────────────────────────────── +def test_same_key_gated_by_category_schema(): + """검증: 숙박 전용 key 를 음식점 스키마로 검증한다. + + 기대결과: 반려. 업종 스키마가 유일한 출처이므로, 업종이 바뀌면 허용 key 도 바뀐다.""" + row = {"key": "check_in_time", "value": "오후 3시", + "evidence": "체크인은 오후 3시, 체크아웃은 오전 11시입니다."} + ok_lodging, _ = _one(row) + ok_restaurant, rejected = _one(row, schema=_RESTAURANT) + assert ok_lodging and not ok_restaurant + assert "스키마에 없는 key" in rejected[0][1] diff --git a/backend/tests/test_fact_api.py b/backend/tests/test_fact_api.py new file mode 100644 index 0000000..91a0bfc --- /dev/null +++ b/backend/tests/test_fact_api.py @@ -0,0 +1,280 @@ +"""facts 도메인 e2e — 생성 / 업데이트(재수집) / 수정 세 프로세스. + +이 도메인이 지켜야 하는 것: + 생성 : 자동 수집 → 후보 → 사람 승인 → 노출. 미검증은 절대 사이트에 안 나간다 + 업데이트: ★ 재수집이 노출 중인 사실을 밀어내지 않는다 + 값이 같으면 검증 유지, 다르면 후보로 쌓이고 사람이 승인해야 교체된다 + 수정 : 사람이 직접 넣으면 즉시 노출값 교체 + 재빌드 대상 표시 +""" +from common.enums import ErrorType, FactStatus, FactWriteOutcome, PlaceCategory, SourceType + +OTA = "https://ota.test/room/1" + + +async def _verified_place(client, headers, category=PlaceCategory.LODGING, kakao="999"): + r = await client.post("/v1/place", headers=headers, json={"name": "테스트업소", "category": category.value}) + pid = r.json()["place"]["place_id"] + await client.post(f"/v1/place/{pid}/verify", headers=headers, json={"external_place_id": kakao}) + return pid + + +async def _crawl(client, headers, pid, key, value, source=SourceType.CRAWL): + return (await client.post(f"/v1/place/{pid}/fact", headers=headers, json={ + "key": key, "value": value, "source_type": source.value, "source_url": OTA, + })).json() + + +async def _own(client, headers, pid, key, value): + return (await client.post(f"/v1/place/{pid}/fact", headers=headers, json={ + "key": key, "value": value, "source_type": SourceType.OWNER.value, + })).json() + + +async def _facts(client, headers, pid, **params): + return (await client.get(f"/v1/place/{pid}/fact/list", headers=headers, params=params)).json() + + +# ── 입력 검증 ──────────────────────────────────────────────────────────── +async def test_schema_endpoint_returns_category_fields(auth_headers, client): + """검증: 숙박 사업장의 fact 스키마 조회. + 기대결과: 업종=lodging, 체크인시간이 critical=True 로 내려온다(관리 화면 폼 생성용).""" + h = await auth_headers("u1") + pid = await _verified_place(client, h) + + body = (await client.get(f"/v1/place/{pid}/fact/schema", headers=h)).json() + assert body["category"] == "lodging" + check_in = next(f for f in body["fields"] if f["key"] == "check_in_time") + assert check_in["critical"] is True + assert check_in["allow_llm"] is False + + +async def test_key_outside_category_schema_is_rejected(auth_headers, client): + """검증: 카페 사업장에 숙박 전용 key(check_in_time)를 기록한다. + 기대결과: FACT_INVALID_KEY — 업종에 없는 필드는 저장되지 않는다.""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, PlaceCategory.CAFE, kakao="c1") + + body = await _own(client, h, pid, "check_in_time", "15:00") + assert body["result"]["code"] == ErrorType.FACT_INVALID_KEY.value + + +async def test_non_owner_source_requires_source_url(auth_headers, client): + """검증: crawl 출처인데 source_url 없이 기록한다. + 기대결과: FACT_SOURCE_REQUIRED — 출처 없는 사실은 받지 않는다.""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="s1") + + r = await client.post(f"/v1/place/{pid}/fact", headers=h, json={ + "key": "check_in_time", "value": "15:00", "source_type": SourceType.CRAWL.value}) + assert r.json()["result"]["code"] == ErrorType.FACT_SOURCE_REQUIRED.value + + +async def test_llm_cannot_write_non_sentence_fields(auth_headers, client): + """검증: LLM 출처로 체크인시간(allow_llm=False)을 기록한다. + 기대결과: 거부 — ★ LLM 은 사실을 만들지 않는다. 소개문(intro)에는 쓸 수 있다.""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="l1") + + body = await _crawl(client, h, pid, "check_in_time", "15:00", SourceType.LLM) + assert body["result"]["code"] == ErrorType.FACT_INVALID_KEY.value + + body = await _crawl(client, h, pid, "intro", "조용한 숙소입니다.", SourceType.LLM) + assert body["result"]["success"] is True + + +# ── 생성 프로세스 ───────────────────────────────────────────────────────── +async def test_crawled_fact_starts_as_candidate_and_is_not_published(auth_headers, client): + """검증: 크롤링으로 처음 들어온 값. + 기대결과: UNVERIFIED 후보로 남고 사이트에 안 나간다 — ★ 절대규칙 1.""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="p1") + + body = await _crawl(client, h, pid, "check_in_time", "15:00") + assert body["outcome"] == FactWriteOutcome.CANDIDATE_CREATED.value + assert body["fact"]["status"] == FactStatus.UNVERIFIED.value + + listed = await _facts(client, h, pid) + assert listed["publishable"] == 0 + assert (await _facts(client, h, pid, publishable_only=True)).get("facts", []) == [] + + +async def test_approving_candidate_publishes_it(auth_headers, client): + """검증: 후보를 VERIFIED 로 승인한다. + 기대결과: verified_at 이 찍히고 사이트에 나갈 수 있게 된다.""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="p2") + fid = (await _crawl(client, h, pid, "check_in_time", "15:00"))["fact"]["fact_id"] + + body = (await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h, + json={"status": FactStatus.VERIFIED.value})).json() + assert body["result"]["success"] is True + assert body["fact"]["status"] == FactStatus.VERIFIED.value + assert body["fact"]["verified_at"] is not None + assert (await _facts(client, h, pid))["publishable"] == 1 + + +async def test_illegal_transition_is_rejected(auth_headers, client): + """검증: UNVERIFIED → CORRECTED 처럼 전이표에 없는 이동. + 기대결과: FACT_INVALID_TRANSITION — 확인을 건너뛴 '정정본'은 만들 수 없다.""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="p3") + fid = (await _crawl(client, h, pid, "check_in_time", "15:00"))["fact"]["fact_id"] + + r = await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h, + json={"status": FactStatus.CORRECTED.value, "value": "16:00"}) + assert r.json()["result"]["code"] == ErrorType.FACT_INVALID_TRANSITION.value + + +# ── 업데이트(재수집) 프로세스 ★ ─────────────────────────────────────────── +async def test_recrawl_same_value_keeps_verification(auth_headers, client): + """검증: 확인된 값과 똑같은 값을 재수집한다. + 기대결과: REFRESHED — 검증이 유지되고 사이트에서 사실이 사라지지 않는다.""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="r1") + fid = (await _crawl(client, h, pid, "check_in_time", "15:00"))["fact"]["fact_id"] + await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h, json={"status": FactStatus.VERIFIED.value}) + assert (await _facts(client, h, pid))["publishable"] == 1 + + body = await _crawl(client, h, pid, "check_in_time", "15:00") + assert body["outcome"] == FactWriteOutcome.REFRESHED.value + assert body["fact"]["status"] == FactStatus.VERIFIED.value + assert (await _facts(client, h, pid))["publishable"] == 1, "★ 재수집이 검증을 초기화하면 안 된다" + + +async def test_recrawl_changed_value_keeps_site_and_queues_candidate(auth_headers, client): + """검증: 확인된 값과 다른 값을 재수집한다(OTA 가 바뀐 경우). + 기대결과: ★ 노출값은 그대로 살아 있고, 새 값은 PENDING_OWNER 후보로만 쌓인다.""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="r2") + fid = (await _crawl(client, h, pid, "check_in_time", "15:00"))["fact"]["fact_id"] + await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h, json={"status": FactStatus.VERIFIED.value}) + + body = await _crawl(client, h, pid, "check_in_time", "16:00") + assert body["outcome"] == FactWriteOutcome.CANDIDATE_CREATED.value + assert body["fact"]["status"] == FactStatus.PENDING_OWNER.value + + listed = await _facts(client, h, pid) + assert listed["publishable"] == 1, "★ 재수집 중에도 사이트에는 확인된 값이 계속 나가야 한다" + assert listed["pending_review"] == 1 + published = (await _facts(client, h, pid, publishable_only=True))["facts"] + assert published[0]["value"] == "15:00" + + +async def test_approving_candidate_replaces_published_value(auth_headers, client): + """검증: 쌓인 후보를 사람이 승인한다(업데이트의 마지막 단계). + 기대결과: 후보가 노출값이 되고 옛 값은 EXPIRED 이력으로 내려간다. 노출값은 여전히 1건.""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="r3") + old = (await _crawl(client, h, pid, "check_in_time", "15:00"))["fact"]["fact_id"] + await client.post(f"/v1/place/{pid}/fact/{old}/transition", headers=h, json={"status": FactStatus.VERIFIED.value}) + new = (await _crawl(client, h, pid, "check_in_time", "16:00"))["fact"]["fact_id"] + + body = (await client.post(f"/v1/place/{pid}/fact/{new}/transition", headers=h, + json={"status": FactStatus.VERIFIED.value})).json() + assert body["result"]["success"] is True + assert body["outcome"] == FactWriteOutcome.PUBLISHED_REPLACED.value + + published = (await _facts(client, h, pid, publishable_only=True))["facts"] + assert len(published) == 1 and published[0]["value"] == "16:00" + assert (await _facts(client, h, pid))["pending_review"] == 0 + + +async def test_repeated_recrawl_does_not_pile_up_candidates(auth_headers, client): + """검증: 같은 출처로 재수집을 세 번 반복한다. + 기대결과: 후보가 쌓이지 않고 하나가 갱신된다(사람 확인 큐가 중복으로 넘치지 않게).""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="r4") + fid = (await _crawl(client, h, pid, "check_in_time", "15:00"))["fact"]["fact_id"] + await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h, json={"status": FactStatus.VERIFIED.value}) + + await _crawl(client, h, pid, "check_in_time", "16:00") + body = await _crawl(client, h, pid, "check_in_time", "17:00") + assert body["outcome"] == FactWriteOutcome.CANDIDATE_UPDATED.value + + listed = await _facts(client, h, pid) + assert listed["pending_review"] == 1 + candidate = next(f for f in listed["facts"] if f["status"] == FactStatus.PENDING_OWNER.value) + assert candidate["value"] == "17:00" + + +async def test_recrawl_cannot_overwrite_corrected_value(auth_headers, client): + """검증: 사람이 정정한 값(CORRECTED)에 다른 값이 재수집된다. + 기대결과: ★ 노출값은 정정본 그대로. 크롤링 값은 버려지지 않고 후보로 남아 불일치가 보인다.""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="r5") + fid = (await _crawl(client, h, pid, "check_in_time", "15:00"))["fact"]["fact_id"] + await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h, json={"status": FactStatus.VERIFIED.value}) + await client.post(f"/v1/place/{pid}/fact/{fid}/transition", headers=h, + json={"status": FactStatus.CORRECTED.value, "value": "16:00"}) + + body = await _crawl(client, h, pid, "check_in_time", "15:00") + assert body["result"]["success"] is True + assert body["fact"]["status"] == FactStatus.PENDING_OWNER.value + + published = (await _facts(client, h, pid, publishable_only=True))["facts"] + assert len(published) == 1 + assert published[0]["value"] == "16:00", "★ 자동 수집이 사람 정정본을 덮어쓰면 안 된다" + assert published[0]["status"] == FactStatus.CORRECTED.value + # OTA 가 아직 15:00 이라는 사실은 후보로 남아 있어야 한다(신호를 버리지 않는다). + assert (await _facts(client, h, pid))["pending_review"] == 1 + + +# ── 수정 프로세스 ──────────────────────────────────────────────────────── +async def test_owner_input_publishes_immediately(auth_headers, client): + """검증: 사람이 직접 값을 넣는다. + 기대결과: 즉시 노출값이 된다 — 넣은 사람이 곧 출처이자 책임 주체다.""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="o1") + + body = await _own(client, h, pid, "check_in_time", "15:00") + assert body["outcome"] == FactWriteOutcome.PUBLISHED_CREATED.value + assert body["fact"]["status"] == FactStatus.VERIFIED.value + assert (await _facts(client, h, pid))["publishable"] == 1 + + +async def test_owner_can_overwrite_own_value(auth_headers, client): + """검증: 사람이 자기가 넣은 값을 다시 고친다. + 기대결과: 노출값이 교체되고(PUBLISHED_REPLACED) 옛 값은 이력으로 내려간다.""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="o2") + await _own(client, h, pid, "check_in_time", "15:00") + + body = await _own(client, h, pid, "check_in_time", "17:00") + assert body["outcome"] == FactWriteOutcome.PUBLISHED_REPLACED.value + + published = (await _facts(client, h, pid, publishable_only=True))["facts"] + assert len(published) == 1 and published[0]["value"] == "17:00" + + +async def test_publishing_marks_place_for_rebuild(auth_headers, client): + """검증: 노출값이 바뀐 뒤 사업장의 content_updated_at. + 기대결과: 값이 찍힌다 — ★ 이 사업장만 재빌드하면 된다는 표시(전체 재빌드 금지).""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="o3") + assert (await client.get(f"/v1/place/{pid}", headers=h)).json()["place"].get("content_updated_at") is None + + await _own(client, h, pid, "check_in_time", "15:00") + place = (await client.get(f"/v1/place/{pid}", headers=h)).json()["place"] + assert place["content_updated_at"] is not None + + +async def test_crawl_only_does_not_mark_rebuild(auth_headers, client): + """검증: 크롤링이 후보만 쌓았을 때 재빌드 표시. + 기대결과: 안 찍힌다 — 사이트에 나가는 내용이 안 바뀌었으니 재빌드가 필요 없다.""" + h = await auth_headers("u1") + pid = await _verified_place(client, h, kakao="o4") + + await _crawl(client, h, pid, "check_in_time", "15:00") + place = (await client.get(f"/v1/place/{pid}", headers=h)).json()["place"] + assert place.get("content_updated_at") is None + + +async def test_facts_are_scoped_to_company(auth_headers, client, other_company_id): + """검증: 다른 회사 계정으로 남의 사업장 fact 를 조회한다. + 기대결과: PLACE_NOT_FOUND — 사업장이 안 보이니 fact 도 안 보인다.""" + h1 = await auth_headers("o1") + pid = await _verified_place(client, h1, kakao="p6") + + h2 = await auth_headers("o2", other_company_id) + r = await client.get(f"/v1/place/{pid}/fact/list", headers=h2) + assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value diff --git a/backend/tests/test_fact_schema.py b/backend/tests/test_fact_schema.py new file mode 100644 index 0000000..fe04ef9 --- /dev/null +++ b/backend/tests/test_fact_schema.py @@ -0,0 +1,163 @@ +"""fact 테이블 제약 — '사이트에 나가는 값은 (사업장, 단위, key) 당 1건' 이 DB 레벨에서 지켜지는지. + +유니크는 **노출 상태(VERIFIED·CORRECTED)에만** 걸린다. + - 걸어야 하는 이유: 안 걸면 체크인 시간이 15시/16시 두 값으로 동시에 노출된다. + - 활성 전체에 걸면 안 되는 이유: 재수집이 올 때마다 확인된 노출값을 밀어내야 하고, + 그 순간 사이트에서 사실이 사라진다. 후보(UNVERIFIED·PENDING_OWNER)는 공존해야 한다. +""" +import uuid + +import pytest +from sqlalchemy import text +from sqlalchemy.exc import IntegrityError + +from common.enums import ( + FACT_STATUS_TRANSITIONS, + LOCKED_FACT_STATUSES, + PUBLISHABLE_FACT_STATUSES, + FactStatus, + PlaceCategory, + PlaceStatus, + SourceType, +) + + +async def _seed_place(db_engine, company_id) -> str: + """검증까지 끝난 사업장 1개를 시드하고 place_id 를 돌려준다.""" + pid = uuid.uuid4() + async with db_engine.begin() as conn: + await conn.execute( + text( + "INSERT INTO places (place_id, company_id, name, category, status, external_place_id, verified_at) " + "VALUES (:pid, :cid, :name, :cat, :status, :kakao, now())" + ), + { + "pid": pid, "cid": uuid.UUID(company_id), "name": "테스트펜션", + "cat": PlaceCategory.LODGING.value, "status": PlaceStatus.DRAFT.value, + "kakao": "12345678", + }, + ) + return str(pid) + + +async def _insert_fact(db_engine, place_id, key, value, status, unit_id=None): + async with db_engine.begin() as conn: + await conn.execute( + text( + "INSERT INTO facts (fact_id, place_id, unit_id, key, value, source_type, status, collected_at) " + "VALUES (:fid, :pid, :uid, :key, :val, :src, :status, now())" + ), + { + "fid": uuid.uuid4(), "pid": uuid.UUID(place_id), "uid": unit_id, + "key": key, "val": value, "src": SourceType.CRAWL.value, "status": status.value, + }, + ) + + +async def test_published_fact_is_unique_per_place_and_key(db_engine, company_id): + """검증: 같은 사업장·같은 key 로 노출 상태 fact 를 두 번 넣는다. + 기대결과: 두 번째 INSERT 가 유니크 인덱스에 막힌다(체크인 시간이 두 값으로 갈라지지 않는다).""" + place_id = await _seed_place(db_engine, company_id) + await _insert_fact(db_engine, place_id, "check_in_time", "15:00", FactStatus.VERIFIED) + + with pytest.raises(IntegrityError): + await _insert_fact(db_engine, place_id, "check_in_time", "16:00", FactStatus.CORRECTED) + + +async def test_candidates_coexist_with_published_value(db_engine, company_id): + """검증: 노출값이 있는 상태에서 재수집 후보를 여러 건 넣는다. + 기대결과: 전부 공존한다 — ★ 재수집이 노출 중인 사실을 밀어내지 않는다.""" + place_id = await _seed_place(db_engine, company_id) + await _insert_fact(db_engine, place_id, "check_in_time", "15:00", FactStatus.VERIFIED) + await _insert_fact(db_engine, place_id, "check_in_time", "16:00", FactStatus.PENDING_OWNER) + await _insert_fact(db_engine, place_id, "check_in_time", "14:00", FactStatus.UNVERIFIED) + + async with db_engine.begin() as conn: + rows = (await conn.execute( + text("SELECT status FROM facts WHERE place_id = :pid AND key = 'check_in_time'"), + {"pid": uuid.UUID(place_id)}, + )).all() + assert len(rows) == 3, "노출값 1건 + 후보 2건이 공존해야 한다" + + +async def test_rejected_fact_frees_the_key(db_engine, company_id): + """검증: 기존 값을 REJECTED 로 내린 뒤 같은 key 를 새로 노출한다. + 기대결과: 통과 — 틀린 값은 이력으로 남고, 새 값이 노출 자리를 차지한다.""" + place_id = await _seed_place(db_engine, company_id) + await _insert_fact(db_engine, place_id, "check_in_time", "15:00", FactStatus.REJECTED) + await _insert_fact(db_engine, place_id, "check_in_time", "16:00", FactStatus.VERIFIED) + + async with db_engine.begin() as conn: + rows = (await conn.execute( + text("SELECT value, status FROM facts WHERE place_id = :pid ORDER BY status"), + {"pid": uuid.UUID(place_id)}, + )).all() + assert len(rows) == 2, "REJECTED 이력과 새 값이 함께 남아야 한다" + + +async def test_expired_fact_frees_the_key(db_engine, company_id): + """검증: 유효기간이 지나 EXPIRED 로 내린 값과 새 수집값의 공존. + 기대결과: 통과 — EXPIRED 도 유니크에서 빠진다.""" + place_id = await _seed_place(db_engine, company_id) + await _insert_fact(db_engine, place_id, "cancel_policy", "구 규정", FactStatus.EXPIRED) + await _insert_fact(db_engine, place_id, "cancel_policy", "새 규정", FactStatus.VERIFIED) + + +async def test_same_key_allowed_across_units(db_engine, company_id): + """검증: 객실이 다르면 같은 key 를 각각 가질 수 있는지. + 기대결과: 통과 — A동·B동이 각자의 기준 인원을 갖는다.""" + place_id = await _seed_place(db_engine, company_id) + unit_a, unit_b = uuid.uuid4(), uuid.uuid4() + async with db_engine.begin() as conn: + for uid, name in ((unit_a, "A동"), (unit_b, "B동")): + await conn.execute( + text("INSERT INTO units (unit_id, place_id, name) VALUES (:uid, :pid, :name)"), + {"uid": uid, "pid": uuid.UUID(place_id), "name": name}, + ) + + await _insert_fact(db_engine, place_id, "standard_capacity", "4", FactStatus.VERIFIED, unit_id=unit_a) + await _insert_fact(db_engine, place_id, "standard_capacity", "2", FactStatus.VERIFIED, unit_id=unit_b) + + with pytest.raises(IntegrityError): # 같은 객실 안에서 노출값은 여전히 1건 + await _insert_fact(db_engine, place_id, "standard_capacity", "6", FactStatus.CORRECTED, unit_id=unit_a) + + +async def test_unit_fact_and_place_fact_are_separate(db_engine, company_id): + """검증: 같은 key 를 사업장 단위와 객실 단위로 동시에 갖는 경우. + 기대결과: 통과 — 부분 인덱스가 unit_id NULL 여부로 갈라져 있다.""" + place_id = await _seed_place(db_engine, company_id) + unit_id = uuid.uuid4() + async with db_engine.begin() as conn: + await conn.execute( + text("INSERT INTO units (unit_id, place_id, name) VALUES (:uid, :pid, :name)"), + {"uid": unit_id, "pid": uuid.UUID(place_id), "name": "A동"}, + ) + await _insert_fact(db_engine, place_id, "has_kitchen", "false", FactStatus.VERIFIED) + await _insert_fact(db_engine, place_id, "has_kitchen", "true", FactStatus.VERIFIED, unit_id=unit_id) + + +def test_only_verified_and_corrected_are_publishable(): + """검증: 노출 가능 상태 집합(절대규칙 1). + 기대결과: VERIFIED·CORRECTED 뿐. 미검증·반려·만료는 절대 사이트에 나가지 않는다.""" + assert PUBLISHABLE_FACT_STATUSES == {FactStatus.VERIFIED, FactStatus.CORRECTED} + for status in (FactStatus.UNVERIFIED, FactStatus.PENDING_OWNER, FactStatus.REJECTED, FactStatus.EXPIRED): + assert status not in PUBLISHABLE_FACT_STATUSES + + +def test_corrected_is_locked_against_auto_update(): + """검증: 사람이 고친 값이 잠기는지(절대규칙 6). + 기대결과: CORRECTED 는 잠금 상태이고, 전이표에서 자동 갱신 경로(UNVERIFIED 등)로 못 돌아간다.""" + assert FactStatus.CORRECTED in LOCKED_FACT_STATUSES + allowed = FACT_STATUS_TRANSITIONS[FactStatus.CORRECTED] + assert FactStatus.UNVERIFIED not in allowed, "자동 수집이 사장님 수정본을 덮어쓸 수 있으면 안 된다" + assert FactStatus.VERIFIED not in allowed + + +def test_transition_table_covers_every_status(): + """검증: 전이표가 모든 상태를 다루는지. + 기대결과: 6개 상태 전부 키로 존재하고, 목적지도 전부 유효한 FactStatus.""" + assert set(FACT_STATUS_TRANSITIONS) == set(FactStatus) + for src, dests in FACT_STATUS_TRANSITIONS.items(): + assert dests, f"{src.name}: 나갈 수 있는 상태가 없다" + for dest in dests: + assert isinstance(dest, FactStatus) diff --git a/backend/tests/test_faq_api.py b/backend/tests/test_faq_api.py new file mode 100644 index 0000000..aa79abb --- /dev/null +++ b/backend/tests/test_faq_api.py @@ -0,0 +1,175 @@ +"""FAQ 조회·승인 e2e. + +이 도메인이 지켜야 하는 것: + - LLM 이 만든 FAQ 는 ★ 사람이 승인하기 전엔 사이트에 안 나간다(FAQPage JSON-LD 에도 안 실린다) + - 상태 전이는 fact 와 같은 표(FACT_STATUS_TRANSITIONS)만 따른다 + - 고쳐서 승인한 FAQ(CORRECTED)는 잠긴다 — 재생성이 사장님 문구를 덮어쓰지 못한다 + - 사장님이 직접 쓴 FAQ 는 바로 노출값이다(사람이 곧 출처) +""" +import uuid + +from sqlalchemy import text + +from common.enums import ErrorType, FactStatus, SourceType + + +async def _place(client, headers, name="FAQ펜션"): + r = await client.post("/v1/place", headers=headers, json={"name": name, "category": 1}) + return r.json()["place"]["place_id"] + + +async def _seed_generated_faq(db_engine, pid, question="체크인은 몇 시인가요?", answer="15시입니다.", order=0): + """COPY 잡이 남기고 간 상태를 그대로 만든다 — LLM 출처 · UNVERIFIED.""" + fid = uuid.uuid4() + async with db_engine.begin() as conn: + await conn.execute( + text("INSERT INTO faqs (faq_id, place_id, question, answer, source_fact_ids, generated_by, status, sort_order) " + "VALUES (:f, :p, :q, :a, CAST(:k AS jsonb), :g, :st, :o)"), + {"f": fid, "p": uuid.UUID(pid), "q": question, "a": answer, "k": '["check_in_time"]', + "g": SourceType.LLM.value, "st": FactStatus.UNVERIFIED.value, "o": order}, + ) + return str(fid) + + +async def _list(client, headers, pid, **params): + return (await client.get(f"/v1/place/{pid}/faq/list", headers=headers, params=params)).json() + + +async def _transition(client, headers, pid, fid, body): + return (await client.post(f"/v1/place/{pid}/faq/{fid}/transition", headers=headers, json=body)).json() + + +# ── 조회 ───────────────────────────────────────────────────────────────── +async def test_generated_faq_is_pending_and_not_publishable(auth_headers, client, db_engine): + """검증: LLM 이 만든 UNVERIFIED FAQ 를 조회한다. + 기대결과: 목록엔 보이되 publishable=0 — ★ 승인 전에는 사이트에 나가지 않는다.""" + h = await auth_headers("u1") + pid = await _place(client, h) + await _seed_generated_faq(db_engine, pid) + + body = await _list(client, h, pid) + assert len(body["faqs"]) == 1 + assert body["faqs"][0]["status"] == FactStatus.UNVERIFIED.value + assert body["publishable"] == 0 + assert body["pending_review"] == 1 + # 사이트 빌드가 보는 것과 같은 집합 — 승인 전에는 비어 있어야 한다. + assert (await _list(client, h, pid, publishable_only=True)).get("faqs", []) == [] + + +async def test_other_company_cannot_read_or_touch_faq(auth_headers, client, db_engine, other_company_id): + """검증: 남의 회사 사용자가 place_id 를 알아내 FAQ 를 조회·전이한다. + 기대결과: PLACE_NOT_FOUND — 존재 여부조차 알려주지 않는다.""" + h = await auth_headers("u1") + pid = await _place(client, h) + fid = await _seed_generated_faq(db_engine, pid) + + other = await auth_headers("u2", other_company_id) + assert (await _list(client, other, pid))["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value + body = await _transition(client, other, pid, fid, {"status": FactStatus.VERIFIED.value}) + assert body["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value + + +# ── 승인 ───────────────────────────────────────────────────────────────── +async def test_approving_faq_makes_it_publishable(auth_headers, client, db_engine): + """검증: UNVERIFIED FAQ 를 VERIFIED 로 승인한다. + 기대결과: 노출 가능해지고 사업장이 재빌드 대상으로 찍힌다(FAQPage 가 바뀌므로).""" + h = await auth_headers("u1") + pid = await _place(client, h) + fid = await _seed_generated_faq(db_engine, pid) + + body = await _transition(client, h, pid, fid, {"status": FactStatus.VERIFIED.value}) + assert body["result"]["success"] is True + assert body["faq"]["status"] == FactStatus.VERIFIED.value + assert (await _list(client, h, pid))["publishable"] == 1 + place = (await client.get(f"/v1/place/{pid}", headers=h)).json()["place"] + assert place["content_updated_at"] is not None + + +async def test_illegal_transition_is_rejected(auth_headers, client, db_engine): + """검증: UNVERIFIED → CORRECTED 처럼 전이표에 없는 이동. + 기대결과: FACT_INVALID_TRANSITION — 확인을 건너뛴 '정정본'은 만들 수 없다.""" + h = await auth_headers("u1") + pid = await _place(client, h) + fid = await _seed_generated_faq(db_engine, pid) + + body = await _transition(client, h, pid, fid, {"status": FactStatus.CORRECTED.value, "answer": "15:00 입니다."}) + assert body["result"]["code"] == ErrorType.FACT_INVALID_TRANSITION.value + + +async def test_correction_requires_new_text(auth_headers, client, db_engine): + """검증: 고친 문구 없이 CORRECTED 로 보낸다. + 기대결과: INVALID_REQUEST_DATA — 고친 게 없으면 그건 정정이 아니라 승인(VERIFIED)이다.""" + h = await auth_headers("u1") + pid = await _place(client, h) + fid = await _seed_generated_faq(db_engine, pid) + await _transition(client, h, pid, fid, {"status": FactStatus.VERIFIED.value}) + + body = await _transition(client, h, pid, fid, {"status": FactStatus.CORRECTED.value}) + assert body["result"]["code"] == ErrorType.INVALID_REQUEST_DATA.value + + +async def test_corrected_faq_is_locked_against_regeneration(auth_headers, client, db_engine): + """검증: 사장님이 문구를 고쳐 승인(CORRECTED)한 뒤 COPY 잡이 재생성을 돌린다. + 기대결과: 고친 문구가 그대로 남는다 — ★ 자동 생성이 사람의 판단을 덮어쓰지 않는다.""" + from common.database.db_session_manager import DB_SESSION_MNG + from common.database.model.models import faqs + from common.utils.gtime import GTime + from crud.faq_crud import FaqCRUD + + h = await auth_headers("u1") + pid = await _place(client, h) + fid = await _seed_generated_faq(db_engine, pid) + await _transition(client, h, pid, fid, {"status": FactStatus.VERIFIED.value}) + + body = await _transition(client, h, pid, fid, {"status": FactStatus.CORRECTED.value, "answer": "15시 이후 입실입니다."}) + assert body["faq"]["status"] == FactStatus.CORRECTED.value + assert body["faq"]["answer"] == "15시 이후 입실입니다." + # 문장의 책임 주체가 사람으로 넘어왔다는 기록. + assert body["faq"]["generated_by"] == SourceType.OWNER.value + + # 재생성이 미확인 FAQ 를 내리는 단계(COPY 잡이 실제로 부르는 그 함수). + await DB_SESSION_MNG.execute_lambda_claim( + faqs.DBType(), + lambda s: FaqCRUD().expire_generated(s, uuid.UUID(pid), GTime.UTC()), + ) + after = await _list(client, h, pid, publishable_only=True) + assert [f["answer"] for f in after["faqs"]] == ["15시 이후 입실입니다."] + + +# ── 직접 추가 ──────────────────────────────────────────────────────────── +async def test_owner_written_faq_is_published_immediately(auth_headers, client): + """검증: 사장님이 FAQ 를 직접 쓴다. + 기대결과: 바로 노출값(VERIFIED) + 출처는 서버가 OWNER 로 고정 — 사람이 곧 출처다.""" + h = await auth_headers("u1") + pid = await _place(client, h) + + body = (await client.post(f"/v1/place/{pid}/faq", headers=h, + json={"question": "주차 되나요?", "answer": "무료 주차 가능합니다."})).json() + assert body["faq"]["status"] == FactStatus.VERIFIED.value + assert body["faq"]["generated_by"] == SourceType.OWNER.value + assert body["faq"]["sort_order"] == 0 + assert (await _list(client, h, pid))["publishable"] == 1 + + +async def test_owner_faq_appends_after_existing_ones(auth_headers, client, db_engine): + """검증: 이미 FAQ 가 있는 사업장에 순서 없이 추가한다. + 기대결과: 맨 뒤에 붙는다 — 기존 FAQ 순서를 흔들지 않는다.""" + h = await auth_headers("u1") + pid = await _place(client, h) + await _seed_generated_faq(db_engine, pid, order=0) + await _seed_generated_faq(db_engine, pid, question="와이파이 되나요?", answer="됩니다.", order=1) + + body = (await client.post(f"/v1/place/{pid}/faq", headers=h, + json={"question": "주차 되나요?", "answer": "무료 주차 가능합니다."})).json() + assert body["faq"]["sort_order"] == 2 + + +async def test_blank_faq_is_rejected(auth_headers, client): + """검증: 공백만 있는 질문으로 FAQ 를 추가한다. + 기대결과: INVALID_REQUEST_DATA — 빈 문답은 렌더도 안 되고 고유 콘텐츠로도 안 세진다.""" + h = await auth_headers("u1") + pid = await _place(client, h) + + body = (await client.post(f"/v1/place/{pid}/faq", headers=h, + json={"question": " ", "answer": "무료 주차 가능합니다."})).json() + assert body["result"]["code"] == ErrorType.INVALID_REQUEST_DATA.value diff --git a/backend/tests/test_gemini.py b/backend/tests/test_gemini.py new file mode 100644 index 0000000..8c860d8 --- /dev/null +++ b/backend/tests/test_gemini.py @@ -0,0 +1,453 @@ +"""Gemini Vision 클라이언트 — 사진 분류·alt 생성의 계약. + +실제 API 를 절대 호출하지 않는다(httpx.MockTransport). 여기서 고정하는 것: + 1. ★ 반환 길이는 항상 입력과 같다 — 실패해도 자리를 지킨다 + 2. ★ 매칭은 순서가 아니라 ref 로 한다 — 순서로 하면 엉뚱한 사진에 남의 alt 가 붙는다 + 3. ★ 신뢰도가 낮으면 needs_review=True — 자동 반영하지 않고 사람 확인 큐로 + 4. 배치 하나가 죽어도 나머지는 산다 + 5. 홍보성 형용사 금지가 프롬프트에 실제로 들어간다 +""" +import base64 +import json +import struct +import zlib + +import httpx +import pytest + +from common.enums import PlaceCategory +from services.external import gemini +from services.llm import gemini as llm +from services.external.gemini import ( + GeminiError, + GeminiNotConfigured, + ImageInput, + analyze_images, +) + + +# ---- 도구 ----------------------------------------------------------------- +def _png(rgb=(10, 20, 30), size=8) -> bytes: + """테스트용 최소 PNG. 시그니처 판별(_sniff_mime)까지 같이 확인된다.""" + def chunk(tag, data): + body = tag + data + return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body) & 0xFFFFFFFF) + + raw = b"".join(b"\x00" + bytes(rgb) * size for _ in range(size)) + return (b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(raw)) + + chunk(b"IEND", b"")) + + +def _inputs(n: int) -> list[ImageInput]: + return [ImageInput(origin_url=f"https://ota.test/p{i}.png", data=_png((i * 20 % 255, 40, 60))) for i in range(n)] + + +def _reply(items: list[dict], *, prompt_tokens=1000, out_tokens=50) -> dict: + """generateContent 성공 응답 흉내. 실호출에서 확인한 구조 그대로 — + parts 에 text 와 thoughtSignature 가 같이 실린다.""" + return { + "candidates": [{ + "content": {"parts": [{"text": json.dumps({"items": items}, ensure_ascii=False), + "thoughtSignature": "xxx"}]}, + "finishReason": "STOP", + }], + "usageMetadata": {"promptTokenCount": prompt_tokens, "candidatesTokenCount": out_tokens}, + } + + +def _item(ref, label="침실", alt="침대와 협탁이 놓인 방", conf=0.95): + return {"ref": ref, "label": label, "alt_text": alt, "confidence": conf} + + +def _client(handler) -> httpx.AsyncClient: + return httpx.AsyncClient(transport=httpx.MockTransport(handler), timeout=5.0) + + +@pytest.fixture(autouse=True) +def _api_key(monkeypatch): + """테스트 환경엔 키가 없다(의도된 것) — 클라이언트 경로를 타려면 넣어줘야 한다.""" + monkeypatch.setattr(llm.external_api_config, "gemini_api_key", "test-key") + + +# ---- 기본 경로 ------------------------------------------------------------- +async def test_parses_label_alt_and_confidence(): + """검증: 정상 응답 1장. + 기대결과: label·alt_text·confidence 가 파싱되고 ok=True, 신뢰도가 높아 확인 불필요.""" + def handler(request): + return httpx.Response(200, json=_reply([_item("img-0", "침실", "침대와 협탁이 놓인 방", 0.93)])) + + async with _client(handler) as c: + res = await analyze_images(_inputs(1), category=PlaceCategory.LODGING, client=c) + + assert len(res) == 1 + assert res[0].ok is True + assert res[0].label == "침실" + assert res[0].alt_text == "침대와 협탁이 놓인 방" + assert res[0].confidence == pytest.approx(0.93) + assert res[0].needs_review is False + + +async def test_result_length_always_matches_input(): + """검증: 입력 5장인데 응답에 3장만 온다. + 기대결과: 길이 5 유지 · 빠진 2장은 ok=False, needs_review=True — ★ 조용히 사라지지 않는다.""" + def handler(request): + return httpx.Response(200, json=_reply([_item("img-0"), _item("img-1"), _item("img-2")])) + + images = _inputs(5) + async with _client(handler) as c: + res = await analyze_images(images, client=c) + + assert len(res) == 5 + assert [r.origin_url for r in res] == [i.origin_url for i in images] + assert all(r.ok for r in res[:3]) + for r in res[3:]: + assert r.ok is False and r.needs_review is True + assert "ref" in (r.error or "") + + +async def test_matches_by_ref_not_by_order(): + """검증: 모델이 순서를 뒤집어 돌려준다(img-2, img-0, img-1). + 기대결과: ★ ref 로 정확히 매칭된다 — 순서로 매칭하면 엉뚱한 사진에 남의 alt 가 붙는다.""" + def handler(request): + return httpx.Response(200, json=_reply([ + _item("img-2", "주방", "싱크대와 조리대"), + _item("img-0", "외관", "건물 정면"), + _item("img-1", "욕실", "세면대와 샤워부스"), + ])) + + images = _inputs(3) + async with _client(handler) as c: + res = await analyze_images(images, client=c) + + by_url = {r.origin_url: r for r in res} + assert by_url[images[0].origin_url].label == "외관" + assert by_url[images[1].origin_url].label == "욕실" + assert by_url[images[2].origin_url].label == "주방" + + +async def test_unknown_ref_in_response_is_discarded(): + """검증: 모델이 존재하지 않는 ref(img-99)를 지어낸다. + 기대결과: 버려지고, 실제 사진은 '응답 누락'으로 표시된다.""" + def handler(request): + return httpx.Response(200, json=_reply([_item("img-99", "침실")])) + + async with _client(handler) as c: + res = await analyze_images(_inputs(1), client=c) + + assert len(res) == 1 + assert res[0].ok is False and res[0].needs_review is True + + +# ---- 신뢰도 게이트 --------------------------------------------------------- +async def test_low_confidence_goes_to_review_queue(): + """검증: 신뢰도 0.4 로 돌아온 사진(임계값 0.7). + 기대결과: ok=True 지만 needs_review=True — ★ 자동 반영하지 않고 사람이 본다.""" + def handler(request): + return httpx.Response(200, json=_reply([_item("img-0", "침실", "흐릿한 실내", 0.4)])) + + async with _client(handler) as c: + res = await analyze_images(_inputs(1), confidence_threshold=0.7, client=c) + + assert res[0].ok is True + assert res[0].needs_review is True + + +async def test_threshold_is_configurable(): + """검증: 같은 0.4 응답에 임계값을 0.3 으로 낮춘다. + 기대결과: 확인 불필요로 내려간다 — 임계값이 실제로 파라미터로 동작한다.""" + def handler(request): + return httpx.Response(200, json=_reply([_item("img-0", "침실", "실내", 0.4)])) + + async with _client(handler) as c: + res = await analyze_images(_inputs(1), confidence_threshold=0.3, client=c) + + assert res[0].needs_review is False + + +async def test_empty_label_forces_review(): + """검증: 신뢰도는 높은데 label 이 빈 문자열이다. + 기대결과: needs_review=True — 쓸 수 없는 결과를 자동 반영하지 않는다.""" + def handler(request): + return httpx.Response(200, json=_reply([_item("img-0", "", "설명", 0.99)])) + + async with _client(handler) as c: + res = await analyze_images(_inputs(1), client=c) + + assert res[0].label is None + assert res[0].needs_review is True + + +# ---- 배치 ----------------------------------------------------------------- +async def test_splits_into_batches(): + """검증: 12장을 batch_size=5 로 보낸다. + 기대결과: 3번 호출된다(5+5+2) — 20~50장을 한 번에 밀어넣지 않는다.""" + calls = [] + + def handler(request): + body = json.loads(request.content) + refs = [p["text"].split("]")[0][1:] for p in body["contents"][0]["parts"] + if "text" in p and p["text"].startswith("[img-")] + calls.append(len(refs)) + return httpx.Response(200, json=_reply([_item(r) for r in refs])) + + async with _client(handler) as c: + res = await analyze_images(_inputs(12), batch_size=5, client=c) + + assert calls == [5, 5, 2] + assert len(res) == 12 + assert all(r.ok for r in res) + + +async def test_one_failed_batch_does_not_kill_the_rest(): + """검증: 3배치 중 두 번째만 500 을 반환한다. + 기대결과: ★ 나머지 배치는 살아남고, 실패 배치의 사진만 ok=False 로 표시된다.""" + state = {"n": 0} + + def handler(request): + state["n"] += 1 + body = json.loads(request.content) + refs = [p["text"][1:-1] for p in body["contents"][0]["parts"] + if "text" in p and p["text"].startswith("[img-")] + if state["n"] == 2: + return httpx.Response(500, text="boom") + return httpx.Response(200, json=_reply([_item(r) for r in refs])) + + async with _client(handler) as c: + res = await analyze_images(_inputs(6), batch_size=2, max_retries=0, client=c) + + assert len(res) == 6 + assert [r.ok for r in res] == [True, True, False, False, True, True] + assert all(r.needs_review for r in res[2:4]) + + +# ---- 재시도 --------------------------------------------------------------- +async def test_retries_5xx_then_succeeds(): + """검증: 첫 호출 503, 두 번째 200. + 기대결과: 재시도로 성공한다 — 일시적 장애로 사진을 버리지 않는다.""" + state = {"n": 0} + + def handler(request): + state["n"] += 1 + if state["n"] == 1: + return httpx.Response(503, text="unavailable") + return httpx.Response(200, json=_reply([_item("img-0")])) + + async with _client(handler) as c: + res = await analyze_images(_inputs(1), max_retries=2, client=c) + + assert state["n"] == 2 + assert res[0].ok is True + + +async def test_does_not_retry_4xx(): + """검증: 400(잘못된 요청)을 반환한다. + 기대결과: 재시도하지 않는다 — 같은 요청을 다시 보내도 결과가 같고 요금만 나간다.""" + state = {"n": 0} + + def handler(request): + state["n"] += 1 + return httpx.Response(400, text="bad request") + + async with _client(handler) as c: + res = await analyze_images(_inputs(1), max_retries=3, client=c) + + assert state["n"] == 1 + assert res[0].ok is False + + +async def test_timeout_is_retried_then_reported(): + """검증: 매번 타임아웃이 난다. + 기대결과: max_retries 만큼 시도한 뒤 해당 사진을 ok=False 로 남긴다(예외를 밖으로 안 던진다).""" + state = {"n": 0} + + def handler(request): + state["n"] += 1 + raise httpx.ReadTimeout("timed out", request=request) + + async with _client(handler) as c: + res = await analyze_images(_inputs(1), max_retries=1, client=c) + + assert state["n"] == 2 + assert res[0].ok is False and res[0].needs_review is True + + +# ---- 오류 처리 ------------------------------------------------------------- +async def test_broken_json_fails_only_that_batch(): + """검증: 구조화 출력이 깨진 JSON 으로 온다. + 기대결과: 그 배치만 실패 처리된다 — 파싱 실패가 전체를 죽이지 않는다.""" + def handler(request): + return httpx.Response(200, json={ + "candidates": [{"content": {"parts": [{"text": "{items: [oops"}]}, "finishReason": "STOP"}] + }) + + async with _client(handler) as c: + res = await analyze_images(_inputs(2), max_retries=0, client=c) + + assert len(res) == 2 + assert all(r.ok is False and r.needs_review for r in res) + + +async def test_safety_blocked_response_is_handled(): + """검증: candidates 가 비어 오는 경우(안전 필터 차단). + 기대결과: 예외가 새지 않고 ok=False 로 남는다.""" + def handler(request): + return httpx.Response(200, json={"candidates": []}) + + async with _client(handler) as c: + res = await analyze_images(_inputs(1), max_retries=0, client=c) + + assert res[0].ok is False + + +async def test_missing_key_raises_not_configured(monkeypatch): + """검증: GEMINI_API_KEY 가 비어 있다. + 기대결과: GeminiNotConfigured — ★ 서버 부팅은 막지 않고 이 어댑터만 비활성이다.""" + monkeypatch.setattr(llm.external_api_config, "gemini_api_key", "") + assert llm.is_configured() is False + with pytest.raises(GeminiNotConfigured): + await analyze_images(_inputs(1)) + + +async def test_auth_error_stops_everything(): + """검증: 401 이 돌아온다. + 기대결과: GeminiNotConfigured 로 전체 중단 — 나머지 배치를 태워봐야 똑같이 실패한다.""" + def handler(request): + return httpx.Response(401, text="unauthorized") + + async with _client(handler) as c: + with pytest.raises(GeminiNotConfigured): + await analyze_images(_inputs(4), batch_size=2, client=c) + + +async def test_image_download_failure_is_isolated(): + """검증: 바이트 없이 URL 만 준 사진의 내려받기가 실패한다. + 기대결과: 그 사진만 ok=False, 같은 배치의 다른 사진은 정상 처리된다.""" + def handler(request): + if request.method == "GET": + return httpx.Response(404) + body = json.loads(request.content) + refs = [p["text"][1:-1] for p in body["contents"][0]["parts"] + if "text" in p and p["text"].startswith("[img-")] + return httpx.Response(200, json=_reply([_item(r) for r in refs])) + + images = [ImageInput(origin_url="https://ota.test/gone.png"), _inputs(1)[0]] + async with _client(handler) as c: + res = await analyze_images(images, client=c) + + assert len(res) == 2 + assert res[0].ok is False and "로드 실패" in res[0].error + assert res[1].ok is True + + +async def test_empty_input_returns_empty(): + """검증: 빈 목록을 넘긴다. + 기대결과: 빈 목록. 호출도 하지 않는다(요금 0).""" + assert await analyze_images([]) == [] + + +# ---- 프롬프트 계약 --------------------------------------------------------- +async def test_prompt_forbids_promotional_adjectives(): + """검증: 실제로 보내는 요청 본문의 지시문. + 기대결과: ★ 홍보성 형용사 금지와 '지어내지 마라' 가 들어 있다 — LLM 은 사실을 만들지 않는다.""" + captured = {} + + def handler(request): + captured["body"] = json.loads(request.content) + return httpx.Response(200, json=_reply([_item("img-0")])) + + async with _client(handler) as c: + await analyze_images(_inputs(1), category=PlaceCategory.LODGING, client=c) + + prompt = captured["body"]["contents"][0]["parts"][0]["text"] + assert "아름다운" in prompt and "홍보성" in prompt + assert "지어내지 마라" in prompt + assert "보이는 것만" in prompt + + +async def test_prompt_uses_category_vocabulary(): + """검증: 업종별 라벨 어휘. + 기대결과: 숙박엔 '침실'이, 카페엔 '디저트'가 들어간다 — 라벨이 업종마다 달라야 화면에서 묶인다.""" + captured = {} + + def handler(request): + captured.setdefault("prompts", []).append( + json.loads(request.content)["contents"][0]["parts"][0]["text"] + ) + return httpx.Response(200, json=_reply([_item("img-0")])) + + async with _client(handler) as c: + await analyze_images(_inputs(1), category=PlaceCategory.LODGING, client=c) + await analyze_images(_inputs(1), category=PlaceCategory.CAFE, client=c) + + assert "침실" in captured["prompts"][0] + assert "디저트" in captured["prompts"][1] + + +async def test_unit_names_are_passed_as_hint(): + """검증: 객실 이름 후보를 넘긴다. + 기대결과: 프롬프트에 실린다 — 라벨을 units 와 맞춰야 나중에 사진이 객실에 붙는다.""" + captured = {} + + def handler(request): + captured["prompt"] = json.loads(request.content)["contents"][0]["parts"][0]["text"] + return httpx.Response(200, json=_reply([_item("img-0")])) + + async with _client(handler) as c: + await analyze_images(_inputs(1), unit_names=["A동 스탠다드", "B동 복층"], client=c) + + assert "A동 스탠다드" in captured["prompt"] + + +async def test_structured_output_schema_is_sent(): + """검증: 요청의 generationConfig. + 기대결과: responseMimeType=application/json + responseSchema 가 실린다 — 파싱 실패를 줄이는 장치.""" + captured = {} + + def handler(request): + captured["body"] = json.loads(request.content) + return httpx.Response(200, json=_reply([_item("img-0")])) + + async with _client(handler) as c: + await analyze_images(_inputs(1), client=c) + + cfg = captured["body"]["generationConfig"] + assert cfg["responseMimeType"] == "application/json" + assert cfg["responseSchema"]["properties"]["items"]["items"]["required"] == [ + "ref", "label", "alt_text", "confidence" + ] + assert cfg["temperature"] == 0 + + +async def test_png_mime_is_sniffed_not_guessed(): + """검증: PNG 바이트를 mime_type 없이 넘긴다. + 기대결과: image/png 로 판별된다 — 수집한 URL 의 확장자는 자주 거짓말한다.""" + captured = {} + + def handler(request): + captured["body"] = json.loads(request.content) + return httpx.Response(200, json=_reply([_item("img-0")])) + + async with _client(handler) as c: + await analyze_images(_inputs(1), client=c) + + inline = [p["inline_data"] for p in captured["body"]["contents"][0]["parts"] if "inline_data" in p] + assert inline[0]["mime_type"] == "image/png" + assert base64.b64decode(inline[0]["data"]).startswith(b"\x89PNG") + + +async def test_confidence_is_clamped(): + """검증: 모델이 범위 밖 신뢰도(1.7, -0.2)를 준다. + 기대결과: 0.0~1.0 으로 잘린다 — 오염된 값이 아래 로직으로 흘러가지 않는다.""" + def handler(request): + return httpx.Response(200, json=_reply([ + _item("img-0", conf=1.7), _item("img-1", conf=-0.2), + ])) + + async with _client(handler) as c: + res = await analyze_images(_inputs(2), client=c) + + assert res[0].confidence == 1.0 + assert res[1].confidence == 0.0 + assert res[1].needs_review is True diff --git a/backend/tests/test_gemini_text.py b/backend/tests/test_gemini_text.py new file mode 100644 index 0000000..0a1087c --- /dev/null +++ b/backend/tests/test_gemini_text.py @@ -0,0 +1,363 @@ +"""Gemini 텍스트 생성 — ★ LLM 이 사실을 만들지 못하게 막는 게 전부다. + +프롬프트로 "지어내지 마라" 라고 부탁하는 것만으로는 부족하다. 모델은 종종 어긴다. +그래서 ground_check 가 결과를 코드로 검증하고, 통과 못 한 문장은 버린다. +이 파일은 그 검증이 실제로 무엇을 잡아내는지 고정한다. +""" +import json + +import httpx +import pytest + +from common.enums import PlaceCategory +# ★ 겹마다 사는 곳이 다르다(services/llm/__init__.py 의 설명 참조). +# 근거 검증 규칙 → grounding, HTTP 호출·키 → llm, 조립 → external. +from services.external import gemini_text as gt +from services.grounding import copy as grounding_copy +from services.llm import gemini as llm + +FACTS = [ + grounding_copy.FactInput("check_in_time", "체크인 시간", "15:00"), + grounding_copy.FactInput("check_out_time", "체크아웃 시간", "11:00"), + grounding_copy.FactInput("pet_allowed", "반려동물 동반", "false"), + grounding_copy.FactInput("cooking_allowed", "취사 가능", "true"), + grounding_copy.FactInput("bbq_fee", "바비큐 이용료", "20000", "원"), + grounding_copy.FactInput("parking", "주차 가능", "true"), +] + + +def _payload(intro="", meta="", faqs=None, intro_keys=None): + body = { + "intro": intro, + "intro_fact_keys": intro_keys if intro_keys is not None else ["check_in_time"], + "meta_description": meta, + "faqs": faqs or [], + } + return { + "candidates": [{ + "content": {"parts": [ + {"thoughtSignature": "..."}, # text 없는 파트가 섞여 온다(실호출 확인) + {"text": json.dumps(body, ensure_ascii=False)}, + ]}, + "finishReason": "STOP", + }], + "usageMetadata": {"promptTokenCount": 800, "candidatesTokenCount": 200}, + } + + +def _client(handler): + return httpx.AsyncClient(transport=httpx.MockTransport(handler)) + + +def _ok(payload, calls=None): + def handler(request): + if calls is not None: + calls.append(request) + return httpx.Response(200, json=payload) + return handler + + +@pytest.fixture(autouse=True) +def _configured(monkeypatch): + """모든 테스트에서 키가 있는 것으로 둔다(실 API 는 MockTransport 가 막는다).""" + monkeypatch.setattr(llm.external_api_config, "gemini_api_key", "test-key") + + +# ── 정상 경로 ───────────────────────────────────────────────────────────── +async def test_generates_intro_meta_and_faqs(): + """검증: 근거 있는 문장만 담긴 정상 응답. + 기대결과: 소개문·메타·FAQ 가 그대로 통과하고 근거 key 가 살아 있다.""" + payload = _payload( + intro="체크인은 15시, 체크아웃은 11시입니다. 취사가 가능하며 주차도 하실 수 있습니다.", + meta="체크인 15시, 취사 가능한 숙소입니다.", + faqs=[{"question": "체크인 시간은 언제인가요?", "answer": "15시부터입니다.", + "fact_keys": ["check_in_time"]}], + ) + async with _client(_ok(payload)) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + assert res.intro and "15시" in res.intro + assert res.meta_description + assert len(res.faqs) == 1 + assert res.faqs[0].fact_keys == ["check_in_time"] + assert res.rejected == [] + + +async def test_request_body_pins_structured_output(): + """검증: 요청 본문. + 기대결과: responseSchema 로 출력 구조가 고정되고 fact 가 프롬프트에 실린다.""" + calls = [] + async with _client(_ok(_payload(intro="체크인은 15시입니다."), calls)) as c: + await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + body = json.loads(calls[0].content) + assert body["generationConfig"]["responseMimeType"] == "application/json" + assert "faqs" in body["generationConfig"]["responseSchema"]["properties"] + assert calls[0].headers["x-goog-api-key"] == "test-key" + prompt = body["contents"][0]["parts"][0]["text"] + assert "check_in_time" in prompt and "15:00" in prompt + assert "지어내지" in prompt or "쓰지 마라" in prompt + + +# ── ★ 환각 차단 ─────────────────────────────────────────────────────────── +async def test_ungrounded_number_is_rejected(): + """검증: fact 는 15:00 인데 모델이 '14시' 라고 썼다. + 기대결과: ★ 소개문이 버려지고 rejected 에 사유가 남는다 — 틀린 시각이 사이트로 나가면 클레임이다.""" + payload = _payload(intro="체크인은 14시부터 가능합니다.", meta="체크인 15시.") + async with _client(_ok(payload)) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + assert res.intro is None + assert any("14" in reason for _text, reason in res.rejected) + + +async def test_ungrounded_facility_is_rejected(): + """검증: fact 에 없는 시설(수영장)을 언급했다. + 기대결과: ★ 반려 — 없는 시설을 보고 온 손님은 헛걸음한다.""" + payload = _payload(intro="수영장을 갖춘 숙소입니다. 체크인은 15시입니다.", meta="체크인 15시.") + async with _client(_ok(payload)) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + assert res.intro is None + assert any("수영장" in reason for _t, reason in res.rejected) + + +async def test_contradicting_boolean_fact_is_rejected(): + """검증: pet_allowed=false 인데 '반려동물 동반 가능' 이라고 썼다. + 기대결과: ★ 반려 — 사실을 뒤집은 문장이다.""" + payload = _payload(intro="반려동물 동반이 가능한 숙소입니다.", meta="체크인 15시.") + async with _client(_ok(payload)) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + assert res.intro is None + assert any("반려동물" in reason for _t, reason in res.rejected) + + +async def test_negated_mention_of_false_fact_passes(): + """검증: pet_allowed=false 를 '불가' 라고 바르게 썼다. + 기대결과: 통과 — 부정 표현까지 막으면 사실을 못 알린다.""" + payload = _payload(intro="반려동물 동반은 불가합니다. 체크인은 15시입니다.", meta="체크인 15시.") + async with _client(_ok(payload)) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + assert res.intro is not None + + +async def test_promotional_language_is_rejected(): + """검증: 최상급·홍보성 표현. + 기대결과: ★ 반려 — 이 서비스의 글은 광고문이 아니라 사실 전달이다.""" + payload = _payload(intro="국내 최고의 완벽한 숙소입니다.", meta="체크인 15시.") + async with _client(_ok(payload)) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + assert res.intro is None + assert any("홍보성" in reason for _t, reason in res.rejected) + + +async def test_scaled_number_matches_fact(): + """검증: fact 는 20000 인데 문장은 '2만원' 이다. + 기대결과: 통과 — 같은 값을 다르게 쓴 것뿐이다(과잉 반려를 막는다).""" + payload = _payload(intro="바비큐 이용료는 2만원입니다. 체크인은 15시입니다.", meta="체크인 15시.") + async with _client(_ok(payload)) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + assert res.intro is not None + + +async def test_faq_without_fact_keys_is_dropped(): + """검증: 근거 key 를 못 대는 FAQ. + 기대결과: ★ 버려진다 — 사실인지 확인할 방법이 없는 문답이다.""" + payload = _payload( + intro="체크인은 15시입니다.", meta="체크인 15시.", + faqs=[ + {"question": "근처에 볼거리가 있나요?", "answer": "많습니다.", "fact_keys": []}, + {"question": "체크인은 언제인가요?", "answer": "15시입니다.", "fact_keys": ["check_in_time"]}, + ], + ) + async with _client(_ok(payload)) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + assert len(res.faqs) == 1 + assert res.faqs[0].question == "체크인은 언제인가요?" + assert any("fact_keys" in reason for _t, reason in res.rejected) + + +async def test_invented_fact_key_is_stripped(): + """검증: 모델이 존재하지 않는 fact key 를 근거로 적었다. + 기대결과: 그 key 만 걸러진다 — 없는 근거를 있는 것처럼 두면 추적이 깨진다.""" + payload = _payload( + intro="체크인은 15시입니다.", meta="체크인 15시.", + intro_keys=["check_in_time", "swimming_pool", "spa_open"], + ) + async with _client(_ok(payload)) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + assert res.intro_fact_keys == ["check_in_time"] + + +async def test_bad_faq_does_not_kill_good_ones(): + """검증: FAQ 3개 중 1개만 근거가 틀렸다. + 기대결과: 그 항목만 버려지고 나머지는 산다 — 하나 때문에 전부 잃으면 안 된다.""" + payload = _payload( + intro="체크인은 15시입니다.", meta="체크인 15시.", + faqs=[ + {"question": "체크인?", "answer": "15시입니다.", "fact_keys": ["check_in_time"]}, + {"question": "수영장 있나요?", "answer": "네 있습니다.", "fact_keys": ["parking"]}, + {"question": "주차 되나요?", "answer": "가능합니다.", "fact_keys": ["parking"]}, + ], + ) + async with _client(_ok(payload)) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + assert len(res.faqs) == 2 + assert all("수영장" not in f.question for f in res.faqs) + + +async def test_faq_question_about_unavailable_facility_survives(): + """검증: 'X 가능한가요?' 라 묻고 '불가합니다' 라 답한 FAQ. + 기대결과: ★ 통과 — 질문은 사실을 주장하지 않는다. (실호출에서 멀쩡한 FAQ 가 버려진 오탐을 고친 것)""" + payload = _payload( + intro="체크인은 15시입니다.", meta="체크인 15시.", + faqs=[{"question": "반려동물 동반이 가능한가요?", "answer": "아니요, 반려동물 동반은 불가합니다.", + "fact_keys": ["pet_allowed"]}], + ) + async with _client(_ok(payload)) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + assert len(res.faqs) == 1, f"멀쩡한 FAQ 가 버려졌다: {res.rejected}" + + +async def test_faq_answer_contradicting_fact_is_rejected(): + """검증: 'X 가능한가요?' 에 사실과 반대로 '네 가능합니다' 라 답했다. + 기대결과: ★ 반려 — 질문을 주장에서 뺀 빈틈을 답변 극성 검사가 막는다.""" + payload = _payload( + intro="체크인은 15시입니다.", meta="체크인 15시.", + faqs=[{"question": "반려동물 동반이 가능한가요?", "answer": "네, 가능합니다.", + "fact_keys": ["pet_allowed"]}], + ) + async with _client(_ok(payload)) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + assert res.faqs == [] + assert any("부정하지 않는다" in reason for _t, reason in res.rejected) + + +def test_question_mentioning_missing_facility_is_still_rejected(): + """검증: 없는 시설을 묻는 질문("수영장 있나요?"). + 기대결과: 반려 — 의문문 예외는 값-반대 판정에만 적용되고, 없는 시설 언급은 그대로 잡는다.""" + ok, reasons = grounding_copy.ground_check("수영장이 있나요? 네 있습니다.", FACTS) + assert ok is False + assert any("수영장" in r for r in reasons) + + +# ── 입력 가드 ───────────────────────────────────────────────────────────── +async def test_no_facts_means_no_call_and_no_output(): + """검증: 근거 fact 가 하나도 없다. + 기대결과: ★ API 를 호출조차 하지 않고 빈 결과 — 근거 없이 쓰면 그게 환각이다.""" + calls = [] + async with _client(_ok(_payload(intro="아무거나"), calls)) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, [], client=c) + + assert calls == [], "근거가 없는데 유료 API 를 호출했다" + assert res.intro is None and res.faqs == [] + assert res.rejected and "근거 fact" in res.rejected[0][1] + + +async def test_missing_api_key_raises(): + """검증: GEMINI_API_KEY 미설정. + 기대결과: GeminiTextNotConfigured — 부팅은 막지 않고 이 어댑터만 비활성이다.""" + llm.external_api_config.gemini_api_key = "" + with pytest.raises(llm.GeminiNotConfigured): + await gt.generate_copy("x", PlaceCategory.LODGING, FACTS) + + +# ── 네트워크 ────────────────────────────────────────────────────────────── +async def test_retries_on_5xx_then_succeeds(): + """검증: 첫 호출이 503, 두 번째가 200. + 기대결과: 재시도해서 성공한다 — 일시적 장애로 생성을 포기하지 않는다.""" + calls = [] + + def handler(request): + calls.append(request) + if len(calls) == 1: + return httpx.Response(503, text="unavailable") + return httpx.Response(200, json=_payload(intro="체크인은 15시입니다.", meta="체크인 15시.")) + + async with _client(handler) as c: + res = await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c, max_retries=2) + + assert len(calls) == 2 + assert res.intro is not None + + +async def test_does_not_retry_on_4xx(): + """검증: 400 응답. + 기대결과: 재시도하지 않는다 — 잘못된 요청은 다시 보내도 같고 요금만 나간다.""" + calls = [] + + def handler(request): + calls.append(request) + return httpx.Response(400, text="bad request") + + async with _client(handler) as c: + with pytest.raises(llm.GeminiError): + await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c, max_retries=2) + + assert len(calls) == 1 + + +async def test_auth_failure_is_not_configured(): + """검증: 401 응답. + 기대결과: GeminiTextNotConfigured — 재시도가 무의미한 설정 문제다.""" + async with _client(lambda r: httpx.Response(401, text="unauthorized")) as c: + with pytest.raises(llm.GeminiNotConfigured): + await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + +async def test_broken_json_raises_invalid_output(): + """검증: 구조화 출력이 JSON 이 아니다. + 기대결과: GeminiTextInvalidOutput — 조용히 빈 결과로 넘기지 않는다.""" + payload = {"candidates": [{"content": {"parts": [{"text": "{깨진 json"}]}, "finishReason": "STOP"}]} + async with _client(_ok(payload)) as c: + with pytest.raises(llm.GeminiInvalidOutput): + await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + +async def test_empty_candidates_raises(): + """검증: 안전 필터 등으로 candidates 가 비어 왔다. + 기대결과: GeminiTextInvalidOutput.""" + async with _client(_ok({"candidates": []})) as c: + with pytest.raises(llm.GeminiInvalidOutput): + await gt.generate_copy("하조대펜션", PlaceCategory.LODGING, FACTS, client=c) + + +# ── ground_check 단위 ───────────────────────────────────────────────────── +def test_ground_check_reports_every_reason(): + """검증: 한 문장에 문제가 여러 개. + 기대결과: 사유가 전부 모여 나온다 — 운영자가 무엇이 문제인지 다 봐야 한다.""" + ok, reasons = grounding_copy.ground_check("국내 최고의 수영장을 갖춘 3층 건물입니다.", FACTS) + assert ok is False + assert len(reasons) >= 3 + + +def test_ground_check_rejects_empty_text(): + """검증: 빈 문장. + 기대결과: 반려.""" + ok, reasons = grounding_copy.ground_check(" ", FACTS) + assert ok is False and reasons == ["빈 문장"] + + +def test_ground_check_allows_facility_word_present_in_fact_value(): + """검증: fact 값 안에 그 낱말이 그대로 있다(대표 메뉴 = '수영장 뷰 라떼'). + 기대결과: 통과 — 근거가 fact 에 실제로 있다.""" + facts = FACTS + [grounding_copy.FactInput("signature_menu", "대표 메뉴", "수영장 뷰 라떼")] + ok, _reasons = grounding_copy.ground_check("대표 메뉴는 수영장 뷰 라떼입니다.", facts) + assert ok is True + + +def test_ground_check_grounds_numbers_from_unit_summaries(): + """검증: 객실 요약에만 있는 숫자(최대 4명)를 문장이 인용했다. + 기대결과: 통과 — generate_copy 가 객실 요약도 근거로 펼쳐 넘긴다.""" + grounding = FACTS + gt._unit_facts([{"name": "A동", "facts": {"max_capacity": "4"}}]) + ok, _reasons = grounding_copy.ground_check("A동은 최대 4명까지 이용하실 수 있습니다.", grounding) + assert ok is True diff --git a/backend/tests/test_healthz.py b/backend/tests/test_healthz.py new file mode 100644 index 0000000..d433702 --- /dev/null +++ b/backend/tests/test_healthz.py @@ -0,0 +1,12 @@ +"""부팅 스모크 — 앱이 뜨고 헬스체크가 응답하는지. + +보일러플레이트 이식 직후의 최소 확인. 도메인 코드가 얹히기 전에도 항상 통과해야 한다. +""" + + +async def test_healthz(client): + """검증: /healthz 호출. + 기대결과: 200, 서버 기동 시각 문자열(API_SERVER_START_TIME)이 그대로 반환.""" + r = await client.get("/healthz") + assert r.status_code == 200 + assert isinstance(r.json(), str) and len(r.json()) > 0 diff --git a/backend/tests/test_indexnow.py b/backend/tests/test_indexnow.py new file mode 100644 index 0000000..a9f4679 --- /dev/null +++ b/backend/tests/test_indexnow.py @@ -0,0 +1,105 @@ +"""발행 URL 의 색인 통보(IndexNow). + +이 경로가 절대 하면 안 되는 것: + - 통보 실패로 발행을 되돌리는 것 — 정적 파일은 이미 올라갔다. 다음 발행에서 다시 보내면 된다. + - 사이트맵에 없는 URL 을 통보하는 것 — 404 통보는 신뢰만 깎는다. +""" +from pathlib import Path + +import httpx +import pytest + +from services import indexnow + +SITEMAP = """ + + https://w4ai.o2o.kr/s/butter/ + https://w4ai.o2o.kr/s/butter/faq + +""" + + +def _out(tmp_path: Path, slug: str, body: str = SITEMAP) -> Path: + site = tmp_path / "s" / slug + site.mkdir(parents=True) + (site / "sitemap.xml").write_text(body) + return tmp_path + + +def test_키가_없으면_통보하지_않는다(monkeypatch): + monkeypatch.delenv("INDEXNOW_KEY", raising=False) + assert indexnow.is_configured() is False + + +def test_보낼_URL_은_사이트맵에서_읽는다(tmp_path, monkeypatch): + monkeypatch.setenv("SITE_OUTPUT_DIR", str(_out(tmp_path, "butter"))) + assert indexnow.site_urls("butter") == [ + "https://w4ai.o2o.kr/s/butter/", + "https://w4ai.o2o.kr/s/butter/faq", + ] + + +def test_사이트맵이_없으면_빈_목록(tmp_path, monkeypatch): + monkeypatch.setenv("SITE_OUTPUT_DIR", str(tmp_path)) + assert indexnow.site_urls("없는사이트") == [] + + +def test_깨진_사이트맵은_예외를_올리지_않는다(tmp_path, monkeypatch): + monkeypatch.setenv("SITE_OUTPUT_DIR", str(_out(tmp_path, "butter", "깨짐"))) + assert indexnow.site_urls("butter") == [] + + +@pytest.mark.asyncio +async def test_키파일_위치와_호스트를_URL에서_뽑는다(tmp_path, monkeypatch): + monkeypatch.setenv("SITE_OUTPUT_DIR", str(_out(tmp_path, "butter"))) + monkeypatch.setenv("INDEXNOW_KEY", "abc12345") + sent = {} + + async def fake_post(self, url, json=None, **kwargs): + sent["url"] = url + sent["body"] = json + return httpx.Response(200, request=httpx.Request("POST", url)) + + monkeypatch.setattr(httpx.AsyncClient, "post", fake_post) + + result = await indexnow.submit("butter") + + assert sent["url"] == indexnow.ENDPOINT + assert sent["body"]["host"] == "w4ai.o2o.kr" + assert sent["body"]["key"] == "abc12345" + # 키 파일은 오리진 루트에 있다 — 사이트 경로(/s/butter) 아래가 아니다. + assert sent["body"]["keyLocation"] == "https://w4ai.o2o.kr/abc12345.txt" + assert sent["body"]["urlList"] == [ + "https://w4ai.o2o.kr/s/butter/", + "https://w4ai.o2o.kr/s/butter/faq", + ] + assert result == {"ok": True, "status": 200, "urls": 2} + + +@pytest.mark.asyncio +async def test_거절되어도_예외를_올리지_않는다(tmp_path, monkeypatch): + monkeypatch.setenv("SITE_OUTPUT_DIR", str(_out(tmp_path, "butter"))) + monkeypatch.setenv("INDEXNOW_KEY", "abc12345") + + async def fake_post(self, url, json=None, **kwargs): + # 403 = 키 파일 대조 실패. 발행은 이미 끝났으므로 되돌리지 않는다. + return httpx.Response(403, text="key not found", request=httpx.Request("POST", url)) + + monkeypatch.setattr(httpx.AsyncClient, "post", fake_post) + + assert await indexnow.submit("butter") == {"ok": False, "status": 403, "urls": 2} + + +@pytest.mark.asyncio +async def test_네트워크_실패도_삼킨다(tmp_path, monkeypatch): + monkeypatch.setenv("SITE_OUTPUT_DIR", str(_out(tmp_path, "butter"))) + monkeypatch.setenv("INDEXNOW_KEY", "abc12345") + + async def fake_post(self, url, json=None, **kwargs): + raise httpx.ConnectTimeout("timed out") + + monkeypatch.setattr(httpx.AsyncClient, "post", fake_post) + + result = await indexnow.submit("butter") + assert result["ok"] is False + assert "ConnectTimeout" in result["error"] diff --git a/backend/tests/test_job_queue.py b/backend/tests/test_job_queue.py new file mode 100644 index 0000000..ac3adde --- /dev/null +++ b/backend/tests/test_job_queue.py @@ -0,0 +1,228 @@ +"""작업 큐 — 도커에서 워커를 여러 개 띄웠을 때 지켜져야 하는 것들. + +수집·비전분석·빌드는 몇 분 걸려 동기 요청으로 못 한다. 그 큐가 실제로: + 1. 같은 잡을 두 워커에 이중 할당하지 않는가 (FOR UPDATE SKIP LOCKED) + 2. 워커가 죽어도 잡이 증발하지 않는가 (lease 만료 → reaper 회수) + 3. 같은 요청을 두 번 눌러도 잡이 두 번 돌지 않는가 (dedupe_key) + 4. 실패가 백오프 재시도 → dead-letter 로 흐르는가 +""" +import asyncio +import uuid + +from sqlalchemy import text + +from common.enums import JobStatus, JobType +from crud.job_crud import JobQueue, compute_backoff +from worker.handlers import UnknownJobType, build_handler +from worker.runner import Worker, run_reaper + + +async def test_enqueue_and_claim(db_engine): + """검증: 잡을 넣고 워커가 claim 한다. + 기대결과: RUNNING 으로 전이되고 attempts 가 1 올라간다.""" + q = JobQueue() + jid = await q.enqueue(JobType.COLLECT.value, {"place_id": "abc"}) + assert jid + + claimed = await q.claim("w1") + assert claimed["job_id"] == jid + assert claimed["payload"] == {"place_id": "abc"} + assert claimed["attempts"] == 1 + + row = await q.get(jid) + assert row["status"] == JobStatus.RUNNING.value + + +async def test_claim_is_atomic_across_workers(db_engine): + """검증: 잡 1건에 워커 5개가 동시에 달려든다. + 기대결과: 정확히 1명만 가져간다 — 도커에서 워커를 몇 개로 스케일하든 이중 실행이 없다.""" + q = JobQueue() + jid = await q.enqueue(JobType.COLLECT.value, {"place_id": "race"}) + + results = await asyncio.gather(*[q.claim(f"w{i}") for i in range(5)]) + won = [r for r in results if r is not None] + assert len(won) == 1, f"이중 할당 발생: {len(won)}명이 같은 잡을 가져갔다" + assert won[0]["job_id"] == jid + + +async def test_claim_returns_none_when_empty(db_engine): + """검증: 빈 큐에서 claim. + 기대결과: None — 워커는 LISTEN 대기로 넘어간다.""" + assert await JobQueue().claim("w1") is None + + +async def test_dedupe_key_blocks_duplicate_active_job(db_engine): + """검증: 같은 dedupe_key 로 두 번 적재한다. + 기대결과: 두 번째는 None — 같은 사업장 수집을 두 번 눌러도 잡은 하나다.""" + q = JobQueue() + key = f"collect:{uuid.uuid4()}" + first = await q.enqueue(JobType.COLLECT.value, {}, dedupe_key=key) + second = await q.enqueue(JobType.COLLECT.value, {}, dedupe_key=key) + + assert first is not None + assert second is None + + active = await q.find_active(key) + assert active["job_id"] == first + + +async def test_dedupe_key_frees_after_completion(db_engine): + """검증: 완료된 뒤 같은 dedupe_key 로 다시 적재한다. + 기대결과: 새 잡이 생긴다 — 부분 유니크가 PENDING/RUNNING 에만 걸리기 때문.""" + q = JobQueue() + key = f"collect:{uuid.uuid4()}" + first = await q.enqueue(JobType.COLLECT.value, {}, dedupe_key=key) + claimed = await q.claim("w1") + assert await q.complete(claimed["job_id"], "w1", {"ok": True}) is True + + second = await q.enqueue(JobType.COLLECT.value, {}, dedupe_key=key) + assert second is not None and second != first + + +async def test_complete_requires_ownership(db_engine): + """검증: 자기가 점유하지 않은 잡을 완료 처리한다. + 기대결과: False — 소유권 가드(worker_id) 때문에 남의 잡을 끝낼 수 없다.""" + q = JobQueue() + await q.enqueue(JobType.BUILD.value, {}) + claimed = await q.claim("w1") + + assert await q.complete(claimed["job_id"], "other-worker", {}) is False + assert await q.complete(claimed["job_id"], "w1", {}) is True + + +async def test_fail_retries_then_dead_letters(db_engine): + """검증: max_attempts 만큼 계속 실패시킨다. + 기대결과: 시도가 남으면 PENDING(백오프), 소진되면 DEAD — 무한 재시도가 없다.""" + q = JobQueue() + jid = await q.enqueue(JobType.VISION.value, {}, max_attempts=2) + + claimed = await q.claim("w1") + assert await q.fail(jid, "w1", "boom", backoff_sec=0) == JobStatus.PENDING.value + + claimed = await q.claim("w1") + assert claimed is not None, "백오프 0 이면 즉시 다시 claim 가능해야 한다" + assert await q.fail(jid, "w1", "boom again", backoff_sec=0) == JobStatus.DEAD.value + + row = await q.get(jid) + assert row["status"] == JobStatus.DEAD.value + assert "boom again" in row["last_error"] + + +async def test_backoff_delays_next_claim(db_engine): + """검증: 실패 후 백오프가 걸린 잡. + 기대결과: run_after 가 지나기 전에는 claim 되지 않는다.""" + q = JobQueue() + jid = await q.enqueue(JobType.COPY.value, {}, max_attempts=5) + await q.claim("w1") + await q.fail(jid, "w1", "transient", backoff_sec=60) + + assert await q.claim("w1") is None, "백오프 중인 잡이 claim 됐다" + + +async def test_reaper_reclaims_dead_worker_job(db_engine): + """검증: 워커가 잡을 쥔 채 죽는다(도커 컨테이너 재시작). + 기대결과: lease 가 만료되면 reaper 가 회수해 다시 대기로 돌린다 — 잡이 증발하지 않는다.""" + q = JobQueue() + jid = await q.enqueue(JobType.COLLECT.value, {}) + await q.claim("dead-worker", lease_sec=120) + + # 워커 사망을 흉내 낸다: lease 를 과거로 돌린다. + async with db_engine.begin() as conn: + await conn.execute( + text("UPDATE jobs SET lease_until = now() - interval '1 minute' WHERE job_id = CAST(:id AS uuid)"), + {"id": jid}, + ) + + reclaimed = await q.reap() + assert jid in reclaimed + + row = await q.get(jid) + assert row["status"] == JobStatus.PENDING.value + assert "lease-expired reclaim" in row["last_error"] + assert await q.claim("new-worker") is not None + + +async def test_requeue_only_works_on_dead_jobs(db_engine): + """검증: DEAD 잡과 PENDING 잡에 각각 재큐를 시도한다. + 기대결과: DEAD 만 되살아나고 attempts 가 0으로 초기화된다.""" + q = JobQueue() + jid = await q.enqueue(JobType.COLLECT.value, {}, max_attempts=1) + await q.claim("w1") + assert await q.fail(jid, "w1", "fatal", backoff_sec=0) == JobStatus.DEAD.value + + assert await q.requeue(jid) == jid + row = await q.get(jid) + assert row["status"] == JobStatus.PENDING.value + assert row["attempts"] == 0 + + assert await q.requeue(jid) is None, "PENDING 잡은 재큐 대상이 아니다" + + +async def test_worker_runs_handler_and_completes(db_engine): + """검증: 워커 루프가 잡을 집어 핸들러를 돌리고 완료 처리한다. + 기대결과: 핸들러 반환값이 result 에 저장되고 status=DONE.""" + q = JobQueue() + jid = await q.enqueue(JobType.COLLECT.value, {"place_id": "p1"}) + + seen = [] + + async def handler(job): + seen.append(job["payload"]) + return {"collected": 3} + + worker = Worker("w-test", q, handler, job_deadline_sec=10) + assert await worker.process_one() is True + + assert seen == [{"place_id": "p1"}] + row = await q.get(jid) + assert row["status"] == JobStatus.DONE.value + assert row["result"] == {"collected": 3} + + +async def test_worker_deadline_cancels_hung_handler(db_engine): + """검증: 핸들러가 행(hang)에 빠진다. + 기대결과: 데드라인에 취소되고 잡은 재큐된다 — 행이 워커 슬롯을 영구 점유하지 않는다.""" + q = JobQueue() + jid = await q.enqueue(JobType.COLLECT.value, {}, max_attempts=5) + + async def hung(job): + await asyncio.sleep(30) + + worker = Worker("w-test", q, hung, job_deadline_sec=0.2, backoff_fn=lambda _a: 0) + assert await worker.process_one() is True + + row = await q.get(jid) + assert row["status"] == JobStatus.PENDING.value + assert row["last_error"].startswith("JobDeadlineExceeded") + + +async def test_unregistered_job_type_fails_loudly(db_engine): + """검증: 핸들러가 등록되지 않은 JobType 을 처리한다. + 기대결과: UnknownJobType 으로 실패하고 last_error 에 남는다(조용히 성공하지 않는다).""" + q = JobQueue() + jid = await q.enqueue(JobType.AI_CHECK.value, {}, max_attempts=1) + + worker = Worker("w-test", q, build_handler(), backoff_fn=lambda _a: 0) + await worker.process_one() + + row = await q.get(jid) + assert row["status"] == JobStatus.DEAD.value + assert UnknownJobType.__name__ in row["last_error"] + + +async def test_reaper_loop_stops_on_event(db_engine): + """검증: reaper 루프에 stop 이벤트를 건다. + 기대결과: 즉시 빠져나온다(graceful shutdown 이 매달리지 않는다).""" + stop = asyncio.Event() + task = asyncio.create_task(run_reaper(JobQueue(), stop, interval=0.05)) + await asyncio.sleep(0.1) + stop.set() + await asyncio.wait_for(task, timeout=2) + + +def test_backoff_is_exponential_and_capped(): + """검증: 백오프 계산. + 기대결과: 5초부터 2배씩 늘고 600초에서 멈춘다.""" + assert compute_backoff(1) == 5 + assert compute_backoff(3) == 20 + assert compute_backoff(99) == 600 diff --git a/backend/tests/test_kakao.py b/backend/tests/test_kakao.py new file mode 100644 index 0000000..c016234 --- /dev/null +++ b/backend/tests/test_kakao.py @@ -0,0 +1,416 @@ +"""카카오 로컬 클라이언트 — 동일 업소 판정과 응답 파싱. + +★ 실제 API 를 호출하지 않는다(httpx.MockTransport). 카카오 호출은 유료라 테스트가 때리면 안 된다. + +여기서 고정하는 것: + 1. x=경도 / y=위도 — 뒤집으면 엉뚱한 지역의 주변 정보가 붙는다 + 2. 동일 업소 판정이 애매할 때 **반드시 ambiguous 로 떨어지는지** — 이 서비스에서 가장 비싼 실수 + 3. 키 미설정·장애가 조용히 빈 값으로 새지 않는지 +""" +import httpx +import pytest + +from services.external.kakao import ( + CATEGORY_RESTAURANT, + KakaoLocalClient, + KakaoNotConfigured, + KakaoPlace, + KakaoRequestFailed, + MatchOutcome, + normalize_name, + normalize_phone, + pick_match, +) + +# ── 카카오 실제 응답 모양 ───────────────────────────────────────────────── +_KEYWORD_DOC = { + "id": "26338954", + "place_name": "하조대펜션", + "category_name": "가정,생활 > 숙박 > 펜션", + "category_group_code": "AD5", + "phone": "033-672-0000", + "address_name": "강원 양양군 현북면 하광정리 3-1", + "road_address_name": "강원 양양군 현북면 하조대해안길 3", + "x": "128.6712345", # ★ 경도 + "y": "38.0451234", # ★ 위도 + "place_url": "http://place.map.kakao.com/26338954", +} + +_COORD2REGION_DOCS = [ + { + "region_type": "B", + "code": "4283025021", + "address_name": "강원도 양양군 현북면 하광정리", + "region_1depth_name": "강원도", + "region_2depth_name": "양양군", + "region_3depth_name": "현북면 하광정리", + }, + { + "region_type": "H", + "code": "4283025000", + "address_name": "강원도 양양군 현북면", + "region_1depth_name": "강원도", + "region_2depth_name": "양양군", + "region_3depth_name": "현북면", + }, +] + + +def _client(handler, api_key: str = "test-kakao-key") -> KakaoLocalClient: + """MockTransport 를 물린 클라이언트. 실제 네트워크를 타지 않는다.""" + return KakaoLocalClient(api_key=api_key, transport=httpx.MockTransport(handler)) + + +def _place(name, kakao_id="1", phone=None, road="강원 양양군 A로 1") -> KakaoPlace: + return KakaoPlace( + kakao_place_id=kakao_id, name=name, road_address=road, address=None, + phone=phone, latitude=38.0, longitude=128.6, category_name=None, place_url=None, + ) + + +# ── 1) 키워드 검색 파싱 ─────────────────────────────────────────────────── +async def test_search_keyword_parses_documents(): + """검증: 키워드 검색 응답을 KakaoPlace 로 파싱한다. + 기대결과: ★ x 가 경도(longitude), y 가 위도(latitude) 로 들어간다 — 뒤집히면 다른 지역이 된다.""" + captured = {} + + def handler(request: httpx.Request) -> httpx.Response: + captured["url"] = str(request.url) + captured["auth"] = request.headers.get("Authorization") + return httpx.Response(200, json={"documents": [_KEYWORD_DOC], "meta": {"total_count": 1}}) + + places = await _client(handler).search_keyword("하조대펜션") + + assert len(places) == 1 + p = places[0] + assert p.kakao_place_id == "26338954" + assert p.name == "하조대펜션" + assert p.phone == "033-672-0000" + assert p.road_address == "강원 양양군 현북면 하조대해안길 3" + assert p.longitude == pytest.approx(128.6712345) # ★ x + assert p.latitude == pytest.approx(38.0451234) # ★ y + assert captured["auth"] == "KakaoAK test-kakao-key" + assert "search/keyword.json" in captured["url"] + + +async def test_search_keyword_sends_coordinates_when_given(): + """검증: 좌표를 주고 키워드 검색한다. + 기대결과: x=경도, y=위도 로 쿼리에 실린다(지역을 알면 후보가 깨끗해진다).""" + captured = {} + + def handler(request: httpx.Request) -> httpx.Response: + captured["params"] = dict(request.url.params) + return httpx.Response(200, json={"documents": []}) + + await _client(handler).search_keyword("펜션", x=128.67, y=38.04) + + assert captured["params"]["x"] == "128.67" # 경도 + assert captured["params"]["y"] == "38.04" # 위도 + + +async def test_search_keyword_empty_result(): + """검증: 후보가 없는 검색. + 기대결과: 빈 리스트 — 예외가 아니다(판정은 pick_match 가 한다).""" + def handler(request): + return httpx.Response(200, json={"documents": []}) + + assert await _client(handler).search_keyword("없는가게") == [] + + +# ── 2) 좌표 → 행정구역 코드 ─────────────────────────────────────────────── +async def test_coord_to_region_prefers_administrative_dong(): + """검증: 좌표를 행정구역 코드로 바꾼다. + 기대결과: 행정동(region_type=H)을 우선 고른다 — 생활권 기준이라 주변 정보와 맞는다.""" + captured = {} + + def handler(request: httpx.Request) -> httpx.Response: + captured["params"] = dict(request.url.params) + return httpx.Response(200, json={"documents": _COORD2REGION_DOCS}) + + region = await _client(handler).coord_to_region(lat=38.0451234, lon=128.6712345) + + assert region.code == "4283025000" # H 문서 + assert region.region_type == "H" + assert region.region_1depth_name == "강원도" + assert region.full_name == "강원도 양양군 현북면" + assert captured["params"]["x"] == "128.6712345" # ★ 경도 + assert captured["params"]["y"] == "38.0451234" # ★ 위도 + + +async def test_coord_to_region_falls_back_to_first_document(): + """검증: 행정동(H) 문서가 없는 응답. + 기대결과: 첫 문서(법정동 B)로 폴백한다.""" + def handler(request): + return httpx.Response(200, json={"documents": [_COORD2REGION_DOCS[0]]}) + + region = await _client(handler).coord_to_region(38.0, 128.6) + assert region.code == "4283025021" + assert region.region_type == "B" + + +async def test_coord_to_region_without_result_raises(): + """검증: 좌표 변환 결과가 비어 있다. + 기대결과: KakaoRequestFailed — ★ 빈 값을 조용히 내보내지 않는다.""" + def handler(request): + return httpx.Response(200, json={"documents": []}) + + with pytest.raises(KakaoRequestFailed): + await _client(handler).coord_to_region(38.0, 128.6) + + +# ── 3) 주변 카테고리 검색 ───────────────────────────────────────────────── +async def test_search_category_sends_expected_params(): + """검증: 주변 맛집(FD6) 검색. + 기대결과: 카테고리 코드·반경·좌표(x=경도, y=위도)가 그대로 실린다.""" + captured = {} + + def handler(request: httpx.Request) -> httpx.Response: + captured["params"] = dict(request.url.params) + return httpx.Response(200, json={"documents": [_KEYWORD_DOC]}) + + places = await _client(handler).search_category( + region_x=128.67, region_y=38.04, category_group_code=CATEGORY_RESTAURANT, + radius=1500, region_code="4283025000", + ) + + assert len(places) == 1 + assert captured["params"]["category_group_code"] == "FD6" + assert captured["params"]["radius"] == "1500" + assert captured["params"]["x"] == "128.67" + assert captured["params"]["y"] == "38.04" + + +async def test_search_category_warns_without_region_code(capsys): + """검증: 행정구역 코드 없이 카테고리 검색을 부른다. + 기대결과: 경고 로그 — 캐시를 안 거치면 같은 지역을 사이트 수만큼 반복 조회하게 된다(건당 2원).""" + def handler(request): + return httpx.Response(200, json={"documents": []}) + + await _client(handler).search_category(128.67, 38.04, CATEGORY_RESTAURANT) + + assert "region_code 없이" in capsys.readouterr().err + + +async def test_search_category_clamps_radius(): + """검증: 카카오 상한(20km)을 넘는 반경을 넘긴다. + 기대결과: 20000 으로 잘린다(400 응답을 미리 막는다).""" + captured = {} + + def handler(request: httpx.Request) -> httpx.Response: + captured["radius"] = dict(request.url.params)["radius"] + return httpx.Response(200, json={"documents": []}) + + await _client(handler).search_category(128.6, 38.0, CATEGORY_RESTAURANT, radius=99999, region_code="X") + assert captured["radius"] == "20000" + + +# ── 4) ★ 동일 업소 판정 ─────────────────────────────────────────────────── +def test_pick_match_no_candidate(): + """검증: 후보가 0건이다. + 기대결과: NO_CANDIDATE — 호출측이 PLACE_VERIFY_NO_CANDIDATE 로 응답한다.""" + result = pick_match("하조대펜션", []) + assert result.outcome == MatchOutcome.NO_CANDIDATE + assert result.place is None + assert result.reason == "no_candidate" + + +def test_pick_match_single_exact_name(): + """검증: 상호명이 정확히 일치하는 후보가 1건이다. + 기대결과: MATCHED — 근거(name_exact)가 함께 남는다.""" + only = _place("하조대펜션", "111") + result = pick_match("하조대펜션", [only]) + + assert result.outcome == MatchOutcome.MATCHED + assert result.place is only + assert result.reason == "name_exact" + assert result.is_matched is True + + +def test_pick_match_ignores_whitespace_and_case(): + """검증: '하조대 펜션' 으로 검색하고 후보는 '하조대펜션' 이다. + 기대결과: MATCHED — 공백/대소문자까지만 정규화한다.""" + result = pick_match("하조대 펜션", [_place("하조대펜션", "111")]) + assert result.outcome == MatchOutcome.MATCHED + + +def test_pick_match_duplicate_names_is_ambiguous(): + """검증: ★ 상호명이 같은 업소가 2건이다(동명 업소). + 기대결과: AMBIGUOUS — 억지로 하나 고르면 남의 가게 정보가 섞인다. 사람이 주소로 골라야 한다.""" + a = _place("하조대펜션", "111", road="강원 양양군 A로 1") + b = _place("하조대펜션", "222", road="강원 양양군 B로 2") + result = pick_match("하조대펜션", [a, b]) + + assert result.outcome == MatchOutcome.AMBIGUOUS + assert result.place is None + assert result.reason == "name_duplicate" + assert len(result.candidates) == 2 + # 근거에 주소가 실려 사람이 고를 수 있어야 한다. + assert "A로 1" in result.detail and "B로 2" in result.detail + + +def test_pick_match_partial_name_is_ambiguous(): + """검증: 후보가 1건뿐이지만 상호명이 정확히 일치하지 않는다('하조대펜션' vs '하조대펜션 별관'). + 기대결과: ★ AMBIGUOUS — 부분일치만으로 확정하지 않는다. 별관은 다른 가게일 수 있다.""" + result = pick_match("하조대펜션", [_place("하조대펜션 별관", "111")]) + + assert result.outcome == MatchOutcome.AMBIGUOUS + assert result.reason == "name_no_exact" + assert result.place is None + + +def test_pick_match_phone_resolves_duplicate_names(): + """검증: 동명 업소 2건인데 전화번호가 주어졌고 1건만 일치한다. + 기대결과: MATCHED — 전화번호가 가장 강한 근거다.""" + a = _place("하조대펜션", "111", phone="033-672-0000") + b = _place("하조대펜션", "222", phone="033-672-9999") + result = pick_match("하조대펜션", [a, b], phone="0336720000") + + assert result.outcome == MatchOutcome.MATCHED + assert result.place is a + assert result.reason == "phone_exact" + + +def test_pick_match_phone_mismatch_falls_back_to_name(): + """검증: 전화번호를 줬지만 어느 후보와도 안 맞는다(동명 2건). + 기대결과: AMBIGUOUS — 전화번호가 안 맞았다고 아무거나 고르지 않는다.""" + a = _place("하조대펜션", "111", phone="033-672-0000") + b = _place("하조대펜션", "222", phone="033-672-9999") + result = pick_match("하조대펜션", [a, b], phone="02-000-0000") + + assert result.outcome == MatchOutcome.AMBIGUOUS + assert result.reason == "name_duplicate" + + +def test_pick_match_phone_narrows_then_name_decides(): + """검증: 전화번호가 같은 후보가 2건이고 그중 상호명이 정확히 맞는 게 1건이다(지점 등록). + 기대결과: MATCHED — 전화번호로 좁힌 뒤 상호명으로 확정하고, 근거에 좁힌 사실이 남는다.""" + a = _place("하조대펜션", "111", phone="033-672-0000") + b = _place("하조대펜션 카페", "222", phone="033-672-0000") + c = _place("다른펜션", "333", phone="033-999-9999") + result = pick_match("하조대펜션", [a, b, c], phone="033-672-0000") + + assert result.outcome == MatchOutcome.MATCHED + assert result.place is a + assert "좁힘" in result.detail + + +def test_pick_match_never_guesses_from_many_unrelated(): + """검증: 상호명이 정확히 맞는 후보 없이 비슷한 이름만 여럿이다. + 기대결과: ★ AMBIGUOUS — 이 서비스에서 자동 판정으로 넘어가면 안 되는 구간이다.""" + candidates = [_place(f"하조대펜션{i}", str(i)) for i in range(5)] + result = pick_match("하조대펜션", candidates) + + assert result.outcome == MatchOutcome.AMBIGUOUS + assert result.place is None + assert len(result.candidates) == 5 + + +def test_normalize_helpers(): + """검증: 비교용 정규화. + 기대결과: 상호명은 공백/대소문자만, 전화번호는 숫자만 남는다.""" + assert normalize_name("하조대 펜션") == normalize_name("하조대펜션") + assert normalize_name("Beach House") == "beachhouse" + assert normalize_name("하조대펜션") != normalize_name("하조대펜션별관") + assert normalize_phone("033-672-0000") == "0336720000" + assert normalize_phone("") == "" + + +# ── 5) 조합: verify_place ───────────────────────────────────────────────── +async def test_verify_place_matches_single_candidate(): + """검증: 상호명으로 검색해 동일 업소까지 한 번에 판정한다. + 기대결과: 키워드 검색 1회로 MATCHED. 반환된 place 에 카카오 장소 ID 가 실린다.""" + def handler(request): + return httpx.Response(200, json={"documents": [_KEYWORD_DOC]}) + + result = await _client(handler).verify_place("하조대펜션", phone="033-672-0000") + + assert result.outcome == MatchOutcome.MATCHED + assert result.place.kakao_place_id == "26338954" + + +async def test_verify_place_ambiguous_when_duplicate_names(): + """검증: 검색 결과에 동명 업소가 2건이다. + 기대결과: AMBIGUOUS + 후보 목록 — 호출측이 PLACE_VERIFY_AMBIGUOUS 로 사람에게 넘긴다.""" + doc2 = {**_KEYWORD_DOC, "id": "999", "phone": "033-000-0000", "road_address_name": "강원 양양군 B로 2"} + + def handler(request): + return httpx.Response(200, json={"documents": [_KEYWORD_DOC, doc2]}) + + result = await _client(handler).verify_place("하조대펜션") + + assert result.outcome == MatchOutcome.AMBIGUOUS + assert len(result.candidates) == 2 + + +# ── 6) 설정·장애 ────────────────────────────────────────────────────────── +async def test_missing_api_key_raises_not_configured(): + """검증: KAKAO_REST_API_KEY 가 비어 있다. + 기대결과: KakaoNotConfigured — 이 어댑터만 비활성이고 서버 부팅은 막지 않는다.""" + client = KakaoLocalClient(api_key="") + assert client.enabled is False + + with pytest.raises(KakaoNotConfigured): + await client.search_keyword("아무거나") + + +async def test_invalid_key_401_raises_not_configured(): + """검증: 키가 있지만 잘못됐다(401). + 기대결과: KakaoNotConfigured — 설정 문제라 재시도해도 소용없다.""" + def handler(request): + return httpx.Response(401, json={"errorType": "AccessDeniedError"}) + + with pytest.raises(KakaoNotConfigured): + await _client(handler).search_keyword("하조대펜션") + + +async def test_server_error_raises_request_failed(): + """검증: 카카오가 5xx 를 돌려준다. + 기대결과: KakaoRequestFailed — ★ 빈 결과로 둔갑시키지 않는다(직전 값 유지는 호출측 책임).""" + def handler(request): + return httpx.Response(503, text="service unavailable") + + with pytest.raises(KakaoRequestFailed): + await _client(handler).search_keyword("하조대펜션") + + +async def test_timeout_raises_request_failed(): + """검증: 요청이 타임아웃된다. + 기대결과: KakaoRequestFailed — 도메인 예외로 감싸 호출측이 LOCAL_FETCH_FAILED 로 처리한다.""" + def handler(request): + raise httpx.ReadTimeout("timed out", request=request) + + with pytest.raises(KakaoRequestFailed): + await _client(handler).coord_to_region(38.0, 128.6) + + +async def test_malformed_json_raises_request_failed(): + """검증: 200 인데 본문이 JSON 이 아니다. + 기대결과: KakaoRequestFailed — 파싱 실패가 조용히 빈 결과가 되지 않는다.""" + def handler(request): + return httpx.Response(200, text="not json") + + with pytest.raises(KakaoRequestFailed): + await _client(handler).search_keyword("하조대펜션") + + +async def test_call_counts_track_cost(): + """검증: 호출할 때마다 누적 카운터가 오른다. + 기대결과: 생성 1건당 검색 횟수를 셀 수 있다(초과 시 키워드 2원 / 좌표변환 0.5원).""" + from services.external import kakao as kakao_mod + + kakao_mod.reset_call_counts() + + def handler(request): + if "coord2regioncode" in str(request.url): + return httpx.Response(200, json={"documents": _COORD2REGION_DOCS}) + return httpx.Response(200, json={"documents": [_KEYWORD_DOC]}) + + client = _client(handler) + await client.search_keyword("하조대펜션") + await client.search_keyword("하조대펜션") + await client.coord_to_region(38.0, 128.6) + + counts = kakao_mod.call_counts() + assert counts["keyword"] == 2 + assert counts["coord2region"] == 1 + kakao_mod.reset_call_counts() diff --git a/backend/tests/test_naver.py b/backend/tests/test_naver.py new file mode 100644 index 0000000..5c73b68 --- /dev/null +++ b/backend/tests/test_naver.py @@ -0,0 +1,476 @@ +"""네이버 지역검색 클라이언트 — 동일 업소 판정과 응답 파싱. + +★ 실제 API 를 호출하지 않는다(httpx.MockTransport). 테스트가 외부 쿼터를 태우면 안 된다. + +여기서 고정하는 것: + 1. mapx=경도 / mapy=위도, 1e7 로 나눈 값이 WGS84 — 뒤집거나 잘못 나누면 엉뚱한 지역이 붙는다 + 2. 네이버 제약(5건 상한 · 전화번호 없음)을 코드가 실제로 인지하는지 + 3. 동일 업소 판정이 애매할 때 **반드시 ambiguous 로 떨어지는지** — 이 서비스에서 가장 비싼 실수 + 4. 지역 캐시 키가 시도 별칭(강원도/강원특별자치도)을 하나로 모으는지, 그리고 10자를 안 넘는지 + 5. 키 미설정·장애가 조용히 빈 값으로 새지 않는지 +""" +import httpx +import pytest + +from services.external.kakao import MatchOutcome +from services.external.naver import ( + NaverLocalClient, + NaverNotConfigured, + NaverPlace, + NaverRequestFailed, + normalize_name, + pick_match, + region_key, + reset_call_counts, + strip_tags, +) + +# ── 네이버 실제 응답 모양 (2026-08-27 실측) ──────────────────────────────── +# 서울특별시청: mapx=1269783882 mapy=375666103 → 126.97839, 37.56661 (실제 37.5663, 126.9779) +_SEOUL_CITY_HALL = { + "title": "서울특별시청", + "link": "https://www.seoul.go.kr/", + "category": "공공,사회기관>시청", + "description": "", + "telephone": "", + "address": "서울특별시 중구 태평로1가 31", + "roadAddress": "서울특별시 중구 세종대로 110", + "mapx": "1269783882", + "mapy": "375666103", +} + +# 하조대 인근 펜션 — title 에 와 & 가 함께 섞인 실제 모양 +_PENSION = { + "title": "풀라운지펜션&글램핑", + "link": "", + "category": "숙박>펜션", + "description": "", + "telephone": "", + "address": "강원특별자치도 양양군 현북면 하광정리 산 1", + "roadAddress": "강원특별자치도 양양군 현북면 하조대2길 48-69", + "mapx": "1287203824", + "mapy": "380236812", +} + + +def _handler(payload, status: int = 200, capture: dict | None = None): + """MockTransport 핸들러. capture 를 주면 요청 정보를 담아준다.""" + + def _h(request: httpx.Request) -> httpx.Response: + if capture is not None: + capture["url"] = str(request.url) + capture["params"] = dict(request.url.params) + capture["headers"] = dict(request.headers) + if isinstance(payload, str): + return httpx.Response(status, text=payload) + return httpx.Response(status, json=payload) + + return _h + + +def _client(handler, client_id="test-id", client_secret="test-secret") -> NaverLocalClient: + """MockTransport 를 물린 클라이언트. 실제 네트워크를 타지 않는다.""" + return NaverLocalClient( + client_id=client_id, client_secret=client_secret, transport=httpx.MockTransport(handler) + ) + + +def _place(name, road="강원특별자치도 양양군 현북면 하조대3길 25", addr=None) -> NaverPlace: + return NaverPlace( + name=name, road_address=road, address=addr, phone=None, + latitude=38.02, longitude=128.72, category_name="숙박>펜션", + place_url=None, naver_place_id=None, + ) + + +@pytest.fixture(autouse=True) +def _reset(): + reset_call_counts() + yield + reset_call_counts() + + +# ── 응답 파싱 ───────────────────────────────────────────────────────────── +async def test_parses_item_and_strips_highlight_tags(): + """검증: title 에 `` 태그와 HTML 엔티티가 섞인 응답을 파싱한다. + 기대결과: 태그·엔티티가 벗겨진 상호명이 나온다('풀라운지펜션&글램핑').""" + c = _client(_handler({"items": [_PENSION]})) + places = await c.search_local("하조대 펜션") + + assert len(places) == 1 + assert places[0].name == "풀라운지펜션&글램핑" + assert places[0].category_name == "숙박>펜션" + assert places[0].road_address == "강원특별자치도 양양군 현북면 하조대2길 48-69" + + +async def test_mapx_is_longitude_and_mapy_is_latitude(): + """검증: 실측 응답(서울특별시청)의 mapx/mapy 를 좌표로 바꾼다. + 기대결과: 1e7 로 나눈 값이 실제 위경도(37.5663, 126.9779)와 오차 0.01 이내로 일치한다. + ★ 뒤집히면 위도 126 도가 되어 지구 밖이다.""" + c = _client(_handler({"items": [_SEOUL_CITY_HALL]})) + place = (await c.search_local("서울특별시청"))[0] + + assert place.longitude == pytest.approx(126.9779, abs=0.01) # ★ mapx = 경도 + assert place.latitude == pytest.approx(37.5663, abs=0.01) # ★ mapy = 위도 + assert 33.0 < place.latitude < 39.0, "위도가 한반도 범위를 벗어났다(mapx/mapy 를 뒤집었을 가능성)" + assert 124.0 < place.longitude < 132.0 + + +async def test_empty_telephone_becomes_none(): + """검증: 네이버가 telephone 을 빈 문자열로 주는 실제 동작. + 기대결과: phone 이 None 이다 — 빈 문자열이 '전화번호가 있다'로 오해되면 안 된다.""" + c = _client(_handler({"items": [_PENSION]})) + place = (await c.search_local("펜션"))[0] + + assert place.phone is None + + +async def test_link_is_business_homepage_not_place_id(): + """검증: link 필드 처리. + 기대결과: place_url 에는 담기지만 naver_place_id 는 None — + 네이버 지역검색의 link 는 플레이스 페이지가 아니라 업체 자체 홈페이지다.""" + c = _client(_handler({"items": [_SEOUL_CITY_HALL]})) + place = (await c.search_local("서울특별시청"))[0] + + assert place.place_url == "https://www.seoul.go.kr/" + assert place.naver_place_id is None + + +async def test_missing_coordinates_do_not_crash(): + """검증: mapx/mapy 가 비었거나 숫자가 아닌 응답. + 기대결과: 좌표만 None 이고 나머지는 정상 파싱된다(파싱 실패로 전체가 죽지 않는다).""" + broken = {**_PENSION, "mapx": "", "mapy": None} + c = _client(_handler({"items": [broken]})) + place = (await c.search_local("펜션"))[0] + + assert place.latitude is None and place.longitude is None + assert place.name == "풀라운지펜션&글램핑" + + +async def test_empty_items_returns_empty_list(): + """검증: 검색 결과가 0건인 응답. + 기대결과: 빈 리스트. 예외가 아니다 — '못 찾음'은 장애가 아니라 정상 결과다.""" + c = _client(_handler({"items": []})) + assert await c.search_local("없는가게") == [] + + +# ── 네이버 제약: 5건 상한 ────────────────────────────────────────────────── +async def test_display_is_clamped_to_five(): + """검증: display 를 15 로 요청한다. + 기대결과: 실제 요청 파라미터가 5 로 잘린다 — 네이버 상한이 5이고, 더 줘도 조용히 5건만 온다.""" + cap: dict = {} + c = _client(_handler({"items": []}, capture=cap)) + await c.search_local("카페", display=15) + + assert cap["params"]["display"] == "5" + + +async def test_display_lower_bound_is_one(): + """검증: display 를 0 이하로 요청한다. + 기대결과: 1 로 올라간다(0 은 네이버가 거부한다).""" + cap: dict = {} + c = _client(_handler({"items": []}, capture=cap)) + await c.search_local("카페", display=0) + + assert cap["params"]["display"] == "1" + + +async def test_auth_headers_are_sent(): + """검증: 요청 헤더. + 기대결과: X-Naver-Client-Id / X-Naver-Client-Secret 가 실린다.""" + cap: dict = {} + c = _client(_handler({"items": []}, capture=cap)) + await c.search_local("카페") + + assert cap["headers"]["x-naver-client-id"] == "test-id" + assert cap["headers"]["x-naver-client-secret"] == "test-secret" + + +# ── 동일 업소 판정 ──────────────────────────────────────────────────────── +def test_pick_match_no_candidate(): + """검증: 후보가 0건이다. + 기대결과: NO_CANDIDATE — 확정도 애매도 아니고 '못 찾음'이다.""" + result = pick_match("하조대펜션", []) + + assert result.outcome == MatchOutcome.NO_CANDIDATE + assert result.place is None + assert result.is_matched is False + + +def test_pick_match_single_exact_name(): + """검증: 상호명이 정확히 1건만 일치한다. + 기대결과: MATCHED(name_exact) — 확정.""" + candidates = [_place("하조대펜션"), _place("핑크비치펜션"), _place("부커스비치호텔")] + result = pick_match("하조대펜션", candidates) + + assert result.outcome == MatchOutcome.MATCHED + assert result.reason == "name_exact" + assert result.place.name == "하조대펜션" + + +def test_pick_match_ignores_spacing_in_name(): + """검증: '하조대 펜션' 으로 찾고 후보는 '하조대펜션' 이다. + 기대결과: MATCHED — 공백 차이는 같은 가게로 본다.""" + result = pick_match("하조대 펜션", [_place("하조대펜션")]) + + assert result.outcome == MatchOutcome.MATCHED + + +def test_pick_match_duplicate_names_is_ambiguous(): + """검증: 상호명이 똑같은 업소가 2건이다(주소 힌트 없음). + 기대결과: ★ AMBIGUOUS — 전화번호가 없어 가를 근거가 없으니 사람이 골라야 한다.""" + candidates = [ + _place("하조대펜션", road="강원특별자치도 양양군 현북면 하조대3길 25"), + _place("하조대펜션", road="강원특별자치도 양양군 손양면 도리단길 7"), + ] + result = pick_match("하조대펜션", candidates) + + assert result.outcome == MatchOutcome.AMBIGUOUS + assert result.reason == "name_duplicate" + assert result.place is None + assert len(result.candidates) == 2 + assert "전화번호를 주지 않아" in result.detail + + +def test_pick_match_address_hint_narrows_duplicates(): + """검증: 동명 업소 2건에 주소 힌트를 준다. + 기대결과: MATCHED(name_address) — 주소로 1건으로 좁혀지면 확정한다.""" + candidates = [ + _place("하조대펜션", road="강원특별자치도 양양군 현북면 하조대3길 25"), + _place("하조대펜션", road="강원특별자치도 양양군 손양면 도리단길 7"), + ] + result = pick_match("하조대펜션", candidates, address_hint="양양군 현북면 하조대3길") + + assert result.outcome == MatchOutcome.MATCHED + assert result.reason == "name_address" + assert "현북면" in result.place.road_address + + +def test_pick_match_address_hint_that_narrows_nothing_stays_ambiguous(): + """검증: 동명 업소 2건인데 주소 힌트가 양쪽에 똑같이 걸린다. + 기대결과: ★ 여전히 AMBIGUOUS — 애매한 걸 억지로 좁혀 확정하지 않는다.""" + candidates = [ + _place("하조대펜션", road="강원특별자치도 양양군 현북면 A길 1"), + _place("하조대펜션", road="강원특별자치도 양양군 현북면 B길 2"), + ] + result = pick_match("하조대펜션", candidates, address_hint="양양군 현북면") + + assert result.outcome == MatchOutcome.AMBIGUOUS + + +def test_pick_match_partial_name_is_ambiguous(): + """검증: 정확히 일치하는 상호명이 없고 부분일치만 있다. + 기대결과: ★ AMBIGUOUS — '하조대펜션' 과 '하조대펜션 별관' 은 다른 가게다. 확정하지 않는다.""" + candidates = [_place("하조대펜션 별관"), _place("하조대펜션앤스파")] + result = pick_match("하조대펜션", candidates) + + assert result.outcome == MatchOutcome.AMBIGUOUS + assert result.reason == "name_no_exact" + assert result.place is None + + +def test_pick_match_single_partial_candidate_is_still_ambiguous(): + """검증: 후보가 딱 1건인데 상호명이 정확히 일치하지 않는다. + 기대결과: ★ AMBIGUOUS — 후보가 하나뿐이라고 그게 맞는 가게는 아니다.""" + result = pick_match("하조대펜션", [_place("하조대풀빌라")]) + + assert result.outcome == MatchOutcome.AMBIGUOUS + assert result.place is None + + +async def test_verify_place_end_to_end(): + """검증: 상호명으로 검색해서 판정까지 한 번에 한다. + 기대결과: 지역검색 1회로 MATCHED 가 나온다.""" + item = {**_PENSION, "title": "하조대펜션"} + c = _client(_handler({"items": [item]})) + result = await c.verify_place("하조대펜션", address_hint="강원특별자치도 양양군") + + assert result.outcome == MatchOutcome.MATCHED + assert result.place.name == "하조대펜션" + + +async def test_verify_place_retries_without_address_when_empty(): + """검증: 주소를 섞어 검색했더니 0건이다. + 기대결과: 상호명만으로 한 번 더 찾아본다 — 주소 표기 차이로 0건이 나는 경우를 흡수한다.""" + calls = {"n": 0} + + def handler(request: httpx.Request) -> httpx.Response: + calls["n"] += 1 + if calls["n"] == 1: + return httpx.Response(200, json={"items": []}) + return httpx.Response(200, json={"items": [{**_PENSION, "title": "하조대펜션"}]}) + + c = _client(handler) + result = await c.verify_place("하조대펜션", address_hint="강원 양양") + + assert calls["n"] == 2 + assert result.outcome == MatchOutcome.MATCHED + + +# ── 지역 캐시 키 ────────────────────────────────────────────────────────── +def test_region_key_basic(): + """검증: 도로명주소에서 시도 + 시군구를 뽑는다. + 기대결과: '51양양군' — 이 키 단위로 지역 정보를 캐싱한다.""" + assert region_key("강원특별자치도 양양군 현북면 하조대3길 25") == "51양양군" + + +def test_region_key_merges_sido_aliases(): + """검증: 같은 지역인데 시도 이름이 옛 이름/새 이름으로 다르게 온다. + 기대결과: ★ 같은 키 — 갈리면 같은 지역을 두 번 조회하게 되어 캐시가 무의미해진다.""" + assert region_key("강원도 양양군 현북면 하조대3길 25") == region_key( + "강원특별자치도 양양군 현북면 하조대3길 25" + ) + assert region_key("전라북도 전주시 완산구 A로 1") == region_key("전북특별자치도 전주시 완산구 A로 1") + assert region_key("제주도 제주시 A로 1") == region_key("제주특별자치도 제주시 A로 1") + + +def test_region_key_metropolitan_district(): + """검증: 특별시·광역시의 자치구. + 기대결과: 구 단위로 남는다('11강남구') — 생활권이 실제로 다르다.""" + assert region_key("서울특별시 강남구 도산대로57길 24 (청담동)") == "11강남구" + assert region_key("부산광역시 해운대구 우동 1394") == "26해운대구" + + +def test_region_key_general_district_collapses_to_city(): + """검증: 일반구(성남시 분당구)를 가진 주소. + 기대결과: 시 단위로 묶인다('41성남시') — 날씨·축제는 구 단위로 다르지 않아 캐시 히트율을 올린다.""" + assert region_key("경기도 성남시 분당구 판교역로 235") == "41성남시" + assert region_key("경기도 성남시 수정구 A로 1") == "41성남시" + + +def test_region_key_single_tier_sejong(): + """검증: 시군구가 없는 세종특별자치시. + 기대결과: '36세종' — 두 번째 토큰이 도로명이라 그대로 쓰면 안 된다.""" + assert region_key("세종특별자치시 한누리대로 2130") == "36세종" + + +def test_region_key_returns_none_when_unmappable(): + """검증: 시도를 알 수 없는 주소(해외·빈 값). + 기대결과: None — 억지로 키를 만들지 않고 호출측에 넘긴다.""" + assert region_key("Tokyo, Japan") is None + assert region_key("") is None + assert region_key(None) is None + assert region_key("강원특별자치도") is None # 시군구가 없다 + + +def test_region_key_fits_db_column(): + """검증: 만들어지는 키의 길이. + 기대결과: 전부 10자 이내 — local_contents.region_code 가 VARCHAR(10) 이라 넘치면 잘린다.""" + addresses = [ + "강원특별자치도 양양군 현북면 하조대3길 25", + "서울특별시 강남구 도산대로57길 24", + "경기도 성남시 분당구 판교역로 235", + "세종특별자치시 한누리대로 2130", + "경상남도 창원시 마산합포구 A로 1", + "제주특별자치도 서귀포시 A로 1", + "경기도 동두천시 A로 1", + ] + for addr in addresses: + key = region_key(addr) + assert key is not None, addr + assert len(key) <= 10, f"{addr} → {key} ({len(key)}자)" + + +def test_region_key_distinguishes_same_name_across_provinces(): + """검증: 이름이 같은 시군구가 다른 시도에 있다(고성군: 강원·경남). + 기대결과: 다른 키 — 시도 코드가 앞에 붙어 안 겹친다.""" + assert region_key("강원특별자치도 고성군 A로 1") != region_key("경상남도 고성군 A로 1") + + +# ── 문자열 유틸 ─────────────────────────────────────────────────────────── +def test_strip_tags_order_protects_literal_text(): + """검증: 본문에 이스케이프된 태그 문자열이 들어 있다. + 기대결과: 태그를 먼저 지우고 엔티티를 나중에 풀어야 리터럴 '' 가 살아남는다.""" + assert strip_tags("카페&베이커리") == "카페&베이커리" + assert strip_tags("공식 <b> 표기") == "공식 표기" + + +def test_normalize_name_only_touches_space_and_case(): + """검증: 상호명 정규화 범위. + 기대결과: 공백·대소문자만 건드린다 — 과하게 정규화하면 다른 가게가 같아 보인다.""" + assert normalize_name("하조대 펜션") == normalize_name("하조대펜션") + assert normalize_name("Blue Ocean") == normalize_name("blueocean") + assert normalize_name("하조대펜션") != normalize_name("하조대펜션별관") + + +# ── 설정·장애 처리 ──────────────────────────────────────────────────────── +async def test_missing_keys_raise_not_configured(): + """검증: 클라이언트 ID/Secret 이 비었다. + 기대결과: NaverNotConfigured — 이 어댑터만 비활성이고 부팅은 안 막는다.""" + c = NaverLocalClient(client_id="", client_secret="") + assert c.enabled is False + + with pytest.raises(NaverNotConfigured): + await c.search_local("카페") + + +async def test_partial_keys_are_treated_as_unconfigured(): + """검증: ID 만 있고 Secret 이 없다. + 기대결과: NaverNotConfigured — 반쪽 설정으로 401 을 맞느니 미설정으로 본다.""" + c = NaverLocalClient(client_id="only-id", client_secret="") + assert c.enabled is False + + with pytest.raises(NaverNotConfigured): + await c.search_local("카페") + + +async def test_401_raises_not_configured(): + """검증: 키는 있는데 인증이 거부된다(401). + 기대결과: NaverNotConfigured — 설정 문제라 재시도해도 소용없다.""" + c = _client(_handler({"errorMessage": "Not Exist Client ID"}, status=401)) + + with pytest.raises(NaverNotConfigured): + await c.search_local("카페") + + +async def test_5xx_raises_request_failed(): + """검증: 네이버가 5xx 를 준다. + 기대결과: NaverRequestFailed — ★ 빈 리스트로 둔갑시키지 않는다. + 빈 값을 내보내면 '주변에 맛집이 없다'가 되어 사이트에 거짓이 실린다.""" + c = _client(_handler("upstream error", status=503)) + + with pytest.raises(NaverRequestFailed): + await c.search_local("카페") + + +async def test_timeout_raises_request_failed(): + """검증: 요청이 타임아웃된다. + 기대결과: NaverRequestFailed — 조용히 빈 값으로 넘어가지 않는다.""" + + def handler(request: httpx.Request) -> httpx.Response: + raise httpx.ReadTimeout("timed out", request=request) + + c = _client(handler) + with pytest.raises(NaverRequestFailed): + await c.search_local("카페") + + +async def test_non_json_body_raises_request_failed(): + """검증: 200 인데 본문이 JSON 이 아니다. + 기대결과: NaverRequestFailed — 파싱 실패를 빈 결과로 삼키지 않는다.""" + c = _client(_handler("maintenance", status=200)) + + with pytest.raises(NaverRequestFailed): + await c.search_local("카페") + + +async def test_call_counts_track_usage(): + """검증: 호출 횟수 누적. + 기대결과: 호출한 만큼 세어진다 — 생성 1건당 검색 횟수를 세는 근거(일 25,000 쿼터).""" + from services.external.naver import call_counts + + c = _client(_handler({"items": []})) + await c.search_local("카페") + await c.search_local("펜션") + + assert call_counts()["local"] == 2 + + +async def test_search_nearby_builds_region_scoped_query(): + """검증: 주변 검색은 반경이 없어 '지역명 + 키워드' 로 찾는다. + 기대결과: 질의가 '양양군 맛집' 으로 조립된다.""" + cap: dict = {} + c = _client(_handler({"items": []}, capture=cap)) + await c.search_nearby("양양군", "맛집", region_key_hint="51양양군") + + assert cap["params"]["query"] == "양양군 맛집" diff --git a/backend/tests/test_naver_place_lookup.py b/backend/tests/test_naver_place_lookup.py new file mode 100644 index 0000000..0706d4a --- /dev/null +++ b/backend/tests/test_naver_place_lookup.py @@ -0,0 +1,151 @@ +"""상호 → 네이버 플레이스 id 해석. + +지역검색 API 가 플레이스 id 를 주지 않아, 모바일 통합검색 결과 원문에서 상호가 일치하는 +id 를 골라낸다. 이 판정이 틀리면 **남의 가게를 이 가게의 공식 채널로 등록**하게 되므로, +"비슷한 것 중 첫 번째"를 고르지 않는 것까지 여기서 지킨다. + +네트워크는 타지 않는다 — 원문 조각을 직접 만들어 판정 규칙만 본다. +""" +import pytest + +from services.external import naver_place_lookup as lookup + + +# 항목 사이를 채우는 잡음. ★ 조회 창(_CONTEXT_BEFORE + _CONTEXT_AFTER)보다 길어야 한다 — +# 실제 원문은 1.3MB 에 항목이 몇 개뿐이라 항목끼리 멀지만, 픽스처를 촘촘히 만들면 +# 옆 항목의 상호가 창 안에 들어와 엉뚱한 id 가 잡힌다(테스트가 실제로 그렇게 잡아냈다). +_FILLER = "
방문자 리뷰 블로그 리뷰 사진 더보기
" * 40 + + +def _html(*entries: tuple[str, str]) -> str: + """검색 결과 원문 흉내. (상호, place id) 를 순서대로 심는다. + + 실제 원문은 id 주변에 리뷰 키워드·블로거 닉네임이 잔뜩 끼어 있고 상호는 그 사이에 + 박혀 있다. 그래서 판정도 '조각 안에 상호가 들어 있는가' 로 한다 — 그 모양을 재현한다. + """ + parts = [] + for name, place_id in entries: + parts.append( + _FILLER + + f'
  • ' + f'{name}' + f'주차하기 편해요
  • ' + + _FILLER + ) + return "
      " + "".join(parts) + "
    " + + +def test_ampersand_in_name_is_matched_through_the_entity(): + """검증: 상호에 `&` 가 있고 원문에는 `&` 로 인코딩돼 있다. + 기대결과: 찾는다. + + ★ 실측(2026-08-28) '누에베 풀빌라&리조트'. 이 한 글자 때문에 place id 를 못 찾아 + 화면이 '네이버 플레이스 못 찾음' 을 띄웠고, 사장님이 네이버 지도에서 주소를 직접 + 복사해 붙여넣어야만 진행됐다 — 10곳 중 1곳이 여기서 막혔다. + """ + html = _html(("누에베 풀빌라&리조트", "1064005604")) + assert lookup._match_in_html(html, "누에베 풀빌라&리조트") == "1064005604" + + +def test_plain_name_still_matches(): + """검증: `&` 도 엔티티도 없는 평범한 상호. + 기대결과: 그대로 찾는다 — 위 수정이 기존 경로를 건드리지 않았다.""" + html = _html(("보사노바 커피로스터스 강릉점", "37093035")) + assert lookup._match_in_html(html, "보사노바 커피로스터스 강릉점") == "37093035" + + +def test_punctuation_differences_are_ignored(): + """검증: 네이버는 '스테이,머뭄' 처럼 구두점을 넣어 표기한다. + 기대결과: 구두점·공백 차이는 무시하고 같은 가게로 본다.""" + html = _html(("스테이, 머뭄", "1133638931")) + assert lookup._match_in_html(html, "스테이머뭄") == "1133638931" + assert lookup._match_in_html(html, "스테이,머뭄") == "1133638931" + + +def test_unrelated_name_is_not_matched(): + """검증: 원문에 id 는 있지만 그 상호는 없다. + 기대결과: None — ★ '비슷한 것 중 첫 번째' 를 고르면 남의 가게를 등록하게 된다.""" + html = _html(("통나무파크", "13149475"), ("도치돌알파카목장", "11111111")) + assert lookup._match_in_html(html, "제주양떼목장") is None + + +def test_correct_id_is_picked_among_several(): + """검증: 후보가 여럿 섞인 원문에서 특정 상호를 찾는다. + 기대결과: 그 상호에 붙은 id 를 고른다(앞에 있는 다른 id 가 아니라).""" + html = _html( + ("통나무파크입구", "99999999"), + ("통나무파크 전기차충전소", "88888888"), + ("누에베 풀빌라&리조트", "1064005604"), + ) + assert lookup._match_in_html(html, "누에베 풀빌라&리조트") == "1064005604" + + +def test_empty_name_never_matches(): + """검증: 상호가 빈 문자열이다. + 기대결과: None — 빈 문자열은 어떤 조각에도 '들어 있으므로' 아무 id 나 잡힌다.""" + html = _html(("통나무파크", "13149475")) + assert lookup._match_in_html(html, "") is None + assert lookup._match_in_html(html, " ") is None + + +async def test_find_place_ids_returns_only_the_ones_it_found(monkeypatch): + """검증: 후보 3건 중 2건만 원문에 있다. + 기대결과: 찾은 2건만 담긴다 — 못 찾은 상호는 빠지고, 검색은 **한 번만** 나간다.""" + calls: list[str] = [] + + async def _fake_fetch(query: str): + calls.append(query) + return _html(("누에베 풀빌라&리조트", "1064005604"), ("통나무파크", "13149475")) + + monkeypatch.setattr(lookup, "_fetch_search_html", _fake_fetch) + + found = await lookup.find_place_ids( + "누에베 풀빌라 제주 애월읍", + ["누에베 풀빌라&리조트", "통나무파크", "여기없는가게"], + ) + + assert found == {"누에베 풀빌라&리조트": "1064005604", "통나무파크": "13149475"} + assert calls == ["누에베 풀빌라 제주 애월읍"], "후보 수만큼 부르면 네이버가 429 로 막는다" + + +async def test_find_place_ids_is_empty_when_search_fails(monkeypatch): + """검증: 검색 자체가 실패했다(네이버가 막았거나 네트워크 오류). + 기대결과: 빈 dict — 호출측이 URL 직접 입력 경로로 안내한다. 예외로 터뜨리지 않는다.""" + + async def _fake_fetch(query: str): + return None + + monkeypatch.setattr(lookup, "_fetch_search_html", _fake_fetch) + assert await lookup.find_place_ids("아무거나", ["가게"]) == {} + + +@pytest.mark.parametrize( + "raw, expected", + [ + ("누에베 풀빌라&리조트", "누에베풀빌라리조트"), + ("스테이, 머뭄", "스테이머뭄"), + ("A-1 Cafe (본점)", "a1cafe본점"), + (None, ""), + ], +) +def test_normalize(raw, expected): + """검증: 비교용 정규화 규칙. + 기대결과: 공백·구두점·`&` 가 사라지고 소문자로 떨어진다.""" + assert lookup._normalize(raw) == expected + + +def test_nearby_entries_can_steal_the_id__known_limit(): + """검증: 두 업소가 조회 창(앞 600자 + 뒤 300자)보다 가깝게 붙어 있다. + 기대결과: **앞 항목의 id 가 잡힌다** — 현재 구현의 알려진 한계다. + + ★ 이건 통과를 축하하는 테스트가 아니라 경계를 적어 두는 테스트다. + 판정이 'id 주변 원문 조각에 상호가 들어 있는가' 라서, 항목이 창보다 촘촘하면 + 옆 가게 상호가 창 안에 들어온다. 실제 검색 원문은 1.3MB 에 항목이 몇 개뿐이라 + 지금은 부딪히지 않지만, 네이버가 결과를 압축해 내려주면 그날로 남의 가게가 잡힌다. + 막으려면 id 와 상호를 같은 항목 안에서 묶어 읽어야 한다(창 기반 판정을 버려야 한다). + """ + dense = ( + '
  • 앞가게
  • ' + '
  • 뒷가게
  • ' + ) + assert lookup._match_in_html(dense, "뒷가게") == "11111111" diff --git a/backend/tests/test_perplexity.py b/backend/tests/test_perplexity.py new file mode 100644 index 0000000..7691177 --- /dev/null +++ b/backend/tests/test_perplexity.py @@ -0,0 +1,460 @@ +"""Perplexity 채널 발견 클라이언트 — 계약 검증(실제 API 호출 없음). + +★ 이 모듈의 계약은 하나다: **URL 만 돌려준다.** + Perplexity 답변에는 동명 업소와 환각이 섞이므로, 상호명·주소·전화 같은 "사실"이 + 반환 구조에 새어나오면 그게 그대로 사이트에 실린다. 그걸 막는 게 여기 테스트의 목적이다. +""" +import httpx +import pytest + +from common.enums import LinkChannel + +# ★ 겹마다 사는 곳이 다르다(services/llm/__init__.py 의 설명 참조). +# 채널 판정·필터 규칙 → grounding, HTTP 호출 → llm, 조립 → external. +from services.grounding.channels import ( + MAX_LINKS, + MAX_LINKS_PER_CHANNEL, + REASON_BLOG, + REASON_CATEGORY, + REASON_OVERFLOW, + REASON_ROOT, + DiscoveredLink, + classify_url, +) +from services.llm import perplexity as llm_perplexity +from services.llm.perplexity import PerplexityError, PerplexityNotConfigured +from services.external import perplexity +from services.external.perplexity import ChannelDiscovery, discover_channels + + +@pytest.fixture(autouse=True) +def _api_key(monkeypatch): + """모든 테스트가 '키 설정됨' 상태에서 시작한다(미설정 케이스는 개별 테스트가 덮어쓴다).""" + monkeypatch.setattr(llm_perplexity.external_api_config, "perplexity_api_key", "pplx-test-key") + + +def _client(handler) -> httpx.AsyncClient: + """MockTransport 로 네트워크를 끊은 클라이언트. 실제 API 를 절대 때리지 않는다.""" + return httpx.AsyncClient(transport=httpx.MockTransport(handler)) + + +def _ok_payload(content: str, search_results=None, usage=None) -> dict: + return { + "choices": [{"message": {"role": "assistant", "content": content}}], + "search_results": search_results if search_results is not None else [], + "usage": usage if usage is not None else {"total_tokens": 500, "num_search_queries": 3}, + } + + +# ── 정상 파싱 ──────────────────────────────────────────────────────────── +async def test_discover_returns_links_raw_and_search_count(): + """검증: 정상 응답을 파싱한다. + 기대결과: links·raw·search_count 가 모두 채워지고, raw 는 응답 원문 그대로다.""" + payload = _ok_payload( + '{"links": [{"url": "https://www.yanolja.com/pension/1", "title": "하조대펜션"}]}', + search_results=[{"url": "https://place.naver.com/restaurant/123", "title": "하조대펜션"}], + usage={"total_tokens": 812, "num_search_queries": 4}, + ) + + async def handler(request): + return httpx.Response(200, json=payload) + + async with _client(handler) as c: + result = await discover_channels("하조대펜션", client=c) + + assert isinstance(result, ChannelDiscovery) + assert result.search_count == 4 + assert result.raw == payload, "raw 는 응답 원문을 통째로 보존해야 한다(환각 추적용)" + + urls = [x.url for x in result.links] + assert "https://www.yanolja.com/pension/1" in urls + assert "https://place.naver.com/restaurant/123" in urls + + +async def test_request_pins_schema_and_domain_filter(): + """검증: 실제로 나가는 요청 본문. + 기대결과: response_format(JSON Schema)로 출력이 고정되고, 도메인이 야놀자·여기어때· + **네이버 플레이스**로 한정된다. naver.com 으로 넓히면 blog.naver.com 후기가 딸려온다(실측).""" + seen = {} + + async def handler(request): + seen["body"] = httpx.Request("POST", request.url, content=request.content).content + seen["auth"] = request.headers.get("Authorization") + import json as _json + + seen["json"] = _json.loads(request.content) + return httpx.Response(200, json=_ok_payload('{"links": []}')) + + async with _client(handler) as c: + await discover_channels("테스트업소", client=c) + + body = seen["json"] + assert seen["auth"] == "Bearer pplx-test-key" + assert body["model"] == "sonar" + assert body["response_format"]["type"] == "json_schema", "구조화 출력으로 파싱 실패를 줄여야 한다" + # ★ 네이버는 호스트가 셋으로 나뉜다. place.naver.com 하나만 두면 실측상 네이버 링크가 + # **한 건도 안 들어온다**(2026-08-27 '도플로'·'버터브루'): 사람이 공유하는 주소는 + # map.naver.com/p/entry/place/... 이거나 naver.me 단축주소이고, place.naver.com 은 + # 그 뒤 리다이렉트로만 나타난다. + assert set(body["search_domain_filter"]) == { + "yanolja.com", "goodchoice.kr", "place.naver.com", "map.naver.com", "naver.me", + } + assert "naver.com" not in body["search_domain_filter"], "넓은 naver.com 은 블로그를 끌어온다" + assert body["max_tokens"] >= 1024, "구조화 출력이 잘리면 파싱이 깨진다 — 넉넉해야 한다" + + +async def test_duplicate_urls_are_collapsed(): + """검증: 모델 답변과 search_results 에 같은 URL 이 중복으로 들어온다. + 기대결과: 1건으로 합쳐진다(place_links 유니크와 충돌하지 않게).""" + url = "https://www.yanolja.com/pension/7" + + async def handler(request): + return httpx.Response(200, json=_ok_payload( + f'{{"links": [{{"url": "{url}"}}]}}', + search_results=[{"url": url, "title": "중복"}], + )) + + async with _client(handler) as c: + result = await discover_channels("중복테스트", client=c) + + assert [x.url for x in result.links] == [url] + + +async def test_non_http_urls_are_dropped(): + """검증: 모델이 http(s) 가 아닌 문자열을 URL 자리에 넣는다. + 기대결과: 버려진다 — 크롤러에 쓰레기가 흘러가면 안 된다.""" + async def handler(request): + return httpx.Response(200, json=_ok_payload( + '{"links": [{"url": "야놀자에서 검색하세요"}, {"url": "javascript:alert(1)"},' + ' {"url": "https://www.yanolja.com/pension/9"}]}' + )) + + async with _client(handler) as c: + result = await discover_channels("쓰레기필터", client=c) + + assert [x.url for x in result.links] == ["https://www.yanolja.com/pension/9"] + + +# ── URL → 채널 매핑 ────────────────────────────────────────────────────── +@pytest.mark.parametrize( + "url,expected", + [ + ("https://www.yanolja.com/pension/123", LinkChannel.YANOLJA), + ("https://place.goodchoice.kr/product/detail/1", LinkChannel.GOODCHOICE), + ("https://www.yeogi.com/domestic-accommodations/1", LinkChannel.GOODCHOICE), + ("https://place.naver.com/restaurant/1234567", LinkChannel.NAVER_PLACE), + ("https://m.place.naver.com/accommodation/1", LinkChannel.NAVER_PLACE), + ("https://naver.me/xAbCdEf", LinkChannel.NAVER_PLACE), + ("https://www.instagram.com/some_pension/", LinkChannel.INSTAGRAM), + ("https://blog.naver.com/someone/12345", LinkChannel.BLOG), + ("https://cafe.naver.com/board/1", LinkChannel.BLOG), + ("https://example.co.kr/", LinkChannel.ETC), + ("not-a-url", LinkChannel.ETC), + ("", LinkChannel.ETC), + ], +) +def test_classify_url(url, expected): + """검증: URL 호스트로 채널을 판정한다. + 기대결과: 야놀자·여기어때·네이버플레이스·인스타는 정확히, 네이버 블로그/카페는 BLOG, + 모르는 도메인은 ETC 로 떨어진다(버리지 않는다).""" + assert classify_url(url) is expected + + +async def test_links_carry_channel_code(): + """검증: 발견된 링크에 채널 코드가 붙는지. + 기대결과: place_links.channel 에 그대로 넣을 수 있는 LinkChannel 값이 실린다.""" + async def handler(request): + return httpx.Response(200, json=_ok_payload( + '{"links": [{"url": "https://www.yanolja.com/pension/1"},' + ' {"url": "https://place.goodchoice.kr/product/1"},' + ' {"url": "https://somewhere.example/x"}]}' + )) + + async with _client(handler) as c: + result = await discover_channels("채널매핑", client=c) + + assert [x.channel for x in result.links] == [ + LinkChannel.YANOLJA, + LinkChannel.GOODCHOICE, + LinkChannel.ETC, + ] + + +# ── ★ URL 발견 전용 계약 ───────────────────────────────────────────────── +async def test_facts_in_answer_do_not_leak_into_result(): + """검증: 응답 본문에 주소·전화·체크인시간 같은 '사실'이 섞여 들어온다. + 기대결과: 반환 구조(links)에는 url·channel·title 만 있고 사실은 하나도 새어나오지 않는다. + ★ Perplexity 답변을 사실로 쓰면 동명 업소·환각이 그대로 사이트에 실린다.""" + async def handler(request): + return httpx.Response(200, json=_ok_payload( + '{"links": [{"url": "https://www.yanolja.com/pension/1", "title": "하조대펜션"}],' + ' "address": "강원 양양군 현북면 하조대해안길 3", "phone": "033-672-0000",' + ' "check_in": "15:00", "price": 180000}' + )) + + async with _client(handler) as c: + result = await discover_channels("하조대펜션", client=c) + + assert len(result.links) == 1 + link = result.links[0] + assert isinstance(link, DiscoveredLink) + # DiscoveredLink 는 url/channel/title 세 필드뿐이다 — 사실을 담을 자리가 없다. + assert set(vars(link)) == {"url", "channel", "title"} + + flat = " ".join(f"{x.url} {x.title}" for x in result.links) + for leaked in ("하조대해안길", "033-672-0000", "15:00", "180000"): + assert leaked not in flat, f"사실이 반환 구조에 새어나왔다: {leaked}" + + # 단, raw 에는 원문이 그대로 남아야 한다(추적용) — 이건 사실 근거가 아니라 증거다. + assert "033-672-0000" in str(result.raw) + + +async def test_prompt_does_not_ask_for_facts(): + """검증: 프롬프트가 무엇을 요구하는지. + 기대결과: URL 만 요구하고, 정보를 쓰지 말라고 명시한다 — 물어보면 모델이 지어낸다.""" + seen = {} + + async def handler(request): + import json as _json + + seen["json"] = _json.loads(request.content) + return httpx.Response(200, json=_ok_payload('{"links": []}')) + + async with _client(handler) as c: + await discover_channels("어떤펜션", address="강원 양양군", client=c) + + user_msg = seen["json"]["messages"][-1]["content"] + assert "URL" in user_msg + assert "쓰지 마라" in user_msg or "지어내" in user_msg + # 출력 스키마에도 사실 필드가 없어야 한다. + props = seen["json"]["response_format"]["json_schema"]["schema"]["properties"] + assert set(props) == {"links"} + + +# ── 실패 처리 ──────────────────────────────────────────────────────────── +async def test_missing_api_key_raises_not_configured(monkeypatch): + """검증: PERPLEXITY_API_KEY 가 비어 있다. + 기대결과: PerplexityNotConfigured — 이 어댑터만 비활성되고 서버 부팅은 막지 않는다.""" + monkeypatch.setattr(llm_perplexity.external_api_config, "perplexity_api_key", "") + + with pytest.raises(PerplexityNotConfigured): + await discover_channels("아무업소") + + assert llm_perplexity.is_configured() is False + + +async def test_blank_name_is_rejected(): + """검증: 상호명 없이 호출한다. + 기대결과: PerplexityError — 검색 요금이 나가기 전에 막는다.""" + with pytest.raises(PerplexityError): + await discover_channels(" ") + + +async def test_timeout_raises_domain_error(): + """검증: 호출이 타임아웃된다. + 기대결과: PerplexityError(→ COLLECT_FETCH_FAILED) — httpx 예외가 그대로 새어나오지 않는다.""" + async def handler(request): + raise httpx.ReadTimeout("too slow", request=request) + + async with _client(handler) as c: + with pytest.raises(PerplexityError, match="타임아웃"): + await discover_channels("느린업소", client=c) + + +async def test_server_error_raises_domain_error(): + """검증: 5xx 응답. + 기대결과: PerplexityError(→ COLLECT_FETCH_FAILED). 잡은 재시도로 흘러간다.""" + async def handler(request): + return httpx.Response(503, text="service unavailable") + + async with _client(handler) as c: + with pytest.raises(PerplexityError, match="503"): + await discover_channels("서버오류", client=c) + + +async def test_broken_structured_output_falls_back_to_search_results(): + """검증: 구조화 출력이 깨진 JSON 으로 온다. + 기대결과: 예외 없이 search_results 의 URL 로 폴백한다 — 검색 요금을 이미 냈으니 버리지 않는다.""" + async def handler(request): + return httpx.Response(200, json=_ok_payload( + "이건 JSON 이 아닙니다", + search_results=[{"url": "https://www.yanolja.com/pension/5", "title": "폴백"}], + )) + + async with _client(handler) as c: + result = await discover_channels("깨진출력", client=c) + + assert [x.url for x in result.links] == ["https://www.yanolja.com/pension/5"] + + +async def test_empty_result_is_not_an_error(): + """검증: 아무 채널도 못 찾았다. + 기대결과: 빈 목록 + 예외 없음 — '못 찾음'은 정상 결과다(사장님 직접 입력으로 폴백).""" + async def handler(request): + return httpx.Response(200, json=_ok_payload('{"links": []}', usage={"num_search_queries": 2})) + + async with _client(handler) as c: + result = await discover_channels("존재하지않는업소", client=c) + + assert result.links == [] + assert result.search_count == 2 + + +async def test_search_count_falls_back_to_search_results_length(): + """검증: usage 에 검색 횟수가 없다. + 기대결과: search_results 개수로 대체한다 — 검색 요금 추적이 0 으로 비면 안 된다.""" + async def handler(request): + return httpx.Response(200, json=_ok_payload( + '{"links": []}', + search_results=[{"url": "https://a.test/1"}, {"url": "https://b.test/2"}], + usage={"total_tokens": 100}, + )) + + async with _client(handler) as c: + result = await discover_channels("카운트없음", client=c) + + assert result.search_count == 2 + + +# ── ★ URL 품질 필터 ────────────────────────────────────────────────────── +# 아래 URL 은 2026-08-27 '핑크비치펜션' 실호출에서 실제로 돌아온 것들이다. +_REAL_JUNK = { + "https://nol.yanolja.com/": REASON_ROOT, + "https://www.goodchoice.kr/": REASON_ROOT, + "https://nol.yanolja.com/sub-home/pension": REASON_CATEGORY, + "https://nol.yanolja.com/programmatic/domestic-accommodation": REASON_CATEGORY, + "https://www.yanolja.com/recommend/ranking?target=W40": REASON_CATEGORY, + "https://blog.naver.com/sodam0526/223364495517": REASON_BLOG, +} +_REAL_DETAIL = [ + "https://nol.yanolja.com/stay/domestic/3017828", + "https://place-site.yanolja.com/places/1000099552", + "https://place-site.yanolja.com/places/10054750/607239/665015", +] + + +async def _discover_with(urls, **kwargs): + """주어진 URL 들이 모델 응답으로 오는 상황을 만든다.""" + import json as _json + + links = _json.dumps({"links": [{"url": u} for u in urls]}, ensure_ascii=False) + + async def handler(request): + return httpx.Response(200, json=_ok_payload(links)) + + async with _client(handler) as c: + return await discover_channels("필터테스트", client=c, **kwargs) + + +@pytest.mark.parametrize("url,reason", sorted(_REAL_JUNK.items())) +async def test_junk_urls_are_filtered_with_reason(url, reason): + """검증: 실호출에서 나온 쓰레기 URL(루트·카테고리·블로그)을 넣는다. + 기대결과: 후보에서 빠지고 filtered_out 에 사유가 남는다 — 조용히 버리지 않는다.""" + result = await _discover_with([url]) + + assert result.links == [], f"{url} 이 후보로 남았다" + assert (url, reason) in result.filtered_out + + +@pytest.mark.parametrize("url", _REAL_DETAIL) +async def test_real_detail_urls_pass(url): + """검증: 실호출에서 나온 진짜 상세 페이지 URL. + 기대결과: 통과한다 — 필터가 과해서 진짜 채널을 버리면 필터가 없느니만 못하다.""" + result = await _discover_with([url]) + + assert [x.url for x in result.links] == [url] + assert result.filtered_out == [] + + +async def test_blogs_pass_when_explicitly_included(): + """검증: include_blogs=True 로 호출한다. + 기대결과: 블로그도 후보로 남는다 — 기본은 제외지만 필요하면 열 수 있어야 한다.""" + url = "https://blog.naver.com/sodam0526/223364495517" + + default = await _discover_with([url]) + opened = await _discover_with([url], include_blogs=True) + + assert default.links == [] + assert [x.url for x in opened.links] == [url] + + +async def test_all_filtered_returns_empty_not_forced_pick(): + """검증: 발견된 URL 이 전부 쓰레기다. + 기대결과: 빈 목록 — ★ 억지로 하나 남기지 않는다. '못 찾음'은 정상 결과다.""" + result = await _discover_with(list(_REAL_JUNK)) + + assert result.links == [] + assert len(result.filtered_out) == len(_REAL_JUNK) + + +async def test_filtered_out_reason_counts(): + """검증: 탈락 사유 집계. + 기대결과: 사유별 건수가 나온다 — 로그 한 줄로 '왜 얼마나 빠졌나'가 보여야 한다.""" + result = await _discover_with(list(_REAL_JUNK)) + + counts = result.reason_counts() + assert counts[REASON_ROOT] == 2 + assert counts[REASON_CATEGORY] == 3 + assert counts[REASON_BLOG] == 1 + + +async def test_too_many_same_channel_urls_are_capped(): + """검증: 같은 채널 상세 URL 이 우수수 들어온다(실측: 야놀자 12건, 전부 다른 숙소). + 기대결과: 채널당 상한까지만 남고 나머지는 overflow 로 기록된다 — + 사람이 12건을 하나씩 열어보게 만들면 안 된다.""" + urls = [f"https://place-site.yanolja.com/places/100{i:04d}" for i in range(10)] + + result = await _discover_with(urls) + + assert len(result.links) == MAX_LINKS_PER_CHANNEL + assert [x.url for x in result.links] == urls[:MAX_LINKS_PER_CHANNEL], "앞선 것(모델 선택)이 남아야 한다" + overflow = [u for u, r in result.filtered_out if r == REASON_OVERFLOW] + assert len(overflow) == len(urls) - MAX_LINKS_PER_CHANNEL + + +async def test_total_cap_across_channels(): + """검증: 여러 채널에서 상세 URL 이 많이 들어온다. + 기대결과: 전체 상한(MAX_LINKS)을 넘지 않는다.""" + urls = ( + [f"https://place-site.yanolja.com/places/1{i}" for i in range(4)] + + [f"https://place.goodchoice.kr/product/detail/{i}" for i in range(4)] + + [f"https://place.naver.com/accommodation/{i}" for i in range(4)] + ) + + result = await _discover_with(urls) + + assert len(result.links) <= MAX_LINKS + + +async def test_prompt_forbids_root_and_listing_pages(): + """검증: 프롬프트가 무엇을 금지하는지. + 기대결과: 첫 화면·목록·블로그를 넣지 말라고 명시한다 — 필터 이전에 애초에 덜 받는 게 싸다.""" + seen = {} + + async def handler(request): + import json as _json + + seen["json"] = _json.loads(request.content) + return httpx.Response(200, json=_ok_payload('{"links": []}')) + + async with _client(handler) as c: + await discover_channels("프롬프트검증", client=c) + + msg = seen["json"]["messages"][-1]["content"] + assert "첫 화면" in msg and "목록" in msg + assert "블로그" in msg + + +async def test_high_search_count_is_warned(caplog): + """검증: 검색 횟수가 기준을 넘는다. + 기대결과: 경고가 남는다 — 검색이 과하면 지연과 오탐 후보가 늘 수 있다.""" + from services.external.perplexity import SEARCH_COUNT_WARN_THRESHOLD + + async def handler(request): + return httpx.Response(200, json=_ok_payload( + '{"links": []}', usage={"num_search_queries": SEARCH_COUNT_WARN_THRESHOLD + 5})) + + async with _client(handler) as c: + result = await discover_channels("비싼검색", client=c) + + assert result.search_count == SEARCH_COUNT_WARN_THRESHOLD + 5 diff --git a/backend/tests/test_place.py b/backend/tests/test_place.py new file mode 100644 index 0000000..8b74e4d --- /dev/null +++ b/backend/tests/test_place.py @@ -0,0 +1,214 @@ +"""places 도메인 e2e — 등록 / 동일 업소 검증 / 회사 스코프 / 채널 URL 확정 게이트. + +★ 이 도메인의 핵심 규칙 두 개를 고정한다: + 1. 검증(verify) 전에는 채널 URL 을 확정할 수 없다 → 크롤링이 안 열린다 + 2. 남의 회사 사업장은 '없음'으로 보인다 +""" +import uuid + +from common.enums import ErrorType, LinkChannel, PlaceCategory, SourceType + + +async def _create_place(client, headers, name="테스트펜션", category=PlaceCategory.LODGING): + r = await client.post("/v1/place", headers=headers, json={"name": name, "category": category.value}) + assert r.status_code == 200, r.text + return r.json() + + +async def test_create_place_starts_unverified(auth_headers, client): + """검증: 상호명만으로 사업장을 등록한다. + 기대결과: 생성되고 status=DRAFT, verified_at 없음 — 아직 수집이 열리지 않은 상태.""" + h = await auth_headers("u1") + body = await _create_place(client, h) + + assert body["result"]["success"] is True + assert body["place"]["name"] == "테스트펜션" + assert body["place"]["status"] == 1 # PlaceStatus.DRAFT + assert body["place"].get("verified_at") is None # RemoveNoneResponse 로 아예 빠진다 + + +async def test_create_place_rejects_blank_name(auth_headers, client): + """검증: 빈 상호명으로 등록. + 기대결과: INVALID_REQUEST_DATA(101).""" + h = await auth_headers("u1") + r = await client.post("/v1/place", headers=h, json={"name": " ", "category": 1}) + assert r.json()["result"]["code"] == ErrorType.INVALID_REQUEST_DATA.value + + +async def test_verify_place_opens_collection(auth_headers, client): + """검증: 카카오 로컬 결과로 동일 업소를 확정한다. + 기대결과: external_place_id·주소·행정구역코드가 박히고 verified_at 이 찍힌다.""" + h = await auth_headers("u1") + pid = (await _create_place(client, h))["place"]["place_id"] + + r = await client.post( + f"/v1/place/{pid}/verify", + headers=h, + json={ + "external_place_id": "26338954", + "road_address": "강원특별자치도 양양군 현북면 하조대해안길 3", + "phone": "033-672-0000", + "latitude": "38.0451234", + "longitude": "128.6712345", + "region_code": "4283025", + }, + ) + body = r.json() + assert body["result"]["success"] is True + assert body["place"]["external_place_id"] == "26338954" + assert body["place"]["region_code"] == "4283025" + assert body["place"]["verified_at"] is not None + + +async def test_duplicate_kakao_place_is_allowed(auth_headers, client): + """검증: 같은 회사에서 같은 카카오 장소를 두 사업장에 붙인다. + 기대결과: 둘 다 등록된다 — 한 사용자가 같은 실제 업장으로 여러 프로젝트를 만들 수 있다.""" + h = await auth_headers("u1") + first = (await _create_place(client, h, "A펜션"))["place"]["place_id"] + second = (await _create_place(client, h, "A펜션(중복)"))["place"]["place_id"] + + await client.post(f"/v1/place/{first}/verify", headers=h, json={"external_place_id": "111"}) + r = await client.post(f"/v1/place/{second}/verify", headers=h, json={"external_place_id": "111"}) + assert r.json()["result"]["success"] is True + + +async def test_naver_verify_without_external_id(auth_headers, client): + """검증: 네이버로 검증한다 — 고유 장소 id 가 없고 도로명주소만 있다. + 기대결과: 확정된다 — 네이버는 카카오 같은 고유 id 를 주지 않으므로 주소가 식별 근거다.""" + h = await auth_headers("u1") + body = await _create_place(client, h, "핑크비치펜션") + pid = body["place"]["place_id"] + + r = await client.post(f"/v1/place/{pid}/verify", headers=h, json={ + "source": 2, # ExternalPlaceSource.NAVER + "road_address": "강원특별자치도 양양군 현북면 하조대3길 11", + "latitude": "38.0219217", "longitude": "128.7221449", + }) + place = r.json()["place"] + assert r.json()["result"]["success"] is True + assert place["verified_at"] is not None + assert place["external_source"] == 2 + assert place.get("external_place_id") is None + + +async def test_naver_duplicate_name_and_address_is_allowed(auth_headers, client): + """검증: 고유 id 없이 같은 상호명·같은 도로명주소로 두 번 등록한다. + 기대결과: 둘 다 등록된다.""" + h = await auth_headers("u1") + addr = "강원특별자치도 양양군 현북면 하조대3길 11" + first = (await _create_place(client, h, "핑크비치펜션"))["place"]["place_id"] + second = (await _create_place(client, h, "핑크비치펜션"))["place"]["place_id"] + + await client.post(f"/v1/place/{first}/verify", headers=h, json={"source": 2, "road_address": addr}) + r = await client.post(f"/v1/place/{second}/verify", headers=h, json={"source": 2, "road_address": addr}) + assert r.json()["result"]["success"] is True + + +async def test_delete_place_removes_it_from_list(auth_headers, client): + """사업장을 삭제하면 단건 조회와 목록에서 모두 사라진다.""" + h = await auth_headers("u1") + pid = (await _create_place(client, h, "삭제할 사업장"))["place"]["place_id"] + + deleted = await client.delete(f"/v1/place/{pid}", headers=h) + assert deleted.json()["result"]["success"] is True + + fetched = await client.get(f"/v1/place/{pid}", headers=h) + assert fetched.json()["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value + + +async def test_same_address_different_business_is_allowed(auth_headers, client): + """검증: 같은 건물(같은 도로명주소)에 상호명이 다른 두 가게를 등록한다. + 기대결과: 둘 다 통과 — ★ 한 건물에 카페와 식당이 같이 있다. 주소만으로 막으면 안 된다.""" + h = await auth_headers("u1") + addr = "서울특별시 강남구 테헤란로 1" + a = (await _create_place(client, h, "1층카페"))["place"]["place_id"] + b = (await _create_place(client, h, "2층식당"))["place"]["place_id"] + + assert (await client.post(f"/v1/place/{a}/verify", headers=h, json={"source": 2, "road_address": addr})).json()["result"]["success"] is True + assert (await client.post(f"/v1/place/{b}/verify", headers=h, json={"source": 2, "road_address": addr})).json()["result"]["success"] is True + + +async def test_verify_without_any_identifier_is_rejected(auth_headers, client): + """검증: 고유 id 도 주소도 없이 확정을 시도한다. + 기대결과: PLACE_VERIFY_NO_CANDIDATE — 식별 근거가 없으면 '그 가게'라고 말할 수 없다.""" + h = await auth_headers("u1") + pid = (await _create_place(client, h))["place"]["place_id"] + + r = await client.post(f"/v1/place/{pid}/verify", headers=h, json={"source": 2, "phone": "033-000-0000"}) + assert r.json()["result"]["code"] == ErrorType.PLACE_VERIFY_NO_CANDIDATE.value + + +async def test_place_is_scoped_to_company(auth_headers, client, other_company_id): + """검증: 다른 회사 계정으로 남의 사업장을 조회한다. + 기대결과: PLACE_NOT_FOUND — 존재 자체가 보이지 않는다(IDOR 차단).""" + h1 = await auth_headers("owner1") + pid = (await _create_place(client, h1))["place"]["place_id"] + + h2 = await auth_headers("owner2", other_company_id) + r = await client.get(f"/v1/place/{pid}", headers=h2) + assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value + + +async def test_link_cannot_be_confirmed_before_place_verified(auth_headers, client): + """검증: 동일 업소 검증 전에 채널 URL 을 확정하려 한다. + 기대결과: PLACE_NOT_VERIFIED — ★ 검증 없이는 크롤링이 열리지 않는다.""" + h = await auth_headers("u1") + pid = (await _create_place(client, h))["place"]["place_id"] + + r = await client.post( + f"/v1/place/{pid}/link", + headers=h, + json={"channel": LinkChannel.YANOLJA.value, "url": "https://www.yanolja.com/pension/1", "discovered_by": SourceType.API.value}, + ) + link_id = r.json()["link"]["link_id"] + + r = await client.post(f"/v1/place/{pid}/link/{link_id}/confirm", headers=h) + assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_VERIFIED.value + + +async def test_confirmed_link_becomes_crawl_target(auth_headers, client): + """검증: 검증 통과 후 채널 URL 을 확정한다. + 기대결과: confirmed_at 이 찍히고 confirmed_only 목록에 나타난다(= 크롤링 대상).""" + h = await auth_headers("u1") + pid = (await _create_place(client, h))["place"]["place_id"] + await client.post(f"/v1/place/{pid}/verify", headers=h, json={"external_place_id": "222"}) + + r = await client.post( + f"/v1/place/{pid}/link", + headers=h, + json={"channel": LinkChannel.NAVER_PLACE.value, "url": "https://place.naver.com/1", "discovered_by": SourceType.API.value}, + ) + link_id = r.json()["link"]["link_id"] + + # 확정 전에는 크롤링 대상이 아니다 + r = await client.get(f"/v1/place/{pid}/link/list", headers=h, params={"confirmed_only": True}) + assert r.json().get("links", []) == [] + + assert (await client.post(f"/v1/place/{pid}/link/{link_id}/confirm", headers=h)).json()["result"]["success"] is True + + r = await client.get(f"/v1/place/{pid}/link/list", headers=h, params={"confirmed_only": True}) + body = r.json() + assert len(body["links"]) == 1 + assert body["links"][0]["confirmed_at"] is not None + + +async def test_confirm_link_twice_is_rejected(auth_headers, client): + """검증: 이미 확정된 링크를 다시 확정한다. + 기대결과: LINK_NOT_FOUND — 조건부 UPDATE 가 0행이라 동시 처리에도 안전하다.""" + h = await auth_headers("u1") + pid = (await _create_place(client, h))["place"]["place_id"] + await client.post(f"/v1/place/{pid}/verify", headers=h, json={"external_place_id": "333"}) + r = await client.post(f"/v1/place/{pid}/link", headers=h, json={"channel": 1, "url": "https://x.test/1"}) + link_id = r.json()["link"]["link_id"] + + await client.post(f"/v1/place/{pid}/link/{link_id}/confirm", headers=h) + r = await client.post(f"/v1/place/{pid}/link/{link_id}/confirm", headers=h) + assert r.json()["result"]["code"] == ErrorType.LINK_NOT_FOUND.value + + +async def test_unknown_place_returns_not_found(auth_headers, client): + """검증: 없는 place_id 조회. + 기대결과: PLACE_NOT_FOUND.""" + h = await auth_headers("u1") + r = await client.get(f"/v1/place/{uuid.uuid4()}", headers=h) + assert r.json()["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value diff --git a/backend/tests/test_publish_gate.py b/backend/tests/test_publish_gate.py new file mode 100644 index 0000000..ac01c81 --- /dev/null +++ b/backend/tests/test_publish_gate.py @@ -0,0 +1,123 @@ +"""발행 검수 게이트 — 절대규칙 1~3 이 실제로 막는가. + +이 게이트를 우회하는 발행 경로가 생기면 안 된다. 여기 테스트가 그 계약이다. +""" +import pytest + +from common.enums import FactStatus, PlaceCategory, PublishRejectReason +from services.publish_gate import ( + GateResult, + check_facts_verified, + check_jsonld_matches, + check_required_fields, + check_unique_content, + evaluate, +) + + +def _f(key, value="x", status=FactStatus.VERIFIED): + return {"key": key, "value": value, "status": status.value} + + +def _lodging_required(): + """숙박 필수 항목을 전부 채운 fact 목록.""" + return [ + _f("check_in_time", "15:00"), _f("check_out_time", "11:00"), + _f("cancel_policy", "7일 전 100% 환불"), _f("cooking_allowed", "true"), + _f("pet_allowed", "false"), + ] + + +def test_unverified_fact_blocks_publish(): + """검증: 미검증 fact 가 노출 대상에 섞여 있다. + 기대결과: ★ 규칙 1 — UNVERIFIED_FACT 로 거부. 틀린 체크인 시간이 나가면 예약 클레임이 난다.""" + facts = _lodging_required() + [_f("wifi", "true", FactStatus.UNVERIFIED)] + r = check_facts_verified(facts) + assert r.passed is False + assert r.reason == PublishRejectReason.UNVERIFIED_FACT + assert r.detail["unverified"][0]["key"] == "wifi" + + +@pytest.mark.parametrize("status", [FactStatus.PENDING_OWNER, FactStatus.REJECTED, FactStatus.EXPIRED]) +def test_every_non_publishable_status_blocks(status): + """검증: 노출 불가 상태 전부(확인대기·반려·만료). + 기대결과: 하나도 통과하지 못한다 — VERIFIED/CORRECTED 만 나간다.""" + assert check_facts_verified([_f("wifi", "true", status)]).passed is False + + +def test_corrected_fact_is_publishable(): + """검증: 사람이 정정한 값(CORRECTED). + 기대결과: 통과 — 정정본은 노출 대상이다.""" + assert check_facts_verified([_f("wifi", "true", FactStatus.CORRECTED)]).passed is True + + +def test_missing_required_field_blocks_publish(): + """검증: 숙박인데 취소 규정이 없다. + 기대결과: REQUIRED_FACT_MISSING — 빈 껍데기 페이지를 발행하지 않는다.""" + facts = [f for f in _lodging_required() if f["key"] != "cancel_policy"] + r = check_required_fields(PlaceCategory.LODGING, facts) + assert r.passed is False + assert r.reason == PublishRejectReason.REQUIRED_FACT_MISSING + assert "cancel_policy" in r.detail["missing"] + assert "취소·환불 규정" in r.detail["labels"] + + +def test_blank_value_counts_as_missing(): + """검증: 필수 fact 가 있긴 한데 값이 빈 문자열이다. + 기대결과: 누락으로 본다 — 빈 값을 채운 척하면 안 된다.""" + facts = _lodging_required() + facts[0]["value"] = " " + assert check_required_fields(PlaceCategory.LODGING, facts).passed is False + + +def test_zero_unique_content_blocks_publish(): + """검증: 고유 콘텐츠가 0건이다. + 기대결과: ★ 규칙 2 — NO_UNIQUE_CONTENT 로 거부. 템플릿 대량 생성은 스팸 판정 대상이다.""" + r = check_unique_content(0) + assert r.passed is False + assert r.reason == PublishRejectReason.NO_UNIQUE_CONTENT + assert check_unique_content(1).passed is True + + +def test_jsonld_mismatch_blocks_publish(): + """검증: 구조화 데이터 값이 화면 값과 다르다. + 기대결과: ★ 규칙 3 — JSONLD_MISMATCH 로 거부. 검색엔진에만 다른 말을 하면 안 된다.""" + r = check_jsonld_matches(["checkinTime: jsonld=14:00 / html=15:00"]) + assert r.passed is False + assert r.reason == PublishRejectReason.JSONLD_MISMATCH + assert "14:00" in r.detail["mismatches"][0] + assert check_jsonld_matches([]).passed is True + + +def test_evaluate_passes_a_complete_site(): + """검증: 모든 조건을 만족하는 사이트. + 기대결과: 통과.""" + r = evaluate(PlaceCategory.LODGING, _lodging_required(), unique_content_count=5, mismatches=[]) + assert r.passed is True + assert r.reason is None + + +def test_evaluate_reports_most_severe_first(): + """검증: 여러 규칙을 동시에 위반한다. + 기대결과: 미검증 fact 가 먼저 잡힌다 — 예약 클레임이 스팸 판정보다 급하다.""" + facts = _lodging_required() + [_f("wifi", "true", FactStatus.UNVERIFIED)] + r = evaluate(PlaceCategory.LODGING, facts, unique_content_count=0, mismatches=["x"]) + assert r.reason == PublishRejectReason.UNVERIFIED_FACT + + +def test_evaluate_does_not_block_thin_content(): + """검증: 고유 문장이 없어도 발행 게이트는 통과한다. + 콘텐츠 품질은 편집기 경고로 안내하고 사장님의 발행 선택을 막지 않는다.""" + r = evaluate(PlaceCategory.LODGING, _lodging_required(), unique_content_count=0, mismatches=[]) + log = r.as_log() + assert r.passed is True + assert log["reason"] is None + + +@pytest.mark.parametrize("category", list(PlaceCategory)) +def test_required_check_works_for_every_category(category): + """검증: 업종 4종 전부에서 필수 검사가 동작하는가. + 기대결과: fact 가 하나도 없으면 전부 거부 — 업종 추가 시 게이트가 자동으로 따라온다.""" + r = check_required_fields(category, []) + assert r.passed is False + assert r.detail["missing"] diff --git a/backend/tests/test_render_report.py b/backend/tests/test_render_report.py new file mode 100644 index 0000000..50f995d --- /dev/null +++ b/backend/tests/test_render_report.py @@ -0,0 +1,76 @@ +"""렌더 보고서 — ★ 발행 기록(DB)과 실제 페이지(정적 파일)의 간극을 드러낸다. + +이 모듈이 절대 하면 안 되는 것: + 1. 페이지가 없는데 "정상" 이라고 답하는 것 (사장님은 404 를 눌러 보고서야 안다) + 2. 낡은 렌더를 현재 버전인 것처럼 통과시키는 것 + 3. 보고서가 깨졌다고 사이트 조회 자체를 실패시키는 것 (부수 산출물이다) +""" +import json + +import pytest + +from services import render_report + + +@pytest.fixture +def payload_dir(tmp_path, monkeypatch): + """프리렌더가 보고서를 쓰는 자리를 임시 디렉토리로 돌린다.""" + monkeypatch.setattr(render_report, "payload_dir", lambda: tmp_path) + (tmp_path / render_report.STATUS_DIR).mkdir() + return tmp_path + + +def _write(payload_dir, slug, **overrides): + report = { + "schemaVersion": 1, + "slug": slug, + "siteId": "s-1", + "placeId": "p-1", + "siteVersion": 2, + "ok": True, + "renderedAt": "2026-08-28T00:00:00.000Z", + "routes": 7, + "bundle": "index-abc.js", + "uniqueContentCount": 14, + "jsonld": [{"@type": "LodgingBusiness", "name": "조이모텔", "telephone": "031-722-1942"}], + "error": None, + } + report.update(overrides) + path = payload_dir / render_report.STATUS_DIR / f"{slug}.json" + path.write_text(json.dumps(report, ensure_ascii=False), encoding="utf-8") + return report + + +# ── 렌더 상태 ──────────────────────────────────────────────────────────────── +def test_보고서가_없으면_아직_안_구운_것이다(payload_dir): + # ★ "없음" 을 "정상" 으로 답하면 발행 직후 404 를 정상이라고 말하게 된다. + assert render_report.render_status("joy", 1)["state"] == "PENDING" + + +def test_현재_버전이_구워져_있으면_OK(payload_dir): + _write(payload_dir, "joy", siteVersion=2) + assert render_report.render_status("joy", 2)["state"] == "OK" + + +def test_구운_버전이_낡았으면_STALE(payload_dir): + # 발행은 됐는데(v3) 프리렌더는 아직 v2 만 구운 상태 — 방문자는 낡은 페이지를 본다. + _write(payload_dir, "joy", siteVersion=2) + assert render_report.render_status("joy", 3)["state"] == "STALE" + + +def test_프리렌더가_실패했으면_FAILED_와_사유(payload_dir): + _write(payload_dir, "joy", ok=False, error="schemaVersion=99") + status = render_report.render_status("joy", 2) + assert status["state"] == "FAILED" + assert status["error"] == "schemaVersion=99" + + +def test_모르는_스키마_버전은_정상이라고_답하지_않는다(payload_dir): + # 반쯤 해석해서 "OK" 라고 답하는 게 최악이다 — 못 읽으면 안 구운 것으로 본다. + _write(payload_dir, "joy", schemaVersion=99) + assert render_report.render_status("joy", 2)["state"] == "PENDING" + + +def test_깨진_보고서가_조회를_실패시키지_않는다(payload_dir): + (payload_dir / render_report.STATUS_DIR / "joy.json").write_text("{깨진 JSON", encoding="utf-8") + assert render_report.render_status("joy", 2)["state"] == "PENDING" diff --git a/backend/tests/test_schema_ddl.py b/backend/tests/test_schema_ddl.py new file mode 100644 index 0000000..31ced49 --- /dev/null +++ b/backend/tests/test_schema_ddl.py @@ -0,0 +1,85 @@ +"""init.sql ↔ ORM 모델 정합성. + +스키마 정의가 두 곳(마이그레이션 SQL / SQLAlchemy 모델)에 있으므로 둘이 어긋나면 +"테스트는 통과하는데 실서버에서 컬럼이 없는" 상황이 난다. DB 없이 파일만 비교해 그걸 잡는다. +""" +import re +from pathlib import Path + +from common.database.model.models import MAIN_BASE + +_INIT_SQL = Path(__file__).resolve().parents[2] / "postgres-init" / "init-data" / "init.sql" + +_CREATE_TABLE_RE = re.compile( + r"CREATE TABLE IF NOT EXISTS\s+(?P\w+)\.(?P\w+)\s*\((?P.*?)\n\);", + re.S | re.I, +) + + +def _parse_init_sql() -> dict: + """init.sql → {"schema.table": {컬럼명, ...}}""" + sql = _INIT_SQL.read_text(encoding="utf-8") + out = {} + for m in _CREATE_TABLE_RE.finditer(sql): + columns = set() + for line in m.group("body").splitlines(): + line = line.strip() + if not line or line.startswith("--"): + continue + name = line.split()[0] + if name.upper() in ("PRIMARY", "UNIQUE", "CONSTRAINT", "FOREIGN", "CHECK"): + continue + columns.add(name) + out[f"{m.group('schema')}.{m.group('table')}"] = columns + return out + + +def test_init_sql_is_readable(): + """검증: init.sql 을 찾고 파싱할 수 있는지. + 기대결과: 파일이 존재하고 CREATE TABLE 이 1개 이상 파싱된다.""" + assert _INIT_SQL.exists(), f"init.sql 이 없다: {_INIT_SQL}" + assert _parse_init_sql(), "init.sql 에서 CREATE TABLE 을 하나도 파싱하지 못했다" + + +def test_every_model_table_exists_in_init_sql(): + """검증: ORM 모델의 모든 테이블이 init.sql 에도 있는지. + 기대결과: 누락 없음 — 모델만 추가하고 마이그레이션을 안 쓴 경우를 잡는다.""" + sql_tables = set(_parse_init_sql()) + model_tables = {f"{t.schema}.{t.name}" for t in MAIN_BASE.metadata.sorted_tables} + missing = sorted(model_tables - sql_tables) + assert not missing, f"init.sql 에 없는 모델 테이블: {missing}" + + +def test_every_init_sql_table_has_a_model(): + """검증: init.sql 의 모든 테이블에 ORM 모델이 있는지. + 기대결과: 누락 없음 — 마이그레이션만 쓰고 모델을 안 만든 경우를 잡는다.""" + sql_tables = set(_parse_init_sql()) + model_tables = {f"{t.schema}.{t.name}" for t in MAIN_BASE.metadata.sorted_tables} + missing = sorted(sql_tables - model_tables) + assert not missing, f"ORM 모델이 없는 init.sql 테이블: {missing}" + + +def test_columns_match_between_model_and_init_sql(): + """검증: 테이블마다 컬럼 집합이 양쪽에서 같은지. + 기대결과: 완전 일치 — 한쪽에만 추가된 컬럼을 잡는다.""" + sql_tables = _parse_init_sql() + problems = [] + for table in MAIN_BASE.metadata.sorted_tables: + name = f"{table.schema}.{table.name}" + if name not in sql_tables: + continue + model_cols = {c.name for c in table.columns} + sql_cols = sql_tables[name] + if model_cols != sql_cols: + problems.append( + f"{name}: 모델에만 {sorted(model_cols - sql_cols)} / init.sql 에만 {sorted(sql_cols - model_cols)}" + ) + assert not problems, "컬럼 불일치:\n" + "\n".join(problems) + + +def test_every_table_has_soft_delete_columns(): + """검증: 모든 테이블이 공통 컬럼(created_at·updated_at·deleted)을 갖는지. + 기대결과: MainTableMixin 을 빠뜨린 모델이 없다 — 소프트 삭제 전제가 깨지면 유니크 부분 인덱스도 깨진다.""" + for table in MAIN_BASE.metadata.sorted_tables: + cols = {c.name for c in table.columns} + assert {"created_at", "updated_at", "deleted"} <= cols, f"{table.schema}.{table.name}: 공통 컬럼 누락" diff --git a/backend/tests/test_seo_audit.py b/backend/tests/test_seo_audit.py new file mode 100644 index 0000000..d880ebc --- /dev/null +++ b/backend/tests/test_seo_audit.py @@ -0,0 +1,46 @@ +from types import SimpleNamespace + +from services.seo_audit import evaluate + + +def _snapshot(facts=8, faqs=3, media=3): + return { + "place": {"name": "테스트", "road_address": "서울 강남구", "phone": "02-123-4567", + "latitude": "37.1", "longitude": "127.1"}, + "facts": [{"key": f"k{i}", "value": "값", "source_url": "https://source.test"} for i in range(facts)], + "faqs": [{"question": f"질문{i}", "answer": "답"} for i in range(faqs)], + "media": [{"alt_text": f"사진{i}"} for i in range(media)], + } + + +def test_complete_site_scores_full_marks(): + report = evaluate( + _snapshot(), verified=True, + site=SimpleNamespace(domain="test-place"), + version=SimpleNamespace(built_at="now", unique_content_count=4), + ) + assert report["seo_score"] == 100 + assert report["aeo_score"] == 100 + assert report["overall_score"] == 100 + + +def test_empty_site_returns_actionable_failures(): + report = evaluate({"place": {}, "facts": [], "faqs": [], "media": []}, verified=False) + assert report["seo_score"] < 30 + assert report["aeo_score"] < 30 + assert any(c["status"] == "fail" and c["recommendation"] for c in report["checks"]) + + +async def test_audit_api_is_company_scoped(auth_headers, client, other_company_id): + h1 = await auth_headers("audit-owner") + pid = (await client.post("/v1/place", headers=h1, json={"name": "진단가게", "category": 2})).json()["place"]["place_id"] + + own = (await client.get(f"/v1/place/{pid}/site/audit", headers=h1)).json() + assert own["result"]["success"] is True + assert 0 <= own["seo_score"] <= 100 + assert 0 <= own["aeo_score"] <= 100 + assert own["checks"] + + h2 = await auth_headers("audit-other", other_company_id) + denied = (await client.get(f"/v1/place/{pid}/site/audit", headers=h2)).json() + assert denied["result"]["success"] is False diff --git a/backend/tests/test_site_slug.py b/backend/tests/test_site_slug.py new file mode 100644 index 0000000..0c78dd5 --- /dev/null +++ b/backend/tests/test_site_slug.py @@ -0,0 +1,140 @@ +"""사이트 주소(네임스페이스) 확인·예약. + +이 경로가 절대 하면 안 되는 것: + - 한글·대문자 주소를 통과시키는 것 — 주소가 퍼센트 인코딩 덩어리가 되어 사장님이 불러줄 수 없다 + - 확인은 통과시키고 저장에서 튕기는 것 — 규칙이 두 곳에 있으면 반드시 생긴다 + - ★ 이미 발행돼 색인된 주소를 바꾸는 것 — AI 검색이 잡아 둔 페이지가 404 가 된다 +""" +import uuid + +import pytest +from sqlalchemy import text + +from common.enums import ErrorType, SiteStatus +from services import site_slug + + +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 _check(client, headers, pid, slug): + return (await client.get(f"/v1/place/{pid}/site/slug/check", headers=headers, params={"slug": slug})).json() + + +async def _reserve(client, headers, pid, slug): + return (await client.post(f"/v1/place/{pid}/site/slug", headers=headers, json={"slug": slug})).json() + + +@pytest.mark.parametrize( + "slug, reason", + [ + ("doflo", None), + ("stay-mumum-2", None), + ("도플로", site_slug.REASON_FORMAT), # 한글 + ("Doflo", site_slug.REASON_FORMAT), # 대문자 + ("my_site", site_slug.REASON_FORMAT), # 언더스코어 + ("a--b", site_slug.REASON_FORMAT), # 연속 하이픈(퓨니코드 접두 xn-- 와 헷갈린다) + ("-doflo", site_slug.REASON_FORMAT), + ("doflo-", site_slug.REASON_FORMAT), + ("ab", site_slug.REASON_LENGTH), # 3자 미만 + ("a" * 51, site_slug.REASON_LENGTH), # 50자 초과 + ("admin", site_slug.REASON_RESERVED), + ("api", site_slug.REASON_RESERVED), + ("robots", site_slug.REASON_RESERVED), + ("undefined", site_slug.REASON_RESERVED), # 프론트 버그가 그대로 주소가 되는 걸 막는다 + ], +) +def test_slug_rules(slug, reason): + """검증: 형식·예약어 규칙(확인과 저장이 같이 쓰는 단 하나의 정의). + 기대결과: 쓸 수 있으면 None, 아니면 사유 코드.""" + assert site_slug.validate_slug(slug) == reason + + +async def test_check_then_reserve(auth_headers, client): + """검증: 주소를 확인하고 예약한다. 사이트 행이 없어도 만들어진다. + 기대결과: available → 저장 → 자기 주소이므로 다시 확인해도 available.""" + h = await auth_headers("slug1") + pid = await _place(client, h) + + assert (await _check(client, h, pid, "doflo"))["available"] is True + + saved = await _reserve(client, h, pid, "doflo") + assert saved["result"]["code"] == ErrorType.SUCCESS.value + assert saved["site"]["domain"] == "doflo" + + # ★ 자기 자신은 중복이 아니다 — 저장해 둔 화면을 다시 열었을 때 '중복'이라고 하면 안 된다. + again = await _check(client, h, pid, "doflo") + assert again["available"] is True and "reason" not in again + + +async def test_invalid_slug_is_refused_on_save_too(auth_headers, client): + """검증: 확인에서 막힌 값은 저장에서도 막힌다(클라이언트 검증을 믿지 않는다). + 기대결과: 두 경로가 같은 사유를 돌려준다.""" + h = await auth_headers("slug2") + pid = await _place(client, h) + + for slug, reason in (("도플로", site_slug.REASON_FORMAT), ("ab", site_slug.REASON_LENGTH), + ("admin", site_slug.REASON_RESERVED)): + checked = await _check(client, h, pid, slug) + assert checked["available"] is False and checked["reason"] == reason + saved = await _reserve(client, h, pid, slug) + assert saved["result"]["success"] is False and saved["reason"] == reason + assert "site" not in saved + + +async def test_taken_by_other_place_offers_suggestion(auth_headers, client): + """검증: 남이 쓰는 주소는 못 쓴다. 대신 쓸 수 있는 대안을 하나 준다. + 기대결과: available=false / TAKEN / suggestion=doflo-2.""" + h = await auth_headers("slug3") + mine = await _place(client, h, "도플로") + other = await _place(client, h, "도플로2호점") + await _reserve(client, h, mine, "doflo") + + checked = await _check(client, h, other, "doflo") + assert checked["available"] is False + assert checked["reason"] == site_slug.REASON_TAKEN + assert checked["suggestion"] == "doflo-2" + + saved = await _reserve(client, h, other, "doflo") + assert saved["result"]["code"] == ErrorType.DB_ALREADY_SAME_KEY.value + assert saved["suggestion"] == "doflo-2" + + # 제안대로면 통과한다 — 제안이 실제로 쓸 수 있는 값이어야 의미가 있다. + assert (await _reserve(client, h, other, "doflo-2"))["site"]["domain"] == "doflo-2" + + +async def test_published_site_slug_is_locked(auth_headers, client, db_engine): + """검증: ★ 이미 발행된 사이트의 주소는 바꿀 수 없다. + 기대결과: SITE_SLUG_LOCKED. 같은 값 재전송은 변경이 아니므로 통과.""" + h = await auth_headers("slug4") + pid = await _place(client, h) + await _reserve(client, h, pid, "published-stay") + + # 발행 상태를 만든다(빌드 잡을 돌리는 대신 상태만) — 잠금은 published_at·status 가 근거다. + 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)}, + ) + + locked = await _reserve(client, h, pid, "published-stay-new") + assert locked["result"]["code"] == ErrorType.SITE_SLUG_LOCKED.value + assert locked["reason"] == site_slug.REASON_LOCKED + + # 같은 값 재전송은 변경이 아니다. + same = await _reserve(client, h, pid, "published-stay") + assert same["result"]["code"] == ErrorType.SUCCESS.value + assert same["site"]["domain"] == "published-stay" + + +async def test_other_company_place_is_blocked(auth_headers, client, other_company_id): + """검증: 남의 회사 사업장 주소는 확인도 예약도 못 한다. + 기대결과: PLACE_NOT_FOUND(존재 여부조차 알려주지 않는다).""" + h = await auth_headers("slug5") + intruder = await auth_headers("slug6", other_company_id) + pid = await _place(client, h) + + assert (await _check(client, intruder, pid, "doflo"))["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value + assert (await _reserve(client, intruder, pid, "doflo"))["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value diff --git a/backend/tests/test_site_template.py b/backend/tests/test_site_template.py new file mode 100644 index 0000000..2e87685 --- /dev/null +++ b/backend/tests/test_site_template.py @@ -0,0 +1,126 @@ +"""템플릿(디자인) 선택 저장. + +이 경로가 절대 하면 안 되는 것: + - 고른 템플릿을 브라우저에만 두는 것 — 발행 잡이 읽을 곳이 없어 업종 기본으로 굽는다. + 사장님이 고른 디자인과 실제 발행본이 갈리는 것이 이 API 가 생긴 이유다. + - ★ 발행됐다고 템플릿을 잠그는 것 — 주소(slug)와 달리 디자인은 바뀌어도 URL 이 그대로다. + 잠글 이유가 없는 것을 잠그면 사장님이 발행 후에 디자인을 못 바꾼다. + - 바꿔놓고 재빌드 표시를 안 하는 것 — 관리 화면은 새 디자인, 나가 있는 페이지는 옛 디자인이 된다. +""" +import uuid + +from sqlalchemy import text + +from common.enums import ErrorType, PlaceCategory, SiteStatus +from services.site_payload import _DEFAULT_THEME, to_site_payload + + +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_template(client, headers, pid, template_id): + return (await client.post(f"/v1/place/{pid}/site/template", headers=headers, + json={"template_id": template_id})).json() + + +async def _get_site(client, headers, pid): + return (await client.get(f"/v1/place/{pid}/site", headers=headers)).json() + + +async def test_set_template_creates_site_row(auth_headers, client): + """검증: 사이트 행이 없어도 템플릿을 먼저 고를 수 있다(고르는 건 발행보다 앞선 결정이다). + 기대결과: SUCCESS + 저장된 값이 조회에도 그대로 나온다.""" + h = await auth_headers("tpl1") + pid = await _place(client, h) + + saved = await _set_template(client, h, pid, "stay-quiet-margin") + assert saved["result"]["code"] == ErrorType.SUCCESS.value + assert saved["site"]["template_id"] == "stay-quiet-margin" + + # 화면이 "지금 어느 템플릿으로 나가는지"를 조회로 다시 읽을 수 있어야 한다. + assert (await _get_site(client, h, pid))["site"]["template_id"] == "stay-quiet-margin" + + +async def test_unknown_template_key_is_accepted(auth_headers, client): + """검증: ★ 서버는 값을 검증하지 않는다 — 템플릿 목록은 프론트가 소유한다. + 기대결과: 모르는 키도 저장된다(화이트리스트를 두면 템플릿 하나 늘릴 때마다 백엔드를 고쳐야 한다).""" + h = await auth_headers("tpl2") + pid = await _place(client, h) + + saved = await _set_template(client, h, pid, "brand-new-template-nobody-knows") + assert saved["result"]["code"] == ErrorType.SUCCESS.value + assert saved["site"]["template_id"] == "brand-new-template-nobody-knows" + + +async def test_too_long_template_is_refused(auth_headers, client): + """검증: 길이(varchar(100))만은 막는다 — 안 막으면 DB 가 트랜잭션째로 튕긴다. + 기대결과: INVALID_REQUEST_DATA.""" + h = await auth_headers("tpl3") + pid = await _place(client, h) + + refused = await _set_template(client, h, pid, "t" * 101) + assert refused["result"]["code"] == ErrorType.INVALID_REQUEST_DATA.value + assert "site" not in refused + + +async def test_empty_value_clears_to_default(auth_headers, client): + """검증: 빈 값은 '고르지 않음'이다 — NULL 로 되돌아가 업종 기본으로 떨어진다. + 기대결과: 저장 후 빈 문자열을 보내면 template_id 가 응답에서 사라진다(None).""" + h = await auth_headers("tpl4") + pid = await _place(client, h) + await _set_template(client, h, pid, "stay-quiet-margin") + + cleared = await _set_template(client, h, pid, "") + assert cleared["result"]["code"] == ErrorType.SUCCESS.value + # RemoveNoneResponse 가 None 필드를 지운다 — 키가 없으면 NULL 이다. + assert "template_id" not in cleared["site"] + + +async def test_published_site_template_is_not_locked(auth_headers, client, db_engine): + """검증: ★ 발행된 사이트도 템플릿은 바꿀 수 있다(주소와 다르다 — URL 이 그대로라 색인이 안 깨진다). + 기대결과: SUCCESS + 재빌드 필요 표시(needs_rebuild).""" + h = await auth_headers("tpl5") + pid = await _place(client, h) + await _set_template(client, h, pid, "stay-o2o-editorial") + + # 발행 상태를 만든다(빌드 잡을 돌리는 대신 상태만). + 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_template(client, h, pid, "stay-quiet-margin") + assert changed["result"]["code"] == ErrorType.SUCCESS.value + assert changed["site"]["template_id"] == "stay-quiet-margin" + # 나가 있는 페이지와 달라졌으므로 이 사업장만 다시 빌드하면 된다는 표시가 서야 한다. + 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("tpl6") + intruder = await auth_headers("tpl7", other_company_id) + pid = await _place(client, h) + + blocked = await _set_template(client, intruder, pid, "stay-quiet-margin") + assert blocked["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value + + +def test_payload_uses_saved_template_and_falls_back(): + """검증: 발행 payload 의 theme.templateId 는 저장된 값을 쓰고, 없으면 업종 기본으로 떨어진다. + 기대결과: 저장값 → 그대로 / NULL → 업종 기본. ★ 고르지 않은 값을 고른 것처럼 굽지 않는다.""" + place = {"place_id": uuid.uuid4(), "category": PlaceCategory.LODGING.value, "name": "스테이,머뭄"} + snapshot = {"place": {"name": "스테이,머뭄", "category": PlaceCategory.LODGING.value}} + version = {"version": 1} + + chosen = to_site_payload(place, snapshot, {"template_id": "stay-quiet-margin"}, version, []) + assert chosen["theme"]["templateId"] == "stay-quiet-margin" + + default_id = _DEFAULT_THEME[PlaceCategory.LODGING.value]["templateId"] + assert to_site_payload(place, snapshot, {"template_id": None}, version, [])["theme"]["templateId"] == default_id + # 색·서체는 여전히 업종 기본이다(그 값들은 아직 저장되는 자리가 없다). + assert chosen["theme"]["fontStyle"] == _DEFAULT_THEME[PlaceCategory.LODGING.value]["fontStyle"] diff --git a/backend/tests/test_site_theme.py b/backend/tests/test_site_theme.py new file mode 100644 index 0000000..e7bd6f3 --- /dev/null +++ b/backend/tests/test_site_theme.py @@ -0,0 +1,297 @@ +"""디자인(색·서체·섹션) 저장과 발행 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] / "frontend/admin/src/data/industryData.ts" +) + +# 에디터 업종 키 → 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] diff --git a/backend/tests/test_snapshot.py b/backend/tests/test_snapshot.py new file mode 100644 index 0000000..30ce380 --- /dev/null +++ b/backend/tests/test_snapshot.py @@ -0,0 +1,215 @@ +"""빌드 스냅샷 — ★ 사이트에 나가면 안 되는 것이 스냅샷에 들어오지 않는가. + +스냅샷이 정적 빌드의 경계다. 여기 들어온 것은 그대로 발행되므로, 필터링이 여기서 새면 끝이다. +""" +import uuid + +from sqlalchemy import text + +from common.enums import FactStatus, MediaStatus, PlaceCategory, SourceType +from services.snapshot import build_snapshot + + +async def _seed(db_engine, company_id, category=PlaceCategory.LODGING): + pid = uuid.uuid4() + async with db_engine.begin() as c: + await c.execute( + text("INSERT INTO places (place_id, company_id, name, category, status, road_address, phone, verified_at) " + "VALUES (:p,:c,:n,:cat,3,:addr,:tel,now())"), + {"p": pid, "c": uuid.UUID(company_id), "n": "스냅샷펜션", "cat": category.value, + "addr": "강원특별자치도 양양군 현북면 하조대3길 11", "tel": "033-000-0000"}, + ) + return pid + + +async def _fact(db_engine, pid, key, value, status, unit_id=None): + async with db_engine.begin() as c: + await c.execute( + text("INSERT INTO facts (fact_id, place_id, unit_id, key, value, source_type, status, collected_at) " + "VALUES (:f,:p,:u,:k,:v,:s,:st,now())"), + {"f": uuid.uuid4(), "p": pid, "u": unit_id, "k": key, "v": value, + "s": SourceType.OWNER.value, "st": status.value}, + ) + + +async def _media(db_engine, pid, url, status, alt="설명"): + async with db_engine.begin() as c: + await c.execute( + text("INSERT INTO media (media_id, place_id, url, origin_url, source_type, status, alt_text, sort_order) " + "VALUES (:m,:p,:u,:u,:s,:st,:a,0)"), + {"m": uuid.uuid4(), "p": pid, "u": url, "s": SourceType.CRAWL.value, "st": status.value, "a": alt}, + ) + + +class _Place: + def __init__(self, pid, category=PlaceCategory.LODGING): + self.place_id = pid + self.category = category.value + self.name = "스냅샷펜션" + self.road_address = "강원특별자치도 양양군 현북면 하조대3길 11" + self.address = None + self.phone = "033-000-0000" + self.latitude = None + self.longitude = None + + +async def test_only_publishable_facts_enter_snapshot(db_engine, company_id): + """검증: 여러 상태의 fact 를 섞어 넣는다. + 기대결과: ★ VERIFIED·CORRECTED 만 스냅샷에 담긴다 — 미검증 값이 사이트로 새지 않는다.""" + pid = await _seed(db_engine, company_id) + await _fact(db_engine, pid, "check_in_time", "15:00", FactStatus.VERIFIED) + await _fact(db_engine, pid, "wifi", "true", FactStatus.CORRECTED) + await _fact(db_engine, pid, "parking", "true", FactStatus.UNVERIFIED) + await _fact(db_engine, pid, "breakfast", "true", FactStatus.PENDING_OWNER) + await _fact(db_engine, pid, "bbq_available", "true", FactStatus.REJECTED) + await _fact(db_engine, pid, "smoking", "false", FactStatus.EXPIRED) + + snap = await build_snapshot(_Place(pid)) + keys = {f["key"] for f in snap["facts"]} + assert keys == {"check_in_time", "wifi"} + + +async def test_only_approved_media_enters_snapshot(db_engine, company_id): + """검증: 승인/확인대기/반려 사진을 섞어 넣는다. + 기대결과: ★ APPROVED 만 담긴다 — Vision 신뢰도가 낮아 확인 큐에 남은 사진은 안 나간다.""" + pid = await _seed(db_engine, company_id) + await _media(db_engine, pid, "https://cdn.test/ok.jpg", MediaStatus.APPROVED) + await _media(db_engine, pid, "https://cdn.test/pending.jpg", MediaStatus.PENDING_REVIEW) + await _media(db_engine, pid, "https://cdn.test/no.jpg", MediaStatus.REJECTED) + + snap = await build_snapshot(_Place(pid)) + assert [m["url"] for m in snap["media"]] == ["https://cdn.test/ok.jpg"] + + +async def test_media_without_alt_is_excluded(db_engine, company_id): + """검증: 승인됐지만 alt 텍스트가 없는 사진. + 기대결과: 빠진다 — alt 없는 이미지는 접근성도 AI 검색 신호도 없다.""" + pid = await _seed(db_engine, company_id) + await _media(db_engine, pid, "https://cdn.test/noalt.jpg", MediaStatus.APPROVED, alt="") + await _media(db_engine, pid, "https://cdn.test/withalt.jpg", MediaStatus.APPROVED, alt="침실 사진") + + snap = await build_snapshot(_Place(pid)) + assert [m["url"] for m in snap["media"]] == ["https://cdn.test/withalt.jpg"] + + +async def test_fact_labels_come_from_category_schema(db_engine, company_id): + """검증: 스냅샷의 fact 라벨. + 기대결과: 업종 스키마의 한글 라벨이 붙는다 — 화면이 key 를 그대로 노출하지 않게.""" + pid = await _seed(db_engine, company_id) + await _fact(db_engine, pid, "check_in_time", "15:00", FactStatus.VERIFIED) + + snap = await build_snapshot(_Place(pid)) + f = snap["facts"][0] + assert f["label"] == "체크인 시간" + assert f["scope"] == "place" + + +async def test_unit_scoped_facts_carry_unit_id(db_engine, company_id): + """검증: 객실 단위 fact. + 기대결과: unit_id 가 실려 빌더가 객실별로 묶을 수 있다.""" + pid = await _seed(db_engine, company_id) + uid = uuid.uuid4() + async with db_engine.begin() as c: + await c.execute(text("INSERT INTO units (unit_id, place_id, name, sort_order) VALUES (:u,:p,:n,0)"), + {"u": uid, "p": pid, "n": "A동"}) + await _fact(db_engine, pid, "max_capacity", "4", FactStatus.VERIFIED, unit_id=uid) + + snap = await build_snapshot(_Place(pid)) + assert snap["units"][0]["name"] == "A동" + assert snap["facts"][0]["unit_id"] == str(uid) + assert snap["facts"][0]["scope"] == "unit" + + +async def test_empty_place_gives_empty_snapshot(db_engine, company_id): + """검증: 아무것도 없는 사업장. + 기대결과: 빈 스냅샷 — 게이트가 고유 콘텐츠 0건으로 거부할 재료가 된다.""" + pid = await _seed(db_engine, company_id) + snap = await build_snapshot(_Place(pid)) + assert snap["facts"] == [] and snap["media"] == [] and snap["faqs"] == [] + assert snap["place"]["name"] == "스냅샷펜션" + + +# ── 지역 정보 ───────────────────────────────────────────────────────────── +# ★ 지역 정보가 스냅샷에 담기는 이유: site_payload 는 DB 를 다시 읽지 않는다. +# 거기서 지역 캐시를 읽으면 발행 시점과 렌더 시점 사이에 값이 바뀌어 '스냅샷과 다른 페이지'가 나온다. + +async def _local(db_engine, region_code, content_type, status, title="지역행사", **cols): + from common.enums import LocalSource + + async with db_engine.begin() as c: + await c.execute( + text("INSERT INTO local_contents " + "(local_content_id, region_code, content_type, source, external_id, title, body, status, " + " display_start_at, display_end_at, collected_at) " + "VALUES (:i,:r,:ct,:src,:ext,:t,cast(:b as jsonb),:st,:ds,:de,now())"), + {"i": uuid.uuid4(), "r": region_code, "ct": content_type.value, "src": LocalSource.TOUR_API.value, + "ext": uuid.uuid4().hex, "t": title, "b": '{"title":"%s"}' % title, "st": status.value, + "ds": cols.get("display_start_at"), "de": cols.get("display_end_at")}, + ) + + +class _RegionPlace(_Place): + """region_code 를 가진 사업장. 지역 캐시의 키는 place_id 가 아니라 region_code 다.""" + + def __init__(self, pid, region_code): + super().__init__(pid) + self.region_code = region_code + + +async def test_only_published_local_content_enters_snapshot(db_engine, company_id): + """검증: 검수대기·종료·발행 지역 정보를 섞어 넣는다. + 기대결과: ★ PUBLISHED 만 담긴다 — 운영자가 검수하지 않은 외부 API 원문이 사이트로 새면 + '미검증 값 노출 금지'가 깨진다(fact 를 VERIFIED 로 거르는 것과 같은 규칙).""" + from common.enums import LocalContentStatus, LocalContentType + + pid = await _seed(db_engine, company_id) + await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "발행축제") + await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.REVIEW, "검수대기축제") + await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.ENDED, "종료축제") + + snap = await build_snapshot(_RegionPlace(pid, "4113500")) + assert [c["title"] for c in snap["local"]["contents"]] == ["발행축제"] + + +async def test_local_content_outside_display_window_is_excluded(db_engine, company_id): + """검증: 발행됐지만 노출 기간을 벗어난 지역 정보. + 기대결과: 빠진다 — 끝난 축제를 '이번 주말 행사'로 걸어두는 것도 틀린 정보다.""" + from datetime import datetime, timedelta, timezone + + from common.enums import LocalContentStatus, LocalContentType + + now = datetime.now(timezone.utc) + pid = await _seed(db_engine, company_id) + await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "지금축제") + await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "끝난축제", + display_end_at=now - timedelta(days=1)) + await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "아직축제", + display_start_at=now + timedelta(days=1)) + + snap = await build_snapshot(_RegionPlace(pid, "4113500")) + assert [c["title"] for c in snap["local"]["contents"]] == ["지금축제"] + + +async def test_local_content_is_scoped_to_the_places_region(db_engine, company_id): + """검증: 지역 캐시는 region_code 로 묶인다. + 기대결과: 다른 지역의 발행 콘텐츠는 담기지 않는다.""" + from common.enums import LocalContentStatus, LocalContentType + + pid = await _seed(db_engine, company_id) + await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "우리지역축제") + await _local(db_engine, "5011025", LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "남의지역축제") + + snap = await build_snapshot(_RegionPlace(pid, "4113500")) + assert [c["title"] for c in snap["local"]["contents"]] == ["우리지역축제"] + + +async def test_place_without_region_code_gets_no_local_content(db_engine, company_id): + """검증: region_code 가 비어 있는 사업장(수집이 지역을 특정하지 못한 경우). + 기대결과: 빈 목록 — 조회할 캐시 키가 없다. 지어내지 않는다.""" + from common.enums import LocalContentStatus, LocalContentType + + pid = await _seed(db_engine, company_id) + await _local(db_engine, "4113500", LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "어딘가축제") + + snap = await build_snapshot(_RegionPlace(pid, "")) + assert snap["local"] == {"region_code": None, "contents": []} diff --git a/backend/tests/test_tour_api_adapter.py b/backend/tests/test_tour_api_adapter.py new file mode 100644 index 0000000..5b82c13 --- /dev/null +++ b/backend/tests/test_tour_api_adapter.py @@ -0,0 +1,304 @@ +"""TourAPI 어댑터 — 값 매핑과 저작권 게이트. + +네트워크를 타지 않는다. TourAPI 실제 응답에서 **그대로 복사한** 표본으로 매핑만 검증한다 +(2026-08-31 실측: 가재와곰펜션 contentId=2708335, 가문 contentId=1052741). + +가장 중요한 것 두 개: + 1. 상업적 이용이 막힌 사진이 수집물에 섞이지 않는가 (docs/DECISIONS.md 1-2) + 2. "불가 (인근 주차장 이용)" 같은 값의 부호가 뒤집히지 않는가 + — 뒤집히면 주차 안 되는 집이 '주차 가능' 으로 발행된다 +""" +import pytest + +from common.category_schema import get_schema +from common.enums import PlaceCategory +from services.collector.tour_api_adapter import ( + COMMERCIAL_OK_LICENSES, + NO_DERIVATIVE_LICENSES, + TourApiAdapter, +) + +ADAPTER = TourApiAdapter() + +# ── 실제 응답에서 복사한 표본 ────────────────────────────────────────────── +_LODGING_INTRO = { + "checkintime": "14:00", "checkouttime": "12:00", + "refundregulation": "예약완료-숙박 6일 전까지 수수료 10% 환불
    금액 100%", + "chkcooking": "가능", "parkinglodging": "가능 (객실당 1대 무료 주차)", + "pickup": "부분 가능", "barbecue": "1", "karaoke": "0", + "roomcount": "13실", "scalelodging": "대지 면적 11,570㎡", "foodplace": "있음", +} +_ROOM_ROW = { + "roomtitle": "황토방", "roomsize1": "12", "roomsize2": "39.6", + "roombasecount": "2", "roommaxcount": "4", + "roomoffseasonminfee1": "100000", "roomoffseasonminfee2": "120000", + "roompeakseasonminfee1": "130000", + "roomcook": "Y", "roomaircondition": "Y", "roombathfacility": "Y", + "roomimg1": "http://tong.visitkorea.or.kr/a.jpg", "roomimg1alt": "황토방 5", "cpyrhtDivCd1": "Type3", + "roomimg2": "http://tong.visitkorea.or.kr/b.jpg", "roomimg2alt": "황토방 4", "cpyrhtDivCd2": "Type2", +} +_RESTAURANT_INTRO = { + "opentimefood": "- 08:30~20:00
    - 준비시간 15:00~16:00", + "restdatefood": "매주 수요일", "firstmenu": "삼선자장", + "treatmenu": "게살해물요리 / 난자완스 / 특색냉채 등", + "parkingfood": "불가 (인근 주차장 이용)", "packing": "가능", + "kidsfacility": "0", "chkcreditcardfood": "없음", "smoking": "모두 금연석", + "infocenterfood": "02-2608-5255", +} + + +def _map(facts): + return {(f.key, f.unit_name): f.value for f in facts} + + +# ── URL 라우팅 ──────────────────────────────────────────────────────────── +@pytest.mark.parametrize("url,expected", [ + ("https://korean.visitkorea.or.kr/detail/ms_detail.do?cotid=2708335", True), + ("tour://32/2708335", True), + ("tour://39/1052741", True), + ("https://gangmunstay.kr/", False), + ("https://m.place.naver.com/accommodation/1/home", False), + ("https://www.yanolja.com/pension/1", False), +]) +def test_can_handle(url, expected): + """검증: 어떤 주소를 받는가. + 기대결과: 구석구석 상세주소와 tour:// 만. 다른 어댑터 영역을 넘보지 않는다.""" + assert ADAPTER.can_handle(url) is expected + + +# ── 부호 판정 (여기가 제일 위험한 자리) ──────────────────────────────────── +@pytest.mark.parametrize("raw,expected", [ + ("가능", True), + ("가능 (객실당 1대 무료 주차)", True), + ("부분 가능", True), + ("불가", False), + ("불가 (인근 주차장 이용)", False), # ★ 뒤에 '이용' 이 있다고 true 가 되면 안 된다 + ("없음", False), + ("", None), + ("문의", None), # 모르면 None — '아니오' 로 단정하지 않는다 +]) +def test_head_bool_reads_leading_token_only(raw, expected): + """검증: '가능/불가 (설명)' 형태의 부호 판정. + + 기대결과: **맨 앞 토큰**으로만 판정한다. 문자열 전체를 훑으면 + "불가 (인근 주차장 이용)" 이 true 로 뒤집혀 주차 안 되는 집이 '주차 가능' 으로 발행된다.""" + assert ADAPTER._head_bool(raw) is expected + + +def test_unknown_value_becomes_no_fact_not_false(): + """검증: 판정할 수 없는 값. + 기대결과: fact 자체를 만들지 않는다. '모름' 과 '아니오' 는 다르다.""" + facts = _map(ADAPTER._lodging_facts({"chkcooking": "문의 바랍니다"})) + assert ("cooking_allowed", None) not in facts + + +# ── 숙박 매핑 ───────────────────────────────────────────────────────────── +def test_lodging_place_facts(): + """검증: 숙박 detailIntro2 → 사업장 fact. + 기대결과: 체크인·환불규정·취사·주차·픽업·바비큐가 스키마 key 로 들어온다.""" + f = _map(ADAPTER._lodging_facts(_LODGING_INTRO)) + assert f[("check_in_time", None)] == "14:00" + assert f[("check_out_time", None)] == "12:00" + assert f[("cooking_allowed", None)] == "true" + assert f[("parking", None)] == "true" + assert f[("pickup_service", None)] == "true" + assert f[("bbq_available", None)] == "true" + assert "
    " not in f[("cancel_policy", None)] + + +def test_lodging_drops_fields_without_schema_slot(): + """검증: 스키마에 자리가 없는 TourAPI 필드(roomcount·scalelodging·foodplace). + + 기대결과: 아무 key 로도 들어오지 않는다. ★ 억지로 다른 key 에 넣으면 + '식음료장 있음' 이 '조식 제공' 으로 둔갑한다.""" + values = {v for v in _map(ADAPTER._lodging_facts(_LODGING_INTRO)).values()} + assert "13실" not in values and "있음" not in values + assert not any("11,570" in str(v) for v in values) + + +def test_room_facts_are_unit_scoped_and_use_square_meters(): + """검증: detailInfo2 → 객실 단위 fact. + + 기대결과: unit_name 이 객실명이고, 면적은 roomsize2(㎡)를 쓴다. + ★ roomsize1 은 평이라 섞으면 3배 틀린 면적이 발행된다.""" + f = _map(ADAPTER._room_facts([_ROOM_ROW])) + assert f[("room_type", "황토방")] == "황토방" + assert f[("standard_capacity", "황토방")] == "2" + assert f[("max_capacity", "황토방")] == "4" + assert f[("room_size", "황토방")] == "39.6" # 12(평)이 아니다 + assert f[("weekday_price", "황토방")] == "100000" + assert f[("weekend_price", "황토방")] == "120000" + assert f[("peak_price", "황토방")] == "130000" + assert f[("has_kitchen", "황토방")] == "true" + + +def test_room_facts_keys_exist_in_lodging_schema(): + """검증: 객실 fact 의 key 가 전부 숙박 스키마에 있는가. + 기대결과: 전부 존재. 없으면 FACT_INVALID_KEY 로 조용히 버려져 화면이 빈다.""" + schema = get_schema(PlaceCategory.LODGING) + for fact in ADAPTER._room_facts([_ROOM_ROW]) + ADAPTER._lodging_facts(_LODGING_INTRO): + spec = schema.get(fact.key) + assert spec is not None, f"숙박 스키마에 없는 key: {fact.key}" + assert spec.scope == fact.scope, f"{fact.key} 스코프 불일치: {spec.scope} != {fact.scope}" + + +# ── 음식점 매핑 ─────────────────────────────────────────────────────────── +def test_restaurant_facts(): + """검증: 음식점 detailIntro2 → 사업장 fact. + 기대결과: 영업시간의
    이 풀리고, 주차는 '불가' 로 정확히 읽힌다.""" + f = _map(ADAPTER._restaurant_facts(_RESTAURANT_INTRO)) + assert f[("business_hours", None)].startswith("- 08:30~20:00") + assert "
    " not in f[("business_hours", None)] + assert f[("closed_days", None)] == "매주 수요일" + assert f[("signature_menu", None)] == "삼선자장" + assert f[("parking", None)] == "false" + assert f[("takeout", None)] == "true" + + +def test_restaurant_never_maps_kids_facility_to_kids_allowed(): + """검증: kidsfacility=0 인 음식점. + + 기대결과: kids_allowed fact 를 만들지 않는다. ★ 실측 회귀 — + '어린이놀이방 없음' 을 '아이 동반 불가' 로 올려 발행하면 손님을 돌려보내게 된다.""" + assert ("kids_allowed", None) not in _map(ADAPTER._restaurant_facts(_RESTAURANT_INTRO)) + + +def test_restaurant_never_maps_credit_card_flag_to_payment_methods(): + """검증: chkcreditcardfood='없음'. + 기대결과: payment_methods 로 들어오지 않는다 — 그 필드는 결제수단 '목록' 이다.""" + assert ("payment_methods", None) not in _map(ADAPTER._restaurant_facts(_RESTAURANT_INTRO)) + + +def test_treat_menu_splits_and_drops_trailing_marker(): + """검증: treatmenu '게살해물요리 / 난자완스 / 특색냉채 등'. + 기대결과: 메뉴 3건. 꼬리의 '등' 은 메뉴가 아니다.""" + names = [f.unit_name for f in ADAPTER._restaurant_facts(_RESTAURANT_INTRO) if f.key == "menu_name"] + assert names == ["게살해물요리", "난자완스", "특색냉채"] + + +def test_restaurant_facts_keys_exist_in_schema(): + """검증: 음식점 fact 의 key 가 전부 스키마에 있는가.""" + schema = get_schema(PlaceCategory.RESTAURANT) + for fact in ADAPTER._restaurant_facts(_RESTAURANT_INTRO): + spec = schema.get(fact.key) + assert spec is not None, f"음식점 스키마에 없는 key: {fact.key}" + assert spec.scope == fact.scope + + +# ── 저작권 게이트 (docs/DECISIONS.md 1-2) ───────────────────────────────── +def test_license_constants_match_kogl(): + """검증: 공공누리 유형 상수. + + 기대결과: 상업적 이용 가능은 1·3유형뿐이고, 변경금지는 3·4유형이다. + (2·4유형 = 상업적 이용금지 / 3·4유형 = 변경금지)""" + assert COMMERCIAL_OK_LICENSES == {"type1", "type3"} + assert NO_DERIVATIVE_LICENSES == {"type3", "type4"} + + +def test_media_drops_non_commercial_license(): + """검증: 같은 객실에 Type3 사진과 Type2 사진이 섞여 온다. + + 기대결과: Type3 만 담고 Type2 는 버린다. ★ 2유형은 상업적 이용금지라 + 사장님 홈페이지(=상업적 이용)에 실으면 조건 위반이다.""" + media = ADAPTER._media({}, [], [_ROOM_ROW]) + urls = [m.origin_url for m in media] + assert "http://tong.visitkorea.or.kr/a.jpg" in urls # Type3 + assert "http://tong.visitkorea.or.kr/b.jpg" not in urls # Type2 — 버려야 한다 + assert all(m.license in COMMERCIAL_OK_LICENSES for m in media) + + +def test_media_drops_unknown_license(): + """검증: 저작권 유형이 비었거나 처음 보는 코드. + + 기대결과: 버린다. 상업 사이트에 실을 사진이라 '모름' 은 안전한 쪽이 아니다 — + 새 코드가 생겼을 때 조용히 통과시키는 것보다 빠뜨리는 쪽이 낫다.""" + rows = [{"roomtitle": "A", "roomimg1": "http://x/1.jpg", "cpyrhtDivCd1": ""}, + {"roomtitle": "B", "roomimg1": "http://x/2.jpg", "cpyrhtDivCd1": "Type9"}] + assert ADAPTER._media({}, [], rows) == [] + + +def test_media_carries_license_so_no_derivative_can_be_honored(): + """검증: 담긴 사진이 라이선스를 들고 나가는가. + + 기대결과: license 가 채워진다. ★ Type3 는 **변경금지**라 뒤에서 크롭·리사이즈하면 + 조건을 어긴다. 어느 사진이 손대면 안 되는지는 수집 시점에만 알 수 있다.""" + media = ADAPTER._media({}, [], [_ROOM_ROW]) + assert media[0].license == "type3" + assert media[0].license in NO_DERIVATIVE_LICENSES + assert media[0].unit_name == "황토방" + + +def test_media_keeps_room_photo_attached_to_its_room(): + """검증: 객실 사진의 unit_name. + 기대결과: 그 객실 이름이 붙는다 — 안 붙으면 전부 대표사진 더미로 섞인다.""" + assert {m.unit_name for m in ADAPTER._media({}, [], [_ROOM_ROW])} == {"황토방"} + + +# ── 값 다듬기 ───────────────────────────────────────────────────────────── +@pytest.mark.parametrize("raw,expected", [ + ("13실", "13"), ("11,570㎡", "11570"), ("39.6", "39.6"), + ("16명", "16"), ("", None), ("문의", None), ("0", None), +]) +def test_number_strips_units_and_commas(raw, expected): + """검증: '13실'·'11,570㎡' 같은 단위 붙은 숫자. + 기대결과: 숫자만 남는다. 숫자로 시작하지 않으면 담지 않는다.""" + assert ADAPTER._number(raw) == expected + + +def test_plain_unwraps_br_but_keeps_negation_words(): + """검증:
    제거가 글자를 지우지 않는가. + 기대결과: '불가' 가 남는다 — 태그 제거하다 부정어가 사라지면 부호가 뒤집힌다.""" + assert "불가" in ADAPTER._plain("주차
    불가
    합니다") + assert "
    " not in ADAPTER._plain("주차
    불가") + + +# ── 콘텐츠 조회 (services/external/tour_lookup.py) ──────────────────────── +# 네트워크를 타지 않는다. 검색어 생성과 상호 대조 규칙만 본다. +from services.external.tour_lookup import ( # noqa: E402 + MAX_QUERY_ATTEMPTS, _name_matches, _query_candidates, normalize, +) + + +def test_query_candidates_shortens_from_the_tail(): + """검증: 등록명보다 긴 상호. + + 기대결과: 전체 → 뒤 토큰을 하나씩 뗀 순서. ★ 실측 회귀 — + '그래비티 조선 서울 판교 오토그래프 컬렉션' 은 searchKeyword2 에서 0건인데 + '그래비티 조선 서울 판교' 로 줄이면 잡힌다. 축약이 없으면 이 호텔은 영영 못 찾는다.""" + got = _query_candidates("그래비티 조선 서울 판교 오토그래프 컬렉션") + assert got[0] == "그래비티 조선 서울 판교 오토그래프 컬렉션" + assert "그래비티 조선 서울 판교" in got + assert len(got) <= MAX_QUERY_ATTEMPTS + + +@pytest.mark.parametrize("name,expected", [ + ("가재와곰펜션", ["가재와곰펜션"]), # 한 토큰이면 후보도 하나 + ("", []), + (" ", []), +]) +def test_query_candidates_edge_cases(name, expected): + """검증: 토큰이 하나거나 비어 있는 상호. + 기대결과: 불필요한 호출을 만들지 않는다.""" + assert _query_candidates(name) == expected + + +@pytest.mark.parametrize("ours,theirs,match", [ + ("그래비티 조선 서울 판교 오토그래프 컬렉션", "그래비티 조선 서울 판교", True), # 등록명이 더 짧다 + ("가재와곰", "가재와곰펜션", True), # 등록명이 더 길다 + ("롯데호텔 월드", "롯데호텔월드", True), # 공백만 다르다 + ("롯데호텔 월드", "롯데호텔 부산", False), # 다른 지점 + ("코트야드 바이 메리어트 서울 판교", "그래비티 조선 서울 판교", False), # 같은 동네 다른 호텔 +]) +def test_name_matches(ours, theirs, match): + """검증: 상호 대조. + + 기대결과: 포함 관계면 같은 업소로 본다. ★ 다른 지점을 같다고 하면 + 남의 가게 객실 요금이 우리 사장님 사이트에 실린다 — 여기가 가장 비싼 실수다.""" + assert _name_matches(ours, theirs) is match + + +def test_normalize_matches_naver_lookup_rule(): + """검증: 상호 정규화 규칙. + 기대결과: 공백·기호를 걷어내고 소문자로 — naver_place_lookup 과 같은 기준이다.""" + assert normalize("롯데호텔 월드") == "롯데호텔월드" + assert normalize("A-1 Cafe & Bar") == "a1cafebar" diff --git a/backend/tests/test_verify_candidates.py b/backend/tests/test_verify_candidates.py new file mode 100644 index 0000000..5a3e45e --- /dev/null +++ b/backend/tests/test_verify_candidates.py @@ -0,0 +1,199 @@ +"""동일 업소 후보 조회 — ★ 서버가 자동 확정하지 않고 사람이 고르게 한다. + +남의 가게를 붙이는 게 이 서비스에서 제일 비싼 실수다(체크인 시간이 틀리면 실제 예약 클레임). +그래서 자동 판정이 MATCHED 여도 후보를 전부 내려보내 UI 가 확인시킬 수 있게 한다. +""" +from common.enums import ErrorType +from services.external import kakao as kakao_client +from services.external import naver as naver_client + + +def _np(name, addr, url=None): + return naver_client.NaverPlace( + name=name, road_address=addr, address=None, phone=None, + latitude=38.0, longitude=128.7, category_name="숙박>펜션", + place_url=url, naver_place_id=None, + ) + + +def _match(outcome, place=None, candidates=None, reason=None): + return naver_client.MatchResult( + outcome=outcome, place=place, candidates=candidates or [], reason=reason, detail=None, + ) + + +async def _place(client, h, name="핑크비치펜션"): + return (await client.post("/v1/place", headers=h, json={"name": name, "category": 1})).json()["place"]["place_id"] + + +def _patch_naver(monkeypatch, result): + """네이버 판정을 고정값으로 바꾼다. 호출 인자를 그대로 돌려줘 호출측 규약도 볼 수 있게 한다.""" + monkeypatch.setattr(kakao_client.KakaoLocalClient, "enabled", property(lambda self: False)) + monkeypatch.setattr(naver_client.NaverLocalClient, "enabled", property(lambda self: True)) + + seen: dict = {} + + async def _verify(self, name, address_hint=None, *, search_query=None): + seen["name"] = name + seen["search_query"] = search_query + return result + + async def _close(self): + return None + + monkeypatch.setattr(naver_client.NaverLocalClient, "verify_place", _verify) + monkeypatch.setattr(naver_client.NaverLocalClient, "aclose", _close) + return seen + + +async def test_single_match_is_auto_selectable(auth_headers, client, monkeypatch): + """검증: 정확히 1건 일치하는 상호명. + 기대결과: auto_selectable=true 로 내려오되 **후보는 그대로 내려온다** — UI 가 한 번 확인시킬 수 있다.""" + only = _np("핑크비치펜션", "강원특별자치도 양양군 현북면 하조대3길 11", "http://pinkbeach.kr") + _patch_naver(monkeypatch, _match(kakao_client.MatchOutcome.MATCHED, only, [only], "name_exact")) + + h = await auth_headers("u1") + pid = await _place(client, h) + body = (await client.get(f"/v1/place/{pid}/verify/candidates", headers=h)).json() + + assert body["result"]["success"] is True + assert body["outcome"] == "matched" + assert body["auto_selectable"] is True + assert len(body["candidates"]) == 1 + assert body["candidates"][0]["place_url"] == "http://pinkbeach.kr" + + +async def test_ambiguous_returns_all_candidates_for_ui(auth_headers, client, monkeypatch): + """검증: 동명 업소가 여러 건이라 자동 판정이 안 된다. + 기대결과: ★ auto_selectable=false + 후보 전체 — UI 가 목록을 그려 사람이 고른다.""" + rows = [ + _np("하조대펜션", "강원특별자치도 양양군 현북면 하조대3길 11"), + _np("하조대펜션", "강원특별자치도 양양군 현북면 하조대2길 48"), + _np("하조대펜션", "강원특별자치도 양양군 손양면 동명로 5"), + ] + _patch_naver(monkeypatch, _match(kakao_client.MatchOutcome.AMBIGUOUS, None, rows, "name_duplicate")) + + h = await auth_headers("u1") + pid = await _place(client, h, "하조대펜션") + body = (await client.get(f"/v1/place/{pid}/verify/candidates", headers=h)).json() + + assert body["outcome"] == "ambiguous" + assert body["auto_selectable"] is False + assert len(body["candidates"]) == 3 + assert body["reason"] == "name_duplicate" + # 사람이 고를 수 있게 주소가 다 실려 있어야 한다 + assert len({c["road_address"] for c in body["candidates"]}) == 3 + + +async def test_no_candidate_is_reported(auth_headers, client, monkeypatch): + """검증: 외부 장소 DB 에 후보가 하나도 없다. + 기대결과: PLACE_VERIFY_NO_CANDIDATE — 사장님이 직접 입력하는 경로로 안내해야 한다.""" + _patch_naver(monkeypatch, _match(kakao_client.MatchOutcome.NO_CANDIDATE, None, [], "empty")) + + h = await auth_headers("u1") + pid = await _place(client, h, "존재하지않는가게") + body = (await client.get(f"/v1/place/{pid}/verify/candidates", headers=h)).json() + assert body["result"]["code"] == ErrorType.PLACE_VERIFY_NO_CANDIDATE.value + + +async def test_picked_candidate_can_be_confirmed(auth_headers, client, monkeypatch): + """검증: 후보 목록에서 하나를 골라 확정한다(UI 흐름 전체). + 기대결과: 확정되고, 후보가 준 홈페이지가 공식 채널로 자동 등록된다.""" + rows = [ + _np("하조대펜션", "강원특별자치도 양양군 현북면 하조대3길 11", "http://hajodae-a.kr"), + _np("하조대펜션", "강원특별자치도 양양군 손양면 동명로 5", "http://hajodae-b.kr"), + ] + _patch_naver(monkeypatch, _match(kakao_client.MatchOutcome.AMBIGUOUS, None, rows, "name_duplicate")) + + h = await auth_headers("u1") + pid = await _place(client, h, "하조대펜션") + cands = (await client.get(f"/v1/place/{pid}/verify/candidates", headers=h)).json()["candidates"] + + picked = cands[1] # 사람이 두 번째를 골랐다 + r = (await client.post(f"/v1/place/{pid}/verify", headers=h, json={ + "source": 2, "road_address": picked["road_address"], + "latitude": picked["latitude"], "longitude": picked["longitude"], + "place_url": picked["place_url"], + })).json() + assert r["result"]["success"] is True + assert r["place"]["road_address"] == "강원특별자치도 양양군 손양면 동명로 5" + + links = (await client.get(f"/v1/place/{pid}/link/list", headers=h)).json()["links"] + official = [l for l in links if l["url"] == "http://hajodae-b.kr"] + assert official, "고른 후보의 홈페이지가 공식 채널로 등록되지 않았다" + assert official[0].get("confirmed_at") is None, "등록만 하고 확정은 따로다" + + +async def test_candidates_require_configured_source(auth_headers, client, monkeypatch): + """검증: 카카오도 네이버도 키가 없다. + 기대결과: LOCAL_NOT_CONFIGURED — 조용히 빈 목록을 주지 않는다.""" + monkeypatch.setattr(kakao_client.KakaoLocalClient, "enabled", property(lambda self: False)) + monkeypatch.setattr(naver_client.NaverLocalClient, "enabled", property(lambda self: False)) + + h = await auth_headers("u1") + pid = await _place(client, h) + body = (await client.get(f"/v1/place/{pid}/verify/candidates", headers=h)).json() + assert body["result"]["code"] == ErrorType.LOCAL_NOT_CONFIGURED.value + + +async def test_candidates_scoped_to_company(auth_headers, client, other_company_id, monkeypatch): + """검증: 다른 회사 계정으로 남의 사업장 후보를 조회한다. + 기대결과: PLACE_NOT_FOUND.""" + _patch_naver(monkeypatch, _match(kakao_client.MatchOutcome.MATCHED, _np("a", "b"), [], "x")) + h1 = await auth_headers("o1") + pid = await _place(client, h1) + h2 = await auth_headers("o2", other_company_id) + body = (await client.get(f"/v1/place/{pid}/verify/candidates", headers=h2)).json() + assert body["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value + + +async def test_region_stays_in_query_and_out_of_the_match_name(auth_headers, client, monkeypatch): + """검증: 화면이 '상호명 + 위치'를 합쳐 query 로 보낸다. + 기대결과: 검색어에는 지역이 그대로 실리고, 판정용 상호명에는 **상호만** 간다. + + ★ 왜 이걸 못 박아 두나: 판정(pick_match)은 후보 상호명과 정확일치를 본다. 지역이 붙은 + 문자열을 판정에 그대로 넘기면 정확일치가 구조적으로 성립할 수 없어, 후보가 단 1건인 + 경우까지 AMBIGUOUS 로 떨어진다 — 사장님은 매번 "비슷한 가게가 여럿입니다"를 읽는다. + 실측(2026-08-28) 10건 전부 그랬다. 검색은 넓게, 판정은 좁게. + """ + only = _np("보사노바 커피로스터스 강릉점", "강원 강릉시 창해로14번길 28") + seen = _patch_naver( + monkeypatch, _match(kakao_client.MatchOutcome.MATCHED, only, [only], "name_exact") + ) + + h = await auth_headers("u1") + pid = await _place(client, h, name="보사노바 커피로스터스 강릉점") + body = ( + await client.get( + f"/v1/place/{pid}/verify/candidates", + headers=h, + params={"query": "보사노바 커피로스터스 강릉점 강릉 견소동"}, + ) + ).json() + + assert body["result"]["success"] is True + assert seen["search_query"] == "보사노바 커피로스터스 강릉점 강릉 견소동" + assert seen["name"] == "보사노바 커피로스터스 강릉점" + + +async def test_match_name_falls_back_to_query_when_place_has_no_name(auth_headers, client, monkeypatch): + """검증: 사업장 상호가 비어 있다(직접 입력 등으로 이름 없이 만들어진 경우). + 기대결과: 검색어를 판정용 상호명으로도 쓴다 — 조회 자체가 실패하지는 않는다.""" + only = _np("핑크비치펜션", "강원특별자치도 양양군") + seen = _patch_naver( + monkeypatch, _match(kakao_client.MatchOutcome.MATCHED, only, [only], "name_exact") + ) + + h = await auth_headers("u1") + pid = await _place(client, h, name="핑크비치펜션") + # 상호를 비운다 — places.name 이 빈 문자열인 상태를 만든다. + await client.patch(f"/v1/place/{pid}", headers=h, json={"name": ""}) + + body = ( + await client.get( + f"/v1/place/{pid}/verify/candidates", headers=h, params={"query": "핑크비치펜션 양양"} + ) + ).json() + + assert body["result"]["success"] is True + assert seen["name"] == "핑크비치펜션 양양" diff --git a/backend/tests/test_vision_api.py b/backend/tests/test_vision_api.py new file mode 100644 index 0000000..c7e37fd --- /dev/null +++ b/backend/tests/test_vision_api.py @@ -0,0 +1,181 @@ +"""사진 분석(VISION) — 잡 배선과 ★ 신뢰도 게이트. + +★ 이 잡이 절대 하면 안 되는 것: + - 신뢰도 낮은 라벨을 자동 반영하는 것 (사람 확인 큐를 건너뛰는 것) + - 한 장 실패로 잡 전체를 실패시키는 것 + - 같은 사진을 재분석해 요금을 두 번 내는 것 +""" +import uuid + +import pytest +from sqlalchemy import text + +from common.enums import ErrorType, JobStatus, JobType, MediaStatus, PlaceCategory, SourceType +from crud.job_crud import JobQueue +from services.external import gemini +from worker.handlers import build_handler +from worker.runner import Worker + + +async def _place_with_media(client, h, db_engine, n=3, kakao="v1"): + 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={"external_place_id": kakao, "source": 1}) + async with db_engine.begin() as c: + for i in range(n): + await c.execute( + text("INSERT INTO media (media_id, place_id, url, origin_url, source_type, status, sort_order) " + "VALUES (:m, :p, :u, :u, :s, :st, :o)"), + {"m": uuid.uuid4(), "p": uuid.UUID(pid), "u": f"https://cdn.test/{pid}/{i}.jpg", + "s": SourceType.CRAWL.value, "st": MediaStatus.PENDING_REVIEW.value, "o": i}, + ) + return pid + + +async def _media_rows(db_engine, pid): + async with db_engine.begin() as c: + return (await c.execute( + text("SELECT origin_url, label, alt_text, vision_confidence, status FROM media " + "WHERE place_id = :p ORDER BY sort_order"), + {"p": uuid.UUID(pid)}, + )).all() + + +def _fake_analyze(results): + """gemini.analyze_images 를 대체 — 실제 API 를 때리지 않는다.""" + async def _fn(images, **kw): + out = [] + for img in images: + r = results.get(img.origin_url) + out.append(r if r else gemini.VisionResult( + origin_url=img.origin_url, label=None, alt_text=None, + confidence=0.0, needs_review=True, ok=False, error="no result")) + return out + return _fn + + +async def test_high_confidence_is_auto_applied(auth_headers, client, db_engine, monkeypatch): + """검증: 신뢰도 높은 분석 결과. + 기대결과: 라벨·alt 가 반영되고 status 가 APPROVED 로 올라간다.""" + h = await auth_headers("u1") + pid = await _place_with_media(client, h, db_engine, n=2) + urls = [r[0] for r in await _media_rows(db_engine, pid)] + + monkeypatch.setattr(gemini, "is_configured", lambda: True) + monkeypatch.setattr(gemini, "analyze_images", _fake_analyze({ + urls[0]: gemini.VisionResult(urls[0], "A동 침실", "침대와 창문이 있는 객실", 0.93, False, True, None), + urls[1]: gemini.VisionResult(urls[1], "외관", "2층 건물 외관", 0.88, False, True, None), + })) + + job_id = (await client.post(f"/v1/place/{pid}/vision", headers=h, json={})).json()["job_id"] + await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).process_one() + + 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"]["approved"] == 2 + + rows = await _media_rows(db_engine, pid) + assert rows[0][1] == "A동 침실" and rows[0][2] == "침대와 창문이 있는 객실" + assert all(r[4] == MediaStatus.APPROVED.value for r in rows) + + +async def test_low_confidence_goes_to_review_queue(auth_headers, client, db_engine, monkeypatch): + """검증: 신뢰도가 임계값 미만인 결과. + 기대결과: ★ 라벨은 저장되지만 status 는 PENDING_REVIEW 로 남는다 — 자동 반영하지 않는다.""" + h = await auth_headers("u1") + pid = await _place_with_media(client, h, db_engine, n=1, kakao="v2") + url = (await _media_rows(db_engine, pid))[0][0] + + monkeypatch.setattr(gemini, "is_configured", lambda: True) + monkeypatch.setattr(gemini, "analyze_images", _fake_analyze({ + url: gemini.VisionResult(url, "수영장", "물이 있는 공간", 0.31, True, True, None), + })) + + job_id = (await client.post(f"/v1/place/{pid}/vision", headers=h, json={})).json()["job_id"] + await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).process_one() + + job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"] + assert job["result"]["needs_review"] == 1 + assert job["result"]["approved"] == 0 + + row = (await _media_rows(db_engine, pid))[0] + assert row[1] == "수영장", "사람이 고칠 재료는 저장돼야 한다" + assert row[4] == MediaStatus.PENDING_REVIEW.value, "★ 신뢰도 낮은 결과가 자동 승인됐다" + + +async def test_partial_failure_does_not_fail_the_job(auth_headers, client, db_engine, monkeypatch): + """검증: 3장 중 1장만 분석에 실패한다. + 기대결과: 잡은 DONE, 실패한 장만 확인 큐에 남는다 — 한 장이 나머지를 죽이지 않는다.""" + h = await auth_headers("u1") + pid = await _place_with_media(client, h, db_engine, n=3, kakao="v3") + urls = [r[0] for r in await _media_rows(db_engine, pid)] + + monkeypatch.setattr(gemini, "is_configured", lambda: True) + monkeypatch.setattr(gemini, "analyze_images", _fake_analyze({ + urls[0]: gemini.VisionResult(urls[0], "외관", "건물 외관", 0.9, False, True, None), + urls[1]: gemini.VisionResult(urls[1], None, None, 0.0, True, False, "download failed"), + urls[2]: gemini.VisionResult(urls[2], "거실", "소파가 있는 거실", 0.85, False, True, None), + })) + + job_id = (await client.post(f"/v1/place/{pid}/vision", headers=h, json={})).json()["job_id"] + await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).process_one() + + job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"] + assert job["status"] == JobStatus.DONE.value + assert job["result"]["approved"] == 2 + assert job["result"]["failed"] == 1 + + +async def test_second_run_skips_already_analyzed(auth_headers, client, db_engine, monkeypatch): + """검증: 분석이 끝난 사업장에 다시 분석을 건다. + 기대결과: MEDIA_NOT_FOUND — 같은 사진 재분석은 요금만 나간다. force 로만 다시 돈다.""" + h = await auth_headers("u1") + pid = await _place_with_media(client, h, db_engine, n=1, kakao="v4") + url = (await _media_rows(db_engine, pid))[0][0] + + monkeypatch.setattr(gemini, "is_configured", lambda: True) + monkeypatch.setattr(gemini, "analyze_images", _fake_analyze({ + url: gemini.VisionResult(url, "외관", "건물 외관", 0.9, False, True, None), + })) + await client.post(f"/v1/place/{pid}/vision", headers=h, json={}) + await Worker("w", JobQueue(), build_handler(), job_deadline_sec=30).process_one() + + r = await client.post(f"/v1/place/{pid}/vision", headers=h, json={}) + assert r.json()["result"]["code"] == ErrorType.MEDIA_NOT_FOUND.value + + forced = await client.post(f"/v1/place/{pid}/vision", headers=h, json={"force": True}) + assert forced.json()["result"]["success"] is True + + +async def test_vision_requires_api_key(auth_headers, client, db_engine, monkeypatch): + """검증: GEMINI_API_KEY 없이 분석을 건다. + 기대결과: GENERATOR_NOT_CONFIGURED — 잡을 만들지 않는다(만들어봐야 DEAD 로 간다).""" + h = await auth_headers("u1") + pid = await _place_with_media(client, h, db_engine, n=1, kakao="v5") + monkeypatch.setattr(gemini, "is_configured", lambda: False) + + r = await client.post(f"/v1/place/{pid}/vision", headers=h, json={}) + assert r.json()["result"]["code"] == ErrorType.GENERATOR_NOT_CONFIGURED.value + + +async def test_collect_chains_vision_job(auth_headers, client, monkeypatch): + """검증: 수집이 사진을 저장하면 사진 분석 잡이 이어서 걸리는가. + 기대결과: 수집 잡 result 에 vision_job_id 가 담기고 그 잡이 큐에 있다 — 파이프라인이 안 끊긴다.""" + from services.collector import MockAdapter + + monkeypatch.setattr(gemini, "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={"external_place_id": "v6", "source": 1}) + url = MockAdapter.url_for(PlaceCategory.LODGING, pid, channel="naver_place") + lid = (await client.post(f"/v1/place/{pid}/link", headers=h, json={"channel": 3, "url": url})).json()["link"]["link_id"] + await client.post(f"/v1/place/{pid}/link/{lid}/confirm", headers=h) + + job_id = (await client.post(f"/v1/place/{pid}/collect", headers=h, json={})).json()["job_id"] + await Worker("w", JobQueue(), build_handler(), job_deadline_sec=120).process_one() + + job = (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"] + vision_id = job["result"].get("vision_job_id") + assert vision_id, "사진을 저장했는데 분석 잡이 안 걸렸다" + chained = await JobQueue().get(vision_id) + assert chained["job_type"] == JobType.VISION.value + assert chained["status"] == JobStatus.PENDING.value diff --git a/backend/tests/test_weather_api.py b/backend/tests/test_weather_api.py new file mode 100644 index 0000000..22be982 --- /dev/null +++ b/backend/tests/test_weather_api.py @@ -0,0 +1,61 @@ +from datetime import datetime, timedelta, timezone + +from common.enums import ErrorType +from services.external.open_meteo import OpenMeteoRequestFailed + + +WEATHER = { + "temperature": 24.3, + "weather_code": 1, + "wind_speed": 3.2, + "observed_at": "2026-08-27T14:00", + "timezone": "Asia/Seoul", + "latitude": 33.46, + "longitude": 126.31, +} + + +async def test_weather_uses_region_cache(client, monkeypatch): + calls = 0 + + async def fetch(_lat, _lon): + nonlocal calls + calls += 1 + return WEATHER + + monkeypatch.setattr("services.local_content_service.fetch_current_weather", fetch) + params = {"region_code": "50110253", "latitude": 33.46, "longitude": 126.31} + + first = (await client.get("/v1/local/weather", params=params)).json() + second = (await client.get("/v1/local/weather", params=params)).json() + + assert first["weather"]["temperature"] == 24.3 + assert first["cached"] is False + assert second["cached"] is True + assert calls == 1 + + +async def test_weather_returns_stale_cache_when_upstream_fails(client, db_engine, monkeypatch): + params = {"region_code": "50110253", "latitude": 33.46, "longitude": 126.31} + monkeypatch.setattr("services.local_content_service.fetch_current_weather", lambda *_: _async_value(WEATHER)) + await client.get("/v1/local/weather", params=params) + + async with db_engine.begin() as conn: + from sqlalchemy import text + await conn.execute(text("UPDATE local.local_contents SET expires_at = :expired"), { + "expired": datetime.now(timezone.utc) - timedelta(minutes=1) + }) + + async def fail(*_args): + raise OpenMeteoRequestFailed("fail") + + monkeypatch.setattr("services.local_content_service.fetch_current_weather", fail) + body = (await client.get("/v1/local/weather", params=params)).json() + assert body["result"]["code"] == ErrorType.SUCCESS.value + assert body["cached"] is True + assert body["stale"] is True + assert body["weather"]["temperature"] == 24.3 + + +async def _async_value(value): + return value diff --git a/backend/web_main.py b/backend/web_main.py new file mode 100644 index 0000000..70490c6 --- /dev/null +++ b/backend/web_main.py @@ -0,0 +1,42 @@ +# 실행 방법 +# pip install -r requirements.txt +# python web_main.py # 기본 local 환경 +# APP_ENV=dev python web_main.py # 환경 지정 +# +# 또는 uvicorn 직접 실행: +# uvicorn router.router:app --reload --host=0.0.0.0 --port=9800 + +import os + +import uvicorn + +from common.logger import LOG +from config.server_configs import web_server_config + +LOG.SetPrefix(web_server_config.server_name) + +# import 시점에 app 및 DB 세션 매니저(싱글톤)가 초기화된다. +import router.router + +if __name__ == "__main__": + LOG.i(f"Server Name : {web_server_config.server_name}") + LOG.i(f"Server Port : {web_server_config.port}") + LOG.i(f"API Server start time : {router.router.API_SERVER_START_TIME}") + + # RELOAD=1 (개발 컨테이너) → 소스 변경 시 자동 재기동. reload 와 workers(다중) 는 함께 못 쓰므로 분기. + reload = os.environ.get("RELOAD") == "1" + + run_kwargs = dict( + host="0.0.0.0", + port=web_server_config.port, + access_log=False, + ) + if reload: + run_kwargs["reload"] = True + else: + run_kwargs["workers"] = web_server_config.process_count + if web_server_config.is_ssl: + run_kwargs["ssl_keyfile"] = "./SSL/key.pem" + run_kwargs["ssl_certfile"] = "./SSL/cert.pem" + + uvicorn.run("router.router:app", **run_kwargs) diff --git a/backend/worker/handlers.py b/backend/worker/handlers.py new file mode 100644 index 0000000..07c383a --- /dev/null +++ b/backend/worker/handlers.py @@ -0,0 +1,94 @@ +"""잡 핸들러 레지스트리 — JobType 별로 '무엇을 하는가'. + +핸들러 규약: `async def handler(job: dict) -> dict` + job : {"job_id", "job_type", "payload", "attempts", "max_attempts"} + 반환값 : jobs.result 에 JSONB 로 저장된다(관측·디버깅용) + 예외 : 워커가 잡아 백오프 재큐(소진 시 DEAD). 재시도해도 소용없는 실패는 + 예외 메시지에 이유를 남긴다 — last_error 로 남아 운영자가 본다 + +핸들러는 **재시도 안전(멱등)** 해야 한다. lease 만료·워커 재시작으로 같은 잡이 다시 돌 수 있다. +수집은 이미 확보한 fact 를 다시 덮어쓰지 않고(특히 CORRECTED), 사진은 origin_url 로 중복을 거른다. + +현재 등록된 핸들러: + JobType.COLLECT ✓ services/collect_service.run_collect — Phase 1 은 MockAdapter 만 등록돼 있다 + JobType.VISION ✓ services/vision_service.run_vision — Gemini Vision 사진 분류 + alt + JobType.COPY ✓ services/copy_service.run_copy — 소개문·FAQ (확보된 fact 만 근거) + JobType.BUILD ✓ services/build_service.run_build — 정적 빌드 + 발행 검수 게이트 + JobType.LOCAL_SYNC → local 모듈이 붙을 때 + JobType.AI_CHECK → reports 모듈이 붙을 때 +""" + +from common.enums import JobType +from common.logger import LOG + + +class UnknownJobType(RuntimeError): + """등록되지 않은 JobType — 재시도해도 소용없다(코드 배포 누락 신호).""" + + +# JobType -> async def handler(job) -> dict +HANDLERS: dict[int, object] = {} + + +def register(job_type: JobType): + """핸들러 등록 데코레이터. 모듈이 붙을 때 자기 핸들러를 여기에 건다. + + @register(JobType.COLLECT) + async def handle_collect(job: dict) -> dict: + ... + """ + def _deco(fn): + if job_type.value in HANDLERS: + raise RuntimeError(f"JobType.{job_type.name} 핸들러가 이미 등록돼 있다") + HANDLERS[job_type.value] = fn + return fn + + return _deco + + +def build_handler(): + """등록된 핸들러로 디스패처를 만든다. 워커에 주입한다.""" + + async def dispatch(job: dict) -> dict: + fn = HANDLERS.get(job["job_type"]) + if fn is None: + name = JobType(job["job_type"]).name if job["job_type"] in {t.value for t in JobType} else job["job_type"] + raise UnknownJobType(f"JobType.{name} 핸들러 미등록 — 이 워커 이미지에 해당 모듈이 없다") + return await fn(job) + + return dispatch + + +def registered_types() -> list[str]: + """기동 로그용 — 이 워커가 처리할 수 있는 잡 종류.""" + return [JobType(v).name for v in sorted(HANDLERS)] + + +def log_registry(): + names = registered_types() + if names: + LOG.i(f"[worker] 처리 가능 잡: {', '.join(names)}") + else: + LOG.w("[worker] 등록된 핸들러가 없습니다 — 적재되는 잡은 모두 UnknownJobType 으로 DEAD 됩니다") + + +# ---- 등록 ------------------------------------------------------------------ +# import 부작용으로 등록한다(모듈을 읽는 것만으로 워커가 처리 능력을 갖는다). +# 순환 import 를 피하려고 파일 맨 아래에서 붙인다. +def _register_builtin(): + from services.collect_service import run_collect + from services.build_service import run_build + from services.copy_service import run_copy + from services.vision_service import run_vision + + if JobType.COLLECT.value not in HANDLERS: + HANDLERS[JobType.COLLECT.value] = run_collect + if JobType.VISION.value not in HANDLERS: + HANDLERS[JobType.VISION.value] = run_vision + if JobType.COPY.value not in HANDLERS: + HANDLERS[JobType.COPY.value] = run_copy + if JobType.BUILD.value not in HANDLERS: + HANDLERS[JobType.BUILD.value] = run_build + + +_register_builtin() diff --git a/backend/worker/notify.py b/backend/worker/notify.py new file mode 100644 index 0000000..85646ad --- /dev/null +++ b/backend/worker/notify.py @@ -0,0 +1,49 @@ +"""LISTEN/NOTIFY 리스너 — 잡 적재 시 워커를 즉시 깨운다(폴링 낭비 제거). (LPS `worker/notify.py` 이식) + +전용 asyncpg 연결로 LISTEN 한다(SQLAlchemy 풀과 분리). 알림이 오면 이벤트를 세팅하고, +워커는 claim 이 비었을 때 wait() 로 알림 또는 짧은 타임아웃(안전망/reaper)까지 대기한다. +""" + +import asyncio + +import asyncpg + +from config.server_configs import main_db_config +from crud.job_crud import JOB_NOTIFY_CHANNEL + + +def _dsn() -> str: + c = main_db_config + pw = f":{c.write_pw}" if c.write_pw else "" + return f"postgresql://{c.write_id}{pw}@{c.write_host}:{c.write_port}/{c.name}" + + +class JobListener: + """잡 적재 NOTIFY 를 받아 워커를 깨우는 전용 asyncpg LISTEN 연결(SQLAlchemy 풀과 분리).""" + + def __init__(self, channel: str = JOB_NOTIFY_CHANNEL): + self._channel = channel + self._conn: asyncpg.Connection | None = None + self._event = asyncio.Event() + + async def start(self): + self._conn = await asyncpg.connect(_dsn()) + await self._conn.add_listener(self._channel, self._on_notify) + + def _on_notify(self, *_args): + self._event.set() + + async def wait(self, timeout: float) -> bool: + """알림이 오거나 timeout 까지 대기. 알림으로 깨면 True, 타임아웃이면 False.""" + try: + await asyncio.wait_for(self._event.wait(), timeout) + return True + except asyncio.TimeoutError: + return False + finally: + self._event.clear() + + async def close(self): + if self._conn is not None: + await self._conn.close() + self._conn = None diff --git a/backend/worker/runner.py b/backend/worker/runner.py new file mode 100644 index 0000000..0adf2e6 --- /dev/null +++ b/backend/worker/runner.py @@ -0,0 +1,125 @@ +"""워커 루프 + reaper. (LPS `worker/runner.py` 이식) + +워커는 큐에서 잡을 원자적으로 claim → 핸들러 실행 → complete/fail 한다. +- 처리 중 heartbeat 로 lease 를 갱신(긴 잡이 reaper 에 회수되지 않게). + 수집·비전분석은 몇 분이 정상이라 heartbeat 없이는 lease 가 먼저 만료된다. +- 핸들러엔 데드라인(job_deadline_sec)을 건다 — heartbeat 가 lease 를 계속 갱신하므로 + 핸들러가 행하면 reaper 로는 영원히 회수 불가. + 초과 시 취소 후 fail 처리 → 백오프 재큐(소진 시 DEAD), 워커 슬롯은 즉시 다음 잡으로. +- claim 이 비면 LISTEN 알림 또는 짧은 타임아웃까지 대기(폴링 최소화). +- 핸들러는 주입식(async def(job)->dict) — 프로덕션은 수집 파이프라인, 테스트는 fake. +""" + +import asyncio + +from common.enums import JobStatus +from common.logger import LOG +from crud.job_crud import JobQueue, compute_backoff + + +class Worker: + """큐에서 잡을 원자적으로 claim → 핸들러 실행 → complete/fail 하는 워커 루프.""" + + def __init__( + self, + worker_id: str, + queue: JobQueue, + handler, + lease_sec: int = 120, + backoff_fn=compute_backoff, + job_deadline_sec: float = 900.0, + ): + self.worker_id = worker_id + self.queue = queue + self.handler = handler + self.lease_sec = lease_sec + self.backoff_fn = backoff_fn + # 잡 1건 처리 시간 상한(0 이면 무제한 — 테스트용). + # 수집 파이프라인은 Perplexity(10~30s) + 크롤링 + Vision(사진 20~50장) 이라 15분을 기본으로 둔다. + self.job_deadline_sec = job_deadline_sec + + async def process_one(self) -> bool: + """대기 잡 1건을 claim·처리. 처리했으면 True, 없으면 False.""" + job = await self.queue.claim(self.worker_id, self.lease_sec) + if not job: + return False + await self._process(job) + return True + + async def drain(self) -> int: + """큐가 빌 때까지 처리(테스트/일회성 배치용). 처리한 잡 수 반환.""" + n = 0 + while await self.process_one(): + n += 1 + return n + + async def run(self, listener=None, stop: asyncio.Event | None = None, idle_timeout: float = 5.0): + """상시 루프. stop 이 설정될 때까지 처리하고, 유휴 시 알림/타임아웃까지 대기.""" + stop = stop or asyncio.Event() + while not stop.is_set(): + try: + worked = await self.process_one() + except Exception as ex: + # claim 자체가 실패(DB 순단 등) — 루프를 죽이지 않는다. 잠깐 쉬고 다시 시도. + LOG.e_no_callstack(f"[{self.worker_id}] claim 실패(계속): {type(ex).__name__}: {ex}") + worked = False + if not worked: + if listener is not None: + await listener.wait(idle_timeout) + else: + await asyncio.sleep(idle_timeout) + + async def _process(self, job: dict): + jid = job["job_id"] + hb = asyncio.create_task(self._heartbeat(jid)) + try: + if self.job_deadline_sec > 0: + result = await asyncio.wait_for(self.handler(job), timeout=self.job_deadline_sec) + else: + result = await self.handler(job) + await self.queue.complete(jid, self.worker_id, result) + LOG.d(f"[{self.worker_id}] done {jid}") + except (asyncio.TimeoutError, TimeoutError): + # 데드라인 초과 — wait_for 가 핸들러 태스크를 취소한 뒤 여기로 온다. + # 행이 워커 슬롯을 영구 점유하는 것보다 낫다. + backoff = self.backoff_fn(job["attempts"]) + st = await self.queue.fail(jid, self.worker_id, f"JobDeadlineExceeded: {self.job_deadline_sec:.0f}s", backoff) + LOG.w(f"[{self.worker_id}] deadline {jid} → {JobStatus(st).name if st else '?'} " + f"({self.job_deadline_sec:.0f}s 초과, 핸들러 취소)") + except Exception as ex: + backoff = self.backoff_fn(job["attempts"]) + st = await self.queue.fail(jid, self.worker_id, f"{type(ex).__name__}: {ex}", backoff) + LOG.w(f"[{self.worker_id}] fail {jid} → {JobStatus(st).name if st else '?'} ({type(ex).__name__}: {ex})") + finally: + hb.cancel() + try: + await hb + except asyncio.CancelledError: + pass + + async def _heartbeat(self, jid: str): + interval = max(1, self.lease_sec // 3) + while True: + await asyncio.sleep(interval) + try: + await self.queue.renew_lease(jid, self.worker_id, self.lease_sec) + except Exception as ex: + # 갱신 실패는 치명적이지 않다(다음 틱 재시도). 계속 실패하면 lease 만료 → reaper 회수. + LOG.w(f"[{self.worker_id}] lease 갱신 실패(계속): {type(ex).__name__}") + + +async def run_reaper(queue: JobQueue, stop: asyncio.Event, interval: float = 30.0): + """만료 lease(워커 사망) 잡을 주기적으로 회수. 재시도 남으면 재큐, 소진되면 DEAD. + + 도커에서 워커 컨테이너가 재시작되면 진행 중이던 잡이 여기서 되살아난다.""" + while not stop.is_set(): + try: + reclaimed = await queue.reap() + if reclaimed: + LOG.w(f"[reaper] reclaimed {len(reclaimed)} stale job(s)") + except Exception as ex: + LOG.e_no_callstack(f"[reaper] {type(ex).__name__}: {ex}") + try: + await asyncio.wait_for(stop.wait(), interval) + except asyncio.TimeoutError: + pass diff --git a/backend/worker_main.py b/backend/worker_main.py new file mode 100644 index 0000000..c1aa763 --- /dev/null +++ b/backend/worker_main.py @@ -0,0 +1,84 @@ +# o2o-web4ai 워커 프로세스 진입점 (API 와 분리 실행 — 코드베이스 공유, 독립 스케일). +# python worker_main.py +# WORKER_CONCURRENCY=3 python worker_main.py +# +# 수집·비전분석·빌드는 몇 분씩 걸려 동기 요청으로 처리할 수 없다. API 는 잡만 적재하고 즉시 응답하며, +# 실제 처리는 이 프로세스가 한다. 큐는 PostgreSQL(job.jobs) — 원자적 claim + lease 소유권이라 +# 워커를 몇 개 띄우든(docker compose --scale) 같은 잡이 두 번 돌지 않는다. + +import asyncio +import os +import signal + +from common.database.db_session_manager import DB_SESSION_MNG +from common.logger import LOG +from config.server_configs import web_server_config +from crud.job_crud import JobQueue +from worker.handlers import build_handler, log_registry +from worker.notify import JobListener +from worker.runner import Worker, run_reaper + +LOG.SetPrefix(f"{web_server_config.server_name}-worker") + +# 잡 1건 처리 시간 상한. Perplexity(10~30s) + 크롤링 + Vision(사진 20~50장 배치)을 감안한 값. +JOB_DEADLINE_SEC = float(os.environ.get("JOB_DEADLINE_SEC", "900")) +# lease 임대 시간. heartbeat 가 lease_sec/3 마다 갱신하므로 짧아도 되지만, +# 워커가 죽었을 때 이만큼 지나야 reaper 가 회수한다. +LEASE_SEC = int(os.environ.get("JOB_LEASE_SEC", "120")) + + +async def main(concurrency: int = 1): + queue = JobQueue() + handler = build_handler() + log_registry() + + stop = asyncio.Event() + listeners: list[JobListener] = [] + tasks: list[asyncio.Task] = [] + + # ── graceful shutdown: SIGINT(Ctrl+C)/SIGTERM(docker stop) → stop 이벤트 ── + # 하던 잡은 마무리하고 새 잡은 받지 않는다. 강제 종료돼도 lease 만료 후 reaper 가 재큐한다. + def _request_stop(sig_name: str): + if not stop.is_set(): + LOG.i(f"{sig_name} 수신 — graceful 종료: 새 잡 중단, 하던 잡 마무리 (한 번 더 = 강제 종료)") + stop.set() + else: + LOG.w(f"{sig_name} 재수신 — 강제 종료(실행 중 잡은 lease 만료 후 reaper 가 재큐)") + for t in tasks: + t.cancel() + + loop = asyncio.get_running_loop() + for sig in (signal.SIGINT, signal.SIGTERM): + loop.add_signal_handler(sig, _request_stop, sig.name) + + for i in range(concurrency): + listener = JobListener() + await listener.start() + listeners.append(listener) + worker = Worker(f"worker-{i}", queue, handler, lease_sec=LEASE_SEC, job_deadline_sec=JOB_DEADLINE_SEC) + tasks.append(asyncio.create_task(worker.run(listener, stop))) + + tasks.append(asyncio.create_task(run_reaper(queue, stop))) + LOG.i(f"워커 {concurrency}개 + reaper 기동 (lease {LEASE_SEC}s · 잡 데드라인 {JOB_DEADLINE_SEC:.0f}s)") + + gathered = asyncio.gather(*tasks) + try: + await gathered + except asyncio.CancelledError: + LOG.w("강제 종료 — 남은 리소스 정리 후 종료") + finally: + stop.set() + for t in tasks: + t.cancel() + await asyncio.gather(gathered, return_exceptions=True) + for listener in listeners: + try: + await listener.close() + except Exception as ex: + LOG.e_no_callstack(f"[shutdown] 리스너 정리 실패(무시): {ex}") + await DB_SESSION_MNG.dispose_all() + LOG.i("워커 종료 완료") + + +if __name__ == "__main__": + asyncio.run(main(int(os.environ.get("WORKER_CONCURRENCY", "1")))) diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..c157e88 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,256 @@ +# ★ 프로젝트 이름을 여기 못 박는다. 안 적으면 compose 가 **디렉터리 이름**을 프로젝트 이름으로 +# 쓰는데, 그러면 폴더를 옮기거나 이름을 바꾸는 순간 컨테이너와 볼륨이 통째로 새로 생긴다 +# (`o2o-site_site-out` → `o2o-web4ai_site-out`). 이름을 고정하면 폴더가 어디에 있든 같은 것을 본다. +name: o2o-web4ai + +# o2o-web4ai 백엔드 (API + 작업 큐 워커). +# +# DB 는 compose 에서 관리하지 않는다 — 컨테이너는 host.docker.internal 로 호스트의 PostgreSQL 에 붙는다 +# (로컬 dev 는 negosium-db 컨테이너가 5432 를 열어두고 있다). 접속값은 config.local.toml 을 +# compose 의 DB_* env 가 덮어쓴다. +# +# docker compose up -d +# API: http://localhost:9800/docs +# 워커: 포트 없음 — docker compose logs -f o2o-web4ai-worker 로 확인 +# +# DB 준비(최초 1회): +# docker exec -i -e PGPASSWORD=password negosium-db \ +# psql -h 127.0.0.1 -U postgres -d postgres -v ON_ERROR_STOP=1 < postgres-init/init-data/init.sql +# (기존 DB 보정은 postgres-init/alters/*.sql 을 날짜순으로 적용) +# +# 외부 API 키(PERPLEXITY/KAKAO/GEMINI/TOUR)는 레포 최상위 .env 에서 읽는다 — cp .env.example .env 후 채운다. +# ※ 컨테이너 안에서는 .env 파일을 직접 읽지 못한다(레포 루트가 이미지 밖). compose 의 env_file 이 +# 실제 환경변수로 주입하고, server_configs 의 env override 가 toml 값을 덮어쓴다. + +# API 와 워커가 공유하는 환경변수. 둘은 **같은 DB 를 본다** — 한쪽만 다른 DB 를 가리키면 +# API 가 넣은 잡을 워커가 영영 못 본다. 그래서 한 곳에서 정의하고 양쪽이 가져다 쓴다. +# +# ★ SCHEDULER_ENABLED 는 여기 두지 않는다. 서비스마다 값이 달라야 하는 유일한 항목이라 +# 공용 블록에 섞으면 실수로 워커에서도 크론이 도는 사고가 난다. +x-common-env: &common-env + APP_ENV: local + PYTHONUNBUFFERED: "1" # 컨테이너 로그 실시간 출력(stdout 버퍼링 끔) + # ── DB 접속 ── + # 이미지 안 config.local.toml 은 example 사본(플레이스홀더)이라 값이 비어 있다. + # 아래 DB_* 가 없으면 `` 로 접속을 시도하다 실패한다 — 반드시 주입해야 한다. + # 기본값은 로컬 dev(negosium-db 컨테이너, postgres/password). 배포는 .env 나 셸 env 로 덮는다. + DB_HOST: ${DB_HOST:-host.docker.internal} # 컨테이너→호스트 DB (toml 의 127.0.0.1 override) + DB_PORT: ${DB_PORT:-5432} + DB_USER: ${DB_USER:-postgres} + DB_PASSWORD: ${DB_PASSWORD:-password} + DB_NAME: ${DB_NAME:-o2o_site_db} + # ── JWT 서명 키 ── + # ★ DB 와 같은 이유로 반드시 주입해야 한다. 이미지의 config.local.toml 은 플레이스홀더라 + # 주입하지 않으면 "" 이라는 공개된 문자열이 서명 키가 된다(부팅 시 경고 로그). + # 운영 배포에서는 .env 나 배포 시크릿으로 반드시 채운다. 두 컨테이너가 같은 키를 봐야 한다. + JWT_ACCESS_SECRET: ${JWT_ACCESS_SECRET:-} + JWT_REFRESH_SECRET: ${JWT_REFRESH_SECRET:-} + # ── 발행 호스트 ── + # 커스텀 도메인이 없는 사이트의 공개 주소(`https://<이 값>/s/`). + # ★ API 와 워커가 **같은 값**을 봐야 한다. API 가 화면에 보여준 주소와 워커가 구운 + # canonical·사이트맵이 갈리면, 사장님 화면은 멀쩡한데 검색엔진만 엉뚱한 주소를 받는다. + SITE_PUBLIC_HOST: ${SITE_PUBLIC_HOST:-w4ai.o2o.kr} + # ── 발행 산출물 ── + # 빌드 잡이 발행마다 payload JSON 을 여기 떨어뜨린다. 호스트의 frontend/site/payloads 로 + # 바인드돼 있어서, o2o-web4ai-web 의 감시 프로세스가 **바뀐 payload 만** 골라 굽는다 — + # docker cp 로 옮기는 수동 단계가 없다. + # + # ★ 이 디렉토리는 양방향이다. 프리렌더가 사이트마다 결과를 + # `.status/.json` 에 써 주고, 백엔드가 그걸 읽어 렌더 상태를 사이트 조회 API 로 + # 내보낸다(services/render_report). 백엔드에 마운트된 유일한 디렉토리라 여기를 쓴다 — + # 이게 없으면 프리렌더가 깨져도 DB 는 "발행됨"이라 답하고 아무도 모른다. + SITE_PAYLOAD_DIR: /app/out/payloads + SITE_OUTPUT_DIR: /app/out/sites + # ── 색인 통보 ── + # 발행 즉시 네이버·Bing 에 알린다(구글은 IndexNow 를 지원하지 않는다 — Search Console 사이트맵 제출이 따로다). + # ★ 프리렌더(o2o-web4ai-web)와 백엔드가 **같은 값**을 봐야 한다. 프리렌더는 이 키로 루트에 + # `.txt` 를 굽고, 검색엔진은 통보를 받으면 그 파일을 열어 대조한다. 어긋나면 403 이다. + INDEXNOW_KEY: ${INDEXNOW_KEY:-} + +services: + # ── API 서버 ──────────────────────────────────────────────────────────── + # 요청 접수/조회만 한다. 수집·비전분석·빌드는 잡으로 큐에 넣고 즉시 응답하며, + # 클라이언트는 GET /v1/job/{id} 를 폴링한다. + api: + build: + context: ./backend + dockerfile: Dockerfile + image: o2o-web4ai-backend # 워커와 공유하는 이미지 태그(한 번만 빌드된다) + container_name: o2o-web4ai-api + command: ["python", "web_main.py"] + env_file: + - .env # 외부 API 키. 없으면 cp .env.example .env + environment: + <<: *common-env + # ★ APScheduler 크론(지역정보 갱신 등)은 **이 컨테이너에서만** 돈다. + # 크론은 '시각'으로 발화하므로 프로세스가 여럿이면 같은 시각에 중복 실행된다 — + # 그래서 단일 컨테이너로 고정한다. 아래 워커의 잡 큐와는 성격이 다르다: + # 잡 큐는 DB 가 원자적으로 한 명에게만 배분(FOR UPDATE SKIP LOCKED)하므로 몇 개를 띄워도 안전하다. + SCHEDULER_ENABLED: "1" + volumes: + # ★ 컨테이너 안에만 두면 컨테이너를 지울 때 발행 산출물이 같이 사라진다. + # SSG 를 돌리는 쪽(호스트의 frontend/site)이 직접 읽어야 하므로 밖으로 뺀다. + - ./frontend/site/payloads:/app/out/payloads + ports: + - "${API_BIND:-0.0.0.0}:9800:9800" # prod 는 API_BIND=127.0.0.1 로 내부만 개방(리버스프록시 뒤) + extra_hosts: + - "host.docker.internal:host-gateway" + restart: unless-stopped + logging: + driver: json-file + options: { max-size: "10m", max-file: "5" } + + # ── 작업 큐 워커 ──────────────────────────────────────────────────────── + # 수집 파이프라인 · 사진 비전 분석 · 사이트 빌드를 처리한다. 한 건에 3~10분 걸리므로 + # API 요청 안에서 처리하지 않는다. + # + # ★ 스케일 안전: docker compose up -d --scale o2o-web4ai-worker=3 + # 큐가 `UPDATE ... WHERE job_id = (SELECT ... FOR UPDATE SKIP LOCKED LIMIT 1) RETURNING` 단일 문장으로 + # 할당하므로 워커가 몇 개든 같은 잡이 두 번 돌지 않는다. 컨테이너가 죽어도 lease(JOB_LEASE_SEC)가 + # 만료되면 reaper 가 회수해 재큐한다 — 잡이 증발하지 않는다. + # (스케일하려면 container_name 을 두면 안 된다 — 이름이 충돌한다. 그래서 여기엔 없다. + # 프로젝트 이름이 붙어 o2o-web4ai-worker-1 로 뜬다.) + worker: + build: + context: ./backend + dockerfile: Dockerfile + image: o2o-web4ai-backend # api 와 동일 이미지 — 두 번 빌드되지 않는다 + command: ["python", "worker_main.py"] + env_file: + - .env + environment: + <<: *common-env + SCHEDULER_ENABLED: "0" # 크론은 API 컨테이너 담당. 워커는 잡 큐만 돈다 + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-1} # 한 프로세스가 동시에 처리할 잡 수 + JOB_DEADLINE_SEC: ${JOB_DEADLINE_SEC:-900} # 잡 1건 처리 상한. Perplexity(10~30s)+크롤링+Vision(사진 20~50장) 감안 + JOB_LEASE_SEC: ${JOB_LEASE_SEC:-120} # 소유권 임대. heartbeat 가 1/3 주기로 갱신, 워커 사망 시 이만큼 뒤 회수 + # ★ 이미지의 HEALTHCHECK 는 API 용(HTTP :9800)이다. 워커는 포트가 없어서 그대로 두면 + # 멀쩡히 잡을 돌면서도 계속 unhealthy 로 뜬다 — 진짜 고장과 구분이 안 되므로 끈다. + # (Dockerfile 주석의 "워커는 이 헬스체크를 쓰지 않는다"를 compose 에서 실제로 반영하는 자리.) + # 워커용 하트비트 기반 체크는 필요해질 때 추가한다. + healthcheck: + disable: true + volumes: + # ★ 컨테이너 안에만 두면 컨테이너를 지울 때 발행 산출물이 같이 사라진다. + # SSG 를 돌리는 쪽(호스트의 frontend/site)이 직접 읽어야 하므로 밖으로 뺀다. + - ./frontend/site/payloads:/app/out/payloads + # 발행 검수 통과 후 워커가 이 산출물을 Azure Blob에 업로드한다. + - site-out:/app/out/sites:ro + extra_hosts: + - "host.docker.internal:host-gateway" + # graceful 종료: SIGTERM → 새 잡 claim 중단 → 하던 잡 마무리 → 종료. + # 이 시간을 넘기면 Docker 가 SIGKILL 하지만, 그래도 안전하다 — lease 가 만료되면 + # reaper 가 그 잡을 재큐한다(작업이 유실되지 않고 다음 워커가 이어받는다). + # 값은 '배포 속도 vs 하던 일 마무리' 트레이드오프다. JOB_DEADLINE_SEC(900)까지 올리면 + # 어떤 잡이든 끝까지 기다리지만 docker compose down 이 최대 15분 매달린다. + stop_grace_period: 300s + depends_on: + - api # 이미지 빌드/기동 순서만 맞춘다(런타임 의존은 DB 뿐) + restart: unless-stopped + logging: + driver: json-file + options: { max-size: "10m", max-file: "5" } + + # ── 발행 사이트 빌더 + 정적 서버 ──────────────────────────────────────── + # 발행 잡이 payload JSON 을 떨어뜨리면(SITE_PAYLOAD_DIR) 이 컨테이너가 그걸 보고 + # 정적 HTML 을 굽고, 같은 결과물을 그대로 서빙한다. + # + # ★ 왜 백엔드가 직접 굽지 않나: 굽는 데 Node 와 프론트 의존성이 필요하다. 파이썬 이미지에 + # 그걸 넣으면 백엔드가 프론트 빌드 도구를 떠안는다. payload 디렉토리를 사이에 두고 + # 백엔드는 파일만 쓰고, 여기는 파일만 읽는다 — 두 쪽이 서로를 모른다. + web: + image: node:24-alpine + container_name: o2o-web4ai-web + working_dir: /app/frontend/site + # 의존성이 없으면 설치부터 한다(최초 1회). 그 뒤 감시와 서버를 동시에 띄운다. + # ★ `&` 는 그 앞의 명령 전체를 배경으로 돌린다 — 앞에 붙인 `cd` 까지 함께 묶여 나가서 + # 뒤 명령이 엉뚱한 디렉토리에서 돈다(실측: /app/frontend 에서 스크립트를 찾다 실패). + # 그래서 cd 를 먼저 끝내고, 배경으로 보내는 것은 서버 하나뿐이다. + command: + - sh + - -c + - | + cd /app/frontend + # ★ `-d node_modules` 로 판단하면 안 된다. 익명 볼륨은 **빈 디렉토리로 이미 존재**해서 + # 설치를 건너뛰고 `vite: not found`(exit 127)로 죽는다. 실행 파일이 있는지를 본다. + [ -x node_modules/.bin/vite ] || npm install + # 외부 진입점은 admin Vite(:3000) 하나다. `/s/*`만 같은 컨테이너의 + # 정적 서버(:3001)로 프록시하고, payload 감시는 백그라운드에서 계속 돈다. + node site/scripts/serve-sites.mjs & + # 감시 프로세스가 기동 때 번들을 한 번 만들고, 그 뒤로는 바뀐 payload 만 굽는다. + # (예전에는 발행 한 건마다 vite 번들 + 전체 사이트를 다시 구웠다 — 사이트가 늘면 못 쓴다.) + node site/scripts/watch-payloads.mjs & + exec npm run dev -w admin + environment: + PORT: 3001 + # 프리렌더가 루트에 `.txt` 를 굽는다. 백엔드와 같은 값이어야 한다. + INDEXNOW_KEY: ${INDEXNOW_KEY:-} + volumes: + # 소스와 산출물을 통째로 마운트한다 — 발행 payload 가 호스트에 그대로 보여야 + # 개발 중 무슨 일이 일어났는지 파일로 확인할 수 있다. + - ./frontend:/app/frontend + # ★ node_modules 만은 컨테이너 것을 쓴다(익명 볼륨으로 마운트를 덮는다). + # 호스트가 macOS(arm64-darwin)라 그 안의 rollup·esbuild 네이티브 바이너리는 + # 리눅스 컨테이너에서 못 쓴다 — 실측: `Cannot find module '@rollup/rollup-linux-arm64-musl'` + # 로 프리렌더가 통째로 실패했고, 발행해도 사이트가 안 구워졌다. + - /app/frontend/node_modules + - /app/frontend/site/node_modules + - /app/frontend/admin/node_modules + # ★ 산출물만 named volume 으로 뺀다(./frontend 마운트 위에 덮인다). + # 호스트 경로에 두면 재배포로 코드를 갈아엎는 순간 out/ 이 비어 전 사이트가 404 다. + # nginx 가 같은 볼륨을 읽는다. + - site-out:/app/frontend/site/out + ports: + # admin(:3000)이 공개 진입점. `/s/*`는 Vite proxy가 내부 :3001로 전달한다. + - "3000:3000" + restart: unless-stopped + logging: + driver: json-file + options: { max-size: "10m", max-file: "5" } + + # ── 발행 사이트 정적 서빙 ─────────────────────────────────────────────── + # + # ★ 굽는 쪽(o2o-web4ai-web)과 서빙하는 쪽을 분리한다. 프리렌더는 파일만 쓰고 여기는 파일만 + # 읽는다 — 볼륨 하나를 사이에 두고 서로를 모른다. + # + # ★ Azure Blob 으로 프록시하지 않는다. 파일이 이미 이 볼륨에 있는데 클라우드로 보냈다가 + # 되받아 오면 요청마다 왕복이 하나 더 붙고, Blob 은 커스텀 도메인 TLS 도 못 붙인다. + # Blob 업로드(azure_static)는 배달 백업으로 남겨 둔다. + nginx: + image: nginx:alpine + container_name: o2o-web4ai-nginx + volumes: + - site-out:/srv/sites:ro + - ./nginx/site.conf:/etc/nginx/conf.d/default.conf:ro + ports: + - "80:80" + # TLS 를 붙이면 여기에 443 과 인증서 볼륨을 추가한다(certbot 또는 발급받은 인증서). + # - "443:443" + depends_on: + - web + restart: unless-stopped + logging: + driver: json-file + options: { max-size: "10m", max-file: "5" } + + # ── (예정) 크롤링 전용 워커 ────────────────────────────────────────────── + # Phase 1 은 collector 가 MockAdapter 만 등록하므로 브라우저가 필요 없다. + # 크롤링 법무 검토(docs/DECISIONS.md 1-1)가 끝나 HeadlessAdapter 를 붙이면 여기에 서비스를 하나 더 만든다. + # 선례는 o2o-negosium 의 lps-worker — 그대로 따라가면 된다: + # + # o2o-web4ai-crawler: + # build: { context: ./backend, dockerfile: Dockerfile.worker } # Chrome + Xvfb + 한글폰트 (~1.5GB) + # platform: linux/amd64 # google-chrome-stable(Linux)은 amd64 전용. arm64 맥에선 명시 없으면 빌드 실패 + # shm_size: "1gb" # Chrome 는 /dev/shm 을 많이 씀 — 부족하면 탭 크래시 + # environment: { DISPLAY: ":99" } + # + # API 이미지(~200MB)에 Chrome 을 넣으면 배포마다 1.5GB 를 밀게 되므로 반드시 이미지를 갈라야 한다. + +# ── 볼륨 ────────────────────────────────────────────────────────────────── +volumes: + # 발행 산출물. 프리렌더가 쓰고, 워커(색인 통보·Azure 업로드)와 nginx 가 읽는다. + # + # ★ `docker compose down` 으로는 지워지지 않는다. `down -v` 만 지운다. + # ★ 재생성물이라 백업 대상이 아니다 — 날아가도 payload 로 다시 굽는다(DEPLOY.md 1절). + # 지켜야 할 것은 DB 와 out/payloads 뿐이고, 그 둘은 여전히 호스트에 bind mount 다. + site-out: diff --git a/docs/API_USAGE.md b/docs/API_USAGE.md new file mode 100644 index 0000000..ccf1e3c --- /dev/null +++ b/docs/API_USAGE.md @@ -0,0 +1,210 @@ +# API 사용 이력 · 비용 기록 + +**집계 시각: 2026-08-27 08:59 KST** +집계 대상: o2o-web4ai 프로젝트 전체 (backend · frontend/admin · frontend/site) + +--- + +## 0. 먼저 — 섞으면 안 되는 두 가지 비용 + +| | 무엇 | 언제 나가나 | 현재 | +|---|---|---|---| +| **A. 제품 원가** | 사이트 **1건 만들 때** 나가는 외부 API 비용 (Perplexity·Kakao·Gemini) | 업소 1곳 처리할 때마다 **반복** | **0원** (아직 한 번도 호출 안 함) | +| **B. 개발비** | 이 코드를 **짜는 데** 쓴 Claude API 비용 | 개발 기간 동안 **한 번** | $70.07 | + +**A 의 상한은 $1(1,400원)이다.** B 는 사이트를 만들 때마다 나가는 돈이 아니다 — 코드가 완성되면 끝나는 일회성 지출이다. 이 문서의 2절은 전부 **B** 얘기다. + +--- + +## 0-1. 한 줄 요약 + +| 구분 | 실제 호출 | 비용 | +|---|---|---| +| **외부 유료 API** (Perplexity · Kakao · Gemini · TourAPI) | **0건** | **0원** | +| **개발 도구 API** (Claude Code / Anthropic Messages API) | 348 요청 | **$70.07** (≈ 98,100원, 1,400원/USD 가정) | + +지금까지 나간 돈은 **전부 개발 과정의 Claude API 요금**이고, 제품이 쓸 외부 API는 아직 **한 번도 실제로 때리지 않았다.** + +--- + +## 1. [A] 제품 원가 — 외부 API 계약 현황과 실호출 이력 + +### 1-1. 키 상태 + +| API | 용도 | 키 설정 | 어댑터 | 실호출 | +|---|---|---|---|---| +| Perplexity Sonar (`api.perplexity.ai`) | 채널 URL 발견 | ✅ 설정됨 | `backend/services/external/perplexity.py` 구현 완료 | **0건** | +| Kakao Local (`dapi.kakao.com`) | 동일 업소 검증 · 주변 정보 | ⬜ 비어 있음 | 미구현 (설계만) | **0건** | +| Gemini (Google AI Studio) | 사진 분류 · 카피 작성 | ✅ 설정됨 | 미구현 | **0건** | +| TourAPI (`data.go.kr`) | 축제 · 관광지 | ⬜ 비어 있음 | 미구현 | **0건** | +| Open-Meteo | 날씨 | 키 불필요 | `frontend/.../useWeather.ts` | **0건** (프론트 코드만 작성) | + +> `.env` 의 키가 비어 있으면 해당 어댑터만 비활성되고 서버는 그대로 뜬다 — 설계상 의도된 동작. + +### 1-2. 실호출이 0건인 근거 + +1. **코드 레벨** — 전체 세션 트랜스크립트에서 위 호스트로 나간 HTTP 요청이 없다. 등장하는 건 전부 소스 작성·문서 편집 텍스트다. +2. **테스트 레벨** — `backend/tests/` 안에서 실제 네트워크를 타는 코드가 없다. `test_perplexity.py` · `test_collector.py` 는 전부 목(mock) 기반이고, `httpx.get/post` 직접 호출은 0건. +3. **설정 레벨** — `DECISIONS.md` 의 결정대로 **`APP_ENV=test` 면 `.env` 를 읽지 않는다.** 실키가 테스트로 새어 외부 API 요금이 나가는 경로 자체를 막아 뒀다. +4. **DB 레벨** — 어떤 테이블에도 외부 API 응답이 적재된 흔적이 없다 (호출 로그 테이블도 아직 없다 — 3-2 참고). + +### 1-3. 단가표 (호출 시작 시 적용될 요금) + +| API | 과금 방식 | 단가 | +|---|---|---| +| Perplexity Sonar | **토큰 요금 + 검색 호출 요금이 별도로 붙는다** | `sonar` 기본, `sonar-pro` 는 더 비쌈. 호출당 검색 횟수는 이미 로그로 남기고 있음 (`perplexity.py` 의 `usage.num_search_queries`) | +| Kakao Local | 무료 쿼터 초과분 종량 | 키워드/카테고리 검색 **2원**, 좌표 변환 **0.5원** (키워드가 4배 비싸다) | +| Gemini | 토큰 종량 (Google AI Studio) | 모델·티어별 | +| TourAPI | 공공데이터 무료 (일 트래픽 제한) | 0원 | +| Open-Meteo | 무료 | 0원 | + +> ⚠️ **Kakao 무료 쿼터 함정** — 무료 쿼터는 개발자 계정의 "첫 번째 활성 앱" 에만 붙는다. dev/stage/prod 앱을 따로 파면 **하나만 무료**다. 앱을 나누기 전에 확인할 것. + +--- + +## 2. [B] 개발비 — Claude (Anthropic Messages API) + +> 사이트 1건당 원가가 **아니다.** 코드를 짜는 데 든 일회성 비용이다. + +### 2-1. 총계 + +| 항목 | 값 | +|---|---| +| 기간 | 2026-08-26 16:23 ~ 2026-08-27 08:58 KST (약 16.6시간) | +| 모델 | `claude-opus-5` (1M 컨텍스트) 단일 | +| 과금 요청 수 | **348건** (메시지 ID 기준 중복 제거) | +| 출력 토큰 | 450,509 | +| 캐시 쓰기 (1h TTL) | 2,020,375 | +| 캐시 쓰기 (5m TTL) | 96,213 | +| 캐시 읽기 | 76,004,125 | +| 캐시 미적용 입력 | 690 | +| 입력 환산 합계 | 78,121,403 | +| **총 비용** | **$70.07** | + +### 2-2. 비용 내역 + +| 항목 | 토큰 | 요율 ($/MTok) | 금액 | +|---|---|---|---| +| 캐시 읽기 (기본 입력가 ×0.1) | 76,004,125 | $0.50 | **$38.00** | +| 캐시 쓰기 1h (기본 입력가 ×2) | 2,020,375 | $10.00 | **$20.20** | +| 출력 | 450,509 | $25.00 | **$11.26** | +| 캐시 쓰기 5m (기본 입력가 ×1.25) | 96,213 | $6.25 | **$0.60** | +| 캐시 미적용 입력 | 690 | $5.00 | $0.003 | +| | | **합계** | **$70.07** | + +> 각 항목은 센트 단위 반올림이라, 눈으로 더하면 합계와 1센트 차이가 날 수 있다. + +**캐시 효과** — 프롬프트 캐싱이 없었다면 같은 작업이 **$401.87** 이었다. 즉 **$331.80 (82.6%) 를 캐시로 아꼈다.** +동시에, 비용의 **54%($38.00)가 캐시 *읽기*** 다. 출력 토큰 값($11.26)의 3배가 넘는다 — 긴 컨텍스트를 반복해서 다시 읽는 패턴이 이 프로젝트 비용 구조를 지배한다는 뜻이다. 줄이려면 출력을 줄이는 게 아니라 **컨텍스트를 작게 유지**해야 한다. + +### 2-3. 세션별 내역 + +| 세션 | 종류 | 시각 (KST) | 요청 | 출력 토큰 | 캐시 읽기 | 비용 | +|---|---|---|---|---|---|---| +| `4db7aca5` | 메인 (backend 주력) | 08-26 16:23 ~ 08-27 08:55 | 157 | 266,385 | 35,748,750 | **$32.65** | +| `99be2a6c` | 메인 | 08-26 17:24 ~ 08-27 08:58 | 92 | 124,641 | 16,660,246 | **$19.79** | +| `19be092e` | 메인 (frontend/admin) | 08-27 08:42 ~ 08:58 | 29 | 25,903 | 2,476,298 | $3.37 | +| `agent-a58…` | 서브에이전트 | 08-27 08:51 ~ 08:57 | 13 | 6,173 | 5,741,359 | $3.21 | +| `agent-afa…` | 서브에이전트 | 08-27 08:52 ~ 08:55 | 14 | 423 | 6,132,381 | $3.21 | +| `6052d29a` | 메인 (이 기록 작성 세션) | 08-27 08:52 ~ 08:58 | 21 | 23,936 | 1,678,581 | $2.92 | +| `agent-aa5…` | 서브에이전트 | 08-27 08:52 ~ 08:58 | 9 | 68 | 3,905,434 | $2.07 | +| `agent-ab1…` | 서브에이전트 | 08-27 08:52 ~ 08:57 | 8 | 165 | 3,466,831 | $1.90 | +| `d56c8333` | 메인 | 08-27 08:52 ~ 08:53 | 5 | 2,815 | 194,245 | $0.95 | +| `2ac02dde` | 메인 (중복 세션) | — | 0 | 0 | 0 | $0.00 | + +**읽을 거리 두 가지:** + +- **서브에이전트 4개 합계 $10.39** — Perplexity/Kakao 클라이언트를 병렬로 짠 fork 들이다. 출력 토큰은 다 합쳐 6,829개뿐인데 캐시 읽기가 **1,925만 토큰**이다. **fork 는 부모 컨텍스트를 통째로 들고 시작하기 때문에**, 실제 작업이 짧아도 부모 컨텍스트가 크면 읽기 요금이 그만큼 붙는다. 병렬 fork 를 쓸지 말지는 "일이 병렬인가" 보다 **"부모 컨텍스트가 큰가"** 로 판단하는 편이 비용상 맞다. +- **`2ac02dde` 는 `99be2a6c` 로 이어진 세션(fork/resume)이라 메시지가 전부 중복** — 0원으로 처리했다. 세션 간 중복을 제거하지 않으면 408건 / **$79.16** 이 나와 **$9.09 과대집계**된다. 재집계할 때 메시지 ID 중복 제거를 반드시 넣을 것. + +### 2-4. 이 숫자를 읽을 때 주의할 점 + +- **구독제(Max/Pro)로 쓰고 있다면 이 금액이 그대로 청구되지는 않는다.** 토큰 사용량을 공개 API 요율로 환산한 "이만큼 썼다" 값이다. 종량제 API 키로 같은 작업을 돌렸다면 나왔을 금액. +- 요율 기준: Opus 5 입력 $5 / 출력 $25 per MTok, 캐시 읽기 ×0.1, 캐시 쓰기 5m ×1.25 · 1h ×2. +- 1M 컨텍스트 구간에 별도 프리미엄이 붙는 경우 실제 금액은 이보다 높을 수 있다 — **하한선으로 읽을 것.** +- 원화 환산은 1,400원/USD 가정이다. 실제 청구 환율과 다를 수 있다. +- **이 스냅샷은 찍는 순간에도 움직인다.** 집계 시각 기준으로 `4db7aca5`·`99be2a6c`·`19be092e`·`6052d29a` 등 여러 세션이 동시에 살아 있었다. 4절의 스크립트로 언제든 다시 뽑을 것. + +--- + +## 3. 앞으로 할 일 + +### 3-1. 비용이 실제로 발생하기 시작하는 지점 + +수집 파이프라인이 도는 순간부터다: + +``` +상호명 → [Perplexity: 채널 URL 발견] ← 토큰 + 검색 호출 과금 + → [Kakao Local: 동일 업소 검증] ← 건당 2원 + → 크롤링(무료) + → [Gemini: 사진 분류 + 카피] ← 토큰 과금 +``` + +업소 1건당 Perplexity 1~2회 + Kakao 여러 건 + Gemini(사진 수만큼)가 붙는다. **업소당 원가를 먼저 실측한 뒤 배치를 키우는 순서**가 안전하다. + +### 3-2. 사이트 1건당 예산: **$1 (1,400원)** — 코드로 강제한다 + +제품 제약이 정해졌다: **업소 1곳의 사이트를 만드는 외부 API 비용은 $1 을 넘으면 안 된다.** + +문서에만 적으면 지켜지지 않으므로 가드를 구현했다 — `backend/common/cost.py` (`CostMeter`), 테스트 `backend/tests/test_cost.py` 8건. + +```python +meter = CostMeter(place_id=42) +meter.guard(Provider.PERPLEXITY, searches=2, tokens=3000) # 호출 "전" 에 확인 → 넘으면 BudgetExceeded +...실제 호출... +meter.charge(Provider.PERPLEXITY, searches=2, tokens=3100) # 호출 "후" 에 실측 기록 +``` + +- `guard()` 가 막으면 **그 호출을 하지 않는다.** 이미 쓴 돈은 못 돌려받지만 손실이 선형으로 늘어나는 걸 끊는다. +- 예산 70% 소진 시 경고 로그, 100% 초과 시 예외. +- 미터 1개 = 사이트 1건. + +**⚠️ 단가표에 아직 추정치가 섞여 있다.** 확정된 건 카카오뿐이다(레포에 2원/0.5원이 적혀 있다). Perplexity·Gemini 는 공식 단가표를 확인해서 `RATES` 를 교체해야 한다. 그때까지 `assert_rates_confirmed()` 가 실배치를 막는다 — 추정치 위에 "예산 안에 들어온다" 는 결론을 세우지 않기 위해서다. + +### 3-3. 지금 없는 것 — 호출 로그 테이블 + +현재 DB 스키마(`backend/common/database/model/models.py`)에 **API 호출·비용을 적재하는 테이블이 없다.** 지금은 애플리케이션 로그로만 남는다 (`perplexity.py` 가 `tokens=` 와 검색 횟수를 찍는 정도). + +파이프라인을 돌리기 전에 `api_call_logs` 같은 테이블(공급자 · 엔드포인트 · 토큰/호출수 · 추정단가 · place_id · 시각)을 얹어두면, 이 문서를 손으로 갱신하지 않고 쿼리로 뽑을 수 있다. + +--- + +## 4. 재집계 방법 + +Claude 사용액은 아래로 다시 뽑는다 (세션 트랜스크립트 기준, 메시지 ID로 중복 제거): + +```bash +cd ~/.claude/projects && python3 - <<'PY' +import json,glob,collections,os +files=sorted(glob.glob("-Users-minachoi-projects-o2o-web4ai*/*.jsonl") + + glob.glob("-Users-minachoi-projects-o2o-web4ai*/*/subagents/*.jsonl"), + key=lambda p:-os.path.getsize(p)) +IN,OUT,CR,W5,W1H = 5.0/1e6, 25.0/1e6, 0.50/1e6, 6.25/1e6, 10.0/1e6 # Opus 5 요율 +seen=set(); t=collections.Counter() +for f in files: + for line in open(f,encoding="utf-8",errors="replace"): + try: o=json.loads(line) + except: continue + m=o.get("message") or {}; u=m.get("usage") + if not u: continue + rid=m.get("id") + if rid: + if rid in seen: continue # ★ fork/resume 중복 제거 — 빠뜨리면 과대집계 + seen.add(rid) + cc=u.get("cache_creation") or {} + w5=cc.get("ephemeral_5m_input_tokens",0); w1=cc.get("ephemeral_1h_input_tokens",0) + if w5+w1==0: w5=u.get("cache_creation_input_tokens",0) + t["in"]+=u.get("input_tokens",0); t["out"]+=u.get("output_tokens",0) + t["w5"]+=w5; t["w1h"]+=w1; t["cr"]+=u.get("cache_read_input_tokens",0); t["n"]+=1 +cost=t["in"]*IN+t["out"]*OUT+t["w5"]*W5+t["w1h"]*W1H+t["cr"]*CR +print(dict(t)); print(f"요청 {t['n']}건 / ${cost:.2f}") +PY +``` + +외부 API 실호출 여부 확인: + +```bash +cd ~/.claude/projects && grep -c "api.perplexity.ai\|generativelanguage.googleapis.com\|dapi.kakao.com" \ + -- -Users-minachoi-projects-o2o-web4ai*/*.jsonl +# 매칭이 있어도 대부분 소스 작성 텍스트다 — tool_use 의 command/url 필드인지 확인할 것 +``` diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..ccdcbbd --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,218 @@ +# ARCHITECTURE + +제품 판단은 [PRODUCT.md](PRODUCT.md), 배포 절차는 [DEPLOY.md](DEPLOY.md), +에이전트가 밟기 쉬운 함정 목록은 [AGENTS.md](../AGENTS.md). 여기는 **구조와 경계**만 다룬다. + +--- + +## 1. 핵심 경계 하나 — payload + +**백엔드는 HTML 을 만들지 않는다.** payload JSON 을 디렉토리에 떨어뜨리고, Node 프리렌더가 +그걸 읽어 정적 사이트를 굽는다. 두 쪽은 서로를 import 하지 않고 **디렉토리 하나로만 만난다.** + +``` +backend (Python) ──쓴다──▶ out/payloads/.json ◀──읽는다── prerender (Node) + out/payloads/.status/.json ──보고──▶ +``` + +이 경계가 있어서 렌더링을 통째로 갈아엎어도 백엔드는 안 건드린다. 반대도 같다. +**둘을 직접 붙이자는 제안은 이 문서를 근거로 거절한다** — 붙이는 순간 파이썬 프로세스가 +React 를 렌더해야 하고, 그때부터 디자인 수정에 백엔드 배포가 필요해진다. + +계약의 타입은 `frontend/shared/src/types/site-payload.ts` 하나다. + +## 2. 발행 파이프라인 + +``` +BUILD 잡 (worker) ─ services/build_service.py:99 run_build() + ├ build_snapshot → site_versions 행 insert (원본 데이터, JSONB) + ├ 1차 게이트 (DB 사실 기준) → publish_gate.evaluate() + ├ site_payload.emit_payload() → out/payloads/.json ★ 백엔드의 유일한 산출물 + │ + │ ┌ [별도 컨테이너 o2o-web4ai-web] + │ │ scripts/watch-payloads.mjs — payloads/ 2초 폴링, 바뀐 것만 + │ │ └ node dist/prerender/prerender.js --payload= + │ │ → out/s//** + out/assets, out/fonts, out/robots.txt … + │ │ → out/payloads/.status/.json (렌더 결과 보고서) + │ └ ★ 기동 시에는 payload 전체를 다시 굽는다 (watch-payloads.mjs:225) + │ + ├ render_report.wait_for() → .status/.json 폴링 + ├ 2차 게이트 (**실제 구워진 HTML** 기준: JSON-LD 불일치 · 고유 콘텐츠 수) + ├ azure_static.publish(slug) → Azure Blob `$web` (설정됐을 때만 — 3절) + └ indexnow.submit(slug) → 네이버·Bing·Yandex 통보 (구글 미지원) +``` + +게이트가 **두 번** 도는 게 핵심이다. 1차는 DB 의 사실을, 2차는 **정말로 그렇게 구워졌는지**를 본다. +1차만 있으면 "데이터는 맞는데 HTML 은 틀린" 상태를 발행한다. + +## 3. 서빙 — 테스트 서버가 정적 파일을 직접 서빙한다 + +**결정 (2026-08-31).** 발행 사이트는 **서버 안에서 nginx 가 정적 파일로 서빙한다.** +Azure Blob 업로드 경로(`azure_static.py`)는 코드에 있고 동작하지만 **지금은 켜지 않는다** — +`AZURE_STORAGE_CONNECTION_STRING` 을 비워 두면 발행 잡이 업로드 단계를 건너뛴다. +클라우드는 고도화 시점에 붙인다. + +``` +프리렌더(o2o-web4ai-web) ──쓴다──▶ named volume `site-out` ◀──읽는다(ro)── nginx(:80) +``` + +굽는 쪽과 서빙하는 쪽이 **볼륨 하나를 사이에 두고 서로를 모른다.** 그래서 재배포로 코드를 +갈아엎어도 사이트가 죽지 않는다 (호스트 경로가 등장하지 않는다). + +| | 지금 | 고도화 때 | +|---|---|---| +| 굽기 | 서버 로컬 `out/` (named volume) | 같음 — 프리렌더는 파일시스템에서 돈다 | +| 서빙 | **nginx `:80` → `/srv/sites`** (`nginx/site.conf`) | Blob `$web` + CDN, 또는 그대로 유지 | +| 켜는 법 | `AZURE_STORAGE_CONNECTION_STRING` **비움** | 채우면 발행 잡이 자동 업로드 | + +**왜 이 순서인가** + +1. **트래픽 비용이 판단 근거가 아니다.** 사이트 1,000개 × 월 100뷰 ≈ 월 24GB — + Azure 무료 egress 한도 안이다. 어느 쪽을 골라도 돈이 안 갈린다 ([DEPLOY.md 1절](DEPLOY.md) 실측). + 비용으로 못 가르면 **운영 편의**로 가르고, 지금 편한 쪽은 서버다. +2. **서버 디스크는 어차피 필요하다.** 프리렌더가 파일시스템에서 도니 `out/` 은 클라우드를 + 쓰든 안 쓰든 존재한다. 즉 지금 안 켜는 건 **빼는 게 아니라 미루는 것**이라 되돌리기 쉽다. +3. **켜는 게 환경변수 하나다.** 코드 변경 없이 위 표의 오른쪽으로 간다. 미리 할 이유가 없다. +4. **Blob 으로 프록시하지는 않는다.** 파일이 이미 이 볼륨에 있는데 클라우드로 보냈다 되받으면 + 요청마다 왕복이 하나 더 붙고, Blob 단독으로는 커스텀 도메인 TLS 도 못 붙인다. + Azure 는 **배달 백업**으로 남겨 둔다. + +⚠️ **정적 서빙에서 지켜야 할 규칙은 하나다: 디렉토리 요청 → `index.html`.** +`/s/` 를 **끝 슬래시 없이** 쳐도 열려야 한다 — 사장님이 주소창에 치는 형태가 그거다. +`python -m http.server` 는 이걸 404 로 준다. 그래서 개발용 `serve-sites.mjs` 가 따로 있고, +nginx 는 `try_files $uri $uri/index.html =404` 로 같은 규칙을 맞춘다 +(`$uri/` 를 거치면 301 이 붙어 크롤러가 리다이렉트를 한 번 더 탄다 — 그래서 `$uri/` 를 안 쓴다). + +⚠️ **클라우드를 안 켠 대가**: 발행 사이트의 가용성이 이 서버 하나에 묶인다. 서버가 죽으면 +**전 사이트가 동시에 내려간다.** 지금은 테스트 단계라 감수하는 리스크이고, +**실사용 고객이 붙는 시점**이 위 표의 오른쪽으로 넘어가는 트리거다. + +## 4. 앱 경계 — 지금 구조와 나눌 지점 + +### 지금 + +``` +frontend/ + admin/ Vite CSR SPA ── /builder 사장님 위저드·에디터 (로그인 안 걸림) + │ └ /places, /places/:id/seo, /local-content + │ 내부 운영 화면 (RequireAuth) + site/ SSR 엔트리 + 프리렌더 → 정적 HTML 발행 사이트 + shared/ 타입·slug·디자인 토큰 (npm workspace) +``` + +**`admin/` 이 성격이 반대인 두 앱을 겸하고 있다.** ([PRODUCT.md 4절](PRODUCT.md) 표) + +### 나눠야 하는 이유 — 취향이 아니라 셋 다 실제 문제다 + +1. **내부 기능이 사장님 번들에 실려 나간다.** 한 앱이면 `/local-content`, `/places/:id/seo` + 같은 내부 라우트 이름과 화면 코드가 사장님 브라우저에 그대로 내려간다. + `UserRole.DEVELOPER` 는 코드 주석에 **"고객사에 존재를 노출하지 않는다"** 고 적혀 있는데, + 번들이 그 약속을 깨고 있다. 라우트 가드는 화면을 가리지 **번들은 못 가린다**. +2. **인증 모델이 정반대다.** 빌더는 일부러 로그인을 안 세운다("만들어 보기도 전에 막힌다"). + 운영 화면은 엄격해야 한다. 한 앱 안에서 두 정책을 유지하면 실수는 항상 **느슨한 쪽으로** 난다. +3. **배포 리듬이 다르다.** 사장님 화면은 조심스럽게, 내부 화면은 매일 고쳐도 된다. + 한 번들이면 내부 화면 수정 때문에 사장님 화면을 재배포한다. + +### 권고 구조 — 레포는 하나, 배포물은 셋 + +``` +o2o-web4ai/ ← 레포 하나 (모노레포). 쪼개지 않는다 +├─ backend/ FastAPI 모듈러 모놀리스 + 워커 +├─ frontend/ +│ ├─ console/ (신설) 사장님용. 현 admin 의 /builder 계열 +│ ├─ admin/ (남김) 내부 운영용. 현 /places, /local-content, /seo +│ ├─ site/ (그대로) 발행 정적 사이트 +│ └─ shared/ (그대로) 세 앱이 공유하는 타입·slug·토큰 +└─ docs/ +``` + +**핵심: 소스는 합치고, 배포 단위만 쪼갠다.** 2026 기준 이 형태(모노레포 + 다중 배포물)가 +이 규모에서 기본값이다. + +**왜 레포를 안 쪼개나 — 이 프로젝트에는 특히 강한 이유가 있다.** +슬러그 규칙이 `site_payload.publish_slug()` 와 `shared/lib/slug.ts` **두 곳에 있고 같아야 한다.** +`SitePayload` 타입도 백엔드 출력과 프론트 입력이 짝이다. 한 레포에서는 이게 어긋나면 +**타입 에러·테스트 실패**로 잡힌다. 레포를 쪼개면 같은 실수가 **운영 404** 로 나타난다. +게다가 지금 만드는 건 세 개의 제품이 아니라 **한 파이프라인의 세 창구**다. + +**백엔드는 쪼개지 않는다.** 마이크로서비스로 가르자는 제안은 지금 근거가 없다 — +팀 규모·트래픽 어느 쪽도 그 비용을 정당화하지 못한다. 대신 **라우터 표면을 청중별로 가른다**: + +``` +/api/v1/... 사장님 (console) — 자기 리소스만 +/api/v1/admin/... 내부 (admin) — 라우터 레벨에서 role >= DEVELOPER 강제 +``` + +엔드포인트마다 `if role >= ...` 를 흩뿌리지 않고 **의존성 하나로 라우터에 건다.** +지금 `common/authz.py is_owner_or_admin()` 이 그 단일 출처 역할을 하고 있으니, 그걸 라우터 +의존성으로 올리면 된다. + +### 마이그레이션 — 하루짜리, 되돌리기 쉬운 순서 + +1. `frontend/console/` 생성 — `admin/` 의 `vite.config.ts`·`tsconfig.json`·`index.html` 복제 +2. `frontend/package.json` workspaces 에 `console` 추가, `dev:console`·`build:console` 스크립트 +3. `pages/BuilderPage.tsx` + `features/builder`, `features/onboarding`, `features/publish` → + `console/` 로 이동. `components/ui`·`lib`·`stores` 중 **양쪽이 쓰는 것은 `shared/` 로 올린다** +4. `admin/src/app/router.tsx` 에서 `/builder` 라우트 제거, `/places` 를 기본 진입으로 +5. `docker-compose.yml` 에 console 서비스 추가 (또는 nginx 에서 경로/서브도메인 분기) +6. 백엔드 `/api/v1/admin/*` 라우터 분리 + role 의존성 + +★ 3번이 유일하게 시간이 드는 단계다. 공용으로 올릴 것과 한쪽 전용인 것을 가르는 작업이고, + 여기서 대충 하면 `shared/` 가 쓰레기통이 된다. + +**아직 실행하지 않았다.** 지금 구조로도 동작하고, 위 3가지 문제는 실사용 고객이 붙기 전까지는 +터지지 않는다. 다만 **사장님에게 계정을 열어주기 전에는 반드시 끝내야 한다** — 1번(번들 노출)이 +그때부터 실제 유출이 되기 때문이다. + +## 5. 산출물 — 사이트 하나 = 한 장 + +**2026-08-31 결정: 사이트는 한 장이다(라우터 없음).** 예전에는 홈·객실·객실상세·주변· +오시는길·FAQ 로 라우트를 갈라 사이트 하나에 30개 안팎의 HTML 을 구웠다. + +**왜 합쳤나** — 소상공인은 원래 내용이 적다. 쪼갤수록 페이지마다 얇아지고, +**검색엔진은 얇은 페이지를 색인에서 버린다.** 한 장에 모으면 알찬 페이지 하나가 된다. +경로형(`/s/`)이라 얇은 페이지의 평가가 도메인 전체로 번지는 것도 막는다. +(근거 주석: `prerender.ts:196`) + +사이트 1개당: + +``` +out/s//index.html 사이트 전체 (한 장) +out/s//llms.txt 확인된 사실 목록 (AEO) +``` + +**오리진 루트** — 크롤러가 읽는 유일한 자리, 전 사이트가 공유: + +``` +out/robots.txt ★ 크롤러는 오리진 루트에서만 읽는다 (RFC 9309) +out/sitemap.xml 전 사이트 URL 을 한 파일에 (사이트맵 1개 = URL 50,000개까지) +out/.txt 색인 통보용 키 파일 +out/assets/index-<해시>.{css,js} Vite 번들 (하이드레이션용, 약 372KB) +out/fonts/ +``` + +★ **사이트별 `sitemap.xml`·`robots.txt` 는 없앴다.** 한 장짜리의 사이트맵은 URL 이 하나뿐이라 +사이트 1,000개면 한 줄짜리 파일이 1,000개 생긴다. 그리고 `/s//robots.txt` 는 +**아무도 읽지 않는다** — RFC 9309 상 크롤러는 오리진 루트만 본다. + +★ **자산은 사이트마다 복사하지 않는다.** 같은 해시 번들을 1,000벌 복사하면 디스크도 낭비지만, +더 나쁜 건 브라우저 캐시가 사이트마다 따로 잡혀 매번 새로 받는다는 점이다. +(**커스텀 도메인** 사이트만 예외 — 호스트가 달라 공용 경로를 공유할 수 없다.) + +**이미지는 굽지 않는다** — 네이버 CDN(`*.pstatic.net`) URL 을 그대로 참조한다. 지도는 OSM iframe. +DB 에 HTML 컬럼은 없다 (`site_versions.snapshot` JSONB 가 원본). + +⚠️ **산출물 크기 실측값은 아직 없다.** 예전 수치(20개 사이트 = 10MB, 최대 2.1MB)는 **라우트를 +갈라 굽던 시절의 것**이라 지금은 맞지 않는다. 인용하지 말고, 한 장 구조에서 다시 측정해 여기 적는다. + +## 6. 프로세스 구성 + +| 컨테이너 | 무엇 | 포트 | +|---|---|---| +| `o2o-web4ai-api` | FastAPI — 화면이 부르는 API | 9800 | +| `o2o-web4ai-worker` | 잡 러너 (BUILD·수집·생성) + 스케줄러 | — | +| `o2o-web4ai-web` | admin Vite + `watch-payloads` 프리렌더 + `serve-sites`(개발용 :3001) | 3000 | +| `o2o-web4ai-nginx` | **발행 사이트 정적 서빙** — `site-out` 볼륨을 읽기 전용으로 | 80 | + +DB(PostgreSQL)는 **compose 밖**이다 — 호스트에서 돌고 `host.docker.internal` 로 붙는다. +데이터 수명이 컨테이너 수명과 달라야 해서다. diff --git a/docs/COLLECTION_SEO_AEO_FLOW.md b/docs/COLLECTION_SEO_AEO_FLOW.md new file mode 100644 index 0000000..f79e814 --- /dev/null +++ b/docs/COLLECTION_SEO_AEO_FLOW.md @@ -0,0 +1,275 @@ +# 수집·LLM·SEO/AEO 동작 구조 + +이 문서는 사업장 등록부터 정적 사이트 발행까지의 현재 구현을 설명한다. + +## 1. 전체 흐름 + +```text +업종·상호 입력 + → 외부 장소 검색 + → 사용자 동일 업소 확인 + → 채널 URL 등록 또는 발견 + → 사용자 채널 확인 + → 확정 URL 크롤링 + → 정보·사진 검토 + → Gemini 콘텐츠 생성 + → 템플릿 편집 + → 정적 빌드 및 발행 검수 + → 발행 +``` + +핵심 원칙은 다음과 같다. + +- 검증된 사업장만 수집하고 발행한다. +- 확정된 채널 URL만 크롤링한다. +- 자동 수집값은 사용자 승인 전까지 사이트에 노출하지 않는다. +- LLM은 확인된 사실을 표현할 뿐 새로운 사실을 만들지 않는다. +- JSON-LD와 실제 화면 내용이 다르면 발행하지 않는다. + +## 2. 사업장 확인 + +사용자가 업종과 상호를 입력하면 네이버 지역검색 등의 외부 장소 API로 후보를 조회한다. 사용자가 자기 사업장을 선택하면 주소, 좌표와 외부 식별자를 저장하고 `verified_at`을 기록한다. + +검증되지 않은 사업장은 수집과 발행이 제한된다. + +주요 코드: + +- `backend/services/place_service.py` +- `backend/router/v1/place/` + +## 3. 채널 URL 확보 + +### 직접 등록 + +사용자가 네이버 플레이스 URL 등을 입력한다. 사용자가 직접 가져온 URL은 해당 사용자의 채널 확인으로 처리한다. + +### 자동 발견 + +`추가 채널까지 AI로 찾기` 옵션을 켜고 자동 찾기를 실행하면 Perplexity Sonar를 한 번 호출한다. + +- 입력: 상호, 주소, 업종 +- 출력: 채널 URL 후보 +- 검색 대상: 야놀자, 여기어때, 네이버 플레이스 등 허용된 도메인 +- 제외 대상: 서비스 홈, 목록, 블로그·카페 후기 + +Perplexity 응답의 영업시간, 가격 같은 본문 정보는 사용하지 않는다. URL 후보만 `place_links`에 미확정 상태로 저장한다. + +사용자가 `내 채널 맞아요`로 확인한 링크만 크롤링과 사이트 노출에 사용한다. + +주요 코드: + +- `backend/services/external/perplexity.py` +- `backend/services/prompts/channel_discovery.py` +- `frontend/admin/src/features/onboarding/useCollectFlow.ts` +- `frontend/admin/src/features/onboarding/ChannelConfirmPanel.tsx` + +## 4. 크롤링 + +수집 잡은 다음 순서로 실행된다. + +```text +채널 발견 + → 확정 링크 조회 + → URL별 어댑터 선택 + → 채널 데이터 파싱 + → 업종 스키마 적용 + → fact·사진 후보 저장 +``` + +업종마다 허용하는 정보가 다르다. + +- 카페: 메뉴, 음료, 좌석, 영업시간 등 +- 음식점: 메뉴, 음식, 룸, 예약 관련 정보 등 +- 숙박: 객실, 입·퇴실, 인원, 편의시설 등 +- 관광·체험: 프로그램, 장비, 운영 정보 등 + +정확한 필드 목록은 `backend/common/category_schema.py`가 관리한다. 어댑터가 값을 찾더라도 업종 스키마에 없는 항목은 정식 fact로 사용하지 않는다. + +주요 코드: + +- `backend/services/collect_service.py` +- `backend/services/collector/` +- `backend/common/category_schema.py` +- `backend/services/fact_service.py` + +## 5. 정보 승인 + +크롤링 결과는 후보 상태로 저장된다. + +- `UNVERIFIED`: 아직 사용자가 확인하지 않은 정보 +- `PENDING_OWNER`: 기존 노출값과 다른 재수집 후보 +- `VERIFIED`: 사용자가 확인한 정보 +- `CORRECTED`: 사용자가 직접 수정한 정보 + +발행 스냅샷에는 `VERIFIED`, `CORRECTED` 등 발행 가능한 상태만 포함한다. 재수집이 사용자가 수정한 값을 자동으로 덮어쓰지 않는다. + +## 6. LLM 사용 위치 + +### Gemini Vision + +수집한 사진에 다음 정보를 생성한다. + +- 업종별 사진 라벨 +- 접근성용 alt 문구 +- 신뢰도 + +결과는 입력 순서가 아닌 `ref`로 연결한다. 신뢰도가 낮은 결과는 사람 확인 대상으로 남긴다. + +관련 파일: + +- `backend/services/external/gemini.py` +- `backend/services/prompts/vision.py` +- `backend/services/vision_service.py` + +### Gemini Text + +확인된 fact만 이용해 다음 콘텐츠를 만든다. + +- 사업장 소개문 +- 검색 결과용 meta description +- FAQ +- 각 문장의 근거 fact key + +생성 후 `ground_check`가 다음 항목을 코드로 검사한다. + +- 근거에 없는 숫자와 가격 +- 근거에 없는 시설 +- `false`, `불가`, `없음` 값의 반대 표현 +- 과장 또는 홍보성 표현 +- 근거 fact key가 없는 FAQ + +검사를 통과하지 못한 결과는 반려 사유와 함께 저장한다. + +관련 파일: + +- `backend/services/external/gemini_text.py` +- `backend/services/prompts/copy.py` +- `backend/services/copy_service.py` + +## 7. 정적 빌드와 발행 + +```text +발행 가능한 데이터로 snapshot 생성 + → 렌더러용 payload 생성 + → 정적 HTML 생성 + → 실제 HTML과 JSON-LD 비교 + → 발행 게이트 검사 + → site_version 저장 + → 발행 +``` + +방문자가 보는 페이지는 DB를 실시간 조회하지 않는 정적 HTML이다. 검색 크롤러도 JavaScript 실행 없이 주요 정보를 읽을 수 있다. + +★ **사이트 하나 = 한 장이다**(2026-08-31 결정, 라우터 없음). 근거는 [ARCHITECTURE.md 5절](ARCHITECTURE.md). + +검수 실패 시 버전은 `FAILED`로 남고 `publish_logs`에 사유를 기록한다. 검수 게이트를 우회하는 발행 옵션은 없다. + +관련 파일: + +- `backend/services/build_service.py` +- `backend/services/snapshot.py` +- `backend/services/site_payload.py` +- `backend/services/publish_gate.py` +- `frontend/site/` + +## 8. SEO 구현 + +발행본에는 다음 항목을 생성한다. + +- 정적 HTML +- title과 meta description +- canonical URL +- Open Graph 메타 태그 +- 이미지 alt 문구 +- `robots.txt` · `sitemap.xml` — ★ **오리진 루트에만** 굽는다(사이트별로 만들지 않는다). + 크롤러는 robots.txt 를 오리진 루트에서만 읽고(RFC 9309), 사이트맵은 전 사이트를 한 파일에 담는다 +- 사업장 JSON-LD +- FAQPage JSON-LD +- 공식 채널 `sameAs` +- `datePublished`, `dateModified` + +관련 파일: + +- `frontend/site/src/seo/head.ts` +- `frontend/site/src/seo/jsonld.ts` +- `frontend/site/src/seo/robots.ts` +- `frontend/site/src/seo/sitemap.ts` + +## 9. AEO 구현 + +답변형 검색 서비스가 사업장을 식별하고 답변할 수 있도록 다음 신호를 제공한다. + +- 검증된 상호, 주소와 좌표 +- 업종별 구조화 데이터 +- 질문형 FAQ와 FAQPage JSON-LD +- 화면에 표시되는 핵심 답변 블록 +- 확인된 사실을 정리한 `llms.txt` +- 사실 출처와 검증 시각 +- 공식 채널 `sameAs` +- 발행일과 수정일 + +JSON-LD 값은 화면에도 동일하게 존재해야 한다. 렌더러가 양쪽을 비교하고 불일치하면 발행 게이트가 거절한다. + +관련 파일: + +- `frontend/site/src/seo/llms.ts` +- `frontend/site/src/seo/verify.ts` +- `frontend/site/src/sections/AnswerBlock.tsx` +- `backend/services/publish_gate.py` + +## 10. SEO·AEO 진단 점수 + +관리자 화면은 현재 저장 정보와 최신 발행본을 기준으로 SEO와 AEO 준비도를 각각 100점으로 계산한다. + +SEO 항목: + +- 정적 빌드 +- 도메인과 canonical +- robots, sitemap, JSON-LD +- 주소와 전화번호 +- 확인된 정보량 +- alt가 있는 이미지 +- 고유 콘텐츠 +- 동일 업소 검증 + +AEO 항목: + +- 사업장 엔티티 식별 +- 좌표와 지역 문맥 +- 확인된 사실량 +- FAQ +- JSON-LD와 `llms.txt` +- 출처와 검증 시각 +- 최신 발행본 + +이 점수는 Google, Naver 또는 외부 SEO 도구의 공식 점수가 아니다. 우리 솔루션이 통제할 수 있는 검색 준비도 지표이며 순위나 AI 인용을 보장하지 않는다. + +관련 파일: + +- `backend/services/seo_audit.py` +- `backend/router/v1/site/site.py` +- `frontend/admin/src/pages/SeoAuditPage.tsx` + +API: + +```http +GET /v1/place/{place_id}/site/audit +``` + +## 11. 블로그 기능 범위 + +현재 블로그 글 자동 작성과 네이버 블로그 자동 발행은 구현되어 있지 않다. + +현재 지원 범위는 공식 블로그 URL을 채널로 등록하고, 사용자가 확인한 뒤 사이트 푸터에 공식 채널 링크로 표시하는 것이다. 블로그·카페 후기는 자동 수집의 공식 사실 출처로 사용하지 않는다. + +## 12. 외부 API와 과금 발생 지점 + +| 단계 | 외부 서비스 | 호출 조건 | +|---|---|---| +| 사업장 검색 | 네이버 지역검색 또는 카카오 로컬 | 사업장 후보 검색 | +| 채널 발견 | Perplexity Sonar | 사용자가 추가 채널 발견 옵션을 선택한 경우 | +| 사진 분석 | Gemini Vision | 분석할 사진이 있는 경우 | +| 소개문·FAQ | Gemini Text | 확인된 근거 fact가 있는 경우 | + +일반 크롤링과 정적 빌드는 별도의 LLM 호출을 하지 않는다. 채널 발견 옵션은 해당 발견 요청 한 번에만 적용되며 이후 크롤링이나 재수집으로 자동 승계되지 않는다. + diff --git a/docs/DATA_SOURCE_RESEARCH.md b/docs/DATA_SOURCE_RESEARCH.md new file mode 100644 index 0000000..7bcfd23 --- /dev/null +++ b/docs/DATA_SOURCE_RESEARCH.md @@ -0,0 +1,498 @@ +# 콘텐츠 소스 리서치 — AEO/SEO/GEO 관점 + +조사일: 2026-08-28. 모든 HTTP 응답은 이 날짜에 이 개발 머신에서 직접 찍은 실측값이다. +`DECISIONS.md` 1-1(크롤링 약관·법적 검토), 1-2(이미지 재게시 권리)에 대한 답을 포함한다. + +--- + +## 0. 한 줄 결론 + +**네이버·카카오 생태계는 AI 검색엔진에게 통째로 닫혀 있다. 그래서 우리가 네이버 플레이스를 복제할 이유가 없어졌고, 오히려 복제하면 안 된다.** +AI 인용을 노린다면 소스 전략은 "OTA에서 긁어오기" → **"공공데이터(인용 가능한 1차 출처) + 사장님 인증 채널(고유 콘텐츠)"** 로 바꿔야 한다. + +--- + +## 1. ★ 결정적 발견 — AI 크롤러 차단 지도 + +각 사이트 `robots.txt` 실측. `전면차단` = `Disallow: /`. + +| 소스 | GPTBot | OAI-SearchBot | ClaudeBot | PerplexityBot | Google-Extended | Googlebot | Yeti(네이버) | +|---|---|---|---|---|---|---|---| +| **m.place.naver.com** (현재 어댑터) | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 전면차단 | **전면차단** | 전면차단 | +| **pcmap.place.naver.com** | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 전면차단 | **전면차단** | 전면차단 | +| map.naver.com | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 거의차단 | 거의차단 | +| blog.naver.com | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 거의차단 | **전면차단** | +| booking.naver.com | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 전면차단 | +| smartstore.naver.com | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 부분제한 | 부분제한 | +| place.map.kakao.com | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 거의차단 | 거의차단 | +| app.catchtable.co.kr | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 전면차단 | 허용 | 허용 | +| www.goodchoice.kr (여기어때) | 전면차단 | 허용 | 전면차단 | 허용 | 전면차단 | 부분제한 | 부분제한 | +| www.diningcode.com | 전면차단 | 부분제한 | **허용** | **허용** | 전면차단 | 부분제한 | 부분제한 | +| www.yanolja.com | 별도규칙 없음(`*`만) | " | " | " | " | " | " | + +### 이게 왜 사업의 핵심인가 + +`m.place.naver.com/robots.txt` 원문 (2026-08-28, 3회 재시도 모두 동일): + +``` +User-agent: * +Disallow: / +``` + +즉 **네이버 플레이스는 예외 없이 모든 크롤러를 금지한다.** 그 결과: + +- 사용자가 ChatGPT/Claude/Perplexity/Gemini에 `"강릉 ○○펜션 반려동물 되나요?"` 를 물으면 → **인용할 소스가 존재하지 않는다.** 네이버 플레이스에 답이 있어도 AI는 그 페이지를 읽을 수 없다. +- 네이버 블로그·카페 후기도 똑같이 막혀 있다. 사장님 블로그를 아무리 잘 써도 글로벌 AI 검색에는 안 잡힌다. +- 캐치테이블·카카오맵도 AI 봇 전면 차단. +- **한국 로컬 비즈니스 정보는 AI 검색 입장에서 통째로 빈 구멍이다.** + +→ 사장님 자체 도메인의 정적 사이트가 그 구멍을 채우면 **경쟁자 없이 독점 인용**된다. 이 제품의 해자가 데이터로 확인됐다. + +### 채널 이원화가 필요하다 + +| 목표 | 인용 소스 특성 | 우리 전략 | +|---|---|---| +| **네이버 AI 브리핑** | 네이버 생태계 편중. 인용 272건 분석 시 블로그가 158건으로 1위. 검색순위와 별개(인용의 49.3%가 검색 10위 밖) | 자체 도메인으로는 뚫기 어렵다. 사장님 블로그 채널이 필요 (현재 미구현 — §11) | +| **Google AI Overview / ChatGPT / Perplexity** | 웹 전체 대상, 자사 도메인 유리. 경쟁 소스(네이버·카카오)가 전부 차단 상태 | **여기가 우리 주전장.** 현재 구조(정적 HTML + JSON-LD + llms.txt)가 정확히 맞다 | + +--- + +## 2. 현재 상태 실측 + +| 항목 | 결과 | +|---|---| +| `m.place.naver.com/{kind}/{id}/home` | **HTTP 200**, `__APOLLO_STATE__` 존재 (restaurant 347KB / accommodation 612KB). 기능적으로는 정상 동작 | +| `pcmap.place.naver.com/restaurant/{id}/home` | HTTP 200, `__APOLLO_STATE__` 존재 | +| **robots.txt 준수 여부** | ❌ **위반 중.** `Disallow: /` 를 무시하고 있다 | +| 네이버 지역검색 API (`openapi.naver.com/v1/search/local`) | ✅ 정상 (2026-08-28 확인). 단 **`telephone`·`description`은 전 표본 100% 빈 문자열** | +| TourAPI `KorService2` | ❌ **HTTP 403** — 키는 유효하나 해당 API 미신청 상태 (같은 키로 축제 API는 200) | +| `KAKAO_REST_API_KEY` | 미설정(빈 값) | + +> **기능이 되는 것과 해도 되는 것은 다르다.** 지금 네이버 플레이스 어댑터는 200을 받지만 robots.txt를 명시적으로 위반한다. `DECISIONS.md` 1-1의 "약관·robots.txt 기준 허용 범위" 질문에 대한 답은 **"robots.txt 기준으로는 명백히 불허"** 다. + +--- + +## 3. OTA 크롤링 — 이미 막혀 있다 + +풀 브라우저 헤더(Chrome 128 UA + sec-ch-ua + Sec-Fetch-* 전체)로 재시도한 결과: + +| URL | 결과 | +|---|---| +| `www.yanolja.com/pension/3013306` | **HTTP 403** + Cloudflare 챌린지 | +| `nol.yanolja.com/hotels/{id}` | HTTP 404/403 + Cloudflare 챌린지 | +| `www.goodchoice.kr/product/detail?ano=...` | **HTTP 403** + Cloudflare 챌린지 (홈페이지는 200) | +| `place.map.kakao.com/{id}` | HTTP 200이나 **3.6KB SPA 셸** — 내용 없음 | +| `place-api.map.kakao.com/places/panel3/{id}` (내부 API) | **HTTP 406** 차단 | + +**야놀자·여기어때 어댑터는 만들어도 못 쓴다.** 뚫으려면 헤드리스 브라우저 + 봇 탐지 우회가 필요한데, 그건 `registry.py`와 `DECISIONS.md`가 **결론과 무관하게 영구 금지**로 못 박은 영역이다. + +### 법적으로도 하면 안 된다 — 야놀자 v 여기어때 + +같은 행위(OTA 숙박정보 크롤링)에 대한 국내 유일 대형 선례다. **형사·민사 결론이 갈렸다.** + +| 구분 | 결론 | +|---|---| +| 형사 (대법원 2022-05-12 확정) | **무죄.** 정보통신망침해·업무방해·저작권법 위반 모두 무죄. "수집한 정보 대부분이 이용자에게 공개된 것", DB의 통상적 이용을 방해한 정도가 아니라고 판단 | +| 민사 (서울중앙지법 2021-08) | **10억 원 배상 + 사용·복제·저장 금지.** 성과물 무단사용(부정경쟁행위) 인정. 야놀자가 영업조직 인건비만 26억 투입한 점을 배상액 산정에 반영 | + +**"형사는 무죄니까 괜찮다"가 아니라 "민사로 10억 물었다"가 우리에게 유효한 신호다.** 우리는 그 정보를 **재게시**까지 하므로 여기어때보다 노출이 크다. + +--- + +## 4. Google Places API — 우리 제품 구조와 약관이 충돌한다 + +| 항목 | 내용 | +|---|---| +| 캐싱 | `place_id`만 무기한 저장 가능. 좌표는 최대 30일. **이름·영업시간·사진·리뷰·전화번호는 캐싱 금지 — 실시간 조회 후 표시해야 한다** | +| 표시 조건 | Google 지도 위에 표시 + Google 로고 및 제3자 제공자 귀속 표기 의무 | + +우리는 **DB를 실시간 조회하지 않는 정적 HTML**을 발행한다(§7). 정적 빌드에 값을 굽는 순간 캐싱 금지 조항 위반이다. +→ **Places API는 콘텐츠 소스로 배제.** (Place ID를 엔티티 식별자로만 쓰는 건 가능) + +--- + +## 5. 업종별 실측: 사장님이 실제로 어디에 콘텐츠를 두는가 + +네이버 지역검색 API `link` 필드 충전율. 업종별 5개 쿼리 × 상위 5건 = **표본 25건씩** (작은 표본이니 방향만 참고). + +| 업종 | link 있음 | 인스타그램 | 자체 도메인·기타 | 시사점 | +|---|---|---|---|---| +| **카페** | 23/25 (**92%**) | **17** | 6 (자체 도메인 2, 스마트스토어 2, 캐치테이블 1) | 카페는 사실상 **인스타가 공식 홈페이지**다 | +| **숙박** | 24/25 (**96%**) | 5 | **19** (개별 도메인 다수: `gangmunstay.kr`, `offinghouse.com` 등) | 숙박은 **자체 홈페이지 보유율이 압도적** | +| **음식점** | 16/25 (64%) | 8 | 8 (네이버블로그 4, 자체 도메인 4) | 절반씩 갈린다. 충전율도 가장 낮다 | + +**이게 어댑터 우선순위를 정해준다:** +- 숙박 → 사장님 **자체 홈페이지 크롤링**(`StaticHtmlAdapter`)이 최고 효율. 사장님이 URL을 확정해주므로 법적으로도 가장 깨끗하다. +- 카페 → **인스타그램**이 유일한 실질 콘텐츠 소스. +- 음식점 → 커버리지가 낮아 공공데이터·사장님 직접입력 비중을 높여야 한다. + +--- + +## 5-1. ★ 업종별로 결론이 다르다 + +세 업종은 **경쟁 상황이 서로 다르다.** "AI가 인용할 대체 소스가 이미 있는가"가 갈림점이다. + +### 숙박 — 야놀자·여기어때는 답이 아니다 + +| 소스 | 실측 | 판정 | +|---|---|---| +| **야놀자** | HTTP **403** + Cloudflare 챌린지 (풀 브라우저 헤더로도 동일) | ✗ 기술적 차단 + 민사 10억 선례 | +| **여기어때** | HTTP **403** + Cloudflare 챌린지 | ✗ 동일 | +| **TourAPI 숙박(32)** | 무료·재게시 자유. 체크인/아웃, 객실 수·유형, 취사, 주차, 픽업, 부대시설 | ◎ **1순위** | +| **사장님 자체 홈페이지** | 표본 보유율 **76%** (숙박이 3업종 중 최고) | ◎ **2순위** | +| LOCALDATA 숙박업 | 객실 수, 시설면적, 영업상태(인허가 기준) | ○ 신뢰 근거 | +| 스테이폴리오 | SSR + JSON-LD 있으나 감성숙소 한정 | △ 커버리지 좁음 | + +> **덧붙일 중요한 사실:** 야놀자·여기어때는 **AI 크롤러에게도 닫혀 있다.** 즉 긁어봐야 "AI가 못 읽는 정보를 위법하게 옮겨오는" 것에 불과하다. GEO 관점에서 얻는 게 없다. + +**단, 숙박만 예외가 하나 있다.** 해외 OTA는 AI에 열려 있다: + +| 소스 | 상세페이지 | GPTBot | ClaudeBot | PerplexityBot | +|---|---|---|---|---| +| 에어비앤비 | HTTP 200 (446KB, SSR) | 허용 | 허용 | 허용 | +| 부킹닷컴 | 접근 가능 | 허용 | 허용 | 허용 | +| 아고다 | 접근 가능 | 허용 | 허용 | 허용 | + +→ **호텔·리조트급은 AI 검색 공백이 아니다.** 부킹닷컴·아고다 페이지가 이미 인용된다. 우리가 긁을 대상이 아니라 **경쟁 소스**로 인식해야 한다. +→ 반대로 **펜션·게스트하우스·독채는 해외 OTA 커버리지가 낮고 국내 채널은 전부 차단** → **공백이 그대로 남아 있다. 여기가 숙박의 진짜 기회다.** + +### 카페 — AI 검색 공백은 최대. 소스는 생각보다 있다 + +> **정정 (2026-08-31).** 초판에서 "TourAPI 카페 커버리지 거의 없음"이라고 썼는데 **틀렸다.** +> 카페는 별도 콘텐츠 타입이 아니라 **음식점(39)의 소분류**(`cat3=A05020900` 카페/전통찻집)로 들어 있고, +> 전국 **1,979건**이 등록돼 있다. 실측으로 확인했다. + +| 소스 | 실측 | 판정 | +|---|---|---| +| **TourAPI (39 / A05020900)** | 전국 1,979건. 영업시간·휴무일·대표메뉴·취급메뉴·주차·사진 | ○ **관광지 인근 편중이지만 실재한다** | +| **인스타그램** | 표본의 **68%**가 인스타를 공식 채널로 등록 (3업종 중 최고) | ◎ 그 외 카페의 주 소스. 사장님 OAuth 필요 | +| LOCALDATA 휴게음식점 | 영업상태·시설면적만 | △ 검증용 | +| 네이버 플레이스 | robots 전면 금지 | ✗ | + +→ 카페는 **AI 검색 공백이 가장 크다**(네이버·카카오·인스타 전부 AI 차단). TourAPI에 등록된 카페는 바로 채워지고, 나머지는 **인스타 OAuth + 사장님 입력**으로 간다. + +### 음식점 — 소스는 가장 많은데 쓸 만한 게 가장 적다 + +| 소스 | 실측 | 판정 | +|---|---|---| +| 배민 / 요기요 / 쿠팡이츠 | 공식 API 없음, 앱 중심 | ✗ | +| 캐치테이블 | SPA 셸(8KB) + **AI봇 전면차단** | ✗ | +| 다이닝코드 | SPA 셸(23KB, JS 필요). 단 **ClaudeBot·PerplexityBot 허용** | △ **경쟁 소스** | +| 식신 | SSR + `LocalBusiness` JSON-LD (상호·전화·주소) | △ 얕음 | +| 미쉐린가이드 | AI봇 허용 | △ 경쟁 소스(해당 업소 한정) | +| 블루리본서베이 | AI봇 전면차단 | ✗ | +| **TourAPI 음식점(39)** | 대표메뉴·취급메뉴·영업시간·쉬는날·포장·예약·좌석 수 | ○ **단 관광지 인근 편중 우려** | +| **LOCALDATA 일반음식점** | 업태(한식/중식…), 시설면적, 영업상태 | ○ | +| 식품안전나라 위생등급 | 공공 인증 | ○ **E-E-A-T 신호로 유용** | +| 사장님 자체 홈페이지 | 표본 보유율 32%, `link` 충전율 **64%로 3업종 최저** | △ | + +→ 음식점은 **자체 채널 보유율이 가장 낮아** 공공데이터와 사장님 직접 입력 비중을 가장 크게 잡아야 한다. + +### 요약 + +| | 대체 소스 | AI 검색 공백 | 주력 소스 | 난이도 | +|---|---|---|---|---| +| **숙박(펜션·독채)** | 야놀자·여기어때 모두 차단 | **완전 공백** | TourAPI + 자체 홈페이지(76%) | **낮음** ← 먼저 공략 | +| 숙박(호텔) | 해외 OTA가 AI에 노출 중 | 부분 공백 | TourAPI + 자체 홈페이지 | 중간 | +| **카페** | 사실상 없음 | **완전 공백** | 인스타 OAuth + 사장님 입력 | 높음 | +| **음식점** | 다이닝코드·미쉐린 일부 노출 | 대부분 공백 | LOCALDATA + TourAPI + 사장님 입력 | 높음 | + +--- + +## 6. 소스 카탈로그 + +### Tier 1 — 공공 API (재게시 자유, GEO에 가장 강함) + +| 소스 | 상태 | 숙박 | 카페 | 음식점 | 라이선스 | +|---|---|---|---|---|---| +| **TourAPI (한국관광공사 KorService2)** | 키는 있으나 **활용신청 필요**(무료·즉시) | ◎ 체크인/아웃, 객실 수·유형, 취사, 주차, 픽업, 부대시설 | ✕ 커버리지 거의 없음 | ○ 대표메뉴, 취급메뉴, 영업시간, 쉬는날, 포장·예약, 좌석 수 | **이용허락범위 제한없음 / 무료.** 개발계정 1,000건/일 → 운영계정 확장 가능 | +| **LOCALDATA (지방행정 인허가)** | 미도입. 무료 신청 | ○ 숙박업 인허가 — 객실 수, 시설면적, 영업상태 | ○ 휴게음식점 | ○ 일반음식점 — 업태(한식/중식…), 시설면적, 영업상태 | 공공데이터. 208개 업종 전체, 좌표 포함(EPSG:5174) | +| **네이버 지역검색 API** | ✅ 사용 중 | △ | △ | △ | 상호·주소·좌표·카테고리·`link`만. **전화·설명 필드는 빈 값** | +| **카카오 로컬 API** | 키 미설정 | △ | △ | △ | 네이버 지역검색과 동급. 콘텐츠 없음 | + +> **TourAPI의 필드 목록은 활용신청 후 `detailIntro2`로 실측 확정 필요.** 현재 403이라 응답 스키마를 직접 확인하지 못했다. + +### Tier 2 — 사장님 인증 채널 (고유 콘텐츠, 법적으로 가장 안전) + +| 소스 | 방식 | 숙박 | 카페 | 음식점 | 비고 | +|---|---|---|---|---|---| +| **사장님 자체 홈페이지** | 사장님이 URL 확정 → `StaticHtmlAdapter` | ◎ (보유율 76%) | △ | ○ | **가장 권장.** 사장님 동의 = 법적 리스크 0. 이미 `LinkChannel.OFFICIAL_SITE` 존재 | +| **인스타그램 Graph API** | 사장님 OAuth (Business/Creator 계정 필요) | △ | ◎ (**68%**) | ○ | 사진 + 캡션. **저작권자가 사장님이라 1-2 미결이 해소된다** | +| **Google Business Profile API** | 사장님 OAuth + Google 접근 승인 필요 | ○ | ○ | ○ | 영업시간·속성·사진 전부. 단 **국내 소상공인 GBP 관리율이 낮아 커버리지 문제**. 신규 프로젝트는 쿼터 0에서 시작, 별도 심사 필요 | +| **사장님 직접 입력** | 관리자 화면 | ◎ | ◎ | ◎ | 커버리지 100%. 이탈률이 유일한 비용 | + +### Tier 3 — 기술적으로 가능하나 권장하지 않음 + +| 소스 | 상태 | +|---|---| +| 식신 (`siksinhot.com`) | HTTP 200, SSR, `LocalBusiness` JSON-LD 제공(상호·전화·주소). 콘텐츠 깊이는 네이버보다 얕고 업소 매칭이 어렵다 | +| 다이닝코드 | HTTP 200이나 **SPA 셸(23KB)** — JS 렌더링 필요. `rid` 매칭 문제 | + +### Tier 4 — 배제 + +야놀자 / 여기어때 (Cloudflare 403 + 민사 10억 선례) · 카카오맵 (406, AI봇 전면차단) · 캐치테이블 (SPA + AI봇 전면차단) · Google Places API (캐싱 금지) · 네이버 블로그·카페 후기 (이미 정책상 배제, robots 전면차단) + +--- + +## 7. GEO 관점에서 소스를 다시 줄 세우면 + +Princeton·Georgia Tech·IIT Delhi 공동연구(KDD 2024)가 확인한 **AI 인용률을 최대 40% 끌어올리는 요인**은 키워드가 아니라 이 셋이다: + +1. **통계·수치 추가 (Statistics Addition)** +2. **출처 인용 (Cite Sources)** +3. **인용문 추가 (Quotation Addition)** + +그리고 ChatGPT·Gemini·Copilot이 인용한 소스의 **10% 미만만 해당 질의 구글 상위 10위에 든다.** 랭킹 신호와 인용 신호는 다른 게임이다. + +이 기준으로 소스를 평가하면 순위가 뒤집힌다: + +| 소스 | 수치 밀도 | **출처로 명시 가능?** | GEO 가치 | +|---|---|---|---| +| **LOCALDATA 인허가** | 높음 (객실 수, 시설면적, 인허가일) | ✅ "○○시 인허가 정보 기준" | **최상** | +| **TourAPI** | 높음 (체크인 시각, 객실 수, 좌석 수) | ✅ "한국관광공사 TourAPI 기준" | **최상** | +| 사장님 확인 정보 | 중간 | ✅ "사업주 확인, 2026-08-28" | 높음 | +| **네이버 플레이스 크롤링** | 높음 | ❌ **밝힐 수 없다** (robots 위반 + 재게시 근거 없음) | **낮음** | + +**핵심 역설: 지금 유일한 소스인 네이버 플레이스가 GEO 관점에서 가장 가치가 낮다.** +출처를 명시할 수 없는 사실은 AI가 신뢰하지 않고, 우리 `AnswerBlock`·`llms.txt`의 "출처와 검증 시각" 신호도 채우지 못한다. 반면 공공데이터는 그 자체가 **인용 가능한 1차 출처**라 GEO 신호를 직접 만든다. + +여기에 하나 더 — **복제 콘텐츠는 GEO에서 마이너스다.** 네이버 플레이스와 같은 문장이 실린 페이지는 `PUBLISH_NO_UNIQUE_CONTENT` 게이트가 이미 경계하는 그 상태다. AI가 굳이 인용할 이유가 없다. + +--- + +## 8. 권고 로드맵 + +| 순위 | 작업 | 근거 | 비용 | +|---|---|---|---| +| **1** | **TourAPI KorService2 활용신청** 후 `tour_api.py` 확장 (`searchStay2`, `detailIntro2`) | 숙박·음식점 fact를 출처 명시 가능한 형태로 확보. 무료, 신청 즉시 승인 | 1일 | +| **2** | **`StaticHtmlAdapter` 등록** (사장님 확정 URL 전용) | 숙박 76%·음식점 32%가 자체 도메인 보유. 사장님 동의 기반이라 법적 리스크 0. `DECISIONS.md` 1-1이 "결론 후 등록"으로 남겨둔 바로 그 어댑터 | 3일 | +| **3** | **LOCALDATA 연동** | 인허가 기반 영업상태·객실수·시설면적. `PLACE_NOT_VERIFIED` 검증 근거로도 사용 가능 | 2일 | +| **4** | **인스타그램 Graph API (사장님 OAuth)** | 카페 68%의 유일한 콘텐츠·사진 소스. **1-2(이미지 재게시 권리) 미결을 구조적으로 해소** | 5일 | +| **5** | 네이버 플레이스 어댑터 **역할 축소** — 사장님 화면의 "대조용 참고값"으로만 사용하고 발행 payload에서 제외 | robots 위반 해소 + 복제 콘텐츠 제거. `COLLECT_ADAPTERS` 환경변수로 코드 수정 없이 즉시 가능 | 0.5일 | +| 6 | 네이버 블로그 채널 (§11 미구현분) | 네이버 AI 브리핑 인용의 58%가 블로그. 글로벌 AI와 별개 전장 | 별도 검토 | + +`registry.py`가 이미 `COLLECT_ADAPTERS` 환경변수로 채널별 on/off를 지원하므로, 5번은 **배포 없이 즉시 실행 가능**하다. + +### 업종 출시 순서 제안 + +소스 확보 난이도와 AI 검색 공백 크기가 같은 방향을 가리킨다. + +1. **숙박(펜션·게스트하우스·독채)** — TourAPI 32 + 자체 홈페이지(보유율 76%)로 fact가 가장 잘 차고, 경쟁 소스가 전부 차단 상태다. **1·2번 작업만으로 출시 가능.** +2. **음식점** — LOCALDATA + TourAPI 39 + 위생등급으로 공공 fact를 채우고 나머지는 사장님 입력. 3번 작업 필요. +3. **카페** — 인스타 OAuth(4번)가 선행되지 않으면 사장님 입력 100% 의존이라 이탈률이 높다. 가장 마지막. + +--- + +## 8-1. 구현됨 (2026-08-28) — 사이트별 파서 대신 LLM 추출 + +조사 도중 방향을 바꿨다. **사장님 홈페이지마다 파서를 짜는 것은 끝이 없다** — 실측으로 확인됐다: + +| 사이트 | 결과 | +|---|---| +| `mulhoe.co.kr` | 본문 2,841자 + JSON-LD 1블록 — **쓸 만함** | +| `gangmunstay.kr` | 8.5KB HTML인데 **본문 9자** — SPA, JS 렌더링 필요 | +| `cheomdangukbap.com` | 834바이트, **본문 0자** — SPA | +| `offinghouse.com` | SSL 자체서명 인증서 오류 | + +4곳 중 1곳만 정적 HTML로 내용이 나온다. 그래서 **입력이 무엇이든(URL 크롤링 본문 / 사장님 붙여넣기 텍스트) 원문 문자열 하나로 모아 Gemini가 업종 스키마로 추출**하는 구조로 만들었다. + +```text +URL → StaticHtmlAdapter (robots 준수) ─┐ +붙여넣기 ────────────────────────────────────┴→ 원문 텍스트 → Gemini 구조화 추출 + → evidence 원문 대조 → fact 후보(UNVERIFIED) +``` + +**핵심 안전장치는 프롬프트가 아니라 코드다.** 모델이 적어 낸 근거 문장이 원문에 실제로 있는지 대조하고, 없으면 버린다. 실측 검증: + +| 공격 케이스 | 결과 | +|---|---| +| 원문에 없는 문장을 근거로 지어냄 | 🚫 차단 | +| 근거는 "반려동물 불가"인데 `pet_allowed=true` | 🚫 차단 (부호 뒤집기) | +| 원문 "오후 3시"를 "15:00"으로 환산 | 🚫 차단 (표기 변경) | +| 업종 스키마에 없는 key | 🚫 차단 | +| unit 스코프인데 `unit_name` 없음 | 🚫 차단 | + +실제 결과 — 파서 한 줄 없이: +- `mulhoe.co.kr` (음식점): 영업시간·주차·포장·예약채널 + 메뉴 5종의 이름/가격/설명 = **fact 19건** +- 붙여넣기 238자 (펜션): 체크인/아웃·주차·와이파이·반려동물(false)·바비큐요금 + 객실 2종의 인원/침대/주중·주말요금 = **fact 15건** + +| 파일 | 역할 | +|---|---| +| `backend/services/collector/static_html_adapter.py` | robots.txt 준수 fetch + JSON-LD/OG 추출. `_DENY_HOSTS` 로 플랫폼 차단 | +| `backend/services/prompts/extract.py` | 추출 프롬프트·응답 스키마 (업종 스키마에서 자동 생성) | +| `backend/services/grounding/extract.py` | **evidence 원문 대조 게이트** | +| `backend/services/external/gemini_extract.py` | 엮는 자리 | +| `backend/tests/test_extract_grounding.py` | 게이트 회귀 테스트 17건 | + +비용: 호출당 약 $0.006 (gemini-3.7-flash, temperature 0.0). + +**남은 작업:** `collect_service` 에서 이 추출 경로를 호출하도록 배선 + 관리자 화면에 "텍스트 붙여넣기" 입력창. 컨테이너는 소스 마운트가 없으므로 `docker compose up -d --build` 로 이미지를 다시 빌드해야 반영된다. + +--- + +## 8-2. 지금 실제로 가져올 수 있는 정보 (2026-08-31 실측) + +TourAPI 활용신청이 승인돼 어댑터를 붙였다. 아래는 **표본 8곳씩 실제로 돌려서 센 것**이지 문서 기준 추정이 아니다. + +### 숙박 — 객실 단위까지 채워진다 + +| 필드 | TourAPI 충전율 | 비고 | +|---|---|---| +| ★ 체크인 / 체크아웃 | **8/8곳** | critical | +| 숙소 소개 | 8/8곳 | | +| 바비큐 이용 | 8/8곳 | | +| 주차 | 6/8곳 | | +| ★ 취사 가능 | 4/8곳 | critical | +| ★ 취소·환불 규정 | 3/8곳 | critical | +| 픽업 서비스 | 3/8곳 | | +| **객실 단위** — 타입·★기준인원·★최대인원·★주중요금·★주말요금·에어컨 | **객실 20개분** | 표본 8곳에서 객실 20개 | +| 객실 면적(㎡) | 객실 17개분 | | +| ★ 성수기 요금 | 객실 14개분 | | +| ★ 주방 여부 | 객실 13개분 | | +| 사진 | 4/8곳 | 객실별로 붙는다 | + +**TourAPI가 못 채우는 13개:** `pet_allowed` `smoking` `extra_person_fee` `reception_hours` `parking_capacity` `wifi` `bbq_fee` `breakfast` `baby_amenities` `bed_type` `bathroom_count` `view` `room_intro` → 자체 홈페이지 추출 또는 사장님 입력. + +### 음식점 · 카페 — 영업정보와 메뉴 이름까지 + +| 필드 | TourAPI 충전율 | +|---|---| +| 가게 소개 · ★영업시간 · ★휴무일 · 대표메뉴 · ★주차 | **8/8곳** | +| 메뉴 이름(단위) | 메뉴 25건 | +| 포장 | 4/8곳 | +| ★ 예약 필수 | 2/8곳 | +| 사진 | **8/8곳** | + +**못 채우는 16개:** `break_time` `last_order` `reservation_channel` `pet_allowed` `kids_allowed` `corkage` `room_available` `group_seat_max` `parking_capacity` `delivery` `payment_methods` `price_range` `wheelchair_accessible` `menu_price` `menu_min_order` `menu_intro` +→ **메뉴 가격이 없는 것이 가장 아프다.** 자체 홈페이지 추출(속초항아리물회에서 메뉴 5종 가격 확보)이나 사장님 입력으로 메운다. + +### 네이버 플레이스와 비교 (같은 날 실측) + +| | 네이버 플레이스 | TourAPI | +|---|---|---| +| 숙박 사업장 fact | **2건** (`intro`, `wifi`) | **8종** (체크인/아웃·취사·주차·픽업·바비큐·환불규정·소개) | +| 숙박 객실 정보 | 객실명(`room_type`)**만** 18개 | 객실 20개의 **인원·요금·면적·주방·에어컨** | +| 음식점 | **수집 실패** (`PlaceDetailBase` 없음) | 영업시간·휴무일·대표메뉴·주차·메뉴명·사진 | +| 출처 표기 | **불가** (robots 위반) | 가능 — 대한민국구석구석 공개 URL | + +**네이버 플레이스를 유지할 이유가 사실상 사라졌다.** 정보량도 적고 출처도 못 밝힌다. + +### 이미지 — 저작권까지 확정 + +TourAPI 숙박 사진 167장 표본의 공공누리 유형: **Type3 161장 · Type1 6장 → 100% 상업적 이용 가능.** +다만 **Type3가 96%이고 제3유형은 '변경금지'** 다. + +> ⚠️ **렌더러 제약:** Type3 사진은 **크롭·리사이즈하면 조건 위반**이다. 썸네일 생성 경로가 이 사진들을 건드리면 안 된다. +> `CollectedMedia.license` 에 유형을 담아 내보내므로 발행 단계에서 판정할 수 있다. +> 상업적 이용이 막힌 Type2·Type4와 유형 미상은 **수집 단계에서 버린다**. + +--- + +## 8-3. API별 수집 카탈로그 — 어디서 무엇을 가져오는가 + +코드에서 뽑은 것이다(2026-08-31). `→` 왼쪽이 API 원본 필드, 오른쪽이 우리 fact key. + +### A. 한국관광공사 TourAPI · `apis.data.go.kr/B551011/KorService2` + +무료 · 이용허락범위 제한없음 · 개발계정 1,000건/일. **fact 의 주력 공급원.** + +| 오퍼레이션 | 원본 → fact key | +|---|---| +| `detailCommon2` | `overview` → **intro** · `firstimage`+`cpyrhtDivCd` → 대표사진
    *참고용으로만 읽음:* `title` `addr1` `mapx/mapy` `homepage` `cat1/2/3` `modifiedtime` | +| `detailIntro2` **숙박(32)** | `checkintime` → **check_in_time** · `checkouttime` → **check_out_time**
    `refundregulation` → **cancel_policy** · `chkcooking` → **cooking_allowed**
    `parkinglodging` → **parking** · `pickup` → **pickup_service** · `barbecue` → **bbq_available** | +| `detailIntro2` **음식점·카페(39)** | `opentimefood` → **business_hours** · `restdatefood` → **closed_days**
    `firstmenu` → **signature_menu** · `treatmenu` → **menu_name**(단위, `/`로 분리)
    `parkingfood` → **parking** · `packing` → **takeout** · `reservationfood` → **reservation_required** | +| `detailInfo2` **숙박(32)** = 객실 행 | `roomtitle` → **room_type**(+ unit_name) · `roombasecount` → **standard_capacity**
    `roommaxcount` → **max_capacity** · `roomsize2` → **room_size**(㎡)
    `roomoffseasonminfee1/2` → **weekday_price / weekend_price**
    `roompeakseasonminfee1` → **peak_price** · `roomcook` → **has_kitchen** · `roomaircondition` → **has_aircon**
    `roomimg1~5` + `cpyrhtDivCd1~5` → 객실 사진 | +| `detailImage2` | `originimgurl` `imgname` `cpyrhtDivCd` → 추가 사진 | + +**일부러 안 쓰는 필드** — 스키마에 자리가 없거나 뜻이 다르다: +`roomcount` `scalelodging` `accomcountlodging` `foodplace` `reservationlodging` `infocenter*` `subfacility` +`seminar/sports/sauna/beauty/beverage/karaoke/campfire/bicycle/fitness/publicpc/publicbath` +`kidsfacility`(놀이방 유무 ≠ 아동 입장) · `chkcreditcardfood`(가능/없음 ≠ 결제수단 목록) · `smoking` · `lcnsno` +`roomsize1`(평 — ㎡와 섞으면 3배 틀린다) · `roombathfacility/tv/cable/internet/refrigerator/toiletries/sofa/table/hairdryer` + +### B. 네이버 지역검색 API · `openapi.naver.com/v1/search/local.json` + +**fact 를 만들지 않는다.** 사업장 후보 검색과 채널 URL 발견에만 쓴다. + +`title`→상호 · `roadAddress`/`address`→주소 · `mapx`/`mapy`→좌표(1e7 스케일) · `category`→업종명 · `link`→**공식 채널 URL 후보** +`telephone`·`description` → **실측 100% 빈 문자열.** 있는 셈 치면 안 된다. + +### C. 카카오 로컬 API · `dapi.kakao.com` *(키 미설정 — 현재 미사용)* + +`id`→kakao_place_id · `place_name` · `road_address_name` · `address_name` · `phone` · `x`/`y`→좌표 · `category_name` · `place_url` +행정구역: `code` · `region_1~3depth_name` · `region_type` → **지역 콘텐츠 캐시 키** + +### D. 네이버 플레이스 크롤링 · `m.place.naver.com` `__APOLLO_STATE__` + +> ⚠️ robots.txt `Disallow: /` 위반 상태. **출처를 밝힐 수 없어 GEO 가치가 없다.** 대조용으로만 남긴다. + +`description`/`microReviews` → **intro** · `Naverhotel3HotelData.checkInStr/checkOutStr` → **check_in_time/check_out_time** +`BusinessHour*` → **business_hours · operating_hours · reception_hours** +`conveniences` + `InformationFacilities*` → **parking wifi bbq_available cooking_allowed breakfast pet_allowed pickup_service baby_amenities has_aircon terrace takeout delivery power_outlet wheelchair_accessible** +`Menu:*` → **room_type**(단위) · `PlaceDetailTopPhotoItem*` → 사진 + +### E. 사장님 자체 홈페이지 · `static_html` 어댑터 *(사장님 확정 URL 한정, robots 준수)* + +**① JSON-LD(schema.org) / OpenGraph 직접 매핑** +`description`/`og:description` → **intro** · `openingHours(Specification)` → **business_hours 등** +`checkinTime`/`checkoutTime` → **check_in_time/check_out_time** · `priceRange` → **price_range** · `paymentAccepted` → **payment_methods** +`petsAllowed` → **pet_allowed** · `smokingAllowed` → **smoking** +`hasMenu.hasMenuItem` → **menu_name · menu_price · menu_intro**(단위) +`amenityFeature` → 편의시설 bool 15종 · `image`/`og:image` → 사진 + +**② Gemini 추출** — ①로 안 잡히면 본문 텍스트에서 **업종 스키마 전 필드**를 뽑는다(근거 원문 대조 통과분만) + +### F. 사장님 붙여넣기 텍스트 · `gemini_extract` + +원문 문자열 하나 → **업종 스키마 전 필드.** E-②와 같은 엔진, 입력만 다르다. + +### G. Perplexity Sonar + +**채널 URL 후보만** (`title`, `url`). ★ 응답 본문의 영업시간·가격 같은 정보는 **쓰지 않는다.** + +### H·I. Gemini + +| | 산출 | +|---|---| +| Vision | `ref` · `label`(업종별 사진 라벨) · `alt_text` · `confidence` | +| Text | `intro` · `meta_description` · FAQ(question/answer/fact_keys) — **확보된 fact 로만** | + +### J·K. 지역 콘텐츠 (사업장 fact 아님 — 주변 정보 블록용) + +| API | 산출 | +|---|---| +| Open-Meteo `api.open-meteo.com/v1/forecast` | `temperature` `weather_code` `wind_speed` `observed_at` `timezone` | +| 공공데이터포털 축제 `tn_pubr_public_cltur_fstvl_api` | `title` `eventstartdate` `eventenddate` `mapx/mapy` `tel` `homepage` `organizer` `overview` | + +--- + +## 9. `DECISIONS.md` 미결 항목에 대한 답 + +### 1-1. OTA·플레이스 크롤링의 약관·법적 검토 → **결론 가능** + +| 대상 | 판정 | 근거 | +|---|---|---| +| 야놀자·여기어때 | **불가** | Cloudflare 403 실측 + 민사 10억 배상 선례. 기술적으로도 법적으로도 막혔다 | +| 네이버 플레이스 | **robots.txt 기준 불허** | `Disallow: /` 실측. 기능은 되지만 준수 상태가 아니다 | +| 카카오맵 | **불가** | 내부 API 406 차단 | +| 사장님 확정 URL(자체 홈페이지) | **가능** | 사장님 동의 기반. `StaticHtmlAdapter` 등록 권고 | + +→ **폴백 3단계(① 공식 API → ② 사장님 직접 붙여넣기 → ③ 최소 정보 생성 + 보완 요청)로 간다**는 기존 설계가 맞았다. 이번 조사는 ①의 실체를 TourAPI·LOCALDATA로 특정한 것이다. + +### 1-2. 크롤링 이미지 재게시 권리 → **회피 경로 확보** + +권리 관계를 다투는 대신 **입력원을 바꾸면 문제가 사라진다.** +- 인스타그램 Graph API (사장님 OAuth) → 저작권자 = 사장님 +- 사장님 직접 업로드 → 동일 +- TourAPI 이미지 → 공공누리 + +`media.source_type`(owner/crawl) 컬럼이 이미 있으므로, 발행 시 `CRAWL` 제외 전환은 준비되어 있다. + +--- + +## 10. 확인하지 못한 것 + +- **TourAPI `detailIntro2` 실제 응답 필드** — 403이라 미확인. 활용신청 후 실측 필요. §6의 필드 목록은 공개 문서 기준 추정치다. +- **업종별 link 충전율 표본이 25건씩**이라 통계적 신뢰구간이 넓다. 방향성 판단용으로만 사용할 것. +- **GBP 국내 소상공인 실제 관리율** — 정량 자료를 찾지 못했다. 도입 전 표본 조사 필요. +- **TourAPI 음식점(39) 커버리지** — 관광지 인근 위주라 도심 일반 음식점 커버리지가 낮을 것으로 보이나 미측정. diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md new file mode 100644 index 0000000..7c5a458 --- /dev/null +++ b/docs/DECISIONS.md @@ -0,0 +1,176 @@ +# DECISIONS + +미결 사항과, 코드가 그 미결을 어떻게 격리해 두고 있는지를 적는다. +**결론이 나면 여기에 날짜와 함께 결론을 적고, 해당 플래그/어댑터를 제거한다.** + +--- + +## 1. 미결 — 결론 전까지 코드로 풀지 않는다 + +### 1-1. 야놀자·여기어때·네이버 플레이스 크롤링의 약관·법적 검토 + +**결론 (2026-08-28) — `docs/DATA_SOURCE_RESEARCH.md` 실측 기준.** 아래 원안은 이력으로 남긴다. + +| 대상 | 판정 | 근거 | +|---|---|---| +| 야놀자 · 여기어때 | **불가** | 풀 브라우저 헤더로도 HTTP 403 + Cloudflare 챌린지. 뚫으려면 봇 탐지 우회가 필요한데 그건 영구 금지 영역이다. 법적으로도 야놀자 v 여기어때 = 형사 무죄(대법원 2022-05-12)지만 **민사 10억 배상 + 복제·저장 금지**(서울중앙지법 2021-08). 우리는 재게시까지 하므로 노출이 더 크다 | +| 네이버 플레이스 | **robots.txt 기준 불허** | `m.place.naver.com/robots.txt` = `User-agent: * / Disallow: /`. 현재 `naver_place` 어댑터는 위반 상태로 동작 중이다. 사장님 본인 업소 1건·사장님 동의·대량 DB 복제 아님이라 야놀자 사건과는 양상이 다르지만, **이 위에 제품을 세우지 않는다** — 대체 소스가 붙는 대로 발행 payload에서 빼고 대조용 참고값으로 내린다 | +| 카카오맵 | **불가** | 상세는 SPA 셸(3.6KB), 내부 API 406 차단 | +| **사장님이 확정한 자체 홈페이지** | **가능** | 사장님 동의 기반. → `StaticHtmlAdapter` 등록(2026-08-28) | + +부수 결론: **네이버·카카오 생태계는 AI 크롤러를 전면 차단**한다(플레이스·지도·블로그·예약·카카오맵 모두 `Disallow: /`). 즉 그 데이터를 긁어와도 AI 검색에는 원래 없던 정보라 GEO 이득이 없고, 출처를 밝힐 수 없어 `llms.txt`·`AnswerBlock`의 "출처와 검증 시각" 신호도 못 채운다. 공공데이터(TourAPI·LOCALDATA)가 그 자리를 대신한다. + +| 항목 | 내용 (원안) | +|---|---| +| 상태 | ~~미결~~ → **결론남 (2026-08-28)** | +| 필요한 결론 | 각 사이트의 이용약관·robots.txt 기준으로 자동 수집이 허용되는 범위 | +| 코드 격리 | `collector` 는 어댑터 패턴. ~~Phase 1 은 `MockAdapter` 만 등록~~ → **2026-08-28: `StaticHtmlAdapter` 등록 완료**(사장님 확정 URL 한정, robots.txt 준수, 플랫폼 호스트는 `_DENY_HOSTS` 로 구조적 차단). `HeadlessAdapter`(Playwright)는 **등록하지 않는다** — Cloudflare 를 뚫는 용도가 되므로 금지 항목과 구분되지 않는다 | +| 결론이 "불가"일 때 | 폴백 3단계로 간다 — ① 공식 API → ② 사장님이 직접 붙여넣기 → ③ 최소 정보로 생성 + 보완 요청. **생성 자체는 실패시키지 않는다** | +| 확정 사항 | 캡차 우회 · 봇 탐지 우회 · IP 회전은 **결론과 무관하게 금지**. 구현하지 않는다 | + +### 1-2. 크롤링한 **이미지**의 재게시 권리 + +| 항목 | 내용 | +|---|---| +| 상태 | **미결** | +| 필요한 결론 | OTA/플레이스에 올라간 사진을 우리가 만든 홈페이지에 다시 게시할 수 있는가 (저작권자 = 사장님인가 OTA인가) | +| 파급 | **막히면 사진 입력원이 "크롤링" → "사장님 업로드"로 바뀌고, Gemini Vision 단계의 입력 자체가 달라진다.** 분류·alt 생성 로직은 같아도 수집 경로가 통째로 교체됨 | +| 코드 격리 | 사진은 `media` 로 들어오되 **출처(`source_type`)를 반드시 남긴다**(`crawl` / `owner`). 발행 시 `source_type` 로 필터링할 수 있어야 한다 | +| 대기 중 | 파일 업로드 경로(Azure Blob 클라이언트)는 원본 보일러플레이트에 있으나 **아직 복사하지 않았다.** 이 결론이 난 뒤 media 모듈과 함께 이식한다 | +| 반영됨 (2026-08-26) | `place.media` 에 `source_type`(owner/crawl)과 `origin_url` 을 NOT NULL / 보존 컬럼으로 두었다. 결론이 "불가"로 나면 발행 시 `source_type = CRAWL` 을 통째로 제외하는 것으로 대응 가능하다 | + +### 1-3. 관리자에서 수정 허용 범위 + +| 항목 | 내용 | +|---|---| +| 상태 | **미결** | +| 필요한 결론 | 사장님이 직접 고칠 수 있는 fact 의 범위. 특히 체크인·취사·반려동물·취소 규정처럼 **틀리면 예약 클레임이 나는 항목**을 자유 입력으로 열 것인가 | +| 확정 사항 | 수정한 값은 **잠긴다**(`status = CORRECTED`). 자동 갱신이 사장님 수정본을 덮어쓰지 않는다 | +| 코드 격리 | fact 상태 전이에서 `CORRECTED` 는 자동 수집(`api`/`crawl`/`llm`)이 갱신할 수 없는 종착 상태로 둔다 | +| 반영됨 (2026-08-26) | `LOCKED_FACT_STATUSES = {CORRECTED}` · `FACT_STATUS_TRANSITIONS[CORRECTED] = {CORRECTED, REJECTED}` — 자동 갱신 경로(UNVERIFIED·VERIFIED)로 돌아갈 수 없다. `tests/test_fact_schema.py` 가 이 규칙을 고정한다 | +| 남은 결정 | **어떤 필드까지 자유 입력을 허용할 것인가.** 업종 스키마의 `critical: true` 필드가 후보 목록이다 — 숙박 14 / 카페 12 / 음식점 15 / 관광체험 17개 | + +### 1-4. 해지 시 사이트 처리 정책 + +| 항목 | 내용 | +|---|---| +| 상태 | **미결** | +| 필요한 결론 | 해지하면 사이트를 즉시 내리는가 / 유예를 두는가 / 도메인은 어떻게 되는가. AI 검색이 이미 색인한 페이지를 갑자기 404 로 만들면 그 자리를 다시 OTA 가 가져간다 | +| 코드 격리 | `site` 에 발행 상태를 두고, 해지 처리는 **삭제가 아니라 상태 전이**로만 구현한다. 물리 삭제 경로를 만들지 않는다 | +| 반영됨 (2026-08-26) | `SiteStatus.SUSPENDED`(해지 유예 — 페이지 살아 있음) / `UNPUBLISHED`(내림)를 분리했다. `PublishAction.SUSPEND`·`RESUME` 으로 `publish_logs` 에 남는다. 유예 기간 길이만 정하면 된다 | + +--- + +## 2. 이식하면서 내린 결정 (2026-08-26) + +원본: `o2o-negosium/negodata/backend` 보일러플레이트. + +| 항목 | 결정 | 이유 | +|---|---|---| +| 레이어 구조 | 원본 그대로 — `router` → `service` → `crud`, 람다 DB 실행, `Req_*`/`Res_*` 프로토콜, `RemoveNoneResponse` | "기존 컨벤션을 그대로 따른다" | +| 포트 | **9800** | negosium 9300 / negodata 9400 / agent 9500 / lps 9600 / anchoring 9700 다음 번호 | +| DB | `o2o_site_db` (테스트 `o2o_site_test_db`), 기존 로컬 postgres(`negosium-db` 컨테이너, 5432) 안의 **별도 database** | 원본과 같은 인스턴스·다른 DB. 스키마 네임스페이스 컨벤션 유지 | +| 마이그레이션 | Alembic 안 씀. `postgres-init/init-data/init.sql`(전체 DDL, 재실행 안전) + `postgres-init/alters/YYYY-MM-DD-<주제>.sql`(누적 ALTER) | 원본 방식 그대로 | +| 남긴 것 | config 로더 · 로거 · 싱글톤 · DB 세션 매니저(R/W 분리) · gmodel · gtime · authz · JWT/bcrypt dependencies · `company.companies`/`company.users` · auth 라우터 · 스케줄러 껍데기 · conftest(테스트 DB 자동 생성/삭제) | 전 모듈이 공통으로 쓰는 인프라. 인증은 places·facts·sites 전부가 `IsValidAccessToken` 에 의존한다 | +| 뺀 것 | quotation · supplier · item · card · dashboard · statistics · learning · renegotiation · landing · admin · notification · LPS 연동 · anchoring · 초청메일(ACS/SMTP) · Azure Blob 클라이언트 | negodata 고유 도메인. Blob 클라이언트만 1-2 결론 후 media 모듈과 함께 재이식 예정 | +| `companies` 테이블 유지 | 유지 | 보일러플레이트의 멀티테넌트 스코프 키(`UserInfo.company_id`)가 전 계층에 박혀 있다. 대행사/운영사 단위로 그대로 쓴다 | +| ErrorType 구간 | 계정 = 1100. 도메인 구간 예약 — places 1200 / facts 1300 / collector 1400 / generator 1500 / local 1600 / sites 1700 / reports 1800 | 원본이 구간을 나눠 쓰는 방식 유지 | +| 외부 API 키 | `[ExternalApiConfig]` 로 toml + env override. **키가 비면 해당 어댑터만 비활성, 서버는 그대로 뜬다** | 부팅이 외부 계약에 묶이면 안 됨 | +| 백그라운드 작업 | 원본에 전용 작업 큐 없음(APScheduler 크론만). 수집·비전분석·빌드는 몇 분 걸리므로 **큐를 새로 얹어야 한다** — 방식 미정 | 원본에 없는 것이라 팀 컨벤션 확인 필요. 아래 3번 참고 | + +--- + +## 3. 다음 단계에서 정해야 할 것 (법무 이슈 아님) + +- **작업 큐 구현 방식.** 원본 보일러플레이트엔 APScheduler 크론만 있고 작업 큐가 없다. + 수집 + 비전 분석 + 빌드는 동기 요청으로 처리할 수 없다(몇 분). 후보: DB 테이블 기반 잡 큐(추가 인프라 0) / Celery + Redis / arq. + → **DB 잡 테이블 + 상태 폴링 API** 를 기본안으로 제안. 완료 시 알림톡. +- **TourAPI areaCode ↔ 카카오 행정구역 코드 매핑 테이블.** 두 체계가 다르므로 매핑을 데이터로 관리할지 코드로 박을지. +- **지역 정보 캐시 TTL.** 행정구역 코드 단위 캐싱은 확정. 날씨/축제/관광지 각각의 갱신 주기만 정하면 된다. + +--- + +## 4. Phase 2 에서 내린 결정 (2026-08-26) + +작업 순서 2번 — 4개 업종 스키마 정의 + 마이그레이션. + +| 항목 | 결정 | 이유 | +|---|---|---| +| 업종 스키마 위치 | `common/category_schema/resources/*.json` + 로더 | 원본의 `common/anchoring/resources/` 패턴 그대로. **업종 추가 = 파일 1개 + enum 1줄** | +| fact 저장 | key-value (`facts.key` / `value` / `unit`) | 업종마다 필드가 완전히 달라 컬럼으로 못 편다 | +| 활성 fact 유니크 | `(place_id, unit_id, key)` 당 1건. **`REJECTED`·`EXPIRED` 는 제외** | 같은 항목에 두 값이 동시 노출되는 것을 DB 가 막는다. 틀린 값·만료 값은 이력으로 남겨야 하므로 유니크에서 뺀다 | +| 유니크 인덱스 2분할 | `unit_id IS NULL` / `IS NOT NULL` 로 나눠 건다 | Postgres 에서 NULL 끼리는 유니크가 안 걸린다. 나누지 않으면 사업장 단위 fact 가 중복된다 | +| `critical` 플래그 | 업종 스키마 필드 속성으로 도입 | 절대규칙 1(미검증 fact 노출 금지)의 대상 목록이 코드가 아니라 데이터에 있어야 업종 추가 시 자동으로 따라온다 | +| `allow_llm` 플래그 | 기본 `False`. `True` 는 소개문 계열 2개뿐 | 절대규칙 7(LLM 은 사실을 만들지 않는다)을 스키마 레벨에서 강제. 테스트가 `required` 필드의 `allow_llm=True` 를 금지한다 | +| 지역 정보 캐시 키 | `local_contents.region_code` (place_id 아님) | 같은 지역에 사이트 50개가 생겨도 외부 조회는 1회. 카카오 키워드 검색이 좌표 변환보다 4배 비싸다 | +| 스키마 네임스페이스 | `place` / `fact` / `local` / `site` | 원본의 도메인별 schema 컨벤션. `local` 은 Postgres 비예약어라 그대로 쓸 수 있다(확인함) | +| 테이블명 | 복수형 (`places`, `facts`) | 원본이 복수형(`companies`, `users`, `quotations`). 스펙 문서의 단수 표기는 엔티티 이름으로 읽었다 | +| `server_default` | 신규 도메인 테이블에만 추가 | ORM `default=` 는 Python 쪽이라 raw INSERT 에 안 먹는다. `create_all`(테스트 DB)과 `init.sql`(실 DB)이 갈라져서 실제로 버그가 났다. **`companies`/`users` 는 원본 그대로 두었다** | +| ORM ↔ init.sql 정합성 | `tests/test_schema_ddl.py` 가 파일을 파싱해 대조 | 스키마 정의가 두 곳에 있는 구조(원본 컨벤션)라, 드리프트를 테스트로 막는다 | +| 외부 API 키 주입 | 레포 최상위 `.env` + `python-dotenv` | 우선순위 = 실제 환경변수 > `.env` > toml. **`APP_ENV=test` 면 `.env` 를 읽지 않는다** — 실키가 새면 테스트가 외부 API 를 때리고 요금이 나간다 | +| 키 출처 | Perplexity·Gemini 는 `o2o-infinith-backend/.env` 값 재사용. 카카오·TourAPI 는 **미발급** | 사내 어디에도 카카오/TourAPI 키가 없다. 발급 후 `.env` 에 채워야 6번 단계가 돈다 | + +### 아직 테이블이 없는 것 + +- **`report` 스키마** — 노출 리포트·유입 통계(GA4 Data API, Search Console API). 작업 순서 6번 이후. +- **작업 큐** — 아래 3번의 미결 사항. 수집·비전분석·빌드를 담을 잡 테이블이 아직 없다. +- **TourAPI areaCode ↔ 카카오 행정구역 코드 매핑** — 테이블 대신 `common/category_schema` 와 같은 리소스 JSON 으로 두는 것을 제안. 3번 참고. + +--- + +## 5. Phase 3 에서 내린 결정 (2026-08-27) + +작업 순서 3번 — places · facts API(검증 상태 전이) + 작업 큐. + +### 5-1. fact 를 '노출값 1건 + 후보 N건' 으로 바꿨다 + +처음엔 활성 유니크를 `status IN (1,2,3,4)` 로 걸었다. 재수집(업데이트)을 넣어 보니 세 가지가 깨졌다 — +실제로 돌려서 확인한 결과다: + +| 상황 | 깨진 것 | +|---|---| +| 값이 그대로인데 재수집 | 검증(VERIFIED)이 초기화돼 사이트에서 사실이 사라졌다 | +| 값이 바뀐 재수집 | 확인된 노출값이 즉시 밀려나 사이트가 비었다 | +| 정정본(CORRECTED)에 재수집 | `FACT_LOCKED` 로 크롤링 값을 통째로 버려 OTA 불일치 신호가 사라졌다 | + +원인은 하나 — **유니크가 "노출값"과 "새로 들어온 값"을 동시에 못 갖게 막고 있었다.** + +**결정: 유니크를 노출 상태(VERIFIED·CORRECTED)에만 건다.** + +``` +노출값 VERIFIED / CORRECTED (place, unit, key) 당 1건 ← 사이트에 나감 +후보 UNVERIFIED / PENDING_OWNER 여러 건 공존 ← 재수집이 쌓임 +이력 REJECTED / EXPIRED +``` + +이걸로 세 프로세스가 분리됐다. + +| 프로세스 | 동작 | outcome | +|---|---|---| +| 생성 | 자동 수집 → 후보 → 사람 승인 → 노출 | `CANDIDATE_CREATED` | +| 업데이트(값 같음) | 검증 유지, 확인 시각만 갱신 | `REFRESHED` | +| 업데이트(값 다름) | **노출값 유지** + 후보 적재 | `CANDIDATE_CREATED` | +| 승인 | 후보 → 노출값, 옛 값 EXPIRED | `PUBLISHED_REPLACED` | +| 수정(사람 직접) | 즉시 노출값 교체 | `PUBLISHED_REPLACED` | + +마이그레이션: `postgres-init/alters/2026-08-27-fact-candidate-model.sql` + +### 5-2. 그 밖의 결정 + +| 항목 | 결정 | 이유 | +|---|---|---| +| 사람 직접 입력 | 즉시 노출값(VERIFIED)으로 들어간다 | 넣은 사람이 곧 출처이자 책임 주체다. 입력→확인 2단계로 만들면 실무에서 안 쓴다. 검수 게이트의 실제 목적은 **자동 수집**을 거르는 것 | +| 정정본 잠금의 의미 | "덮어쓰기 금지"이지 "기록 금지"가 아니다 | 크롤링 값을 버리면 OTA 가 아직 다른 값이라는 신호를 잃는다. 후보로 남겨 사람이 본다 | +| `places.content_updated_at` | 노출값이 **실제로 바뀔 때만** 찍는다 | 개별 재빌드 대상 판별(`site_versions.built_at < content_updated_at`). 후보만 쌓였을 땐 안 찍힌다 — 사이트 내용이 안 바뀌었으니 재빌드가 불필요 | +| 작업 큐 | LPS(`o2o-negosium/lps`)의 `job` 큐를 그대로 이식 | 사내 선례이고 도커에서 검증된 구조. 원자적 claim(`FOR UPDATE SKIP LOCKED`) + lease 소유권 + dedupe + dead-letter. Redis/Celery 를 안 쓰는 이유는 운영 컴포넌트가 늘면 장애 지점이 늘기 때문 | +| 큐 세션 진입점 | `DB_SESSION_MNG.execute_lambda_write` 를 새로 추가 | 큐 전이는 `UPDATE ... RETURNING` 이라 조회/변경을 못 나눈다. 기존 `execute_lambda_run`(ErrorType만) / `execute_lambda_claim`(rowcount만) 로는 값을 못 받는다 | +| `jobs.job_id` server_default | 이 테이블만 PK 에 `gen_random_uuid()` 를 건다 | 큐만 raw SQL 로 INSERT 해서 ORM 의 Python default 가 안 먹는다. `create_all`(테스트 DB)과 `init.sql`(실 DB)이 갈라져 실제로 버그가 났다 | +| 수집 중복 방지 | `dedupe_key = "collect:{place_id}"` | 사업장당 활성 수집 잡 1건. 버튼을 두 번 눌러도 두 번 돌지 않는다 | + +### 5-3. 아직 안 한 것 + +- **`검색어 → URL 발견 → 크롤링 → 에셋` 체인은 아직 안 돈다.** 작업순서 4번(collector). + 지금은 URL 을 **받아서** 저장하는 그릇만 있다(Perplexity 자동 호출 없음). +- 사진(`place.media`)은 테이블만 있고 업로드·저장 경로가 없다. 이미지 재게시 권리(1-2)가 미결이라 + Azure Blob 클라이언트를 일부러 아직 이식하지 않았다. +- 카카오 REST API 키 / TourAPI 키가 사내 어디에도 없다. 발급해서 `.env` 에 채워야 실제 연동이 돈다. diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md new file mode 100644 index 0000000..460a5fe --- /dev/null +++ b/docs/DEPLOY.md @@ -0,0 +1,180 @@ +# 배포 · 스토리지 + +> **현재 결정 (2026-08-31): 발행 사이트는 서버 안에서 nginx 가 정적 서빙한다.** +> Azure Blob 은 코드에 있으나 **켜지 않는다**(`AZURE_STORAGE_CONNECTION_STRING` 비움). +> 클라우드는 고도화 때 붙인다 — 근거는 [ARCHITECTURE.md 3절](ARCHITECTURE.md). +> 이 문서의 **3절이 지금 밟는 절차**이고, **4절은 나중에 켤 때** 본다. + +## 1. 산출물을 어디에 둘 것인가 + +역할이 셋인데 하나로 묶어 생각하면 헷갈린다. **원본 / 작업공간 / 배달**을 나눈다. + +| 층 | 무엇 | 어디 | 잃어버리면 | +|---|---|---|---| +| 원본 | DB (`site_versions.snapshot`) + `out/payloads/*.json` | PostgreSQL + 서버 디스크 | 진짜 손실. 백업 대상은 **여기뿐** | +| 작업공간 · 배달 | `out/` 정적 트리 | Docker named volume `site-out` (nginx 가 읽는다) | 괜찮다 — payload 로 다시 굽는다 | +| 배달(백업) | 같은 파일의 사본 | Azure Blob `$web` | 다시 올리면 된다 | + +**결론: 공개 서빙은 nginx 가 맡는다(2026-08-31 결정).** 파일이 이미 `site-out` 볼륨에 있는데 +Blob 으로 보냈다가 되받아 오면 요청마다 왕복이 하나 더 붙고, Blob 은 커스텀 도메인 TLS 도 못 붙여 +CDN 을 억지로 끼워야 한다. `azure_static.py` 의 업로드는 **배달 백업**으로 남긴다 — +웹서버를 여러 대로 늘릴 때 다시 볼 문제다. + +### 트래픽은 클라우드가 더 걸리지 않는다 + +방문자가 받는 바이트는 어디서 주든 똑같다. 달라지는 건 **누가 그 비용을 어떤 형태로 내는가**다. + +- 서버 직접 서빙: 대역폭은 보통 VM 요금에 포함(무료처럼 보인다). 대신 CPU·가용성·TLS 갱신· + 캐시 헤더·장애 시 전 사이트 동시 다운을 우리가 떠안는다. +- Blob+CDN: egress 를 GB 단위로 낸다. 대신 서버가 트래픽을 아예 안 받는다. + +실측 기준 1회 방문 바이트: + +``` +첫 방문 HTML 50~100KB + CSS 35KB + JS 320KB ≈ 420KB +재방문 HTML 만 (assets 는 immutable 1년 캐시) ≈ 60KB, 대개 304 +이미지 0KB ← 네이버 CDN 이 대신 낸다 +``` + +사이트 1,000개 × 월 100뷰 = 월 10만 PV ≈ **월 24GB**. Azure 무료 egress 한도(월 100GB) 안이다. +즉 **지금 규모에서 트래픽 비용은 판단 근거가 아니다.** 운영 편의로 고르면 된다. + +⚠️ 단, 이미지를 `pstatic.net` 에서 핫링크하고 있다. 우리 트래픽 비용을 0으로 만드는 대신 +네이버가 referer 차단하거나 이미지를 내리면 **전 사이트가 동시에 깨진다.** 발행 시점에 +이미지를 우리 Blob 으로 복사해 두는 게 중기 과제다. + +### 사이트 하나에 들어가는 파일 + +2026-08-31 부터 사이트는 **한 장**이다(라우터 없음). 사이트당 30개 안팎이던 HTML 이 둘로 줄었다. + +``` +site-out/ + assets/ 공용 번들(전 사이트 공유) robots.txt 크롤러가 읽는 유일한 자리 + fonts/ 공용 sitemap.xml 전 사이트 URL 한 파일 + s//index.html 사이트 전체 + s//llms.txt 확인된 사실 목록(AEO) +``` + +사이트별 `sitemap.xml`·`robots.txt` 는 없앴다 — 한 장짜리의 사이트맵은 URL 이 하나뿐이고, +`/s//robots.txt` 는 애초에 아무도 읽지 않는다(RFC 9309: 오리진 루트만). + +## 2. CSS 주소는 불변이 아니다 + +`/assets/index-DvNTmLhy.css` 의 해시는 **렌더러 CSS 가 바뀌면 바뀐다.** 프리렌더가 +`dist/client/.vite/manifest.json` 을 읽어 HTML 에 박으므로 새로 굽는 HTML 은 항상 맞다. +문제는 **이미 구워져 올라간 HTML** 이다. + +``` +프론트 수정 → 새 번들(새 해시) + 로컬 out/assets : 통째로 교체 (옛 해시 삭제) ← 재굽기 안 한 사이트는 CSS 404 + Azure : 새 해시 추가, 옛 해시 유지 ← 안 깨지지만 옛 디자인 그대로 박제 +``` + +프리렌더 컨테이너는 **기동할 때 payload 전체를 다시 굽는다.** 그래서 로컬 out/ 은 재시작만 +하면 정합이 맞는다. 하지만 Azure 는 발행 잡이 도는 사이트 하나씩만 올린다 — 그 짝을 맞추는 게 +`backend/scripts/republish_all.py` 다. + +**규칙: `frontend/site` 를 배포하면 반드시 전체 재굽기 + 전체 재업로드.** + +```bash +docker compose restart web # 기동하며 전체 재굽기 +docker compose logs -f web # "[watch] 기동" 배치가 끝날 때까지 대기 +docker compose exec worker python scripts/republish_all.py +``` + +## 3. 서버에 올리는 순서 (지금 밟는 경로) + +굽는 것과 서빙하는 것을 **한 번에 바꾸지 않는다.** 깨졌을 때 어느 쪽인지 못 가린다. + +### 0단계 — 도메인부터 정한다 (코드가 하드코딩이라 먼저다) +발행 호스트는 **백엔드·프론트 두 곳**에 있고 값이 같아야 한다. + +| 어디 | 무엇 | 기본값 | +|---|---|---| +| 백엔드 | `SITE_PUBLIC_HOST` (`site_payload.py`) | `w4ai.o2o.kr` | +| 프론트(admin) | `VITE_PUBLISH_HOST` | 없으면 현재 브라우저 호스트 | + +이 값이 canonical·og:url·sitemap·IndexNow 통보에 전부 들어간다. 다른 주소에 올릴 거면 +`SITE_PUBLIC_HOST` 를 먼저 덮는다. 안 고치면 발행은 성공하는데 사이트맵과 색인 통보가 +존재하지 않는 주소를 가리킨다 — **조용히 틀리는 종류라 아무도 눈치채지 못한다.** + +★ `origin` 은 payload JSON 에 **구워져 들어간다**(`out/payloads/.json`). 호스트를 바꾼 뒤 + 프리렌더만 다시 돌리면 옛 주소가 그대로 나온다. 반드시 **백엔드에서 재발행**해 payload 를 + 다시 만들어야 한다. + +### 1단계 — 서버에서 "굽기"만 재현 (Azure 끔) +```bash +# 서버에서 +cp .env.example .env # DB_*, JWT_*, 외부 API 키 채우기 +# AZURE_STORAGE_CONNECTION_STRING 은 비워 둔다 ← 이번 단계에서는 안 올린다 +# INDEXNOW_KEY 도 비워 둔다 ← 없는 주소를 색인 통보하지 않는다 +docker compose up -d +docker compose logs -f worker +``` +확인: 사이트 1개 발행 → `curl -I http://<서버>:3000/s/` 200 · +`out/s//index.html` 생성 · `out/payloads/.status/.json` 의 `ok: true`. + +여기서 막히면 Azure 문제가 아니다. **DB 연결 / payload 디렉토리 마운트 / node_modules** 셋 중 하나다. + +### 2단계 — 정적 서빙을 nginx 로 교체 (구현됨) +`serve-sites.mjs` 는 개발용이다. 운영은 `o2o-web4ai-nginx` 컨테이너가 맡는다(`nginx/site.conf`). + +★ **산출물은 named volume `site-out` 에 있다.** 프리렌더가 쓰고 nginx·워커가 읽는다. + 호스트 경로가 등장하지 않으므로 재배포로 코드를 갈아엎어도 사이트가 죽지 않는다. + `docker compose down` 으로는 안 지워진다 — `down -v` 만 지운다. + +```bash +docker compose up -d # nginx 포함 전부 +docker compose exec nginx ls /usr/share/nginx/html/s # 들여다볼 때 +``` + +확인은 스크립트가 한다. 색인을 기다리지 않고 **지금 볼 수 있는 것만** 본다 — +파일이 그 자리에 있는지, JSON-LD 가 HTML 소스에 들어 있는지, +그리고 **크롤러 UA 로 받았을 때 200 이 나오는지**(CDN·WAF 가 봇을 막는 설정이 기본값인 경우가 있는데 +브라우저로는 절대 안 보인다). + +```bash +docker compose exec worker python scripts/check_search_ready.py https://<도메인> +``` + +`/s/` (끝 슬래시 없음)이 열리는지도 이 스크립트가 본다 — 사장님이 주소창에 치는 형태가 그거다. + +### 2-1단계 — TLS +`nginx/site.conf` 에 443 과 인증서 볼륨을 추가한다. Blob 단독으로는 커스텀 도메인 TLS 가 +안 되지만 nginx 는 Let's Encrypt 로 끝난다 — CDN 을 억지로 끼울 이유가 없다. + +--- + +## 4. 나중에 — Azure Blob 을 켤 때 + +**언제 켜나:** 실사용 고객이 붙어 "서버 하나가 죽으면 전 사이트가 동시에 내려간다"를 +더는 감수할 수 없을 때. 그 전에는 켜지 않는다 ([ARCHITECTURE.md 3절](ARCHITECTURE.md)). + +### 4-1단계 — Azure Blob 붙이기 +```bash +# 접두사 함정: HTML 이 /assets/… 를 루트 절대경로로 가리킨다. +# CDN 오리진 경로를 세팅하기 전까지는 접두사를 비운다. +AZURE_STORAGE_CONNECTION_STRING=<연결문자열> +AZURE_STORAGE_CONTAINER='$web' +AZURE_STORAGE_PREFIX= +``` +```bash +docker compose exec worker python scripts/republish_all.py --dry-run # 대상 확인 +docker compose exec worker python scripts/republish_all.py # 전체 업로드 +``` +확인: `https://.z*.web.core.windows.net/s/` 가 **CSS 까지 입혀서** 뜨는지. +스타일이 없으면 접두사/경로 문제다(2절 참고). + +### 4-2단계 — 도메인 · TLS · 색인 +1. DNS 를 Blob 정적 웹사이트(또는 앞단 CDN)로 연결 +2. HTTPS 확인 — 커스텀 도메인 + TLS 는 Blob 단독으로는 안 되고 CDN/Front Door 가 필요하다 +3. `DEFAULT_HOST` 가 실제 도메인과 같은지 재확인 → 다르면 고치고 **전체 재발행** +4. 그 다음에야 `INDEXNOW_KEY` 를 채운다. 백엔드와 `o2o-web4ai-web` 이 **같은 값**이어야 한다 + (프리렌더가 루트에 `.txt` 를 굽고 검색엔진이 대조한다 — 어긋나면 403) +5. `https://<도메인>/.txt` 와 `https://<도메인>/robots.txt` 가 열리는지 확인 +6. 구글은 IndexNow 미지원 → Search Console 에 `https://<도메인>/sitemap.xml` 수동 제출 + +## 5. 되돌리기 +`out/` 은 재생성물이라 백업이 필요 없다. 문제가 생기면 +`docker compose restart web` → 전체 재굽기 → `republish_all.py`. +지켜야 할 건 **DB 와 `out/payloads/`** 뿐이다. diff --git a/docs/DEVELOPMENT_DIRECTION.md b/docs/DEVELOPMENT_DIRECTION.md new file mode 100644 index 0000000..492b284 --- /dev/null +++ b/docs/DEVELOPMENT_DIRECTION.md @@ -0,0 +1,214 @@ +# Web4AI 개발 방향 — v19 설계서와 현재 구현 비교 + +> 기준일: 2026-08-31 +> 비교 대상: `Web4AI_SW설계서_및_개발일정_v19.pdf`(22쪽)와 이 저장소의 현재 코드·문서 +> 목적: 설계서를 그대로 복제하는 것이 아니라, 현재 제품에서 **유지할 결정**, **방향을 다시 정할 결정**, **추가할 개발 항목**을 구분한다. + +설계서 표지는 파일명과 달리 `v18 · 2026.08.30`으로 표기되어 있다. 아래에서는 전달받은 파일을 편의상 “v19 설계서”라고 부르되, 계약·일정 확정 전 문서 버전부터 확인해야 한다. + +--- + +## 1. 결론 + +현재 프로젝트는 설계서 전체의 축소판이 아니라, 설계서의 **Site AEO(A1~A8) 일부를 소상공인용 제품으로 먼저 구현한 별도 MVP**에 가깝다. + +- 현재 강점은 `사업장 확인 → 허용된 소스 수집 → fact 승인 → 근거 기반 문구 생성 → 정적 HTML 발행 → IndexNow`가 실제 코드와 테스트로 연결되어 있다는 점이다. +- 가장 큰 공백은 **Brand AEO 전체(B1~B9)**, **규제 검사(A4)**, **소유권 검증(A1)**, **원본 변경·AI 크롤러 재방문 추적(A9)**이다. +- 가장 큰 방향 충돌은 **타겟 업종**, **Playwright 크롤링**, **배포 도메인**, **마이크로서비스·공통 인프라**다. 이 항목은 “미구현”으로 보고 바로 만들면 안 되고 제품·법무·운영 결정을 먼저 내려야 한다. +- 권장 방향은 현 구조를 버리고 5계층/2엔진으로 즉시 재작성하는 것이 아니다. 현재 시스템을 **Site AEO MVP 기준선**으로 유지하고, Brand AEO를 경계가 분명한 모듈로 붙인 뒤 부하와 조직 규모가 실제 분리를 요구할 때 서비스로 분리한다. + +### 현재 범위의 대략적인 위치 + +| 설계서 영역 | 현재 판단 | +|---|---| +| Site AEO A1~A9 | **부분 구현** — A3·A5·A6·A7 일부와 A8 중심 | +| Brand AEO B1~B9 | **미구현** — 준비도 자체 점수만 있으며 실제 AI 응답 측정은 없음 | +| 운영 콘솔 15개 화면 | **부분 구현** — 사업장·빌더·지역정보·SEO/AEO 준비도 중심 | +| 계약 A~G / BFF | **미구현** — 단일 FastAPI API를 admin이 직접 호출 | +| 25테이블 append-only Fact Graph | **다른 모델로 구현** — 승인 후보/노출값 중심의 key-value fact 모델 | +| 8개 스프린트 일정 | **현재 코드에 바로 적용 불가** — 이미 구현된 것과 방향 충돌 항목이 섞여 있어 재산정 필요 | + +--- + +## 2. 방향이 다른 부분 + +아래는 단순히 덜 만든 기능이 아니라, 설계서와 현재 프로젝트가 서로 다른 결정을 내린 항목이다. + +| 항목 | v19 설계서 | 현재 프로젝트 | 권장 판단 | +|---|---|---|---| +| 제품 범위 | Site AEO + Brand AEO 이원 플랫폼 | 상호명 기반 소상공인 정적 홈페이지 생성·발행 | 현재 제품을 Site AEO MVP로 명시하고 Brand AEO 확장 여부를 별도 마일스톤으로 승인 | +| 1차 업종 | 숙박, 법무법인, 성형외과 | 숙박, 카페, 음식점, 관광체험 | **반드시 사업 결정 필요.** 법률·의료를 넣으면 데이터 스키마뿐 아니라 규제·승인·감사 체계가 선행되어야 함 | +| 입력 방식 | 고객 원본 사이트를 depth 3·최대 200페이지 크롤 | 공식 API, 사용자 확정 URL, 정적 HTML; 플랫폼 우회 수집 금지 | 현재의 출처·동의·robots 원칙 유지. 대규모 원본 사이트 수집은 별도 제품 모드로 분리 | +| 동적 크롤링 | 정적 우선, Playwright 폴백 | 봇 탐지 우회로 변질될 수 있어 HeadlessAdapter 미등록·금지 | 포괄적인 Playwright 폴백은 채택하지 않음. 소유권이 검증된 고객 도메인에만 허용할지 법무·보안 결정 후 제한적으로 검토 | +| 발행 도메인 | 고객 도메인 서브패스 권장, 서브도메인 차선 | 기본 `w4ai.o2o.kr/s/`, custom domain 경로 미완성 | 설계서 방향이 검색 권위 측면에서 더 적합. 고객 도메인 연결·소유권 검증을 우선 과제로 추가 | +| 백엔드 구조 | Site/Brand 엔진, BFF, 엔진별 DB 분리 | 단일 FastAPI + PostgreSQL + admin 직접 호출 | 파일럿 단계에서는 모듈 경계와 API 계약만 먼저 만들고, 물리 분리는 트래픽·팀 소유권 근거가 생긴 뒤 수행 | +| 작업 인프라 | Temporal, Redis, Celery 등 공통 인프라 | PostgreSQL 잡 큐 + lease + dead-letter | 현재 DB 큐 유지. 동일 책임의 인프라를 중복 도입하지 않음. 장기 워크플로 보상·분산 추적 요구가 확인될 때 Temporal 재평가 | +| Fact Graph | 엔티티·predicate·snapshot, append-only | 업종 스키마 기반 key-value fact, 후보/노출/이력 상태 | 현재 모델은 발행 안전성에 적합. Brand 측정 재현성에 필요한 snapshot과 entity 관계만 점진적으로 확장 | +| 점수 | Site AEO Score + 실제 4개 AI 엔진 기반 AVS | 내부 데이터 기반 SEO/AEO **준비도** 점수 | 이름과 의미를 분리 유지. 실제 측정 전 현재 점수를 AVS/가시성 점수라고 부르지 않음 | +| 운영 사용자 | Reviewer/Owner 권한과 15개 통합 화면 | USER/OWNER/DEVELOPER, 사장님 빌더와 운영 화면이 한 앱 | 규제 기능 도입 전 Reviewer 역할·서버 계산 `allowed_actions` 추가. 사장님 앱과 내부 콘솔 분리 계획 수립 | +| 이미지 | 원본 사진·영상이 EEAT 근거 | 이미지 호스팅을 현재 non-goal로 두고 외부 URL 사용 | 저작권 결론과 소유자 업로드 저장소가 먼저. 크롤 이미지 재게시를 전제로 개발하지 않음 | + +--- + +## 3. 설계서 항목별 구현 차이 + +### 3-1. Site AEO A1~A9 + +| 단계 | 현재 상태 | 코드 근거 | 추가할 것 | +|---|---|---|---| +| A1 사이트 진단·소유권 검증 | **일부** | 사업장 동일 업소 확인과 `verified_at`, SEO 진단은 있으나 DNS TXT/meta/well-known 검증은 없음 | 도메인 소유권 challenge, 만료·재검증, 발행 차단 정책 | +| A2 크롤·추출 | **일부** | collector registry, `StaticHtmlAdapter`, TourAPI, 네이버 장소 조회, 사용자 확정 링크 | 허용 도메인용 crawl run/document 기록, 원본 hash, 제한·재시도·수집 보고서 | +| A3 Fact Graph | **부분 구현** | `facts`, 업종 스키마, 출처·신뢰도·상태 전이, 승인 후보 모델 | source URL의 selector/snippet, entity 관계, 측정용 불변 snapshot | +| A4 규제·과장 검사 | **기초만 존재** | 생성 문구의 과장·근거 없는 숫자/시설 검사는 있으나 업종별 법규 3단 분류와 승인 감사는 없음 | 외부화된 규칙, SAFE/REVIEW/BLOCK 판정, 규칙 버전, 근거 snippet, Reviewer 승인 로그 | +| A5 AEO 콘텐츠 생성 | **구현** | Gemini Text, 소개문·meta·FAQ, 근거 fact key, ground check | 질문은행과 생성 페이지의 연결, 질문형 콘텐츠 단위의 버저닝 | +| A6 JSON-LD | **구현** | 업종별 JSON-LD, FAQPage, Breadcrumb, WebPage, sameAs | 법률·의료 도입 시 타입·자격·저자 스키마 확장 | +| A7 3-way 일치성 | **부분 구현** | JSON-LD↔표시 텍스트 검증, 생성문↔fact 근거 검사, publish gate | 원본↔발행본 SimHash 중복도, 모든 사실 문장의 fact ID 역참조 보고서 | +| A8 배포 | **대부분 구현** | 프리렌더 정적 HTML, canonical, sitemap, robots, llms.txt, IndexNow, nginx/Azure 경로 | 고객 도메인 서브패스·서브도메인 연결, TLS/DNS 자동화, Search Console 제출 자동화 여부 | +| A9 모니터링·변경 감지 | **미구현** | `ai_check_results` 테이블과 `AI_CHECK` enum은 있으나 worker handler·보고 모듈 없음 | CDN 크롤러 로그 수집, 원본 hash 비교, fact 만료/재검토, 재생성 큐 | + +### 3-2. Brand AEO B1~B9 + +현재 `seo_audit.py`의 점수는 “발행 준비도”다. 설계서의 Brand AEO처럼 ChatGPT·Gemini·Claude·Perplexity 응답을 정기 호출하여 브랜드 언급·인용·순위·사실성을 측정하지 않는다. + +필요한 기능은 다음 순서가 적절하다. + +1. **B1 질문은행**: 업종×지역×의도 질문, 버전, 활성 세트, 고객 편집 이력 +2. **B2 측정 스케줄**: 주기, 엔진, 반복 횟수, 비용 상한, 중지 조건 +3. **B3~B4 엔진 어댑터와 원문 보존**: 모델·버전·프롬프트·응답·citation 정규화 +4. **B5 분석**: 브랜드 alias 언급, 인용 URL, 추천 위치, 감성, fact snapshot 대조 +5. **B8 이원 점수**: 원계열, 반복 평균, 신뢰구간, MA4를 모두 보존하고 준비도 점수와 별도 표시 +6. **B6~B7 개선 루프**: EEAT 결손과 외부 인용원을 제안하되, 자동 발행하지 않고 fact 확인/A4/A7을 재통과 +7. **B9 리포트**: 주간·월간 리포트, 모델 교체 마커, 비용과 데이터 결손 표시 + +100문항×4엔진×3회라는 설계서 기본값은 테넌트당 주 1,200회 호출이다. 현재 제품 원가 상한인 **사이트당 약 $1**과 충돌할 가능성이 높으므로, 구현 전 모델별 실측 단가와 파일럿 질문 수를 다시 계산해야 한다. 초기에는 10~20개 핵심 질문, 1~2개 엔진, 반복 3회로 시작하고 통계적 유효성과 비용을 함께 측정하는 편이 안전하다. + +### 3-3. 콘솔·계약·데이터 + +- 현재 admin에는 로그인, 사업장 목록/상세, 빌더, 지역 콘텐츠, SEO 진단 등이 있으나 설계서의 질문 빌더·규제 승인·AI 퍼포먼스·랭킹·인용출처·정기 리포트 화면은 없다. +- 프론트는 단일 API를 직접 호출한다. 설계서의 BFF, 서비스 JWT 교환, 섹션별 부분 실패, 계약 A~G는 없다. +- DB에는 현재 17개 ORM 모델이 있으며 설계서의 `document`, `predicate_def`, `entity`, `fact_snapshot`, `compliance_rule`, `review`, `publication_question`, `index_state`, `regeneration_request`, `event_outbox`, `audit_log` 등에 해당하는 완성 모델은 없다. +- 현재 fact는 수정 잠금과 후보 이력을 보존하지만, 설계서가 요구하는 전체 append-only 불변식·스냅샷 재현성 모델과 같지는 않다. + +계약 A~G를 한 번에 33개 REST/7개 이벤트로 만드는 것보다, 먼저 아래 세 계약만 버전 고정하는 것을 권장한다. + +1. `FactSnapshot`: 측정 당시의 발행 사실을 재현할 수 있는 읽기 전용 계약 +2. `QuestionSet`: 생성 대상과 측정 대상을 같은 question ID로 연결하는 계약 +3. `Publication`: 발행 URL과 question ID를 연결해 인용 성과를 귀속하는 계약 + +이 세 계약이 있어야 Brand AEO 결과가 단순한 “브랜드가 나왔다”를 넘어 “어떤 질문을 겨냥한 어떤 페이지가 인용됐다”까지 설명할 수 있다. + +--- + +## 4. 권장 개발 우선순위 + +### P0 — 개발 전에 확정할 결정 + +- **제품 범위**: Site AEO 소상공인 MVP를 유지할지, 법률·의료와 Brand AEO를 이번 제품 범위에 포함할지 +- **1차 파일럿**: Stay 머뭄 1곳 우선인지, 3업종 동시인지 +- **도메인 전략**: 고객 서브패스 / 고객 서브도메인 / 플랫폼 공용 경로의 지원 우선순위 +- **크롤 정책**: 소유권 검증 고객 도메인의 JS 렌더링 허용 범위. 플랫폼 robots·봇 차단 우회 금지는 유지 +- **이미지 권리**: 소유자 업로드만 허용할지, 기존 플랫폼 사진 재게시를 허용할지 +- **비용 예산**: Brand 측정의 테넌트당 주간 호출·금액 상한 +- **문서 버전**: 전달 파일의 파일명 v19와 표지 v18 불일치 해소 + +### P1 — 현재 Site AEO를 설계서 수준으로 닫기 + +1. 도메인 소유권 검증과 만료 시 발행 차단 +2. crawl run/document와 원본 hash 저장 +3. A7 SimHash 중복도 검사 및 fact 역참조 리포트 +4. A9 원본 변경 감지, fact 만료/검토, AI 크롤러 방문 로그 +5. 고객 도메인 연결, TLS/DNS 운영 절차 +6. 관리자/사장님 앱 경계 정리와 서버 계산 `allowed_actions` + +완료 기준은 “페이지가 만들어진다”가 아니라, **소유권이 확인된 원본에서 출처가 남는 fact를 만들고 두 게이트를 통과해 고객 도메인에 발행되며, 변경과 재방문을 관측할 수 있다**는 것이다. + +### P2 — 규제 업종을 넣는 경우에만 선행 + +1. Reviewer 역할과 승인 워크벤치 +2. 외부화된 업종별 규칙과 버전 관리 +3. SAFE / NEEDS_EVIDENCE / PROHIBITED 3단 판정 +4. 규칙 ID·근거 snippet·판정 모델·승인자·시각을 남기는 감사 로그 +5. 성형외과 사전심의 상태와 자격/면허 fact 모델 +6. 법률·의료 전문가의 규칙 승인 및 변경 절차 + +A4가 완성되기 전에는 법무법인·성형외과 콘텐츠 자동 발행을 열지 않는다. + +### P3 — Brand AEO 최소 측정 루프 + +1. 질문은행과 publication-question 연결 +2. fact snapshot +3. 1~2개 AI 엔진 어댑터와 응답 원문·모델 버전 저장 +4. 언급·인용 URL·추천 위치·사실성 분석 +5. 반복 측정, 신뢰구간, MA4, 비용 집계 +6. 읽기 전용 퍼포먼스·인용출처 화면 + +처음부터 자동 EEAT 재생성까지 닫지 말고, 먼저 **같은 질문을 반복 측정했을 때 지표가 의사결정에 쓸 만큼 안정적인지** 검증한다. + +### P4 — 개선 폐루프와 운영 확장 + +- EEAT 결손 → 고객 확인 요청 / 재생성 요청 분기 +- 재생성 요청의 A4·A7 재통과 +- 정기 리포트와 외부 채널 전략 +- BFF의 섹션별 부분 실패와 서비스 JWT +- 데이터·트래픽·팀 소유권이 임계에 도달하면 Site/Brand 저장소 및 배포 단위 분리 + +--- + +## 5. 재작성하지 않고 유지할 현재 구현 + +설계서와 다르더라도 아래는 현재 제품에 맞고 이미 안전장치가 있으므로 유지하는 편이 낫다. + +- PostgreSQL 기반 잡 큐의 원자적 claim, lease, dedupe, dead-letter +- `VERIFIED`/`CORRECTED`만 발행하고 재수집 후보가 정정값을 덮지 않는 상태 모델 +- 백엔드는 payload만 만들고 프론트 프리렌더러가 정적 HTML을 생성하는 경계 +- JSON-LD와 화면값 불일치 시 발행을 막는 게이트 +- 외부 API 키가 없어도 해당 어댑터만 비활성화하는 구성 +- robots.txt와 약관을 우회하지 않는 수집 원칙 +- 현재 SEO/AEO 점수를 “준비도”로 명시하는 정직한 표현 + +--- + +## 6. 일정 재구성 제안 + +설계서의 S1~S8은 신규 구축 기준이라 현재 저장소에 그대로 적용하면 이미 끝난 기반 작업을 반복하고, 미결 정책을 코드로 먼저 굳히게 된다. 다음과 같이 게이트 중심으로 다시 잡는다. + +| 마일스톤 | 목표 | 종료 조건 | +|---|---|---| +| M0 방향 확정 | 범위·업종·도메인·크롤·비용 결정 | P0 결정 기록과 승인 | +| M1 Site 완결 | A1/A7/A9 공백과 고객 도메인 보완 | 소유권→발행→변경감지 E2E 통과 | +| M2 규제 게이트 | 법률·의료를 할 경우 A4 구축 | 전문가 승인 룰셋과 감사 가능한 차단/승인 | +| M3 Visibility 파일럿 | 질문은행·snapshot·최소 엔진 측정 | 반복 측정의 비용·분산·인용 검출 정확도 보고 | +| M4 개선 루프 | 측정 결과를 안전한 재생성 요청으로 연결 | 고객 확인 또는 A4/A7 재통과 후 발행 | +| M5 플랫폼화 | 콘솔/BFF/서비스 분리 | 실제 트래픽·팀 소유권 기준 충족 시에만 수행 | + +주차 추정치는 P0의 업종 수, AI 엔진 수, 외부 전문가 검토 가능일이 정해진 뒤 산정한다. 특히 3개 업종 동시 개발과 4개 엔진×3회 측정을 전제로 한 기존 8스프린트 일정은 현재 인력·비용 정보 없이 확정 일정으로 취급하면 안 된다. + +--- + +## 7. 바로 만들 백로그 + +| 우선순위 | 에픽 | 대표 산출물 | +|---|---|---| +| 1 | 소유권 검증 | challenge 테이블/API, DNS/meta/well-known 검증기, 만료 정책, 발행 게이트 | +| 2 | 수집 재현성 | crawl run, document hash, source selector/snippet, 변경 비교 | +| 3 | 일치성 강화 | SimHash, fact 역참조 커버리지, 실패 사유 UI | +| 4 | 발행 관측 | crawler visit/index 상태, CDN 로그 적재, 재수집/재생성 조건 | +| 5 | 고객 도메인 | 서브패스/서브도메인 연결, canonical·sitemap 검증, TLS/DNS 운영 | +| 6 | 측정 계약 | question set, fact snapshot, publication-question 연결 | +| 7 | Visibility 파일럿 | 엔진 어댑터, 원문 로그, mention/citation/position/factuality 분석, 비용 상한 | +| 8 | 운영 화면 | 소유권·수집·게이트·발행 상태부터 추가, 이후 질문/성과/인용 화면 | +| 조건부 | 규제 업종 | 규칙 저장소, Reviewer, 승인 워크벤치, 감사 로그, 사전심의 | + +--- + +## 8. 관련 현재 문서 + +이 문서는 비교와 향후 방향만 다룬다. 현재 제품 원칙과 구현 상세는 중복해서 관리하지 않는다. + +- 제품 범위와 non-goal: [PRODUCT.md](PRODUCT.md) +- 현재 수집·생성·발행 흐름: [COLLECTION_SEO_AEO_FLOW.md](COLLECTION_SEO_AEO_FLOW.md) +- 법무·데이터·작업 큐 결정: [DECISIONS.md](DECISIONS.md) +- 데이터 소스 실측: [DATA_SOURCE_RESEARCH.md](DATA_SOURCE_RESEARCH.md) +- 배포와 도메인 운영: [DEPLOY.md](DEPLOY.md) +- 외부 API 비용: [API_USAGE.md](API_USAGE.md) + diff --git a/docs/PRODUCT.md b/docs/PRODUCT.md new file mode 100644 index 0000000..9870407 --- /dev/null +++ b/docs/PRODUCT.md @@ -0,0 +1,113 @@ +# PRODUCT — 무엇을, 누구를 위해, 무엇을 안 하는가 + +이 문서는 **제품 판단의 단일 출처**다. 코드에서 읽을 수 없는 것만 적는다 — +누구를 위한 것인지, 무엇을 성공으로 볼 것인지, 그리고 **하지 않기로 한 것**이 무엇인지. +구현이 궁금하면 [ARCHITECTURE.md](ARCHITECTURE.md), 미결 사항은 [DECISIONS.md](DECISIONS.md). + +--- + +## 1. 한 문장 + +> 상호명 하나를 입력하면, **AI 검색이 그 가게를 공식 홈페이지 기준으로 설명하게 만드는** +> 정적 홈페이지를 만들어 발행한다. + +"예쁜 사이트를 싸게"가 아니다. 예쁜 사이트는 이미 흔하다. 우리가 파는 건 **검색·AI 답변에서의 +1차 출처 지위**다. 이 문장이 제품의 모든 트레이드오프를 정한다 — 아래 3절이 그 결과다. + +## 2. 문제 + +소상공인은 이미 네이버 플레이스·인스타그램에 정보를 올려 두고 있다. 그런데: + +- 그 정보는 **AI 검색엔진이 읽지 못한다.** 네이버·카카오 생태계는 AI 크롤러를 통째로 차단한다 + (실측 근거: [DATA_SOURCE_RESEARCH.md](DATA_SOURCE_RESEARCH.md) 1절). +- 그래서 ChatGPT·Perplexity·Gemini 가 그 가게를 설명할 때 **근거로 삼을 1차 출처가 없다.** + 블로그 후기나 오래된 기사에서 추측한다. +- 사장님이 직접 홈페이지를 만들어도, CSR 로 만들면 크롤러는 `
    ` 만 읽고 떠난다. + +**빈 판이다.** 경쟁자가 스스로 문을 잠갔기 때문에, 크롤러가 읽을 수 있는 정적 HTML 하나만 +정확히 놓아도 그 가게의 정답이 된다. + +## 3. 그래서 정한 제품 원칙 + +이건 취향이 아니라 1절에서 기계적으로 따라 나온 결론이다. 어길 거면 1절부터 다시 논의한다. + +| 원칙 | 왜 | 어디에 박혀 있나 | +|---|---|---| +| **발행물은 정적 HTML** — 서버도 JS 실행도 없이 읽힌다 | 크롤러가 읽어야 존재하는 것이다 | `frontend/site` 프리렌더 | +| **확인된 값만 발행한다** | 틀린 정보를 1차 출처로 만들면 제품이 해를 끼친다 | `publish_gate.py` 규칙 1 | +| **고유 콘텐츠 0건이면 발행 거부** | 같은 템플릿 대량 생성은 검색엔진의 스팸 판정 대상 | `publish_gate.py` 규칙 2 | +| **JSON-LD 값 = 화면 값** | 어긋나면 구조화 데이터 조작이다. 색인에서 통째로 불신당한다 | `publish_gate.py` 규칙 3, 빌드 실패 | +| **백엔드는 HTML 을 만들지 않는다** | 렌더링과 데이터를 한 몸으로 묶으면 둘 다 못 고친다 | payload JSON 경계 | +| **뚫어야 볼 수 있는 데이터는 안 쓴다** | 봇 탐지 우회는 결론과 무관하게 영구 금지 | `DECISIONS.md` 1-1 | + +## 4. 사용자 — 셋이고, 요구가 서로 반대다 + +| | 사장님 | 우리 회사 운영자 | 손님 · **AI 크롤러** | +|---|---|---|---| +| 무엇을 한다 | 내 가게 정보 확인·수정, 사진 고르기, 발행 | 전체 사이트 품질·발행 상태 관리, 수집 소스 운영 | 읽는다 | +| 원하는 것 | 몇 번 눌러서 끝나기 | 무엇이 왜 막혔는지 보이기 | 정확한 사실, 즉시 | +| 로그인 | 최소 (막히면 만들어 보지도 못한다) | 엄격 | 없음 | +| 화면 성격 | 위저드 + 에디터 | 대시보드 + 목록 | 정적 문서 | +| 현재 코드 | `admin/` `/builder` | `admin/` `/places`, `/local-content` | `site/` | + +★ **앞의 둘이 지금 한 앱에 섞여 있다.** 왜 나눠야 하는지와 나누는 방법은 +[ARCHITECTURE.md 4절](ARCHITECTURE.md#4-앱-경계--지금-구조와-나눌-지점). + +권한 코드는 `common/enums.py UserRole`: `1 USER`(사장님) / `2 OWNER`(고객사 최상위) / +`3 DEVELOPER`(내부 운영 — **고객사에 존재를 노출하지 않는다**). + +## 5. 지금 하는 것 (범위) + +- 업종: **숙박 · 카페 · 음식점 · 관광체험** (`PlaceCategory`). 업종 추가 = 코드 1줄 + 스키마 파일 1개 +- 수집 → 사장님 확인 → LLM 생성 → 편집 → 발행 게이트 → 정적 발행 → IndexNow 통보 +- **사이트 하나 = 한 장**(2026-08-31 결정). 쪼개면 페이지가 얇아지고 검색엔진이 색인에서 버린다 + — 자세한 근거는 [ARCHITECTURE.md 5절](ARCHITECTURE.md) +- 발행 후 색인 통보: 네이버 · Bing · Yandex (IndexNow). **구글은 IndexNow 미지원** → 사이트맵 제출 + +## 6. 하지 않는 것 (Non-goals) + +여기 적힌 걸 하자는 제안이 오면, 하기 전에 이 줄을 지우는 합의부터 한다. + +| 안 한다 | 왜 | +|---|---| +| **네이버 플레이스를 복제한 사이트** | AI 크롤러가 못 읽는 걸 옮겨 봐야 목표(1절)에 기여가 0이다. 게다가 robots.txt 위반 | +| **봇 탐지 우회 크롤링** (헤드리스 브라우저, IP 회전, 핑거프린트 위조) | 영구 금지. 야놀자 v 여기어때 = 민사 10억 배상 + 복제 금지 선례 | +| **범용 홈페이지 빌더 / 자유 편집** | 자유도를 주면 게이트(3절)를 우회할 수 있다. 게이트가 제품이다 | +| **이미지 호스팅** | 지금은 네이버 CDN 핫링크. ⚠️ 중기 리스크는 [DEPLOY.md 1절](DEPLOY.md) 참고 | +| **예약·결제 처리** | 사이트는 예약 채널로 **보낸다**. 거래를 품지 않는다 | +| **CSR 발행 사이트** | 크롤러가 못 읽으면 만든 의미가 없다 | + +## 7. 성공 기준 + +**제품이 동작한다고 말할 수 있는 조건** (코드가 이미 강제하는 것): + +1. 발행된 사이트가 게이트 3규칙을 통과한다 — 미검증 fact 0, 고유 콘텐츠 ≥ 1, JSON-LD 불일치 0 +2. `/s/` 가 **끝 슬래시 없이도** 200 (사장님이 주소창에 치는 형태) +3. 크롤러가 JS 없이 본문·JSON-LD·`llms.txt` 를 전부 읽는다 +4. 사이트맵과 IndexNow 통보가 **실제로 존재하는 주소**를 가리킨다 + (조용히 틀리는 종류라 자동 검증이 유일한 방어 — `scripts/check_search_ready.py`) + +**사업 기준** — 아직 정하지 않았다. 정하면 여기에 날짜와 함께 적는다. +후보: 발행 후 N일 내 AI 답변 인용률 / 구글 색인 등재율 / 사장님 발행 완주율. + +## 8. 제약 + +- **제품 원가 상한: 사이트 1건당 $1 (약 1,400원).** Perplexity·Kakao·Gemini 호출 합계. + 이 상한이 "LLM 을 몇 번 부를 수 있나"를 정한다. 현황: [API_USAGE.md](API_USAGE.md) + (★ 개발비와 섞지 말 것 — 그건 일회성이다) +- **법적 제약**은 [DECISIONS.md](DECISIONS.md) 1절이 단일 출처다. 수집 어댑터를 추가하기 전에 읽는다. +- **발행 호스트는 백엔드·프론트 두 곳에 있고 값이 같아야 한다.** 그리고 payload JSON 에 + 구워져 들어간다 — 바꾸면 재발행이 필요하다. ([AGENTS.md](../AGENTS.md) 함정 목록) + +## 9. 아직 안 정한 것 + +정해지는 대로 이 절에서 위로 올린다. 코드로 미리 풀지 않는다. +★ **개발 착수 전에 확정해야 할 결정 목록은 +[DEVELOPMENT_DIRECTION.md P0](DEVELOPMENT_DIRECTION.md)** 가 단일 출처다 — 여기 복사하지 않는다. +아래는 그중 **제품 정의**에 해당하는 것만 남긴다. + +- 사업 성공 지표 (7절) +- 관리자가 사장님 콘텐츠를 어디까지 고칠 수 있나 ([DECISIONS.md](DECISIONS.md) 1-3) +- 과금 모델 — 건당 / 구독 / 무료+상위요금제 +- 사장님 해지 시 발행된 사이트의 운명 ([DECISIONS.md](DECISIONS.md) 1-4) +- 고객사(에이전시) 다중 입점 여부 — `companies` 테이블은 이미 있으나 제품 결정은 미정 diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..9cdd441 --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1,14 @@ +node_modules/ +dist/ +.ssr-dist/ +*.tsbuildinfo + +# 발행 산출물 — 빌드 잡이 매번 새로 굽는다. 커밋하지 않는다. +out/ + +# 환경변수: 실제 값은 커밋하지 않는다(.env.example 만 커밋). +.env +.env.* +!.env.example + +.DS_Store diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000..8c1c72c --- /dev/null +++ b/frontend/README.md @@ -0,0 +1,150 @@ +# o2o-web4ai frontend + +소상공인 홈페이지 자동 생성 솔루션의 프론트엔드. +`o2o-negosium/negodata/front` 보일러플레이트를 이식했다 — 빌드 도구·구조·프로토콜 규약은 원본과 같다. + +**목표는 예쁜 사이트가 아니라 AI 검색이 이 가게를 공식 홈페이지 기준으로 설명하게 만드는 것**이다 +(백엔드 README 와 같은 문장). 그래서 두 앱의 요구사항이 정반대다. + +| | `admin/` (빌더) | `site/` (발행 사이트) | +|---|---|---| +| 사용자 | 사장님 · 운영자 | 손님 · **검색/AI 크롤러** | +| 렌더링 | CSR SPA | **SSG (정적 HTML)** | +| 색인 | `noindex` | 색인·인용되라고 존재 | +| 런타임 | Vite dev / 정적 호스팅 | **서버 없음.** 파일만 | +| 데이터 | 편집 중 상태(미확인 값 포함) | `SitePayload` — **확인된 값만** | + +한 레포에 두 앱을 두되 빌드를 나눈 이유가 이 표다. 보일러플레이트는 순수 CSR 이라 +발행 사이트에 그대로 쓰면 크롤러가 `
    ` 만 읽고 떠난다. + +``` +frontend/ +├── shared/ 두 앱이 공유 — 도메인 enum · SitePayload 계약 · 디자인 토큰 · fact 필터 +├── admin/ 빌더 (위저드 4단계 + 실시간 에디터 + 발행 게이트) +└── site/ 발행 사이트 렌더러 + 프리렌더 스크립트 +``` + +## 실행 + +### Docker Compose (기본 실행 방식) + +```bash +docker compose up -d +``` + +- 발행 사이트: `http://localhost:3000/s/` +- API/Swagger: `http://localhost:9800/docs` +- 정적 사이트 저장 위치: `frontend/site/out/s//` +- 프리렌더 입력 payload: `frontend/site/payloads/.json` +- 컨테이너 내부 정적 서버는 3001을 사용하지만, Docker가 호스트 3000으로만 공개한다. + +예: `http://localhost:3000/s/grazz` + +```bash +npm install # 워크스페이스 루트에서 한 번 + +npm run dev # 빌더 → http://localhost:3000 +npm run dev:site # 발행 사이트 → http://localhost:3001 (데모 payload 로 CSR) + +npm run build # 전체 타입체크 + 린트 + 빌드 +npm run prerender # ★ 정적 사이트 굽기 → site/out// +``` + +백엔드는 기본 `http://localhost:9800` 으로 본다. 바꾸려면 `admin/.env` 에 `VITE_API_BASE_URL`. +`cp admin/.env.example admin/.env` 로 시작한다. + +## 발행 파이프라인 + +``` +관리자 편집 → [발행 게이트] → SitePayload JSON → prerender → 정적 파일 + ↓ 막히면 발행 불가 + 미검증 fact / 필수 항목 누락 / 고유 콘텐츠 0건 +``` + +```bash +# 데모 payload 로 +npm run prerender + +# 실제 payload 로 (백엔드 BUILD 잡이 부르는 자리) +npm run prerender -- --payload=./payloads --out=/var/www +``` + +사이트 하나당 나오는 것: + +``` +out// +├── index.html 홈 (JSON-LD 4종 + 본문 전체가 HTML 에) +├── rooms/index.html 하위 단위 목록 ← 업종별 경로(rooms/menu/programs) +├── rooms//index.html 단위 상세 +├── guide|location|faq/index.html +├── sitemap.xml +├── robots.txt ★ AI 크롤러 명시 허용 +├── llms.txt ★ LLM 이 읽을 사실 목록 +└── assets/ 하이드레이션 번들 +``` + +## SEO / AEO 가 어디에 박혀 있나 + +| 무엇 | 어디 | 왜 | +|---|---|---| +| 정적 HTML | `site/scripts/prerender.ts` | JS 를 실행 안 하는 AI 크롤러가 본문을 그대로 읽는다 | +| 구조화 데이터 | `site/src/seo/jsonld.ts` | 업종별 Schema.org 타입 + FAQPage + BreadcrumbList + WebPage | +| meta · OG · geo | `site/src/seo/meta.ts` `head.ts` | description 을 **확인된 fact 로 조립**한다(지어내지 않는다) | +| `llms.txt` | `site/src/seo/llms.ts` | 사실만. 형용사 금지. 모르는 건 "정보 없음"이라고 적는다 | +| `robots.txt` | `site/src/seo/robots.ts` | GPTBot · ClaudeBot · PerplexityBot 등 **명시 허용** | +| 핵심 정보 요약 | `site/src/sections/AnswerBlock.tsx` | AI 가 답으로 뽑아 가는 단정문을 상단에 고정 배치 | +| FAQ | `site/src/sections/FaqSection.tsx` | `
    ` — 접혀 있어도 크롤러가 읽는다 | +| 발행 게이트 | `admin/src/features/publish/publishGate.ts` | 백엔드 `PublishRejectReason` 과 1:1 | + +### 절대규칙 1 이 지켜지는 지점 + +> 확인되지 않은 fact 는 사이트에 나가지 않는다. + +한 곳에서만 거른다 — `shared/src/lib/facts.ts`. + +- `selectPublishable()` — `VERIFIED` · `CORRECTED` 만 통과 +- `sanitizePayloadForPublish()` — **프리렌더가 payload 를 여기 통과시킨 뒤 렌더와 임베드 양쪽에 쓴다** + +두 번째가 중요하다. 정적 HTML 은 하이드레이션용으로 payload 를 통째로 심는데, +화면과 JSON-LD 만 걸러 두면 그 블롭에 미검증 값이 남아 원본 HTML 을 읽는 AI 가 그걸 읽는다. +(실제로 한 번 그렇게 샜고, 그래서 이 함수가 생겼다.) + +## 백엔드 연결 + +API 클라이언트는 **전부 orval 생성물**이다(React Query 훅). 화면은 `@/api` 하나만 import 한다. +자세한 규약은 [admin/src/api/README.md](admin/src/api/README.md). + +```bash +npm run orval -w admin # 백엔드가 떠 있을 때 + +cd ../backend && python scripts/export_openapi.py # 서버 없이 — 스펙을 먼저 뽑고 +cd ../frontend && ORVAL_INPUT=../../backend/openapi.json npm run orval -w admin +``` + +열려 있는 도메인은 `auth` / `place` / `fact` / `job` / `site` 전부다. + +| 화면 | 부르는 것 | +|---|---| +| 사업장 목록·상세 | `useListPlaces` `useGetPlace` `useListFacts` `useListLinks` `useTransitionFact` `useConfirmLink` | +| 위저드 2단계(수집) | `POST /place/{id}/collect` → 잡 폴링 — `useGatherSimulation.ts` | +| 위저드 4단계(생성) | `POST /place/{id}/copy` → 잡 폴링 — `Step4Generating.tsx` | +| 발행 | `POST /place/{id}/site/build {publish:true}` → 잡 폴링 — `features/publish/usePublishSite.ts` | + +**발행 = 빌드다.** 백엔드에 발행 엔드포인트가 따로 없는 것이 맞다 — 발행 검수 게이트가 +빌드 잡 안에 있어서(`services/build_service` → `publish_gate`) 게이트를 우회하는 경로가 없다. +그래서 잡이 DONE 이어도 발행됐다는 뜻이 아니다. `job.result.gate.passed` 를 봐야 한다. + +★ `placeId` 가 없는 데모 경로(`/builder`)는 이 호출을 하나도 하지 않는다 — +로그인 없이 도는 화면이라 예전의 타이머 시뮬레이션으로 떨어진다. 실사업장은 `/builder?placeId=`. + +CORS 는 백엔드 `config.local.toml` 의 `client_url` 이 정한다(쉼표로 여러 오리진). +vite 가 3000 을 못 잡고 3001·3002 로 옮겨 뜨면 거기서 막히므로 개발 포트 대역을 함께 적어 둔다. + +## 아직 안 한 것 + +- **폰트 self-host** — `*/public/fonts/PretendardVariable.woff2` 가 없다. 지금은 Noto Sans KR 로 폴백된다 +- **이미지 최적화** — 원본 URL 을 그대로 쓴다. `srcset`/WebP 변환은 media 파이프라인이 붙은 뒤 +- **admin 번들 분할** — 626KB(gzip 185KB). 라우트 단위 `lazy()` 로 나눌 수 있다 +- **사진(media) 연동** — 백엔드에 media 조회 엔드포인트가 없어 빌더의 사진 탭은 실데이터가 비어 있다 + (`stores/builder.ts` 의 `photos: []`). VISION 잡이 붙인 분류·alt 를 읽을 창구가 열리면 채운다 +- **발행 주소** — `sites.domain` 을 채우는 경로가 아직 없다. 그때까지는 상호 슬러그로 주소를 만든다 diff --git a/frontend/admin/.env.example b/frontend/admin/.env.example new file mode 100644 index 0000000..ec8f129 --- /dev/null +++ b/frontend/admin/.env.example @@ -0,0 +1,15 @@ +# 관리자(빌더)가 호출할 백엔드. o2o-web4ai 백엔드 기본 포트는 9800. +VITE_API_BASE_URL=http://localhost:9800 + +# 발행 사이트의 기본 호스트. 발행 모달이 보여줄 주소를 이걸로 만든다. +# 커스텀 도메인이 붙기 전까지 .<이 값> 형태로 나간다. +VITE_PUBLISH_HOST=w4ai.o2o.kr + +# 발행 사이트 렌더러 개발 서버. 에디터 상단 "발행본 사이트 열기" 가 이 주소를 연다. +VITE_SITE_PREVIEW_URL=http://localhost:3000 + +# ── 개발 전용 자동 로그인(선택) ──────────────────────────── +# 값이 있으면 개발 서버에서 빌더를 열 때 이 계정으로 자동 로그인한다. +# 운영 번들에는 들어가지 않는다. 실제 값은 .env 에만 둔다(커밋 금지). +VITE_DEV_LOGIN_ID= +VITE_DEV_LOGIN_PW= diff --git a/frontend/admin/components.json b/frontend/admin/components.json new file mode 100644 index 0000000..15addee --- /dev/null +++ b/frontend/admin/components.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "base-nova", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/index.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "iconLibrary": "lucide", + "rtl": false, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "menuColor": "default", + "menuAccent": "subtle", + "registries": {} +} diff --git a/frontend/admin/eslint.config.js b/frontend/admin/eslint.config.js new file mode 100644 index 0000000..b669fb4 --- /dev/null +++ b/frontend/admin/eslint.config.js @@ -0,0 +1,31 @@ +// 최소 게이트 — 전체 스타일 린트가 아니라, tsc 가 못 잡는 런타임 크래시 버그만 막는다. +// (negodata 보일러플레이트에서 이식. 도입 계기는 로컬 const 가 동명 import 를 가려 +// zustand 셀렉터가 TDZ 참조 → 프로덕션 크래시. 그 케이스는 tsc --noEmit 도 통과했다.) +import tseslint from 'typescript-eslint'; +import reactHooks from 'eslint-plugin-react-hooks'; + +export default tseslint.config({ + files: ['src/**/*.{ts,tsx}'], + ignores: ['src/api/generated/**'], + languageOptions: { + parser: tseslint.parser, + }, + plugins: { + '@typescript-eslint': tseslint.plugin, + 'react-hooks': reactHooks, + }, + rules: { + // 훅 호출 순서 위반은 런타임 크래시라 error, deps 누락은 기존 코드가 많아 warn. + 'react-hooks/rules-of-hooks': 'error', + 'react-hooks/exhaustive-deps': 'warn', + // 선언보다 위에서 변수를 쓰는 것(TDZ) 차단. 함수/타입 호이스팅은 안전하므로 허용. + 'no-use-before-define': 'off', + '@typescript-eslint/no-use-before-define': [ + 'error', + {functions: false, classes: false, typedefs: false, enums: false, variables: true}, + ], + // 상위 스코프(import 포함) 이름을 가리는 재선언 차단. + 'no-shadow': 'off', + '@typescript-eslint/no-shadow': 'error', + }, +}); diff --git a/frontend/admin/index.html b/frontend/admin/index.html new file mode 100644 index 0000000..c243534 --- /dev/null +++ b/frontend/admin/index.html @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + Web4Ai · AI 웹 빌더 + + +
    + + + diff --git a/frontend/admin/orval.config.ts b/frontend/admin/orval.config.ts new file mode 100644 index 0000000..201c5a7 --- /dev/null +++ b/frontend/admin/orval.config.ts @@ -0,0 +1,51 @@ +import {defineConfig} from 'orval'; + +/** + * Orval config + * + * Backend: FastAPI (o2o-web4ai API) — OpenAPI 스키마를 `${BACKEND_URL}/openapi.json` 에 자동 노출한다. + * 포트 9800 (negosium 9300 / negodata 9400 / agent 9500 / lps 9600 / anchoring 9700 다음 번호). + * + * 네이티브 `fetch` 기반 React Query 클라이언트를 만든다(axios 불필요). + * 실행: `npm run orval` + * + * 서버를 안 띄우고 생성하려면 백엔드가 뽑아둔 파일을 지정한다: + * ORVAL_INPUT=../../backend/openapi.json npm run orval + */ +export default defineConfig({ + o2oSite: { + input: { + target: process.env.ORVAL_INPUT ?? 'http://localhost:9800/openapi.json', + }, + output: { + mode: 'tags-split', + target: './src/api/generated', + schemas: './src/api/generated/model', + client: 'react-query', + // httpClient: 'fetch' 를 쓰면 오퍼레이션마다 Response200/404/Success/Error/Response + // 상태코드별 유니온 타입이 강제로 쏟아진다. 우리 mutator 는 본문(data)만 반환하므로 + // 기본 mutator 방식(config-object)으로 두어 함수가 본문 타입을 바로 반환하게 한다. + clean: true, + prettier: true, + override: { + // FastAPI 기본 operationId("list_places_v1_place_list_get")에서 "_v1_" 앞부분만 취해 + // camelCase 로 정리 → listPlaces/useListPlaces 등으로 복원(백엔드 무수정). + operationName: (operation) => { + const id = operation.operationId ?? ''; + const base = id.split('_v1_')[0] || id; + return base.replace(/_([a-z])/g, (_m, c) => c.toUpperCase()); + }, + // 모든 생성 호출을 공통 fetch mutator 로 통과시킨다(토큰/에러/baseURL 처리). + mutator: { + path: './src/api/mutator/custom-fetch.ts', + name: 'customFetch', + }, + query: { + useQuery: true, + useInfinite: false, + signal: true, + }, + }, + }, + }, +}); diff --git a/frontend/admin/package.json b/frontend/admin/package.json new file mode 100644 index 0000000..98acb29 --- /dev/null +++ b/frontend/admin/package.json @@ -0,0 +1,49 @@ +{ + "name": "@o2o/admin", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite --port=3000 --host=0.0.0.0", + "build": "tsc --noEmit && eslint src && vite build", + "preview": "vite preview", + "clean": "rm -rf dist", + "lint": "tsc --noEmit && eslint src", + "orval": "orval --config ./orval.config.ts" + }, + "dependencies": { + "@dnd-kit/core": "^6.3.1", + "@dnd-kit/sortable": "^10.0.0", + "@dnd-kit/utilities": "^3.2.2", + "@hookform/resolvers": "^5.4.0", + "@o2o/shared": "*", + "@tailwindcss/vite": "^4.1.14", + "@tanstack/react-query": "^5.62.0", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^0.546.0", + "motion": "^12.23.24", + "react": "^19.0.1", + "react-dom": "^19.0.1", + "react-hook-form": "^7.79.0", + "react-router": "^7.17.0", + "sonner": "^2.0.7", + "tailwind-merge": "^3.6.0", + "tw-animate-css": "^1.4.0", + "zod": "^4.4.3", + "zustand": "^5.0.14" + }, + "devDependencies": { + "@types/node": "^22.14.0", + "@types/react": "^19.2.17", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^5.0.4", + "eslint": "^9.36.0", + "eslint-plugin-react-hooks": "^7.1.1", + "orval": "^7.3.0", + "tailwindcss": "^4.1.14", + "typescript": "~5.8.2", + "typescript-eslint": "^8.45.0", + "vite": "^6.2.3" + } +} diff --git a/frontend/admin/public/apple-touch-icon.png b/frontend/admin/public/apple-touch-icon.png new file mode 100644 index 0000000..f426fd7 Binary files /dev/null and b/frontend/admin/public/apple-touch-icon.png differ diff --git a/frontend/admin/public/brand/ai-for-web-logo.png b/frontend/admin/public/brand/ai-for-web-logo.png new file mode 100644 index 0000000..7d7d9bd Binary files /dev/null and b/frontend/admin/public/brand/ai-for-web-logo.png differ diff --git a/frontend/admin/public/brand/ai-for-web-mark-512.png b/frontend/admin/public/brand/ai-for-web-mark-512.png new file mode 100644 index 0000000..be01ba9 Binary files /dev/null and b/frontend/admin/public/brand/ai-for-web-mark-512.png differ diff --git a/frontend/admin/public/brand/ai-for-web-wordmark.svg b/frontend/admin/public/brand/ai-for-web-wordmark.svg new file mode 100644 index 0000000..f0106fb --- /dev/null +++ b/frontend/admin/public/brand/ai-for-web-wordmark.svg @@ -0,0 +1,6 @@ + + AI FOR WEB + + AIFOR WEB + + diff --git a/frontend/admin/public/brand/favicon-afw.svg b/frontend/admin/public/brand/favicon-afw.svg new file mode 100644 index 0000000..d6d2897 --- /dev/null +++ b/frontend/admin/public/brand/favicon-afw.svg @@ -0,0 +1,3 @@ + + AFW + diff --git a/frontend/admin/public/brand/favicon-cursor.svg b/frontend/admin/public/brand/favicon-cursor.svg new file mode 100644 index 0000000..c0364ef --- /dev/null +++ b/frontend/admin/public/brand/favicon-cursor.svg @@ -0,0 +1,3 @@ + + + diff --git a/frontend/admin/public/brand/favicon-magic-wand.svg b/frontend/admin/public/brand/favicon-magic-wand.svg new file mode 100644 index 0000000..f0b5abf --- /dev/null +++ b/frontend/admin/public/brand/favicon-magic-wand.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/frontend/admin/public/brand/favicon-top-hat-cursor.svg b/frontend/admin/public/brand/favicon-top-hat-cursor.svg new file mode 100644 index 0000000..e197c7d --- /dev/null +++ b/frontend/admin/public/brand/favicon-top-hat-cursor.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/frontend/admin/public/brand/favicon-top-hat.svg b/frontend/admin/public/brand/favicon-top-hat.svg new file mode 100644 index 0000000..fd89612 --- /dev/null +++ b/frontend/admin/public/brand/favicon-top-hat.svg @@ -0,0 +1,4 @@ + + + + diff --git a/frontend/admin/public/brand/favicon-w4a.svg b/frontend/admin/public/brand/favicon-w4a.svg new file mode 100644 index 0000000..fc674ab --- /dev/null +++ b/frontend/admin/public/brand/favicon-w4a.svg @@ -0,0 +1,3 @@ + + W4A + diff --git a/frontend/admin/public/brand/web4ai-wordmark.svg b/frontend/admin/public/brand/web4ai-wordmark.svg new file mode 100644 index 0000000..b9c24fe --- /dev/null +++ b/frontend/admin/public/brand/web4ai-wordmark.svg @@ -0,0 +1,6 @@ + + Web4Ai + + Web4Ai + + diff --git a/frontend/admin/public/favicon-32.png b/frontend/admin/public/favicon-32.png new file mode 100644 index 0000000..46bf1fd Binary files /dev/null and b/frontend/admin/public/favicon-32.png differ diff --git a/frontend/admin/public/favicon.svg b/frontend/admin/public/favicon.svg new file mode 100644 index 0000000..fd89612 --- /dev/null +++ b/frontend/admin/public/favicon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/frontend/admin/public/fonts/README.md b/frontend/admin/public/fonts/README.md new file mode 100644 index 0000000..00b1824 --- /dev/null +++ b/frontend/admin/public/fonts/README.md @@ -0,0 +1,15 @@ +# fonts + +`PretendardVariable.woff2` 를 여기 두면 한글 본문이 Pretendard 로 뜬다. + +없어도 빌드는 깨지지 않는다 — `@font-face` 가 조용히 실패하고 +`Noto Sans KR`(구글폰트 CDN) → `system-ui` 순서로 폴백된다. +빌드 시 "didn't resolve at build time" 경고가 뜨는 건 그 때문이고, 무해하다. + +```bash +curl -L -o PretendardVariable.woff2 \ + https://github.com/orioncactus/pretendard/raw/main/packages/pretendard/dist/web/variable/woff2/PretendardVariable.woff2 +``` + +★ 발행 사이트(`site/public/fonts/`)에도 같은 파일이 필요하다 — + 프리렌더가 `public/` 을 사이트 폴더로 복사하므로, 두면 자동으로 따라간다. diff --git a/frontend/admin/src/api/README.md b/frontend/admin/src/api/README.md new file mode 100644 index 0000000..de20869 --- /dev/null +++ b/frontend/admin/src/api/README.md @@ -0,0 +1,71 @@ +# api + +``` +api/ +├── index.ts ★ 화면이 import 하는 단 하나의 입구 +├── generated/ orval 산출물 — 손대지 않는다 +├── mutator/custom-fetch.ts 모든 호출이 지나는 길목(토큰·에러·baseURL·434 재발급) +└── pollJob.ts 잡 폴링(수집·비전·생성·빌드 공용) +``` + +화면은 `@/api` 하나만 본다. + +```ts +import {useListPlaces, useTransitionFact, startBuild, pollJob} from '@/api'; +import type {PlaceData, FactStatus} from '@/api'; +``` + +## 재생성 + +백엔드 OpenAPI 가 바뀌면 다시 뽑는다. **`generated/` 를 손으로 고치지 않는다.** + +```bash +# 백엔드가 떠 있을 때 +npm run orval -w admin + +# 서버 없이 (스펙 파일을 먼저 뽑는다) +cd backend && python scripts/export_openapi.py +cd ../frontend && ORVAL_INPUT=../../backend/openapi.json npm run orval -w admin +``` + +생성되는 것 — 태그(도메인)별 훅과 모델. + +| 태그 | 훅 | +|---|---| +| `auth` | `useLogin` `useRefreshToken` `useMe` `useUpdateMe` | +| `place` | `useListPlaces` `useCreatePlace` `useGetPlace` `useUpdatePlace` `useVerifyCandidates` `useVerifyPlace` `useListUnits` `useCreateUnit` `useListLinks` `useCreateLink` `useConfirmLink` `useStartCollect` `useStartVision` `useStartCopy` | +| `fact` | `useGetSchema` `useListFacts` `useUpsertFact` `useTransitionFact` | +| `job` | `useGetJob` `useJobOps` `useRequeueJob` | +| `site` | `useGetSite` `useStartBuild` `useListVersions` `useListLogs` `useChangeStatus` | + +`orval.config.ts` 의 `operationName` 이 FastAPI 의 `list_places_v1_place_list_get` 를 +`listPlaces` 로 되돌린다 — 백엔드는 무수정이다. + +## 규약 세 가지 + +**1. 거절도 HTTP 200 이다.** 도메인 거절은 `result.success=false` + `result.desc`(ErrorType 이름)로 온다. +React Query 는 성공으로 보므로 `onSuccess` 안에서 직접 봐야 한다. 안 보면 저장 안 된 값이 저장된 것처럼 보인다. + +```ts +onSuccess: (res) => { + if (res.result?.success === false) return notifyApiError({data: res}); + ... +} +``` + +문구 변환은 `@/lib/errorMessages` 한 곳에 있다(`PLACE_NOT_VERIFIED` → "동일 업소 검증을 먼저…"). + +**2. 응답의 `None` 필드는 키째 사라진다**(백엔드 `RemoveNoneResponse`). 게다가 백엔드가 기본값을 준 +필드는 OpenAPI 에서 required 가 아니라 생성 타입이 전부 optional 이다 — `undefined` 를 각오하고 쓴다. + +**3. 몇 분 걸리는 일은 잡이다.** 수집·비전·생성·빌드는 `job_id` 를 받고 폴링한다. +루프는 `pollJob()` 하나뿐이다 — 화면마다 다시 쓰지 않는다. + +```ts +const started = await startCollect(placeId, {}); +const outcome = await pollJob(started.job_id!, {signal, onTick: (job) => ...}); +// outcome.kind: done | dead | timeout | aborted | unreachable +``` + +★ `done` 은 "잡이 끝났다"이지 "성공했다"가 아니다. 빌드는 게이트에 막혀도 정상 종료하고 +`job.result.gate.passed` 가 false 로 온다 — 판정은 `features/publish/usePublishSite.ts` 가 읽는다. diff --git a/frontend/admin/src/api/generated/.gitkeep b/frontend/admin/src/api/generated/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/frontend/admin/src/api/generated/auth/auth.ts b/frontend/admin/src/api/generated/auth/auth.ts new file mode 100644 index 0000000..f957880 --- /dev/null +++ b/frontend/admin/src/api/generated/auth/auth.ts @@ -0,0 +1,327 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import { + useMutation, + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + MutationFunction, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseMutationOptions, + UseMutationResult, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + HTTPValidationError, + ReqLogin, + ReqUpdateMe, + ResLogin, + ResMe, + ResRefreshToken +} from '.././model'; + +import { customFetch } from '../../mutator/custom-fetch'; + + +type SecondParameter unknown> = Parameters[1]; + + + +/** + * id/pw 로 로그인하고 JWT 토큰을 발급한다. + * @summary 로그인 + */ +export const login = ( + reqLogin: ReqLogin, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/auth/login`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqLogin, signal + }, + options); + } + + + +export const getLoginMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{data: ReqLogin}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{data: ReqLogin}, TContext> => { + +const mutationKey = ['login']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {data: ReqLogin}> = (props) => { + const {data} = props ?? {}; + + return login(data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type LoginMutationResult = NonNullable>> + export type LoginMutationBody = ReqLogin + export type LoginMutationError = void | HTTPValidationError + + /** + * @summary 로그인 + */ +export const useLogin = (options?: { mutation?:UseMutationOptions>, TError,{data: ReqLogin}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {data: ReqLogin}, + TContext + > => { + + const mutationOptions = getLoginMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * refresh 토큰으로 access 토큰을 재발급한다. + * @summary 액세스 토큰 갱신 + */ +export const refreshToken = ( + + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/auth/refresh_token`, method: 'POST', signal + }, + options); + } + + + +export const getRefreshTokenMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,void, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,void, TContext> => { + +const mutationKey = ['refreshToken']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, void> = () => { + + + return refreshToken(requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type RefreshTokenMutationResult = NonNullable>> + + export type RefreshTokenMutationError = void + + /** + * @summary 액세스 토큰 갱신 + */ +export const useRefreshToken = (options?: { mutation?:UseMutationOptions>, TError,void, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + void, + TContext + > => { + + const mutationOptions = getRefreshTokenMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * 유효한 access 토큰이 있어야 호출 가능. 토큰의 유저+회사 정보를 반환한다. + * @summary 내 정보 + */ +export const me = ( + + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/auth/me`, method: 'GET', signal + }, + options); + } + + + + +export const getMeQueryKey = () => { + return [ + `/v1/auth/me` + ] as const; + } + + +export const getMeQueryOptions = >, TError = void>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getMeQueryKey(); + + + + const queryFn: QueryFunction>> = ({ signal }) => me(requestOptions, signal); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type MeQueryResult = NonNullable>> +export type MeQueryError = void + + +export function useMe>, TError = void>( + options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useMe>, TError = void>( + options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useMe>, TError = void>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 내 정보 + */ + +export function useMe>, TError = void>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getMeQueryOptions(options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * 본인 이름/이메일/연락처/비밀번호를 수정한다(권한·소속·ID 변경 불가). + * @summary 내 정보 수정 + */ +export const updateMe = ( + reqUpdateMe: ReqUpdateMe, + options?: SecondParameter,) => { + + + return customFetch( + {url: `/v1/auth/me`, method: 'PATCH', + headers: {'Content-Type': 'application/json', }, + data: reqUpdateMe + }, + options); + } + + + +export const getUpdateMeMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{data: ReqUpdateMe}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{data: ReqUpdateMe}, TContext> => { + +const mutationKey = ['updateMe']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {data: ReqUpdateMe}> = (props) => { + const {data} = props ?? {}; + + return updateMe(data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type UpdateMeMutationResult = NonNullable>> + export type UpdateMeMutationBody = ReqUpdateMe + export type UpdateMeMutationError = void | HTTPValidationError + + /** + * @summary 내 정보 수정 + */ +export const useUpdateMe = (options?: { mutation?:UseMutationOptions>, TError,{data: ReqUpdateMe}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {data: ReqUpdateMe}, + TContext + > => { + + const mutationOptions = getUpdateMeMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + \ No newline at end of file diff --git a/frontend/admin/src/api/generated/default/default.ts b/frontend/admin/src/api/generated/default/default.ts new file mode 100644 index 0000000..6b08931 --- /dev/null +++ b/frontend/admin/src/api/generated/default/default.ts @@ -0,0 +1,120 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import { + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import { customFetch } from '../../mutator/custom-fetch'; + + +type SecondParameter unknown> = Parameters[1]; + + + +/** + * @summary Healthz + */ +export const healthzHealthzGet = ( + + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/healthz`, method: 'GET', signal + }, + options); + } + + + + +export const getHealthzHealthzGetQueryKey = () => { + return [ + `/healthz` + ] as const; + } + + +export const getHealthzHealthzGetQueryOptions = >, TError = void>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getHealthzHealthzGetQueryKey(); + + + + const queryFn: QueryFunction>> = ({ signal }) => healthzHealthzGet(requestOptions, signal); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type HealthzHealthzGetQueryResult = NonNullable>> +export type HealthzHealthzGetQueryError = void + + +export function useHealthzHealthzGet>, TError = void>( + options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useHealthzHealthzGet>, TError = void>( + options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useHealthzHealthzGet>, TError = void>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary Healthz + */ + +export function useHealthzHealthzGet>, TError = void>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getHealthzHealthzGetQueryOptions(options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + diff --git a/frontend/admin/src/api/generated/fact/fact.ts b/frontend/admin/src/api/generated/fact/fact.ts new file mode 100644 index 0000000..a068d43 --- /dev/null +++ b/frontend/admin/src/api/generated/fact/fact.ts @@ -0,0 +1,438 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import { + useMutation, + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + MutationFunction, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseMutationOptions, + UseMutationResult, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + HTTPValidationError, + ListFactsParams, + ReqExtractFacts, + ReqTransitionFact, + ReqUpsertFact, + ResCategorySchema, + ResExtractFacts, + ResFact, + ResFactList +} from '.././model'; + +import { customFetch } from '../../mutator/custom-fetch'; + + +type SecondParameter unknown> = Parameters[1]; + + + +/** + * 이 사업장의 업종에 존재하는 fact 필드 정의. 관리 화면이 입력 폼을 그리는 데 쓴다. + * @summary 업종 fact 스키마 + */ +export const getSchema = ( + placeId: string, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/fact/schema`, method: 'GET', signal + }, + options); + } + + + + +export const getGetSchemaQueryKey = (placeId?: string,) => { + return [ + `/v1/place/${placeId}/fact/schema` + ] as const; + } + + +export const getGetSchemaQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetSchemaQueryKey(placeId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getSchema(placeId, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetSchemaQueryResult = NonNullable>> +export type GetSchemaQueryError = void | HTTPValidationError + + +export function useGetSchema>, TError = void | HTTPValidationError>( + placeId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetSchema>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetSchema>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 업종 fact 스키마 + */ + +export function useGetSchema>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetSchemaQueryOptions(placeId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * publishable_only=true 면 ★ 사이트에 나갈 수 있는 것(VERIFIED·CORRECTED)만. + * @summary fact 목록 + */ +export const listFacts = ( + placeId: string, + params?: ListFactsParams, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/fact/list`, method: 'GET', + params, signal + }, + options); + } + + + + +export const getListFactsQueryKey = (placeId?: string, + params?: ListFactsParams,) => { + return [ + `/v1/place/${placeId}/fact/list`, ...(params ? [params]: []) + ] as const; + } + + +export const getListFactsQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, + params?: ListFactsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListFactsQueryKey(placeId,params); + + + + const queryFn: QueryFunction>> = ({ signal }) => listFacts(placeId,params, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListFactsQueryResult = NonNullable>> +export type ListFactsQueryError = void | HTTPValidationError + + +export function useListFacts>, TError = void | HTTPValidationError>( + placeId: string, + params: undefined | ListFactsParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListFacts>, TError = void | HTTPValidationError>( + placeId: string, + params?: ListFactsParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListFacts>, TError = void | HTTPValidationError>( + placeId: string, + params?: ListFactsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary fact 목록 + */ + +export function useListFacts>, TError = void | HTTPValidationError>( + placeId: string, + params?: ListFactsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListFactsQueryOptions(placeId,params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * 같은 key 의 활성 fact 는 EXPIRED 로 밀리고 새 행이 들어간다(값 이력 보존). ★ 자동 수집(api/crawl/llm)은 사장님 수정본(CORRECTED)을 덮어쓸 수 없다. + * @summary fact 기록 + */ +export const upsertFact = ( + placeId: string, + reqUpsertFact: ReqUpsertFact, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/fact`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqUpsertFact, signal + }, + options); + } + + + +export const getUpsertFactMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqUpsertFact}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqUpsertFact}, TContext> => { + +const mutationKey = ['upsertFact']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqUpsertFact}> = (props) => { + const {placeId,data} = props ?? {}; + + return upsertFact(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type UpsertFactMutationResult = NonNullable>> + export type UpsertFactMutationBody = ReqUpsertFact + export type UpsertFactMutationError = void | HTTPValidationError + + /** + * @summary fact 기록 + */ +export const useUpsertFact = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqUpsertFact}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqUpsertFact}, + TContext + > => { + + const mutationOptions = getUpsertFactMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * 허용 전이만 통과한다(FACT_STATUS_TRANSITIONS). CORRECTED 로 갈 때는 value 가 필수다. + * @summary 검증 상태 전이 + */ +export const transitionFact = ( + placeId: string, + factId: string, + reqTransitionFact: ReqTransitionFact, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/fact/${factId}/transition`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqTransitionFact, signal + }, + options); + } + + + +export const getTransitionFactMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;factId: string;data: ReqTransitionFact}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;factId: string;data: ReqTransitionFact}, TContext> => { + +const mutationKey = ['transitionFact']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;factId: string;data: ReqTransitionFact}> = (props) => { + const {placeId,factId,data} = props ?? {}; + + return transitionFact(placeId,factId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type TransitionFactMutationResult = NonNullable>> + export type TransitionFactMutationBody = ReqTransitionFact + export type TransitionFactMutationError = void | HTTPValidationError + + /** + * @summary 검증 상태 전이 + */ +export const useTransitionFact = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;factId: string;data: ReqTransitionFact}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;factId: string;data: ReqTransitionFact}, + TContext + > => { + + const mutationOptions = getTransitionFactMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * 사장님이 붙여넣은 소개글·안내문에서 업종 스키마 fact 를 뽑는다. ★ 뽑은 값의 **근거 문장이 원문에 실제로 있는지 대조**해 통과한 것만 저장한다. 저장된 값은 전부 후보(UNVERIFIED)라 사장님이 확인해야 사이트에 나간다. 버려진 항목은 사유와 함께 돌려준다. + * @summary 붙여넣은 텍스트에서 fact 추출 + */ +export const extractFactsFromText = ( + placeId: string, + reqExtractFacts: ReqExtractFacts, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/fact/extract`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqExtractFacts, signal + }, + options); + } + + + +export const getExtractFactsFromTextMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqExtractFacts}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqExtractFacts}, TContext> => { + +const mutationKey = ['extractFactsFromText']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqExtractFacts}> = (props) => { + const {placeId,data} = props ?? {}; + + return extractFactsFromText(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type ExtractFactsFromTextMutationResult = NonNullable>> + export type ExtractFactsFromTextMutationBody = ReqExtractFacts + export type ExtractFactsFromTextMutationError = void | HTTPValidationError + + /** + * @summary 붙여넣은 텍스트에서 fact 추출 + */ +export const useExtractFactsFromText = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqExtractFacts}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqExtractFacts}, + TContext + > => { + + const mutationOptions = getExtractFactsFromTextMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + \ No newline at end of file diff --git a/frontend/admin/src/api/generated/faq/faq.ts b/frontend/admin/src/api/generated/faq/faq.ts new file mode 100644 index 0000000..9b6b4a1 --- /dev/null +++ b/frontend/admin/src/api/generated/faq/faq.ts @@ -0,0 +1,276 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import { + useMutation, + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + MutationFunction, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseMutationOptions, + UseMutationResult, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + HTTPValidationError, + ListFaqsParams, + ReqCreateFaq, + ReqTransitionFaq, + ResFaq, + ResFaqList +} from '.././model'; + +import { customFetch } from '../../mutator/custom-fetch'; + + +type SecondParameter unknown> = Parameters[1]; + + + +/** + * publishable_only=true 면 ★ 사이트에 나갈 수 있는 것(VERIFIED·CORRECTED)만. 기본은 승인 대기(UNVERIFIED)까지 함께 준다 — 승인할 대상을 봐야 하기 때문이다. + * @summary FAQ 목록 + */ +export const listFaqs = ( + placeId: string, + params?: ListFaqsParams, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/faq/list`, method: 'GET', + params, signal + }, + options); + } + + + + +export const getListFaqsQueryKey = (placeId?: string, + params?: ListFaqsParams,) => { + return [ + `/v1/place/${placeId}/faq/list`, ...(params ? [params]: []) + ] as const; + } + + +export const getListFaqsQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, + params?: ListFaqsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListFaqsQueryKey(placeId,params); + + + + const queryFn: QueryFunction>> = ({ signal }) => listFaqs(placeId,params, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListFaqsQueryResult = NonNullable>> +export type ListFaqsQueryError = void | HTTPValidationError + + +export function useListFaqs>, TError = void | HTTPValidationError>( + placeId: string, + params: undefined | ListFaqsParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListFaqs>, TError = void | HTTPValidationError>( + placeId: string, + params?: ListFaqsParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListFaqs>, TError = void | HTTPValidationError>( + placeId: string, + params?: ListFaqsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary FAQ 목록 + */ + +export function useListFaqs>, TError = void | HTTPValidationError>( + placeId: string, + params?: ListFaqsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListFaqsQueryOptions(placeId,params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * 사장님이 직접 쓴 FAQ. fact 의 owner 입력과 같이 바로 노출값(VERIFIED)이 된다 — 사람이 곧 출처다. 출처(generated_by)는 서버가 OWNER 로 고정한다. + * @summary FAQ 직접 추가 + */ +export const createFaq = ( + placeId: string, + reqCreateFaq: ReqCreateFaq, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/faq`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqCreateFaq, signal + }, + options); + } + + + +export const getCreateFaqMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqCreateFaq}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqCreateFaq}, TContext> => { + +const mutationKey = ['createFaq']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqCreateFaq}> = (props) => { + const {placeId,data} = props ?? {}; + + return createFaq(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type CreateFaqMutationResult = NonNullable>> + export type CreateFaqMutationBody = ReqCreateFaq + export type CreateFaqMutationError = void | HTTPValidationError + + /** + * @summary FAQ 직접 추가 + */ +export const useCreateFaq = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqCreateFaq}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqCreateFaq}, + TContext + > => { + + const mutationOptions = getCreateFaqMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * 허용 전이만 통과한다(FACT_STATUS_TRANSITIONS — fact 와 같은 표). CORRECTED 로 갈 때는 고친 question/answer 중 하나 이상이 필요하고, 그 뒤로는 ★ 잠긴 상태라 재생성이 덮어쓰지 못한다. + * @summary 검증 상태 전이(승인·정정·반려) + */ +export const transitionFaq = ( + placeId: string, + faqId: string, + reqTransitionFaq: ReqTransitionFaq, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/faq/${faqId}/transition`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqTransitionFaq, signal + }, + options); + } + + + +export const getTransitionFaqMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;faqId: string;data: ReqTransitionFaq}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;faqId: string;data: ReqTransitionFaq}, TContext> => { + +const mutationKey = ['transitionFaq']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;faqId: string;data: ReqTransitionFaq}> = (props) => { + const {placeId,faqId,data} = props ?? {}; + + return transitionFaq(placeId,faqId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type TransitionFaqMutationResult = NonNullable>> + export type TransitionFaqMutationBody = ReqTransitionFaq + export type TransitionFaqMutationError = void | HTTPValidationError + + /** + * @summary 검증 상태 전이(승인·정정·반려) + */ +export const useTransitionFaq = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;faqId: string;data: ReqTransitionFaq}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;faqId: string;data: ReqTransitionFaq}, + TContext + > => { + + const mutationOptions = getTransitionFaqMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + \ No newline at end of file diff --git a/frontend/admin/src/api/generated/job/job.ts b/frontend/admin/src/api/generated/job/job.ts new file mode 100644 index 0000000..50eeca5 --- /dev/null +++ b/frontend/admin/src/api/generated/job/job.ts @@ -0,0 +1,287 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import { + useMutation, + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + MutationFunction, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseMutationOptions, + UseMutationResult, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + HTTPValidationError, + ResJob, + ResJobOps +} from '.././model'; + +import { customFetch } from '../../mutator/custom-fetch'; + + +type SecondParameter unknown> = Parameters[1]; + + + +/** + * 상태별 카운트 + 큐 지연 + 최근 1시간 DEAD + 좀비(stuck). 내부 운영 전용. + * @summary 큐 운영 스냅샷 + */ +export const jobOps = ( + + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/job/ops`, method: 'GET', signal + }, + options); + } + + + + +export const getJobOpsQueryKey = () => { + return [ + `/v1/job/ops` + ] as const; + } + + +export const getJobOpsQueryOptions = >, TError = void>( options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getJobOpsQueryKey(); + + + + const queryFn: QueryFunction>> = ({ signal }) => jobOps(requestOptions, signal); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type JobOpsQueryResult = NonNullable>> +export type JobOpsQueryError = void + + +export function useJobOps>, TError = void>( + options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useJobOps>, TError = void>( + options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useJobOps>, TError = void>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 큐 운영 스냅샷 + */ + +export function useJobOps>, TError = void>( + options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getJobOpsQueryOptions(options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * @summary 잡 상태 조회(폴링) + */ +export const getJob = ( + jobId: string, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/job/${jobId}`, method: 'GET', signal + }, + options); + } + + + + +export const getGetJobQueryKey = (jobId?: string,) => { + return [ + `/v1/job/${jobId}` + ] as const; + } + + +export const getGetJobQueryOptions = >, TError = void | HTTPValidationError>(jobId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetJobQueryKey(jobId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getJob(jobId, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(jobId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetJobQueryResult = NonNullable>> +export type GetJobQueryError = void | HTTPValidationError + + +export function useGetJob>, TError = void | HTTPValidationError>( + jobId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetJob>, TError = void | HTTPValidationError>( + jobId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetJob>, TError = void | HTTPValidationError>( + jobId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 잡 상태 조회(폴링) + */ + +export function useGetJob>, TError = void | HTTPValidationError>( + jobId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetJobQueryOptions(jobId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * max_attempts 를 소진해 dead-letter 로 간 잡을 다시 대기로 돌린다. 내부 운영 전용. + * @summary DEAD 잡 재큐 + */ +export const requeueJob = ( + jobId: string, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/job/${jobId}/requeue`, method: 'POST', signal + }, + options); + } + + + +export const getRequeueJobMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{jobId: string}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{jobId: string}, TContext> => { + +const mutationKey = ['requeueJob']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {jobId: string}> = (props) => { + const {jobId} = props ?? {}; + + return requeueJob(jobId,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type RequeueJobMutationResult = NonNullable>> + + export type RequeueJobMutationError = void | HTTPValidationError + + /** + * @summary DEAD 잡 재큐 + */ +export const useRequeueJob = (options?: { mutation?:UseMutationOptions>, TError,{jobId: string}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {jobId: string}, + TContext + > => { + + const mutationOptions = getRequeueJobMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + \ No newline at end of file diff --git a/frontend/admin/src/api/generated/local-content/local-content.ts b/frontend/admin/src/api/generated/local-content/local-content.ts new file mode 100644 index 0000000..60bfdc2 --- /dev/null +++ b/frontend/admin/src/api/generated/local-content/local-content.ts @@ -0,0 +1,484 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import { + useMutation, + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + MutationFunction, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseMutationOptions, + UseMutationResult, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + GetWeatherParams, + HTTPValidationError, + ListContentsParams, + ReqPublishLocalContent, + ReqSyncFestivals, + ReqUpdateLocalContent, + ResLocalContentList, + ResSyncFestivals, + ResWeather +} from '.././model'; + +import { customFetch } from '../../mutator/custom-fetch'; + + +type SecondParameter unknown> = Parameters[1]; + + + +/** + * @summary List Contents + */ +export const listContents = ( + params?: ListContentsParams, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/admin/local-content`, method: 'GET', + params, signal + }, + options); + } + + + + +export const getListContentsQueryKey = (params?: ListContentsParams,) => { + return [ + `/v1/admin/local-content`, ...(params ? [params]: []) + ] as const; + } + + +export const getListContentsQueryOptions = >, TError = HTTPValidationError>(params?: ListContentsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListContentsQueryKey(params); + + + + const queryFn: QueryFunction>> = ({ signal }) => listContents(params, requestOptions, signal); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListContentsQueryResult = NonNullable>> +export type ListContentsQueryError = HTTPValidationError + + +export function useListContents>, TError = HTTPValidationError>( + params: undefined | ListContentsParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListContents>, TError = HTTPValidationError>( + params?: ListContentsParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListContents>, TError = HTTPValidationError>( + params?: ListContentsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary List Contents + */ + +export function useListContents>, TError = HTTPValidationError>( + params?: ListContentsParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListContentsQueryOptions(params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * @summary Sync Festivals + */ +export const syncFestivals = ( + reqSyncFestivals: ReqSyncFestivals, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/admin/local-content/sync-festivals`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqSyncFestivals, signal + }, + options); + } + + + +export const getSyncFestivalsMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{data: ReqSyncFestivals}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{data: ReqSyncFestivals}, TContext> => { + +const mutationKey = ['syncFestivals']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {data: ReqSyncFestivals}> = (props) => { + const {data} = props ?? {}; + + return syncFestivals(data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type SyncFestivalsMutationResult = NonNullable>> + export type SyncFestivalsMutationBody = ReqSyncFestivals + export type SyncFestivalsMutationError = HTTPValidationError + + /** + * @summary Sync Festivals + */ +export const useSyncFestivals = (options?: { mutation?:UseMutationOptions>, TError,{data: ReqSyncFestivals}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {data: ReqSyncFestivals}, + TContext + > => { + + const mutationOptions = getSyncFestivalsMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * @summary Publish + */ +export const publish = ( + reqPublishLocalContent: ReqPublishLocalContent, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/admin/local-content/publish`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqPublishLocalContent, signal + }, + options); + } + + + +export const getPublishMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{data: ReqPublishLocalContent}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{data: ReqPublishLocalContent}, TContext> => { + +const mutationKey = ['publish']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {data: ReqPublishLocalContent}> = (props) => { + const {data} = props ?? {}; + + return publish(data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type PublishMutationResult = NonNullable>> + export type PublishMutationBody = ReqPublishLocalContent + export type PublishMutationError = HTTPValidationError + + /** + * @summary Publish + */ +export const usePublish = (options?: { mutation?:UseMutationOptions>, TError,{data: ReqPublishLocalContent}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {data: ReqPublishLocalContent}, + TContext + > => { + + const mutationOptions = getPublishMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * @summary Update Content + */ +export const updateContent = ( + contentId: string, + reqUpdateLocalContent: ReqUpdateLocalContent, + options?: SecondParameter,) => { + + + return customFetch( + {url: `/v1/admin/local-content/${contentId}`, method: 'PATCH', + headers: {'Content-Type': 'application/json', }, + data: reqUpdateLocalContent + }, + options); + } + + + +export const getUpdateContentMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{contentId: string;data: ReqUpdateLocalContent}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{contentId: string;data: ReqUpdateLocalContent}, TContext> => { + +const mutationKey = ['updateContent']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {contentId: string;data: ReqUpdateLocalContent}> = (props) => { + const {contentId,data} = props ?? {}; + + return updateContent(contentId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type UpdateContentMutationResult = NonNullable>> + export type UpdateContentMutationBody = ReqUpdateLocalContent + export type UpdateContentMutationError = HTTPValidationError + + /** + * @summary Update Content + */ +export const useUpdateContent = (options?: { mutation?:UseMutationOptions>, TError,{contentId: string;data: ReqUpdateLocalContent}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {contentId: string;data: ReqUpdateLocalContent}, + TContext + > => { + + const mutationOptions = getUpdateContentMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * @summary End Content + */ +export const endContent = ( + contentId: string, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/admin/local-content/${contentId}/end`, method: 'POST', signal + }, + options); + } + + + +export const getEndContentMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{contentId: string}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{contentId: string}, TContext> => { + +const mutationKey = ['endContent']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {contentId: string}> = (props) => { + const {contentId} = props ?? {}; + + return endContent(contentId,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type EndContentMutationResult = NonNullable>> + + export type EndContentMutationError = HTTPValidationError + + /** + * @summary End Content + */ +export const useEndContent = (options?: { mutation?:UseMutationOptions>, TError,{contentId: string}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {contentId: string}, + TContext + > => { + + const mutationOptions = getEndContentMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * @summary 현재 날씨 조회 (cache-aside) + */ +export const getWeather = ( + params: GetWeatherParams, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/local/weather`, method: 'GET', + params, signal + }, + options); + } + + + + +export const getGetWeatherQueryKey = (params?: GetWeatherParams,) => { + return [ + `/v1/local/weather`, ...(params ? [params]: []) + ] as const; + } + + +export const getGetWeatherQueryOptions = >, TError = HTTPValidationError>(params: GetWeatherParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetWeatherQueryKey(params); + + + + const queryFn: QueryFunction>> = ({ signal }) => getWeather(params, requestOptions, signal); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetWeatherQueryResult = NonNullable>> +export type GetWeatherQueryError = HTTPValidationError + + +export function useGetWeather>, TError = HTTPValidationError>( + params: GetWeatherParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetWeather>, TError = HTTPValidationError>( + params: GetWeatherParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetWeather>, TError = HTTPValidationError>( + params: GetWeatherParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 현재 날씨 조회 (cache-aside) + */ + +export function useGetWeather>, TError = HTTPValidationError>( + params: GetWeatherParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetWeatherQueryOptions(params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + diff --git a/frontend/admin/src/api/generated/media/media.ts b/frontend/admin/src/api/generated/media/media.ts new file mode 100644 index 0000000..b9aa6d9 --- /dev/null +++ b/frontend/admin/src/api/generated/media/media.ts @@ -0,0 +1,135 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import { + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + HTTPValidationError, + ListMediaParams, + ResMediaList +} from '.././model'; + +import { customFetch } from '../../mutator/custom-fetch'; + + +type SecondParameter unknown> = Parameters[1]; + + + +/** + * publishable_only=true 면 ★ 사이트에 실제로 나갈 수 있는 것(승인 + alt 있음)만 — 빌드 스냅샷과 같은 기준이다. unit_id 를 주면 그 객실·메뉴 사진만. ★ 응답에는 항상 source_type(owner/crawl)과 origin_url 이 실린다 — 크롤링 이미지 재게시 권리가 미결이라(docs/DECISIONS.md 1-2) 결론에 따라 CRAWL 을 통째로 걸러내야 하고, 화면이 출처를 모르면 그 판단을 못 한다. + * @summary 사진 목록 + */ +export const listMedia = ( + placeId: string, + params?: ListMediaParams, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/media/list`, method: 'GET', + params, signal + }, + options); + } + + + + +export const getListMediaQueryKey = (placeId?: string, + params?: ListMediaParams,) => { + return [ + `/v1/place/${placeId}/media/list`, ...(params ? [params]: []) + ] as const; + } + + +export const getListMediaQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, + params?: ListMediaParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListMediaQueryKey(placeId,params); + + + + const queryFn: QueryFunction>> = ({ signal }) => listMedia(placeId,params, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListMediaQueryResult = NonNullable>> +export type ListMediaQueryError = void | HTTPValidationError + + +export function useListMedia>, TError = void | HTTPValidationError>( + placeId: string, + params: undefined | ListMediaParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListMedia>, TError = void | HTTPValidationError>( + placeId: string, + params?: ListMediaParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListMedia>, TError = void | HTTPValidationError>( + placeId: string, + params?: ListMediaParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 사진 목록 + */ + +export function useListMedia>, TError = void | HTTPValidationError>( + placeId: string, + params?: ListMediaParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListMediaQueryOptions(placeId,params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + diff --git a/frontend/admin/src/api/generated/model/auditCheckData.ts b/frontend/admin/src/api/generated/model/auditCheckData.ts new file mode 100644 index 0000000..7e9def8 --- /dev/null +++ b/frontend/admin/src/api/generated/model/auditCheckData.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { AuditCheckDataRecommendation } from './auditCheckDataRecommendation'; + +export interface AuditCheckData { + id: string; + group: string; + label: string; + points: number; + earned: number; + status: string; + detail: string; + recommendation?: AuditCheckDataRecommendation; +} diff --git a/frontend/admin/src/api/generated/model/auditCheckDataRecommendation.ts b/frontend/admin/src/api/generated/model/auditCheckDataRecommendation.ts new file mode 100644 index 0000000..c083f4e --- /dev/null +++ b/frontend/admin/src/api/generated/model/auditCheckDataRecommendation.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type AuditCheckDataRecommendation = string | null; diff --git a/frontend/admin/src/api/generated/model/buildStatus.ts b/frontend/admin/src/api/generated/model/buildStatus.ts new file mode 100644 index 0000000..f04faeb --- /dev/null +++ b/frontend/admin/src/api/generated/model/buildStatus.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * site_versions.build_status 코드값. 정적 빌드는 개별 재빌드 단위로 돈다. + */ +export type BuildStatus = typeof BuildStatus[keyof typeof BuildStatus]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const BuildStatus = { + PENDING: 1, + BUILDING: 2, + BUILT: 3, + FAILED: 4, +} as const; diff --git a/frontend/admin/src/api/generated/model/checkSlugParams.ts b/frontend/admin/src/api/generated/model/checkSlugParams.ts new file mode 100644 index 0000000..119448b --- /dev/null +++ b/frontend/admin/src/api/generated/model/checkSlugParams.ts @@ -0,0 +1,13 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type CheckSlugParams = { +/** + * 쓰고 싶은 주소(예: doflo) + */ +slug: string; +}; diff --git a/frontend/admin/src/api/generated/model/companyData.ts b/frontend/admin/src/api/generated/model/companyData.ts new file mode 100644 index 0000000..1229a4c --- /dev/null +++ b/frontend/admin/src/api/generated/model/companyData.ts @@ -0,0 +1,11 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export interface CompanyData { + company_id?: string; + name?: string; +} diff --git a/frontend/admin/src/api/generated/model/errorInfo.ts b/frontend/admin/src/api/generated/model/errorInfo.ts new file mode 100644 index 0000000..5db7ee8 --- /dev/null +++ b/frontend/admin/src/api/generated/model/errorInfo.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfoSuccess } from './errorInfoSuccess'; +import type { ErrorInfoCode } from './errorInfoCode'; +import type { ErrorInfoDesc } from './errorInfoDesc'; + +/** + * 모든 응답에 공통으로 실리는 결과 정보. result.success / code / desc 로 내려간다. + */ +export interface ErrorInfo { + success?: ErrorInfoSuccess; + code?: ErrorInfoCode; + desc?: ErrorInfoDesc; +} diff --git a/frontend/admin/src/api/generated/model/errorInfoCode.ts b/frontend/admin/src/api/generated/model/errorInfoCode.ts new file mode 100644 index 0000000..90f7cde --- /dev/null +++ b/frontend/admin/src/api/generated/model/errorInfoCode.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ErrorInfoCode = number | null; diff --git a/frontend/admin/src/api/generated/model/errorInfoDesc.ts b/frontend/admin/src/api/generated/model/errorInfoDesc.ts new file mode 100644 index 0000000..5245761 --- /dev/null +++ b/frontend/admin/src/api/generated/model/errorInfoDesc.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ErrorInfoDesc = string | null; diff --git a/frontend/admin/src/api/generated/model/errorInfoSuccess.ts b/frontend/admin/src/api/generated/model/errorInfoSuccess.ts new file mode 100644 index 0000000..27f7828 --- /dev/null +++ b/frontend/admin/src/api/generated/model/errorInfoSuccess.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ErrorInfoSuccess = boolean | null; diff --git a/frontend/admin/src/api/generated/model/externalPlaceSource.ts b/frontend/admin/src/api/generated/model/externalPlaceSource.ts new file mode 100644 index 0000000..756cc7d --- /dev/null +++ b/frontend/admin/src/api/generated/model/externalPlaceSource.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * places.external_source 코드값. 동일 업소 검증에 쓴 외부 장소 DB. + +카카오는 안정적인 고유 place id 를 준다 → 그걸로 중복 등록을 막는다. +네이버는 고유 id 가 없다(응답의 link 는 업체 홈페이지다) → 상호명+도로명주소로 막는다. + */ +export type ExternalPlaceSource = typeof ExternalPlaceSource[keyof typeof ExternalPlaceSource]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const ExternalPlaceSource = { + KAKAO: 1, + NAVER: 2, +} as const; diff --git a/frontend/admin/src/api/generated/model/factData.ts b/frontend/admin/src/api/generated/model/factData.ts new file mode 100644 index 0000000..fd6ca73 --- /dev/null +++ b/frontend/admin/src/api/generated/model/factData.ts @@ -0,0 +1,32 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { FactDataUnitId } from './factDataUnitId'; +import type { FactDataValue } from './factDataValue'; +import type { FactDataUnit } from './factDataUnit'; +import type { SourceType } from './sourceType'; +import type { FactDataSourceUrl } from './factDataSourceUrl'; +import type { FactDataCollectedAt } from './factDataCollectedAt'; +import type { FactDataVerifiedBy } from './factDataVerifiedBy'; +import type { FactDataVerifiedAt } from './factDataVerifiedAt'; +import type { FactStatus } from './factStatus'; +import type { FactDataExpiresAt } from './factDataExpiresAt'; + +export interface FactData { + fact_id: string; + place_id: string; + unit_id?: FactDataUnitId; + key: string; + value?: FactDataValue; + unit?: FactDataUnit; + source_type: SourceType; + source_url?: FactDataSourceUrl; + collected_at?: FactDataCollectedAt; + verified_by?: FactDataVerifiedBy; + verified_at?: FactDataVerifiedAt; + status: FactStatus; + expires_at?: FactDataExpiresAt; +} diff --git a/frontend/admin/src/api/generated/model/factDataCollectedAt.ts b/frontend/admin/src/api/generated/model/factDataCollectedAt.ts new file mode 100644 index 0000000..4925e83 --- /dev/null +++ b/frontend/admin/src/api/generated/model/factDataCollectedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type FactDataCollectedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/factDataExpiresAt.ts b/frontend/admin/src/api/generated/model/factDataExpiresAt.ts new file mode 100644 index 0000000..eae0272 --- /dev/null +++ b/frontend/admin/src/api/generated/model/factDataExpiresAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type FactDataExpiresAt = string | null; diff --git a/frontend/admin/src/api/generated/model/factDataSourceUrl.ts b/frontend/admin/src/api/generated/model/factDataSourceUrl.ts new file mode 100644 index 0000000..24fdd72 --- /dev/null +++ b/frontend/admin/src/api/generated/model/factDataSourceUrl.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type FactDataSourceUrl = string | null; diff --git a/frontend/admin/src/api/generated/model/factDataUnit.ts b/frontend/admin/src/api/generated/model/factDataUnit.ts new file mode 100644 index 0000000..cda8e2c --- /dev/null +++ b/frontend/admin/src/api/generated/model/factDataUnit.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type FactDataUnit = string | null; diff --git a/frontend/admin/src/api/generated/model/factDataUnitId.ts b/frontend/admin/src/api/generated/model/factDataUnitId.ts new file mode 100644 index 0000000..528d743 --- /dev/null +++ b/frontend/admin/src/api/generated/model/factDataUnitId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type FactDataUnitId = string | null; diff --git a/frontend/admin/src/api/generated/model/factDataValue.ts b/frontend/admin/src/api/generated/model/factDataValue.ts new file mode 100644 index 0000000..8fc1478 --- /dev/null +++ b/frontend/admin/src/api/generated/model/factDataValue.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type FactDataValue = string | null; diff --git a/frontend/admin/src/api/generated/model/factDataVerifiedAt.ts b/frontend/admin/src/api/generated/model/factDataVerifiedAt.ts new file mode 100644 index 0000000..b44cd44 --- /dev/null +++ b/frontend/admin/src/api/generated/model/factDataVerifiedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type FactDataVerifiedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/factDataVerifiedBy.ts b/frontend/admin/src/api/generated/model/factDataVerifiedBy.ts new file mode 100644 index 0000000..c20a7e1 --- /dev/null +++ b/frontend/admin/src/api/generated/model/factDataVerifiedBy.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type FactDataVerifiedBy = string | null; diff --git a/frontend/admin/src/api/generated/model/factStatus.ts b/frontend/admin/src/api/generated/model/factStatus.ts new file mode 100644 index 0000000..0c78010 --- /dev/null +++ b/frontend/admin/src/api/generated/model/factStatus.ts @@ -0,0 +1,23 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * facts.status / faqs.status / routes.status 공용 검증 상태. +★ VERIFIED 와 CORRECTED 만 사이트에 노출한다(PUBLISHABLE_FACT_STATUSES). + */ +export type FactStatus = typeof FactStatus[keyof typeof FactStatus]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const FactStatus = { + UNVERIFIED: 1, + PENDING_OWNER: 2, + VERIFIED: 3, + CORRECTED: 4, + REJECTED: 5, + EXPIRED: 6, +} as const; diff --git a/frontend/admin/src/api/generated/model/factWriteOutcome.ts b/frontend/admin/src/api/generated/model/factWriteOutcome.ts new file mode 100644 index 0000000..d1791cb --- /dev/null +++ b/frontend/admin/src/api/generated/model/factWriteOutcome.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * fact 기록 결과. 재수집(업데이트)이 무엇을 했는지 호출측이 알아야 한다 — +특히 사이트 재빌드가 필요한 경우(PUBLISHED_REPLACED)를 구분해야 한다. + */ +export type FactWriteOutcome = typeof FactWriteOutcome[keyof typeof FactWriteOutcome]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const FactWriteOutcome = { + PUBLISHED_CREATED: 1, + PUBLISHED_REPLACED: 2, + REFRESHED: 3, + CANDIDATE_CREATED: 4, + CANDIDATE_UPDATED: 5, +} as const; diff --git a/frontend/admin/src/api/generated/model/faqData.ts b/frontend/admin/src/api/generated/model/faqData.ts new file mode 100644 index 0000000..f196959 --- /dev/null +++ b/frontend/admin/src/api/generated/model/faqData.ts @@ -0,0 +1,24 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { FaqDataSourceFactIds } from './faqDataSourceFactIds'; +import type { SourceType } from './sourceType'; +import type { FactStatus } from './factStatus'; +import type { FaqDataCreatedAt } from './faqDataCreatedAt'; +import type { FaqDataUpdatedAt } from './faqDataUpdatedAt'; + +export interface FaqData { + faq_id: string; + place_id: string; + question: string; + answer: string; + source_fact_ids?: FaqDataSourceFactIds; + generated_by: SourceType; + status: FactStatus; + sort_order?: number; + created_at?: FaqDataCreatedAt; + updated_at?: FaqDataUpdatedAt; +} diff --git a/frontend/admin/src/api/generated/model/faqDataCreatedAt.ts b/frontend/admin/src/api/generated/model/faqDataCreatedAt.ts new file mode 100644 index 0000000..270e5da --- /dev/null +++ b/frontend/admin/src/api/generated/model/faqDataCreatedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type FaqDataCreatedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/faqDataSourceFactIds.ts b/frontend/admin/src/api/generated/model/faqDataSourceFactIds.ts new file mode 100644 index 0000000..94663d0 --- /dev/null +++ b/frontend/admin/src/api/generated/model/faqDataSourceFactIds.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type FaqDataSourceFactIds = string[] | null; diff --git a/frontend/admin/src/api/generated/model/faqDataUpdatedAt.ts b/frontend/admin/src/api/generated/model/faqDataUpdatedAt.ts new file mode 100644 index 0000000..c2fd593 --- /dev/null +++ b/frontend/admin/src/api/generated/model/faqDataUpdatedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type FaqDataUpdatedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/fieldSpecData.ts b/frontend/admin/src/api/generated/model/fieldSpecData.ts new file mode 100644 index 0000000..9b6109c --- /dev/null +++ b/frontend/admin/src/api/generated/model/fieldSpecData.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { FieldSpecDataUnit } from './fieldSpecDataUnit'; + +/** + * 업종 스키마의 필드 정의 — 관리 화면이 입력 폼을 그리는 데 쓴다. + */ +export interface FieldSpecData { + key: string; + label: string; + type: string; + scope: string; + required: boolean; + critical: boolean; + allow_llm: boolean; + unit?: FieldSpecDataUnit; +} diff --git a/frontend/admin/src/api/generated/model/fieldSpecDataUnit.ts b/frontend/admin/src/api/generated/model/fieldSpecDataUnit.ts new file mode 100644 index 0000000..0f9dff7 --- /dev/null +++ b/frontend/admin/src/api/generated/model/fieldSpecDataUnit.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type FieldSpecDataUnit = string | null; diff --git a/frontend/admin/src/api/generated/model/getWeatherParams.ts b/frontend/admin/src/api/generated/model/getWeatherParams.ts new file mode 100644 index 0000000..022c056 --- /dev/null +++ b/frontend/admin/src/api/generated/model/getWeatherParams.ts @@ -0,0 +1,24 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type GetWeatherParams = { +/** + * @minLength 1 + * @maxLength 10 + */ +region_code: string; +/** + * @minimum -90 + * @maximum 90 + */ +latitude: number; +/** + * @minimum -180 + * @maximum 180 + */ +longitude: number; +}; diff --git a/frontend/admin/src/api/generated/model/hTTPValidationError.ts b/frontend/admin/src/api/generated/model/hTTPValidationError.ts new file mode 100644 index 0000000..37970db --- /dev/null +++ b/frontend/admin/src/api/generated/model/hTTPValidationError.ts @@ -0,0 +1,11 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ValidationError } from './validationError'; + +export interface HTTPValidationError { + detail?: ValidationError[]; +} diff --git a/frontend/admin/src/api/generated/model/index.ts b/frontend/admin/src/api/generated/model/index.ts new file mode 100644 index 0000000..f864869 --- /dev/null +++ b/frontend/admin/src/api/generated/model/index.ts @@ -0,0 +1,292 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export * from './auditCheckData'; +export * from './auditCheckDataRecommendation'; +export * from './buildStatus'; +export * from './checkSlugParams'; +export * from './companyData'; +export * from './errorInfo'; +export * from './errorInfoCode'; +export * from './errorInfoDesc'; +export * from './errorInfoSuccess'; +export * from './externalPlaceSource'; +export * from './factData'; +export * from './factDataCollectedAt'; +export * from './factDataExpiresAt'; +export * from './factDataSourceUrl'; +export * from './factDataUnit'; +export * from './factDataUnitId'; +export * from './factDataValue'; +export * from './factDataVerifiedAt'; +export * from './factDataVerifiedBy'; +export * from './factStatus'; +export * from './factWriteOutcome'; +export * from './faqData'; +export * from './faqDataCreatedAt'; +export * from './faqDataSourceFactIds'; +export * from './faqDataUpdatedAt'; +export * from './fieldSpecData'; +export * from './fieldSpecDataUnit'; +export * from './getWeatherParams'; +export * from './hTTPValidationError'; +export * from './jobData'; +export * from './jobDataCreatedAt'; +export * from './jobDataLastError'; +export * from './jobDataResult'; +export * from './jobDataRunAfter'; +export * from './jobDataRunStartedAt'; +export * from './jobDataUpdatedAt'; +export * from './jobStatus'; +export * from './jobType'; +export * from './linkChannel'; +export * from './linkData'; +export * from './linkDataConfirmedAt'; +export * from './linkDataDiscoveredAt'; +export * from './linkDataTitle'; +export * from './listContentsParams'; +export * from './listFactsParams'; +export * from './listFaqsParams'; +export * from './listLinksParams'; +export * from './listMediaParams'; +export * from './listPlacesParams'; +export * from './localContentData'; +export * from './localContentDataBody'; +export * from './localContentDataCollectedAt'; +export * from './localContentDataDisplayEndAt'; +export * from './localContentDataDisplayStartAt'; +export * from './localContentDataExternalId'; +export * from './localContentDataPublishedAt'; +export * from './localContentDataTitle'; +export * from './localContentStatus'; +export * from './localContentType'; +export * from './localSource'; +export * from './mediaData'; +export * from './mediaDataAltText'; +export * from './mediaDataCreatedAt'; +export * from './mediaDataHeight'; +export * from './mediaDataLabel'; +export * from './mediaDataOriginUrl'; +export * from './mediaDataSourceUrl'; +export * from './mediaDataUnitId'; +export * from './mediaDataVisionConfidence'; +export * from './mediaDataWidth'; +export * from './mediaStatus'; +export * from './placeCandidate'; +export * from './placeCandidateAddress'; +export * from './placeCandidateCategoryName'; +export * from './placeCandidateExternalPlaceId'; +export * from './placeCandidateLatitude'; +export * from './placeCandidateLongitude'; +export * from './placeCandidateNaverPlaceUrl'; +export * from './placeCandidatePhone'; +export * from './placeCandidatePlaceUrl'; +export * from './placeCandidateRoadAddress'; +export * from './placeCategory'; +export * from './placeData'; +export * from './placeDataAddress'; +export * from './placeDataContentUpdatedAt'; +export * from './placeDataCreatedAt'; +export * from './placeDataExternalPlaceId'; +export * from './placeDataExternalSource'; +export * from './placeDataLatitude'; +export * from './placeDataLongitude'; +export * from './placeDataOwnerUserId'; +export * from './placeDataPhone'; +export * from './placeDataRegionCode'; +export * from './placeDataRoadAddress'; +export * from './placeDataVerifiedAt'; +export * from './placeStatus'; +export * from './publishAction'; +export * from './publishLogData'; +export * from './publishLogDataCreatedAt'; +export * from './publishLogDataDetail'; +export * from './publishLogDataRejectReason'; +export * from './publishRejectReason'; +export * from './publishResult'; +export * from './renderStatusData'; +export * from './renderStatusDataError'; +export * from './renderStatusDataRenderedAt'; +export * from './renderStatusDataRenderedVersion'; +export * from './reqCreateFaq'; +export * from './reqCreateFaqSortOrder'; +export * from './reqCreateLink'; +export * from './reqCreateLinkTitle'; +export * from './reqCreatePlace'; +export * from './reqCreatePlaceOwnerUserId'; +export * from './reqCreateUnit'; +export * from './reqExtractFacts'; +export * from './reqLogin'; +export * from './reqPublishLocalContent'; +export * from './reqSiteSlug'; +export * from './reqSiteStatus'; +export * from './reqSiteTemplate'; +export * from './reqSiteTheme'; +export * from './reqSiteThemeTheme'; +export * from './reqStartBuild'; +export * from './reqStartCollect'; +export * from './reqStartCopy'; +export * from './reqStartVision'; +export * from './reqSyncFestivals'; +export * from './reqSyncFestivalsAreaCode'; +export * from './reqSyncFestivalsStartDate'; +export * from './reqTransitionFact'; +export * from './reqTransitionFactValue'; +export * from './reqTransitionFaq'; +export * from './reqTransitionFaqAnswer'; +export * from './reqTransitionFaqQuestion'; +export * from './reqUpdateLocalContent'; +export * from './reqUpdateLocalContentBody'; +export * from './reqUpdateLocalContentBodyAnyOf'; +export * from './reqUpdateLocalContentDisplayEndAt'; +export * from './reqUpdateLocalContentDisplayStartAt'; +export * from './reqUpdateLocalContentTitle'; +export * from './reqUpdateMe'; +export * from './reqUpdateMeContactNumber'; +export * from './reqUpdateMeEmail'; +export * from './reqUpdateMeName'; +export * from './reqUpdateMePassword'; +export * from './reqUpdatePlace'; +export * from './reqUpdatePlaceName'; +export * from './reqUpdatePlaceOwnerUserId'; +export * from './reqUpdatePlaceStatus'; +export * from './reqUpsertFact'; +export * from './reqUpsertFactExpiresAt'; +export * from './reqUpsertFactSourceUrl'; +export * from './reqUpsertFactUnitId'; +export * from './reqUpsertFactValue'; +export * from './reqVerifyPlace'; +export * from './reqVerifyPlaceAddress'; +export * from './reqVerifyPlaceByUrl'; +export * from './reqVerifyPlaceLatitude'; +export * from './reqVerifyPlaceLongitude'; +export * from './reqVerifyPlacePhone'; +export * from './reqVerifyPlacePlaceUrl'; +export * from './reqVerifyPlaceRegionCode'; +export * from './reqVerifyPlaceRoadAddress'; +export * from './resCategorySchema'; +export * from './resCategorySchemaCategory'; +export * from './resCategorySchemaLabel'; +export * from './resCategorySchemaMsg'; +export * from './resExtractFacts'; +export * from './resExtractFactsMsg'; +export * from './resExtractedFact'; +export * from './resExtractedFactReason'; +export * from './resExtractedFactUnitName'; +export * from './resFact'; +export * from './resFactFact'; +export * from './resFactList'; +export * from './resFactListMsg'; +export * from './resFactMsg'; +export * from './resFactOutcome'; +export * from './resFaq'; +export * from './resFaqFaq'; +export * from './resFaqList'; +export * from './resFaqListMsg'; +export * from './resFaqMsg'; +export * from './resJob'; +export * from './resJobJob'; +export * from './resJobMsg'; +export * from './resJobOps'; +export * from './resJobOpsMsg'; +export * from './resLink'; +export * from './resLinkLink'; +export * from './resLinkList'; +export * from './resLinkListMsg'; +export * from './resLinkMsg'; +export * from './resLocalContentList'; +export * from './resLocalContentListMsg'; +export * from './resLogin'; +export * from './resLoginMsg'; +export * from './resMe'; +export * from './resMeCompany'; +export * from './resMeContactNumber'; +export * from './resMeEmail'; +export * from './resMeMsg'; +export * from './resMeName'; +export * from './resMediaList'; +export * from './resMediaListMsg'; +export * from './resPlace'; +export * from './resPlaceList'; +export * from './resPlaceListMsg'; +export * from './resPlaceMsg'; +export * from './resPlacePlace'; +export * from './resPublishLogs'; +export * from './resPublishLogsMsg'; +export * from './resRefreshToken'; +export * from './resRefreshTokenMsg'; +export * from './resSeoAudit'; +export * from './resSeoAuditMsg'; +export * from './resSeoAuditSummary'; +export * from './resSeoAuditVisibility'; +export * from './resSite'; +export * from './resSiteCurrentVersion'; +export * from './resSiteMsg'; +export * from './resSiteSite'; +export * from './resSiteSlug'; +export * from './resSiteSlugMsg'; +export * from './resSiteSlugReason'; +export * from './resSiteSlugSite'; +export * from './resSiteSlugSuggestion'; +export * from './resSiteVersions'; +export * from './resSiteVersionsMsg'; +export * from './resSlugCheck'; +export * from './resSlugCheckMsg'; +export * from './resSlugCheckReason'; +export * from './resSlugCheckSuggestion'; +export * from './resStartBuild'; +export * from './resStartBuildJobId'; +export * from './resStartBuildMsg'; +export * from './resStartBuildStatus'; +export * from './resStartCollect'; +export * from './resStartCollectJobId'; +export * from './resStartCollectMsg'; +export * from './resStartCollectStatus'; +export * from './resStartCopy'; +export * from './resStartCopyJobId'; +export * from './resStartCopyMsg'; +export * from './resStartCopyStatus'; +export * from './resStartVision'; +export * from './resStartVisionJobId'; +export * from './resStartVisionMsg'; +export * from './resStartVisionStatus'; +export * from './resSyncFestivals'; +export * from './resSyncFestivalsMsg'; +export * from './resUnit'; +export * from './resUnitList'; +export * from './resUnitListMsg'; +export * from './resUnitMsg'; +export * from './resUnitUnit'; +export * from './resVerifyCandidates'; +export * from './resVerifyCandidatesMsg'; +export * from './resVerifyCandidatesReason'; +export * from './resVerifyCandidatesSource'; +export * from './resWeather'; +export * from './resWeatherMsg'; +export * from './resWeatherWeather'; +export * from './siteData'; +export * from './siteDataCurrentVersionId'; +export * from './siteDataDomain'; +export * from './siteDataPublishedAt'; +export * from './siteDataTemplateId'; +export * from './siteDataTheme'; +export * from './siteDataThemeAnyOf'; +export * from './siteStatus'; +export * from './siteVersionData'; +export * from './siteVersionDataBuildError'; +export * from './siteVersionDataBuiltAt'; +export * from './siteVersionDataCreatedAt'; +export * from './sourceType'; +export * from './unitData'; +export * from './userRole'; +export * from './validationError'; +export * from './validationErrorCtx'; +export * from './validationErrorLocItem'; +export * from './verifyCandidatesParams'; +export * from './weatherData'; +export * from './weatherDataTimezone'; +export * from './weatherDataWindSpeed'; \ No newline at end of file diff --git a/frontend/admin/src/api/generated/model/jobData.ts b/frontend/admin/src/api/generated/model/jobData.ts new file mode 100644 index 0000000..f7914a7 --- /dev/null +++ b/frontend/admin/src/api/generated/model/jobData.ts @@ -0,0 +1,28 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { JobType } from './jobType'; +import type { JobStatus } from './jobStatus'; +import type { JobDataResult } from './jobDataResult'; +import type { JobDataLastError } from './jobDataLastError'; +import type { JobDataRunAfter } from './jobDataRunAfter'; +import type { JobDataRunStartedAt } from './jobDataRunStartedAt'; +import type { JobDataCreatedAt } from './jobDataCreatedAt'; +import type { JobDataUpdatedAt } from './jobDataUpdatedAt'; + +export interface JobData { + job_id: string; + job_type: JobType; + status: JobStatus; + attempts?: number; + max_attempts?: number; + result?: JobDataResult; + last_error?: JobDataLastError; + run_after?: JobDataRunAfter; + run_started_at?: JobDataRunStartedAt; + created_at?: JobDataCreatedAt; + updated_at?: JobDataUpdatedAt; +} diff --git a/frontend/admin/src/api/generated/model/jobDataCreatedAt.ts b/frontend/admin/src/api/generated/model/jobDataCreatedAt.ts new file mode 100644 index 0000000..1fe1f11 --- /dev/null +++ b/frontend/admin/src/api/generated/model/jobDataCreatedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type JobDataCreatedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/jobDataLastError.ts b/frontend/admin/src/api/generated/model/jobDataLastError.ts new file mode 100644 index 0000000..fa5dbc4 --- /dev/null +++ b/frontend/admin/src/api/generated/model/jobDataLastError.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type JobDataLastError = string | null; diff --git a/frontend/admin/src/api/generated/model/jobDataResult.ts b/frontend/admin/src/api/generated/model/jobDataResult.ts new file mode 100644 index 0000000..4ed480f --- /dev/null +++ b/frontend/admin/src/api/generated/model/jobDataResult.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type JobDataResult = unknown | null; diff --git a/frontend/admin/src/api/generated/model/jobDataRunAfter.ts b/frontend/admin/src/api/generated/model/jobDataRunAfter.ts new file mode 100644 index 0000000..3f54985 --- /dev/null +++ b/frontend/admin/src/api/generated/model/jobDataRunAfter.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type JobDataRunAfter = string | null; diff --git a/frontend/admin/src/api/generated/model/jobDataRunStartedAt.ts b/frontend/admin/src/api/generated/model/jobDataRunStartedAt.ts new file mode 100644 index 0000000..3468668 --- /dev/null +++ b/frontend/admin/src/api/generated/model/jobDataRunStartedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type JobDataRunStartedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/jobDataUpdatedAt.ts b/frontend/admin/src/api/generated/model/jobDataUpdatedAt.ts new file mode 100644 index 0000000..0ed50fd --- /dev/null +++ b/frontend/admin/src/api/generated/model/jobDataUpdatedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type JobDataUpdatedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/jobStatus.ts b/frontend/admin/src/api/generated/model/jobStatus.ts new file mode 100644 index 0000000..98296b3 --- /dev/null +++ b/frontend/admin/src/api/generated/model/jobStatus.ts @@ -0,0 +1,23 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * jobs.status 코드값. 작업 큐 상태. + +전이는 전부 조건부 원자 UPDATE(CAS)로만 한다. 실패는 재시도 가능하면 +PENDING(run_after=백오프)으로 되돌리고, 소진되면 DEAD(dead-letter). + */ +export type JobStatus = typeof JobStatus[keyof typeof JobStatus]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const JobStatus = { + PENDING: 1, + RUNNING: 2, + DONE: 3, + DEAD: 4, +} as const; diff --git a/frontend/admin/src/api/generated/model/jobType.ts b/frontend/admin/src/api/generated/model/jobType.ts new file mode 100644 index 0000000..be8484e --- /dev/null +++ b/frontend/admin/src/api/generated/model/jobType.ts @@ -0,0 +1,25 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * jobs.job_type 코드값. 수집·비전·빌드는 몇 분씩 걸려 동기 요청으로 처리할 수 없다. + +무거운 잡(브라우저 필요)과 가벼운 잡(HTTP API 만)을 코드로 갈라 둔다 — +크롤링 법무 결론이 나면 무거운 잡만 별도 워커 이미지로 분리한다. + */ +export type JobType = typeof JobType[keyof typeof JobType]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const JobType = { + COLLECT: 1, + VISION: 2, + COPY: 3, + BUILD: 4, + LOCAL_SYNC: 5, + AI_CHECK: 6, +} as const; diff --git a/frontend/admin/src/api/generated/model/linkChannel.ts b/frontend/admin/src/api/generated/model/linkChannel.ts new file mode 100644 index 0000000..58cf6b4 --- /dev/null +++ b/frontend/admin/src/api/generated/model/linkChannel.ts @@ -0,0 +1,23 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * place_links.channel 코드값. Perplexity 가 발견하는 채널 종류. + */ +export type LinkChannel = typeof LinkChannel[keyof typeof LinkChannel]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const LinkChannel = { + YANOLJA: 1, + GOODCHOICE: 2, + NAVER_PLACE: 3, + INSTAGRAM: 4, + OFFICIAL_SITE: 5, + BLOG: 6, + ETC: 99, +} as const; diff --git a/frontend/admin/src/api/generated/model/linkData.ts b/frontend/admin/src/api/generated/model/linkData.ts new file mode 100644 index 0000000..4054e12 --- /dev/null +++ b/frontend/admin/src/api/generated/model/linkData.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { LinkChannel } from './linkChannel'; +import type { LinkDataTitle } from './linkDataTitle'; +import type { SourceType } from './sourceType'; +import type { LinkDataDiscoveredAt } from './linkDataDiscoveredAt'; +import type { LinkDataConfirmedAt } from './linkDataConfirmedAt'; + +export interface LinkData { + link_id: string; + place_id: string; + channel: LinkChannel; + url: string; + title?: LinkDataTitle; + discovered_by: SourceType; + discovered_at?: LinkDataDiscoveredAt; + confirmed_at?: LinkDataConfirmedAt; +} diff --git a/frontend/admin/src/api/generated/model/linkDataConfirmedAt.ts b/frontend/admin/src/api/generated/model/linkDataConfirmedAt.ts new file mode 100644 index 0000000..3d7419b --- /dev/null +++ b/frontend/admin/src/api/generated/model/linkDataConfirmedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type LinkDataConfirmedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/linkDataDiscoveredAt.ts b/frontend/admin/src/api/generated/model/linkDataDiscoveredAt.ts new file mode 100644 index 0000000..f1ab0e4 --- /dev/null +++ b/frontend/admin/src/api/generated/model/linkDataDiscoveredAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type LinkDataDiscoveredAt = string | null; diff --git a/frontend/admin/src/api/generated/model/linkDataTitle.ts b/frontend/admin/src/api/generated/model/linkDataTitle.ts new file mode 100644 index 0000000..773170e --- /dev/null +++ b/frontend/admin/src/api/generated/model/linkDataTitle.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type LinkDataTitle = string | null; diff --git a/frontend/admin/src/api/generated/model/listContentsParams.ts b/frontend/admin/src/api/generated/model/listContentsParams.ts new file mode 100644 index 0000000..0ee2437 --- /dev/null +++ b/frontend/admin/src/api/generated/model/listContentsParams.ts @@ -0,0 +1,12 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { LocalContentStatus } from './localContentStatus'; + +export type ListContentsParams = { +status?: LocalContentStatus | null; +region_code?: string | null; +}; diff --git a/frontend/admin/src/api/generated/model/listFactsParams.ts b/frontend/admin/src/api/generated/model/listFactsParams.ts new file mode 100644 index 0000000..c3fa47b --- /dev/null +++ b/frontend/admin/src/api/generated/model/listFactsParams.ts @@ -0,0 +1,14 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ListFactsParams = { +/** + * 객실·메뉴·프로그램 단위 fact 만 + */ +unit_id?: string | null; +publishable_only?: boolean; +}; diff --git a/frontend/admin/src/api/generated/model/listFaqsParams.ts b/frontend/admin/src/api/generated/model/listFaqsParams.ts new file mode 100644 index 0000000..d306229 --- /dev/null +++ b/frontend/admin/src/api/generated/model/listFaqsParams.ts @@ -0,0 +1,10 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ListFaqsParams = { +publishable_only?: boolean; +}; diff --git a/frontend/admin/src/api/generated/model/listLinksParams.ts b/frontend/admin/src/api/generated/model/listLinksParams.ts new file mode 100644 index 0000000..5a33484 --- /dev/null +++ b/frontend/admin/src/api/generated/model/listLinksParams.ts @@ -0,0 +1,10 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ListLinksParams = { +confirmed_only?: boolean; +}; diff --git a/frontend/admin/src/api/generated/model/listMediaParams.ts b/frontend/admin/src/api/generated/model/listMediaParams.ts new file mode 100644 index 0000000..a7cf96f --- /dev/null +++ b/frontend/admin/src/api/generated/model/listMediaParams.ts @@ -0,0 +1,14 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ListMediaParams = { +/** + * 객실·메뉴 단위 사진만 + */ +unit_id?: string | null; +publishable_only?: boolean; +}; diff --git a/frontend/admin/src/api/generated/model/listPlacesParams.ts b/frontend/admin/src/api/generated/model/listPlacesParams.ts new file mode 100644 index 0000000..37d7f34 --- /dev/null +++ b/frontend/admin/src/api/generated/model/listPlacesParams.ts @@ -0,0 +1,32 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { PlaceCategory } from './placeCategory'; +import type { PlaceStatus } from './placeStatus'; + +export type ListPlacesParams = { +/** + * 상호명·주소 부분일치 + */ +search?: string | null; +/** + * 업종 + */ +category?: PlaceCategory | null; +/** + * 상태 + */ +status?: PlaceStatus | null; +/** + * @minimum 1 + */ +page?: number; +/** + * @minimum 1 + * @maximum 100 + */ +size?: number; +}; diff --git a/frontend/admin/src/api/generated/model/localContentData.ts b/frontend/admin/src/api/generated/model/localContentData.ts new file mode 100644 index 0000000..51d2f37 --- /dev/null +++ b/frontend/admin/src/api/generated/model/localContentData.ts @@ -0,0 +1,31 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { LocalContentType } from './localContentType'; +import type { LocalSource } from './localSource'; +import type { LocalContentDataExternalId } from './localContentDataExternalId'; +import type { LocalContentDataTitle } from './localContentDataTitle'; +import type { LocalContentDataBody } from './localContentDataBody'; +import type { LocalContentStatus } from './localContentStatus'; +import type { LocalContentDataCollectedAt } from './localContentDataCollectedAt'; +import type { LocalContentDataPublishedAt } from './localContentDataPublishedAt'; +import type { LocalContentDataDisplayStartAt } from './localContentDataDisplayStartAt'; +import type { LocalContentDataDisplayEndAt } from './localContentDataDisplayEndAt'; + +export interface LocalContentData { + local_content_id: string; + region_code: string; + content_type: LocalContentType; + source: LocalSource; + external_id?: LocalContentDataExternalId; + title?: LocalContentDataTitle; + body: LocalContentDataBody; + status: LocalContentStatus; + collected_at?: LocalContentDataCollectedAt; + published_at?: LocalContentDataPublishedAt; + display_start_at?: LocalContentDataDisplayStartAt; + display_end_at?: LocalContentDataDisplayEndAt; +} diff --git a/frontend/admin/src/api/generated/model/localContentDataBody.ts b/frontend/admin/src/api/generated/model/localContentDataBody.ts new file mode 100644 index 0000000..ca4fe17 --- /dev/null +++ b/frontend/admin/src/api/generated/model/localContentDataBody.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type LocalContentDataBody = { [key: string]: unknown }; diff --git a/frontend/admin/src/api/generated/model/localContentDataCollectedAt.ts b/frontend/admin/src/api/generated/model/localContentDataCollectedAt.ts new file mode 100644 index 0000000..b2c3342 --- /dev/null +++ b/frontend/admin/src/api/generated/model/localContentDataCollectedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type LocalContentDataCollectedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/localContentDataDisplayEndAt.ts b/frontend/admin/src/api/generated/model/localContentDataDisplayEndAt.ts new file mode 100644 index 0000000..790a4e7 --- /dev/null +++ b/frontend/admin/src/api/generated/model/localContentDataDisplayEndAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type LocalContentDataDisplayEndAt = string | null; diff --git a/frontend/admin/src/api/generated/model/localContentDataDisplayStartAt.ts b/frontend/admin/src/api/generated/model/localContentDataDisplayStartAt.ts new file mode 100644 index 0000000..cb3ffb1 --- /dev/null +++ b/frontend/admin/src/api/generated/model/localContentDataDisplayStartAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type LocalContentDataDisplayStartAt = string | null; diff --git a/frontend/admin/src/api/generated/model/localContentDataExternalId.ts b/frontend/admin/src/api/generated/model/localContentDataExternalId.ts new file mode 100644 index 0000000..2c4d34b --- /dev/null +++ b/frontend/admin/src/api/generated/model/localContentDataExternalId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type LocalContentDataExternalId = string | null; diff --git a/frontend/admin/src/api/generated/model/localContentDataPublishedAt.ts b/frontend/admin/src/api/generated/model/localContentDataPublishedAt.ts new file mode 100644 index 0000000..f53525a --- /dev/null +++ b/frontend/admin/src/api/generated/model/localContentDataPublishedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type LocalContentDataPublishedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/localContentDataTitle.ts b/frontend/admin/src/api/generated/model/localContentDataTitle.ts new file mode 100644 index 0000000..8551e3c --- /dev/null +++ b/frontend/admin/src/api/generated/model/localContentDataTitle.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type LocalContentDataTitle = string | null; diff --git a/frontend/admin/src/api/generated/model/localContentStatus.ts b/frontend/admin/src/api/generated/model/localContentStatus.ts new file mode 100644 index 0000000..51092d9 --- /dev/null +++ b/frontend/admin/src/api/generated/model/localContentStatus.ts @@ -0,0 +1,19 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * 운영 관리자가 검수하는 지역 콘텐츠 발행 상태. + */ +export type LocalContentStatus = typeof LocalContentStatus[keyof typeof LocalContentStatus]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const LocalContentStatus = { + REVIEW: 1, + PUBLISHED: 2, + ENDED: 3, +} as const; diff --git a/frontend/admin/src/api/generated/model/localContentType.ts b/frontend/admin/src/api/generated/model/localContentType.ts new file mode 100644 index 0000000..36d49de --- /dev/null +++ b/frontend/admin/src/api/generated/model/localContentType.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * local_contents.content_type 코드값. 행정구역 코드 단위로 캐싱되는 지역 정보 종류. + */ +export type LocalContentType = typeof LocalContentType[keyof typeof LocalContentType]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const LocalContentType = { + WEATHER: 1, + FESTIVAL: 2, + ATTRACTION: 3, + RESTAURANT: 4, +} as const; diff --git a/frontend/admin/src/api/generated/model/localSource.ts b/frontend/admin/src/api/generated/model/localSource.ts new file mode 100644 index 0000000..163adc6 --- /dev/null +++ b/frontend/admin/src/api/generated/model/localSource.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * local_contents.source 코드값. 어느 외부 API 에서 왔는지. + */ +export type LocalSource = typeof LocalSource[keyof typeof LocalSource]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const LocalSource = { + OPEN_METEO: 1, + TOUR_API: 2, + KAKAO_LOCAL: 3, + OFFICIAL_WEB: 4, +} as const; diff --git a/frontend/admin/src/api/generated/model/mediaData.ts b/frontend/admin/src/api/generated/model/mediaData.ts new file mode 100644 index 0000000..1539854 --- /dev/null +++ b/frontend/admin/src/api/generated/model/mediaData.ts @@ -0,0 +1,44 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { MediaDataUnitId } from './mediaDataUnitId'; +import type { MediaDataOriginUrl } from './mediaDataOriginUrl'; +import type { SourceType } from './sourceType'; +import type { MediaDataSourceUrl } from './mediaDataSourceUrl'; +import type { MediaDataLabel } from './mediaDataLabel'; +import type { MediaDataAltText } from './mediaDataAltText'; +import type { MediaDataVisionConfidence } from './mediaDataVisionConfidence'; +import type { MediaStatus } from './mediaStatus'; +import type { MediaDataWidth } from './mediaDataWidth'; +import type { MediaDataHeight } from './mediaDataHeight'; +import type { MediaDataCreatedAt } from './mediaDataCreatedAt'; + +/** + * 사진 1건. + +★ source_type 과 origin_url 을 반드시 함께 내려보낸다 — 크롤링 이미지의 재게시 권리가 + 아직 미결이라(docs/DECISIONS.md 1-2), 결론이 '불가'로 나면 발행에서 source_type = CRAWL 을 + 통째로 제외해야 한다. 화면이 출처를 모르면 무엇이 빠질지도 미리 보여줄 수 없다. + origin_url 은 그때 '이 사진은 어디서 왔는가'를 증명하는 유일한 근거다. + */ +export interface MediaData { + media_id: string; + place_id: string; + unit_id?: MediaDataUnitId; + url: string; + origin_url?: MediaDataOriginUrl; + source_type: SourceType; + source_url?: MediaDataSourceUrl; + label?: MediaDataLabel; + alt_text?: MediaDataAltText; + vision_confidence?: MediaDataVisionConfidence; + status: MediaStatus; + width?: MediaDataWidth; + height?: MediaDataHeight; + sort_order?: number; + created_at?: MediaDataCreatedAt; + publishable?: boolean; +} diff --git a/frontend/admin/src/api/generated/model/mediaDataAltText.ts b/frontend/admin/src/api/generated/model/mediaDataAltText.ts new file mode 100644 index 0000000..4d24922 --- /dev/null +++ b/frontend/admin/src/api/generated/model/mediaDataAltText.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type MediaDataAltText = string | null; diff --git a/frontend/admin/src/api/generated/model/mediaDataCreatedAt.ts b/frontend/admin/src/api/generated/model/mediaDataCreatedAt.ts new file mode 100644 index 0000000..67c4fc8 --- /dev/null +++ b/frontend/admin/src/api/generated/model/mediaDataCreatedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type MediaDataCreatedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/mediaDataHeight.ts b/frontend/admin/src/api/generated/model/mediaDataHeight.ts new file mode 100644 index 0000000..f467666 --- /dev/null +++ b/frontend/admin/src/api/generated/model/mediaDataHeight.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type MediaDataHeight = number | null; diff --git a/frontend/admin/src/api/generated/model/mediaDataLabel.ts b/frontend/admin/src/api/generated/model/mediaDataLabel.ts new file mode 100644 index 0000000..45b36da --- /dev/null +++ b/frontend/admin/src/api/generated/model/mediaDataLabel.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type MediaDataLabel = string | null; diff --git a/frontend/admin/src/api/generated/model/mediaDataOriginUrl.ts b/frontend/admin/src/api/generated/model/mediaDataOriginUrl.ts new file mode 100644 index 0000000..9a3ce73 --- /dev/null +++ b/frontend/admin/src/api/generated/model/mediaDataOriginUrl.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type MediaDataOriginUrl = string | null; diff --git a/frontend/admin/src/api/generated/model/mediaDataSourceUrl.ts b/frontend/admin/src/api/generated/model/mediaDataSourceUrl.ts new file mode 100644 index 0000000..988a438 --- /dev/null +++ b/frontend/admin/src/api/generated/model/mediaDataSourceUrl.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type MediaDataSourceUrl = string | null; diff --git a/frontend/admin/src/api/generated/model/mediaDataUnitId.ts b/frontend/admin/src/api/generated/model/mediaDataUnitId.ts new file mode 100644 index 0000000..fad3e28 --- /dev/null +++ b/frontend/admin/src/api/generated/model/mediaDataUnitId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type MediaDataUnitId = string | null; diff --git a/frontend/admin/src/api/generated/model/mediaDataVisionConfidence.ts b/frontend/admin/src/api/generated/model/mediaDataVisionConfidence.ts new file mode 100644 index 0000000..ef511d7 --- /dev/null +++ b/frontend/admin/src/api/generated/model/mediaDataVisionConfidence.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type MediaDataVisionConfidence = string | null; diff --git a/frontend/admin/src/api/generated/model/mediaDataWidth.ts b/frontend/admin/src/api/generated/model/mediaDataWidth.ts new file mode 100644 index 0000000..a81c96c --- /dev/null +++ b/frontend/admin/src/api/generated/model/mediaDataWidth.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type MediaDataWidth = number | null; diff --git a/frontend/admin/src/api/generated/model/mediaStatus.ts b/frontend/admin/src/api/generated/model/mediaStatus.ts new file mode 100644 index 0000000..f8541c1 --- /dev/null +++ b/frontend/admin/src/api/generated/model/mediaStatus.ts @@ -0,0 +1,19 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * media.status 코드값. 비전 결과 신뢰도가 낮으면 자동 반영하지 않고 PENDING_REVIEW 로 둔다. + */ +export type MediaStatus = typeof MediaStatus[keyof typeof MediaStatus]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const MediaStatus = { + PENDING_REVIEW: 1, + APPROVED: 2, + REJECTED: 3, +} as const; diff --git a/frontend/admin/src/api/generated/model/placeCandidate.ts b/frontend/admin/src/api/generated/model/placeCandidate.ts new file mode 100644 index 0000000..0cd639a --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeCandidate.ts @@ -0,0 +1,31 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { PlaceCandidateExternalPlaceId } from './placeCandidateExternalPlaceId'; +import type { PlaceCandidateRoadAddress } from './placeCandidateRoadAddress'; +import type { PlaceCandidateAddress } from './placeCandidateAddress'; +import type { PlaceCandidatePhone } from './placeCandidatePhone'; +import type { PlaceCandidateLatitude } from './placeCandidateLatitude'; +import type { PlaceCandidateLongitude } from './placeCandidateLongitude'; +import type { PlaceCandidateCategoryName } from './placeCandidateCategoryName'; +import type { PlaceCandidatePlaceUrl } from './placeCandidatePlaceUrl'; +import type { PlaceCandidateNaverPlaceUrl } from './placeCandidateNaverPlaceUrl'; + +/** + * 외부 장소 DB 에서 찾은 후보 1건. UI 가 이걸 카드로 그려 사람이 고른다. + */ +export interface PlaceCandidate { + external_place_id?: PlaceCandidateExternalPlaceId; + name?: string; + road_address?: PlaceCandidateRoadAddress; + address?: PlaceCandidateAddress; + phone?: PlaceCandidatePhone; + latitude?: PlaceCandidateLatitude; + longitude?: PlaceCandidateLongitude; + category_name?: PlaceCandidateCategoryName; + place_url?: PlaceCandidatePlaceUrl; + naver_place_url?: PlaceCandidateNaverPlaceUrl; +} diff --git a/frontend/admin/src/api/generated/model/placeCandidateAddress.ts b/frontend/admin/src/api/generated/model/placeCandidateAddress.ts new file mode 100644 index 0000000..739ebde --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeCandidateAddress.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceCandidateAddress = string | null; diff --git a/frontend/admin/src/api/generated/model/placeCandidateCategoryName.ts b/frontend/admin/src/api/generated/model/placeCandidateCategoryName.ts new file mode 100644 index 0000000..1651384 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeCandidateCategoryName.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceCandidateCategoryName = string | null; diff --git a/frontend/admin/src/api/generated/model/placeCandidateExternalPlaceId.ts b/frontend/admin/src/api/generated/model/placeCandidateExternalPlaceId.ts new file mode 100644 index 0000000..695418b --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeCandidateExternalPlaceId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceCandidateExternalPlaceId = string | null; diff --git a/frontend/admin/src/api/generated/model/placeCandidateLatitude.ts b/frontend/admin/src/api/generated/model/placeCandidateLatitude.ts new file mode 100644 index 0000000..5f4f6ee --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeCandidateLatitude.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceCandidateLatitude = string | null; diff --git a/frontend/admin/src/api/generated/model/placeCandidateLongitude.ts b/frontend/admin/src/api/generated/model/placeCandidateLongitude.ts new file mode 100644 index 0000000..23c0167 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeCandidateLongitude.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceCandidateLongitude = string | null; diff --git a/frontend/admin/src/api/generated/model/placeCandidateNaverPlaceUrl.ts b/frontend/admin/src/api/generated/model/placeCandidateNaverPlaceUrl.ts new file mode 100644 index 0000000..3704b15 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeCandidateNaverPlaceUrl.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceCandidateNaverPlaceUrl = string | null; diff --git a/frontend/admin/src/api/generated/model/placeCandidatePhone.ts b/frontend/admin/src/api/generated/model/placeCandidatePhone.ts new file mode 100644 index 0000000..ad76415 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeCandidatePhone.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceCandidatePhone = string | null; diff --git a/frontend/admin/src/api/generated/model/placeCandidatePlaceUrl.ts b/frontend/admin/src/api/generated/model/placeCandidatePlaceUrl.ts new file mode 100644 index 0000000..a8bbc62 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeCandidatePlaceUrl.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceCandidatePlaceUrl = string | null; diff --git a/frontend/admin/src/api/generated/model/placeCandidateRoadAddress.ts b/frontend/admin/src/api/generated/model/placeCandidateRoadAddress.ts new file mode 100644 index 0000000..b18a287 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeCandidateRoadAddress.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceCandidateRoadAddress = string | null; diff --git a/frontend/admin/src/api/generated/model/placeCategory.ts b/frontend/admin/src/api/generated/model/placeCategory.ts new file mode 100644 index 0000000..7573e1f --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeCategory.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * places.category 코드값. 업종 — 스키마 파일(common/category_schema/resources/*.json)과 1:1. +업종 추가 = 여기에 코드 추가 + 스키마 파일 1개 추가. + */ +export type PlaceCategory = typeof PlaceCategory[keyof typeof PlaceCategory]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const PlaceCategory = { + LODGING: 1, + CAFE: 2, + RESTAURANT: 3, + TOUR_ACTIVITY: 4, +} as const; diff --git a/frontend/admin/src/api/generated/model/placeData.ts b/frontend/admin/src/api/generated/model/placeData.ts new file mode 100644 index 0000000..7fbfef8 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeData.ts @@ -0,0 +1,39 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { PlaceCategory } from './placeCategory'; +import type { PlaceStatus } from './placeStatus'; +import type { PlaceDataOwnerUserId } from './placeDataOwnerUserId'; +import type { PlaceDataExternalSource } from './placeDataExternalSource'; +import type { PlaceDataExternalPlaceId } from './placeDataExternalPlaceId'; +import type { PlaceDataRoadAddress } from './placeDataRoadAddress'; +import type { PlaceDataAddress } from './placeDataAddress'; +import type { PlaceDataPhone } from './placeDataPhone'; +import type { PlaceDataLatitude } from './placeDataLatitude'; +import type { PlaceDataLongitude } from './placeDataLongitude'; +import type { PlaceDataRegionCode } from './placeDataRegionCode'; +import type { PlaceDataVerifiedAt } from './placeDataVerifiedAt'; +import type { PlaceDataContentUpdatedAt } from './placeDataContentUpdatedAt'; +import type { PlaceDataCreatedAt } from './placeDataCreatedAt'; + +export interface PlaceData { + place_id: string; + name: string; + category: PlaceCategory; + status: PlaceStatus; + owner_user_id?: PlaceDataOwnerUserId; + external_source?: PlaceDataExternalSource; + external_place_id?: PlaceDataExternalPlaceId; + road_address?: PlaceDataRoadAddress; + address?: PlaceDataAddress; + phone?: PlaceDataPhone; + latitude?: PlaceDataLatitude; + longitude?: PlaceDataLongitude; + region_code?: PlaceDataRegionCode; + verified_at?: PlaceDataVerifiedAt; + content_updated_at?: PlaceDataContentUpdatedAt; + created_at?: PlaceDataCreatedAt; +} diff --git a/frontend/admin/src/api/generated/model/placeDataAddress.ts b/frontend/admin/src/api/generated/model/placeDataAddress.ts new file mode 100644 index 0000000..1c50f14 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeDataAddress.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceDataAddress = string | null; diff --git a/frontend/admin/src/api/generated/model/placeDataContentUpdatedAt.ts b/frontend/admin/src/api/generated/model/placeDataContentUpdatedAt.ts new file mode 100644 index 0000000..436a2ca --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeDataContentUpdatedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceDataContentUpdatedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/placeDataCreatedAt.ts b/frontend/admin/src/api/generated/model/placeDataCreatedAt.ts new file mode 100644 index 0000000..f3b28c5 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeDataCreatedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceDataCreatedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/placeDataExternalPlaceId.ts b/frontend/admin/src/api/generated/model/placeDataExternalPlaceId.ts new file mode 100644 index 0000000..c8aab93 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeDataExternalPlaceId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceDataExternalPlaceId = string | null; diff --git a/frontend/admin/src/api/generated/model/placeDataExternalSource.ts b/frontend/admin/src/api/generated/model/placeDataExternalSource.ts new file mode 100644 index 0000000..03c0749 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeDataExternalSource.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ExternalPlaceSource } from './externalPlaceSource'; + +export type PlaceDataExternalSource = ExternalPlaceSource | null; diff --git a/frontend/admin/src/api/generated/model/placeDataLatitude.ts b/frontend/admin/src/api/generated/model/placeDataLatitude.ts new file mode 100644 index 0000000..97af93e --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeDataLatitude.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceDataLatitude = string | null; diff --git a/frontend/admin/src/api/generated/model/placeDataLongitude.ts b/frontend/admin/src/api/generated/model/placeDataLongitude.ts new file mode 100644 index 0000000..5f845b9 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeDataLongitude.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceDataLongitude = string | null; diff --git a/frontend/admin/src/api/generated/model/placeDataOwnerUserId.ts b/frontend/admin/src/api/generated/model/placeDataOwnerUserId.ts new file mode 100644 index 0000000..e10034f --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeDataOwnerUserId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceDataOwnerUserId = string | null; diff --git a/frontend/admin/src/api/generated/model/placeDataPhone.ts b/frontend/admin/src/api/generated/model/placeDataPhone.ts new file mode 100644 index 0000000..074428a --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeDataPhone.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceDataPhone = string | null; diff --git a/frontend/admin/src/api/generated/model/placeDataRegionCode.ts b/frontend/admin/src/api/generated/model/placeDataRegionCode.ts new file mode 100644 index 0000000..8ee3725 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeDataRegionCode.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceDataRegionCode = string | null; diff --git a/frontend/admin/src/api/generated/model/placeDataRoadAddress.ts b/frontend/admin/src/api/generated/model/placeDataRoadAddress.ts new file mode 100644 index 0000000..7afa156 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeDataRoadAddress.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceDataRoadAddress = string | null; diff --git a/frontend/admin/src/api/generated/model/placeDataVerifiedAt.ts b/frontend/admin/src/api/generated/model/placeDataVerifiedAt.ts new file mode 100644 index 0000000..339909d --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeDataVerifiedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PlaceDataVerifiedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/placeStatus.ts b/frontend/admin/src/api/generated/model/placeStatus.ts new file mode 100644 index 0000000..5693a00 --- /dev/null +++ b/frontend/admin/src/api/generated/model/placeStatus.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * places.status 코드값. 사업장 생애주기. +해지는 삭제가 아니라 SUSPENDED 로의 상태 전이다(색인된 페이지를 갑자기 404 로 만들지 않는다). + */ +export type PlaceStatus = typeof PlaceStatus[keyof typeof PlaceStatus]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const PlaceStatus = { + DRAFT: 1, + COLLECTING: 2, + REVIEW: 3, + PUBLISHED: 4, + SUSPENDED: 5, +} as const; diff --git a/frontend/admin/src/api/generated/model/publishAction.ts b/frontend/admin/src/api/generated/model/publishAction.ts new file mode 100644 index 0000000..0d56e92 --- /dev/null +++ b/frontend/admin/src/api/generated/model/publishAction.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * publish_logs.action 코드값. + */ +export type PublishAction = typeof PublishAction[keyof typeof PublishAction]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const PublishAction = { + PUBLISH: 1, + UNPUBLISH: 2, + REBUILD: 3, + SUSPEND: 4, + RESUME: 5, +} as const; diff --git a/frontend/admin/src/api/generated/model/publishLogData.ts b/frontend/admin/src/api/generated/model/publishLogData.ts new file mode 100644 index 0000000..2e0ed79 --- /dev/null +++ b/frontend/admin/src/api/generated/model/publishLogData.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { PublishAction } from './publishAction'; +import type { PublishResult } from './publishResult'; +import type { PublishLogDataRejectReason } from './publishLogDataRejectReason'; +import type { PublishLogDataDetail } from './publishLogDataDetail'; +import type { PublishLogDataCreatedAt } from './publishLogDataCreatedAt'; + +export interface PublishLogData { + publish_log_id: string; + action: PublishAction; + result: PublishResult; + reject_reason?: PublishLogDataRejectReason; + detail?: PublishLogDataDetail; + created_at?: PublishLogDataCreatedAt; +} diff --git a/frontend/admin/src/api/generated/model/publishLogDataCreatedAt.ts b/frontend/admin/src/api/generated/model/publishLogDataCreatedAt.ts new file mode 100644 index 0000000..dcd9922 --- /dev/null +++ b/frontend/admin/src/api/generated/model/publishLogDataCreatedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PublishLogDataCreatedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/publishLogDataDetail.ts b/frontend/admin/src/api/generated/model/publishLogDataDetail.ts new file mode 100644 index 0000000..182dd4a --- /dev/null +++ b/frontend/admin/src/api/generated/model/publishLogDataDetail.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type PublishLogDataDetail = unknown | null; diff --git a/frontend/admin/src/api/generated/model/publishLogDataRejectReason.ts b/frontend/admin/src/api/generated/model/publishLogDataRejectReason.ts new file mode 100644 index 0000000..db9fb8f --- /dev/null +++ b/frontend/admin/src/api/generated/model/publishLogDataRejectReason.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { PublishRejectReason } from './publishRejectReason'; + +export type PublishLogDataRejectReason = PublishRejectReason | null; diff --git a/frontend/admin/src/api/generated/model/publishRejectReason.ts b/frontend/admin/src/api/generated/model/publishRejectReason.ts new file mode 100644 index 0000000..6fcb170 --- /dev/null +++ b/frontend/admin/src/api/generated/model/publishRejectReason.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * publish_logs.reject_reason 코드값. 검수 게이트가 발행을 막은 이유(절대규칙 1~3). + */ +export type PublishRejectReason = typeof PublishRejectReason[keyof typeof PublishRejectReason]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const PublishRejectReason = { + UNVERIFIED_FACT: 1, + NO_UNIQUE_CONTENT: 2, + JSONLD_MISMATCH: 3, + REQUIRED_FACT_MISSING: 4, +} as const; diff --git a/frontend/admin/src/api/generated/model/publishResult.ts b/frontend/admin/src/api/generated/model/publishResult.ts new file mode 100644 index 0000000..1c2d2a4 --- /dev/null +++ b/frontend/admin/src/api/generated/model/publishResult.ts @@ -0,0 +1,19 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * publish_logs.result 코드값. + */ +export type PublishResult = typeof PublishResult[keyof typeof PublishResult]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const PublishResult = { + SUCCESS: 1, + REJECTED: 2, + FAILED: 3, +} as const; diff --git a/frontend/admin/src/api/generated/model/renderStatusData.ts b/frontend/admin/src/api/generated/model/renderStatusData.ts new file mode 100644 index 0000000..697aa96 --- /dev/null +++ b/frontend/admin/src/api/generated/model/renderStatusData.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { RenderStatusDataRenderedAt } from './renderStatusDataRenderedAt'; +import type { RenderStatusDataRenderedVersion } from './renderStatusDataRenderedVersion'; +import type { RenderStatusDataError } from './renderStatusDataError'; + +/** + * 정적 페이지가 실제로 구워졌는지. 프리렌더가 남긴 보고서를 그대로 옮긴다. + +★ 발행 기록(DB)과 실제 페이지(파일)는 다른 곳에 산다. 이게 없으면 프리렌더가 깨져도 + DB 는 "발행됨"이라 말하고 사장님은 [사이트 열기] 를 눌러야 404 로 알게 된다. + */ +export interface RenderStatusData { + state?: string; + rendered_at?: RenderStatusDataRenderedAt; + rendered_version?: RenderStatusDataRenderedVersion; + error?: RenderStatusDataError; +} diff --git a/frontend/admin/src/api/generated/model/renderStatusDataError.ts b/frontend/admin/src/api/generated/model/renderStatusDataError.ts new file mode 100644 index 0000000..9c51189 --- /dev/null +++ b/frontend/admin/src/api/generated/model/renderStatusDataError.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type RenderStatusDataError = string | null; diff --git a/frontend/admin/src/api/generated/model/renderStatusDataRenderedAt.ts b/frontend/admin/src/api/generated/model/renderStatusDataRenderedAt.ts new file mode 100644 index 0000000..0bebf92 --- /dev/null +++ b/frontend/admin/src/api/generated/model/renderStatusDataRenderedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type RenderStatusDataRenderedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/renderStatusDataRenderedVersion.ts b/frontend/admin/src/api/generated/model/renderStatusDataRenderedVersion.ts new file mode 100644 index 0000000..5979662 --- /dev/null +++ b/frontend/admin/src/api/generated/model/renderStatusDataRenderedVersion.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type RenderStatusDataRenderedVersion = number | null; diff --git a/frontend/admin/src/api/generated/model/reqCreateFaq.ts b/frontend/admin/src/api/generated/model/reqCreateFaq.ts new file mode 100644 index 0000000..7e5c5f6 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqCreateFaq.ts @@ -0,0 +1,19 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ReqCreateFaqSortOrder } from './reqCreateFaqSortOrder'; + +/** + * 사장님이 직접 쓴 FAQ. + +★ generated_by 를 요청으로 받지 않는다 — 받으면 LLM 생성물을 사람이 쓴 것처럼 올려 + 승인 절차를 통째로 건너뛸 수 있다. 출처는 서버가 OWNER 로 고정한다. + */ +export interface ReqCreateFaq { + question?: string; + answer?: string; + sort_order?: ReqCreateFaqSortOrder; +} diff --git a/frontend/admin/src/api/generated/model/reqCreateFaqSortOrder.ts b/frontend/admin/src/api/generated/model/reqCreateFaqSortOrder.ts new file mode 100644 index 0000000..267d6c9 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqCreateFaqSortOrder.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqCreateFaqSortOrder = number | null; diff --git a/frontend/admin/src/api/generated/model/reqCreateLink.ts b/frontend/admin/src/api/generated/model/reqCreateLink.ts new file mode 100644 index 0000000..df1e00b --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqCreateLink.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { LinkChannel } from './linkChannel'; +import type { ReqCreateLinkTitle } from './reqCreateLinkTitle'; +import type { SourceType } from './sourceType'; + +export interface ReqCreateLink { + channel?: LinkChannel; + url?: string; + title?: ReqCreateLinkTitle; + discovered_by?: SourceType; +} diff --git a/frontend/admin/src/api/generated/model/reqCreateLinkTitle.ts b/frontend/admin/src/api/generated/model/reqCreateLinkTitle.ts new file mode 100644 index 0000000..10d5422 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqCreateLinkTitle.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqCreateLinkTitle = string | null; diff --git a/frontend/admin/src/api/generated/model/reqCreatePlace.ts b/frontend/admin/src/api/generated/model/reqCreatePlace.ts new file mode 100644 index 0000000..d117aab --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqCreatePlace.ts @@ -0,0 +1,14 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { PlaceCategory } from './placeCategory'; +import type { ReqCreatePlaceOwnerUserId } from './reqCreatePlaceOwnerUserId'; + +export interface ReqCreatePlace { + name?: string; + category?: PlaceCategory; + owner_user_id?: ReqCreatePlaceOwnerUserId; +} diff --git a/frontend/admin/src/api/generated/model/reqCreatePlaceOwnerUserId.ts b/frontend/admin/src/api/generated/model/reqCreatePlaceOwnerUserId.ts new file mode 100644 index 0000000..26da46e --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqCreatePlaceOwnerUserId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqCreatePlaceOwnerUserId = string | null; diff --git a/frontend/admin/src/api/generated/model/reqCreateUnit.ts b/frontend/admin/src/api/generated/model/reqCreateUnit.ts new file mode 100644 index 0000000..85bb0f3 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqCreateUnit.ts @@ -0,0 +1,11 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export interface ReqCreateUnit { + name?: string; + sort_order?: number; +} diff --git a/frontend/admin/src/api/generated/model/reqExtractFacts.ts b/frontend/admin/src/api/generated/model/reqExtractFacts.ts new file mode 100644 index 0000000..97a4448 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqExtractFacts.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * 사장님이 붙여넣은 원문에서 fact 를 뽑는다. + +★ 왜 이 입구가 필요한가 (2026-08-31) + TourAPI 에 없고 네이버에도 요금표뿐인 업소가 흔하다(실측: 조이모텔 — 수집 fact 6건이 + 전부 대실·숙박 요금이었다). 그런 업소는 자동 수집만으로는 발행 근거가 영영 안 찬다. + 폴백 3단계의 2번(사장님이 직접 붙여넣기)이 여기다. + +★ 뽑은 값은 전부 **후보(UNVERIFIED)** 로 들어간다. 사장님이 확인해야 사이트에 나간다. + */ +export interface ReqExtractFacts { + text?: string; +} diff --git a/frontend/admin/src/api/generated/model/reqLogin.ts b/frontend/admin/src/api/generated/model/reqLogin.ts new file mode 100644 index 0000000..a5506f8 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqLogin.ts @@ -0,0 +1,11 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export interface ReqLogin { + id?: string; + password?: string; +} diff --git a/frontend/admin/src/api/generated/model/reqPublishLocalContent.ts b/frontend/admin/src/api/generated/model/reqPublishLocalContent.ts new file mode 100644 index 0000000..a64e66e --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqPublishLocalContent.ts @@ -0,0 +1,14 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export interface ReqPublishLocalContent { + /** + * @minItems 1 + * @maxItems 100 + */ + content_ids: string[]; +} diff --git a/frontend/admin/src/api/generated/model/reqSiteSlug.ts b/frontend/admin/src/api/generated/model/reqSiteSlug.ts new file mode 100644 index 0000000..e13f161 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqSiteSlug.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * 사이트 주소(네임스페이스) 예약. + +★ 서버가 상호명으로 자동 확정하지 않는다 — 사장님이 고른다. + 주소는 AI 검색이 색인하는 영구 식별자라, 한 번 정해지면 되돌리는 비용이 사장님 몫이 된다. + */ +export interface ReqSiteSlug { + slug?: string; +} diff --git a/frontend/admin/src/api/generated/model/reqSiteStatus.ts b/frontend/admin/src/api/generated/model/reqSiteStatus.ts new file mode 100644 index 0000000..d1037bd --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqSiteStatus.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { PublishAction } from './publishAction'; + +/** + * 발행 상태 전이. ★ 해지는 삭제가 아니라 상태 전이다 — +색인된 페이지를 갑자기 404 로 만들면 그 자리를 다시 OTA 가 가져간다. + */ +export interface ReqSiteStatus { + action?: PublishAction; +} diff --git a/frontend/admin/src/api/generated/model/reqSiteTemplate.ts b/frontend/admin/src/api/generated/model/reqSiteTemplate.ts new file mode 100644 index 0000000..af09de5 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqSiteTemplate.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * 템플릿 선택 저장. + +★ 서버는 값을 검증하지 않는다. 템플릿 목록은 프론트(배리에이션 레지스트리)가 소유하므로 + 여기서 화이트리스트를 두면 템플릿을 하나 늘릴 때마다 백엔드를 같이 고쳐야 한다. + 잘못된 키가 들어와도 발행 잡이 업종 기본으로 떨어뜨린다 — 화면이 깨지지 않는다. + */ +export interface ReqSiteTemplate { + template_id?: string; +} diff --git a/frontend/admin/src/api/generated/model/reqSiteTheme.ts b/frontend/admin/src/api/generated/model/reqSiteTheme.ts new file mode 100644 index 0000000..f6fa1ae --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqSiteTheme.ts @@ -0,0 +1,39 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ReqSiteThemeTheme } from './reqSiteThemeTheme'; + +/** + * 디자인(색·서체·섹션) 저장. 에디터 좌측 패널과 [디자인] 탭이 만든 결과 그대로 온다. + +★ Req_SiteTemplate 과 같은 철학이다 — 서버는 값을 해석하지도 검증하지도 않는다. + 섹션 목록도, 배리에이션 키도, 색 토큰 이름도 프론트(배리에이션 레지스트리)가 소유한다. + 여기에 화이트리스트를 두면 프론트에 섹션이나 배리에이션이 하나 늘 때마다 백엔드를 같이 고쳐야 하고, + 그 사이 사장님이 고른 값은 조용히 버려진다. 모르는 값이 들어와도 발행 잡이 업종 기본으로 + 떨어뜨리므로 화면은 깨지지 않는다. + +★ 그래서 필드를 펼치지 않고 dict 하나로 받는다. 계약은 이렇다: + {"theme": {"colors": {...}, "fontStyle": "...", "colorPaletteId": "...", "sections": [...]}} + sections 는 {id, name, enabled, locked, variantId?} 의 목록이고 **배열 순서가 곧 섹션 순서**다 + (별도 order 필드가 없다). variantId 는 고른 게 있을 때만 키가 붙는다. + pydantic 으로 모양을 고정하면 프론트가 항목을 추가한 순간 백엔드가 그걸 조용히 떨어뜨린다 — + 서버는 배달부지 심판이 아니다. + +★ colorPaletteId 는 **에디터 복원 전용**이다. 사장님이 고른 색 프리셋 id 이고, + 발행 렌더러는 이걸 안 쓰고 해석된 colors 만 쓴다. DB 에는 저장하고 응답으로도 그대로 돌려주지만, + 발행 payload 의 theme 에는 싣지 않는다 — 발행 계약(SitePayload.SiteTheme)에 없는 필드다. + +★ templateId 는 이 body 에 없다. sites.template_id 컬럼과 POST /template 이 계속 담당한다 — + 두 곳에 두면 어느 쪽이 진짜인지 갈린다. + +★ 딱 하나 막는 것은 크기다. 해석하지 않는 값을 그대로 보관한다는 건 곧 무엇이든 들어올 수 있다는 + 뜻이라, 상한이 없으면 jsonb 컬럼 하나가 DB 와 스냅샷을 통째로 부풀린다. + 상한(services/site_service._THEME_MAX_BYTES)은 서비스가 직렬화 크기로 잰다 — + 필드 개수로 재면 값 하나가 긴 경우를 못 막는다. + */ +export interface ReqSiteTheme { + theme?: ReqSiteThemeTheme; +} diff --git a/frontend/admin/src/api/generated/model/reqSiteThemeTheme.ts b/frontend/admin/src/api/generated/model/reqSiteThemeTheme.ts new file mode 100644 index 0000000..626e913 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqSiteThemeTheme.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqSiteThemeTheme = { [key: string]: unknown }; diff --git a/frontend/admin/src/api/generated/model/reqStartBuild.ts b/frontend/admin/src/api/generated/model/reqStartBuild.ts new file mode 100644 index 0000000..d161507 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqStartBuild.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * 정적 빌드 시작. + +publish=true 면 발행 검수 게이트를 통과했을 때 바로 발행까지 한다. +★ 게이트를 통과하지 못하면 발행되지 않는다 — 우회 옵션은 없다. + */ +export interface ReqStartBuild { + publish?: boolean; +} diff --git a/frontend/admin/src/api/generated/model/reqStartCollect.ts b/frontend/admin/src/api/generated/model/reqStartCollect.ts new file mode 100644 index 0000000..16a6651 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqStartCollect.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * 수집 시작. 몇 분 걸리므로 동기로 처리하지 않고 잡을 적재한 뒤 즉시 응답한다. + */ +export interface ReqStartCollect { + link_ids?: string[]; + force?: boolean; + discover_channels?: boolean; +} diff --git a/frontend/admin/src/api/generated/model/reqStartCopy.ts b/frontend/admin/src/api/generated/model/reqStartCopy.ts new file mode 100644 index 0000000..65d37ca --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqStartCopy.ts @@ -0,0 +1,13 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * 소개문·FAQ 생성 시작. + +★ 확인된 fact 만 근거로 쓴다. 근거가 없으면 생성하지 않는다(유료 호출조차 안 한다). + */ +export interface ReqStartCopy { [key: string]: unknown } diff --git a/frontend/admin/src/api/generated/model/reqStartVision.ts b/frontend/admin/src/api/generated/model/reqStartVision.ts new file mode 100644 index 0000000..04af070 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqStartVision.ts @@ -0,0 +1,13 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * 사진 분석 시작. 사진 20~50장이라 몇 분 걸린다 — 잡으로 처리한다. + */ +export interface ReqStartVision { + force?: boolean; +} diff --git a/frontend/admin/src/api/generated/model/reqSyncFestivals.ts b/frontend/admin/src/api/generated/model/reqSyncFestivals.ts new file mode 100644 index 0000000..5dbf5e9 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqSyncFestivals.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ReqSyncFestivalsAreaCode } from './reqSyncFestivalsAreaCode'; +import type { ReqSyncFestivalsStartDate } from './reqSyncFestivalsStartDate'; + +export interface ReqSyncFestivals { + /** + * @minLength 1 + * @maxLength 10 + */ + region_code: string; + area_code?: ReqSyncFestivalsAreaCode; + start_date?: ReqSyncFestivalsStartDate; +} diff --git a/frontend/admin/src/api/generated/model/reqSyncFestivalsAreaCode.ts b/frontend/admin/src/api/generated/model/reqSyncFestivalsAreaCode.ts new file mode 100644 index 0000000..aa1d905 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqSyncFestivalsAreaCode.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqSyncFestivalsAreaCode = string | null; diff --git a/frontend/admin/src/api/generated/model/reqSyncFestivalsStartDate.ts b/frontend/admin/src/api/generated/model/reqSyncFestivalsStartDate.ts new file mode 100644 index 0000000..5d2794a --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqSyncFestivalsStartDate.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqSyncFestivalsStartDate = string | null; diff --git a/frontend/admin/src/api/generated/model/reqTransitionFact.ts b/frontend/admin/src/api/generated/model/reqTransitionFact.ts new file mode 100644 index 0000000..2cdbcfe --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqTransitionFact.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { FactStatus } from './factStatus'; +import type { ReqTransitionFactValue } from './reqTransitionFactValue'; + +/** + * 검증 상태 전이. 허용 전이는 FACT_STATUS_TRANSITIONS 가 유일한 소스다. + */ +export interface ReqTransitionFact { + status?: FactStatus; + value?: ReqTransitionFactValue; +} diff --git a/frontend/admin/src/api/generated/model/reqTransitionFactValue.ts b/frontend/admin/src/api/generated/model/reqTransitionFactValue.ts new file mode 100644 index 0000000..c7b0d62 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqTransitionFactValue.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqTransitionFactValue = string | null; diff --git a/frontend/admin/src/api/generated/model/reqTransitionFaq.ts b/frontend/admin/src/api/generated/model/reqTransitionFaq.ts new file mode 100644 index 0000000..a83b581 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqTransitionFaq.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { FactStatus } from './factStatus'; +import type { ReqTransitionFaqQuestion } from './reqTransitionFaqQuestion'; +import type { ReqTransitionFaqAnswer } from './reqTransitionFaqAnswer'; + +/** + * 검증 상태 전이. 허용 전이는 fact 와 같은 표(FACT_STATUS_TRANSITIONS)가 유일한 소스다. + +CORRECTED 로 갈 때는 고친 question / answer 중 하나 이상이 필요하다(다른 전이에선 무시). + */ +export interface ReqTransitionFaq { + status?: FactStatus; + question?: ReqTransitionFaqQuestion; + answer?: ReqTransitionFaqAnswer; +} diff --git a/frontend/admin/src/api/generated/model/reqTransitionFaqAnswer.ts b/frontend/admin/src/api/generated/model/reqTransitionFaqAnswer.ts new file mode 100644 index 0000000..1fbdfb2 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqTransitionFaqAnswer.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqTransitionFaqAnswer = string | null; diff --git a/frontend/admin/src/api/generated/model/reqTransitionFaqQuestion.ts b/frontend/admin/src/api/generated/model/reqTransitionFaqQuestion.ts new file mode 100644 index 0000000..f91ccd2 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqTransitionFaqQuestion.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqTransitionFaqQuestion = string | null; diff --git a/frontend/admin/src/api/generated/model/reqUpdateLocalContent.ts b/frontend/admin/src/api/generated/model/reqUpdateLocalContent.ts new file mode 100644 index 0000000..1d868f0 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdateLocalContent.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ReqUpdateLocalContentTitle } from './reqUpdateLocalContentTitle'; +import type { ReqUpdateLocalContentBody } from './reqUpdateLocalContentBody'; +import type { ReqUpdateLocalContentDisplayStartAt } from './reqUpdateLocalContentDisplayStartAt'; +import type { ReqUpdateLocalContentDisplayEndAt } from './reqUpdateLocalContentDisplayEndAt'; + +export interface ReqUpdateLocalContent { + title?: ReqUpdateLocalContentTitle; + body?: ReqUpdateLocalContentBody; + display_start_at?: ReqUpdateLocalContentDisplayStartAt; + display_end_at?: ReqUpdateLocalContentDisplayEndAt; +} diff --git a/frontend/admin/src/api/generated/model/reqUpdateLocalContentBody.ts b/frontend/admin/src/api/generated/model/reqUpdateLocalContentBody.ts new file mode 100644 index 0000000..be3d4ce --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdateLocalContentBody.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ReqUpdateLocalContentBodyAnyOf } from './reqUpdateLocalContentBodyAnyOf'; + +export type ReqUpdateLocalContentBody = ReqUpdateLocalContentBodyAnyOf | null; diff --git a/frontend/admin/src/api/generated/model/reqUpdateLocalContentBodyAnyOf.ts b/frontend/admin/src/api/generated/model/reqUpdateLocalContentBodyAnyOf.ts new file mode 100644 index 0000000..aa6d244 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdateLocalContentBodyAnyOf.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpdateLocalContentBodyAnyOf = { [key: string]: unknown }; diff --git a/frontend/admin/src/api/generated/model/reqUpdateLocalContentDisplayEndAt.ts b/frontend/admin/src/api/generated/model/reqUpdateLocalContentDisplayEndAt.ts new file mode 100644 index 0000000..1a790c2 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdateLocalContentDisplayEndAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpdateLocalContentDisplayEndAt = string | null; diff --git a/frontend/admin/src/api/generated/model/reqUpdateLocalContentDisplayStartAt.ts b/frontend/admin/src/api/generated/model/reqUpdateLocalContentDisplayStartAt.ts new file mode 100644 index 0000000..dc2125d --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdateLocalContentDisplayStartAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpdateLocalContentDisplayStartAt = string | null; diff --git a/frontend/admin/src/api/generated/model/reqUpdateLocalContentTitle.ts b/frontend/admin/src/api/generated/model/reqUpdateLocalContentTitle.ts new file mode 100644 index 0000000..9b81dd2 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdateLocalContentTitle.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpdateLocalContentTitle = string | null; diff --git a/frontend/admin/src/api/generated/model/reqUpdateMe.ts b/frontend/admin/src/api/generated/model/reqUpdateMe.ts new file mode 100644 index 0000000..288ebaa --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdateMe.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ReqUpdateMeName } from './reqUpdateMeName'; +import type { ReqUpdateMeEmail } from './reqUpdateMeEmail'; +import type { ReqUpdateMeContactNumber } from './reqUpdateMeContactNumber'; +import type { ReqUpdateMePassword } from './reqUpdateMePassword'; + +export interface ReqUpdateMe { + name?: ReqUpdateMeName; + email?: ReqUpdateMeEmail; + contact_number?: ReqUpdateMeContactNumber; + password?: ReqUpdateMePassword; +} diff --git a/frontend/admin/src/api/generated/model/reqUpdateMeContactNumber.ts b/frontend/admin/src/api/generated/model/reqUpdateMeContactNumber.ts new file mode 100644 index 0000000..04d1655 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdateMeContactNumber.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpdateMeContactNumber = string | null; diff --git a/frontend/admin/src/api/generated/model/reqUpdateMeEmail.ts b/frontend/admin/src/api/generated/model/reqUpdateMeEmail.ts new file mode 100644 index 0000000..6531f04 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdateMeEmail.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpdateMeEmail = string | null; diff --git a/frontend/admin/src/api/generated/model/reqUpdateMeName.ts b/frontend/admin/src/api/generated/model/reqUpdateMeName.ts new file mode 100644 index 0000000..c4a3983 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdateMeName.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpdateMeName = string | null; diff --git a/frontend/admin/src/api/generated/model/reqUpdateMePassword.ts b/frontend/admin/src/api/generated/model/reqUpdateMePassword.ts new file mode 100644 index 0000000..4b92231 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdateMePassword.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpdateMePassword = string | null; diff --git a/frontend/admin/src/api/generated/model/reqUpdatePlace.ts b/frontend/admin/src/api/generated/model/reqUpdatePlace.ts new file mode 100644 index 0000000..86f7688 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdatePlace.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ReqUpdatePlaceName } from './reqUpdatePlaceName'; +import type { ReqUpdatePlaceOwnerUserId } from './reqUpdatePlaceOwnerUserId'; +import type { ReqUpdatePlaceStatus } from './reqUpdatePlaceStatus'; + +export interface ReqUpdatePlace { + name?: ReqUpdatePlaceName; + owner_user_id?: ReqUpdatePlaceOwnerUserId; + status?: ReqUpdatePlaceStatus; +} diff --git a/frontend/admin/src/api/generated/model/reqUpdatePlaceName.ts b/frontend/admin/src/api/generated/model/reqUpdatePlaceName.ts new file mode 100644 index 0000000..3b5f45d --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdatePlaceName.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpdatePlaceName = string | null; diff --git a/frontend/admin/src/api/generated/model/reqUpdatePlaceOwnerUserId.ts b/frontend/admin/src/api/generated/model/reqUpdatePlaceOwnerUserId.ts new file mode 100644 index 0000000..c1b2515 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdatePlaceOwnerUserId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpdatePlaceOwnerUserId = string | null; diff --git a/frontend/admin/src/api/generated/model/reqUpdatePlaceStatus.ts b/frontend/admin/src/api/generated/model/reqUpdatePlaceStatus.ts new file mode 100644 index 0000000..a1da292 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpdatePlaceStatus.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { PlaceStatus } from './placeStatus'; + +export type ReqUpdatePlaceStatus = PlaceStatus | null; diff --git a/frontend/admin/src/api/generated/model/reqUpsertFact.ts b/frontend/admin/src/api/generated/model/reqUpsertFact.ts new file mode 100644 index 0000000..24c2e6e --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpsertFact.ts @@ -0,0 +1,25 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ReqUpsertFactValue } from './reqUpsertFactValue'; +import type { ReqUpsertFactUnitId } from './reqUpsertFactUnitId'; +import type { SourceType } from './sourceType'; +import type { ReqUpsertFactSourceUrl } from './reqUpsertFactSourceUrl'; +import type { ReqUpsertFactExpiresAt } from './reqUpsertFactExpiresAt'; + +/** + * fact 기록. key 는 사업장 업종의 스키마에 있는 것만 허용한다. + +★ source_type 이 owner 가 아니면 source_url 이 필수다 — 출처 없는 사실은 받지 않는다. + */ +export interface ReqUpsertFact { + key?: string; + value?: ReqUpsertFactValue; + unit_id?: ReqUpsertFactUnitId; + source_type?: SourceType; + source_url?: ReqUpsertFactSourceUrl; + expires_at?: ReqUpsertFactExpiresAt; +} diff --git a/frontend/admin/src/api/generated/model/reqUpsertFactExpiresAt.ts b/frontend/admin/src/api/generated/model/reqUpsertFactExpiresAt.ts new file mode 100644 index 0000000..6eb47ae --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpsertFactExpiresAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpsertFactExpiresAt = string | null; diff --git a/frontend/admin/src/api/generated/model/reqUpsertFactSourceUrl.ts b/frontend/admin/src/api/generated/model/reqUpsertFactSourceUrl.ts new file mode 100644 index 0000000..d6fa338 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpsertFactSourceUrl.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpsertFactSourceUrl = string | null; diff --git a/frontend/admin/src/api/generated/model/reqUpsertFactUnitId.ts b/frontend/admin/src/api/generated/model/reqUpsertFactUnitId.ts new file mode 100644 index 0000000..315b2fa --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpsertFactUnitId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpsertFactUnitId = string | null; diff --git a/frontend/admin/src/api/generated/model/reqUpsertFactValue.ts b/frontend/admin/src/api/generated/model/reqUpsertFactValue.ts new file mode 100644 index 0000000..73d55bf --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqUpsertFactValue.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqUpsertFactValue = string | null; diff --git a/frontend/admin/src/api/generated/model/reqVerifyPlace.ts b/frontend/admin/src/api/generated/model/reqVerifyPlace.ts new file mode 100644 index 0000000..30de6c0 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqVerifyPlace.ts @@ -0,0 +1,33 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ExternalPlaceSource } from './externalPlaceSource'; +import type { ReqVerifyPlacePlaceUrl } from './reqVerifyPlacePlaceUrl'; +import type { ReqVerifyPlaceRoadAddress } from './reqVerifyPlaceRoadAddress'; +import type { ReqVerifyPlaceAddress } from './reqVerifyPlaceAddress'; +import type { ReqVerifyPlacePhone } from './reqVerifyPlacePhone'; +import type { ReqVerifyPlaceLatitude } from './reqVerifyPlaceLatitude'; +import type { ReqVerifyPlaceLongitude } from './reqVerifyPlaceLongitude'; +import type { ReqVerifyPlaceRegionCode } from './reqVerifyPlaceRegionCode'; + +/** + * 카카오 로컬 조회 결과를 사업장에 박제한다(동일 업소 확정). + +★ 이 단계를 통과해야 수집이 열린다. + external_place_id 는 소스에 따라 없을 수 있다 — 네이버는 고유 장소 id 를 주지 않는다. + 그 경우 상호명 + 도로명주소가 중복 판정 키가 되므로 road_address 를 반드시 채워야 한다. + */ +export interface ReqVerifyPlace { + source?: ExternalPlaceSource; + external_place_id?: string; + place_url?: ReqVerifyPlacePlaceUrl; + road_address?: ReqVerifyPlaceRoadAddress; + address?: ReqVerifyPlaceAddress; + phone?: ReqVerifyPlacePhone; + latitude?: ReqVerifyPlaceLatitude; + longitude?: ReqVerifyPlaceLongitude; + region_code?: ReqVerifyPlaceRegionCode; +} diff --git a/frontend/admin/src/api/generated/model/reqVerifyPlaceAddress.ts b/frontend/admin/src/api/generated/model/reqVerifyPlaceAddress.ts new file mode 100644 index 0000000..4180daa --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqVerifyPlaceAddress.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqVerifyPlaceAddress = string | null; diff --git a/frontend/admin/src/api/generated/model/reqVerifyPlaceByUrl.ts b/frontend/admin/src/api/generated/model/reqVerifyPlaceByUrl.ts new file mode 100644 index 0000000..2c9d898 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqVerifyPlaceByUrl.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * 네이버 플레이스 URL 하나로 동일 업소를 확정한다. + +★ 왜 이 경로가 필요한가 + 상호 검색으로 place id 를 자동 해석하는 경로는 실패한다(실측: '롯데호텔 서울'). + Perplexity 도 네이버 플레이스를 못 찾는다 — 안내 페이지를 물어온 적도 있다. + 그런데 사장님은 **자기 가게 주소를 이미 알고 있다.** 붙여넣게 하는 것이 가장 + 정확하고 빠르며, 그 붙여넣기 자체가 "이 가게가 맞다"는 사람의 확인이다. + + 서버는 그 URL 로 네이버 상세를 읽어 상호·주소·좌표를 가져온다 — 사장님이 손으로 + 옮겨 적게 하지 않는다(오타가 곧 남의 가게가 된다). + */ +export interface ReqVerifyPlaceByUrl { + url?: string; +} diff --git a/frontend/admin/src/api/generated/model/reqVerifyPlaceLatitude.ts b/frontend/admin/src/api/generated/model/reqVerifyPlaceLatitude.ts new file mode 100644 index 0000000..f7c8fe2 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqVerifyPlaceLatitude.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqVerifyPlaceLatitude = number | string | null; diff --git a/frontend/admin/src/api/generated/model/reqVerifyPlaceLongitude.ts b/frontend/admin/src/api/generated/model/reqVerifyPlaceLongitude.ts new file mode 100644 index 0000000..32daffe --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqVerifyPlaceLongitude.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqVerifyPlaceLongitude = number | string | null; diff --git a/frontend/admin/src/api/generated/model/reqVerifyPlacePhone.ts b/frontend/admin/src/api/generated/model/reqVerifyPlacePhone.ts new file mode 100644 index 0000000..8860084 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqVerifyPlacePhone.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqVerifyPlacePhone = string | null; diff --git a/frontend/admin/src/api/generated/model/reqVerifyPlacePlaceUrl.ts b/frontend/admin/src/api/generated/model/reqVerifyPlacePlaceUrl.ts new file mode 100644 index 0000000..1d89842 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqVerifyPlacePlaceUrl.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqVerifyPlacePlaceUrl = string | null; diff --git a/frontend/admin/src/api/generated/model/reqVerifyPlaceRegionCode.ts b/frontend/admin/src/api/generated/model/reqVerifyPlaceRegionCode.ts new file mode 100644 index 0000000..a558684 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqVerifyPlaceRegionCode.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqVerifyPlaceRegionCode = string | null; diff --git a/frontend/admin/src/api/generated/model/reqVerifyPlaceRoadAddress.ts b/frontend/admin/src/api/generated/model/reqVerifyPlaceRoadAddress.ts new file mode 100644 index 0000000..b6cd0f4 --- /dev/null +++ b/frontend/admin/src/api/generated/model/reqVerifyPlaceRoadAddress.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ReqVerifyPlaceRoadAddress = string | null; diff --git a/frontend/admin/src/api/generated/model/resCategorySchema.ts b/frontend/admin/src/api/generated/model/resCategorySchema.ts new file mode 100644 index 0000000..bf4a647 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resCategorySchema.ts @@ -0,0 +1,19 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResCategorySchemaMsg } from './resCategorySchemaMsg'; +import type { ResCategorySchemaCategory } from './resCategorySchemaCategory'; +import type { ResCategorySchemaLabel } from './resCategorySchemaLabel'; +import type { FieldSpecData } from './fieldSpecData'; + +export interface ResCategorySchema { + result?: ErrorInfo; + msg?: ResCategorySchemaMsg; + category?: ResCategorySchemaCategory; + label?: ResCategorySchemaLabel; + fields?: FieldSpecData[]; +} diff --git a/frontend/admin/src/api/generated/model/resCategorySchemaCategory.ts b/frontend/admin/src/api/generated/model/resCategorySchemaCategory.ts new file mode 100644 index 0000000..6cde090 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resCategorySchemaCategory.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResCategorySchemaCategory = string | null; diff --git a/frontend/admin/src/api/generated/model/resCategorySchemaLabel.ts b/frontend/admin/src/api/generated/model/resCategorySchemaLabel.ts new file mode 100644 index 0000000..9ca5cd5 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resCategorySchemaLabel.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResCategorySchemaLabel = string | null; diff --git a/frontend/admin/src/api/generated/model/resCategorySchemaMsg.ts b/frontend/admin/src/api/generated/model/resCategorySchemaMsg.ts new file mode 100644 index 0000000..56ff5ca --- /dev/null +++ b/frontend/admin/src/api/generated/model/resCategorySchemaMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResCategorySchemaMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resExtractFacts.ts b/frontend/admin/src/api/generated/model/resExtractFacts.ts new file mode 100644 index 0000000..0c0c9ed --- /dev/null +++ b/frontend/admin/src/api/generated/model/resExtractFacts.ts @@ -0,0 +1,24 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResExtractFactsMsg } from './resExtractFactsMsg'; +import type { ResExtractedFact } from './resExtractedFact'; + +/** + * 뽑힌 것과 버려진 것을 **둘 다** 돌려준다. + +★ 조용히 버리지 않는다 — 사장님이 "내가 쓴 체크인 시간이 왜 안 들어갔지" 를 + 화면에서 바로 확인할 수 있어야 한다. + */ +export interface ResExtractFacts { + result?: ErrorInfo; + msg?: ResExtractFactsMsg; + stored?: number; + rejected?: number; + facts?: ResExtractedFact[]; + rejections?: string[][]; +} diff --git a/frontend/admin/src/api/generated/model/resExtractFactsMsg.ts b/frontend/admin/src/api/generated/model/resExtractFactsMsg.ts new file mode 100644 index 0000000..ac3ad4a --- /dev/null +++ b/frontend/admin/src/api/generated/model/resExtractFactsMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResExtractFactsMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resExtractedFact.ts b/frontend/admin/src/api/generated/model/resExtractedFact.ts new file mode 100644 index 0000000..b468695 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resExtractedFact.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ResExtractedFactUnitName } from './resExtractedFactUnitName'; +import type { ResExtractedFactReason } from './resExtractedFactReason'; + +export interface ResExtractedFact { + key?: string; + label?: string; + value?: string; + unit_name?: ResExtractedFactUnitName; + stored?: boolean; + reason?: ResExtractedFactReason; +} diff --git a/frontend/admin/src/api/generated/model/resExtractedFactReason.ts b/frontend/admin/src/api/generated/model/resExtractedFactReason.ts new file mode 100644 index 0000000..29ebcd8 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resExtractedFactReason.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResExtractedFactReason = string | null; diff --git a/frontend/admin/src/api/generated/model/resExtractedFactUnitName.ts b/frontend/admin/src/api/generated/model/resExtractedFactUnitName.ts new file mode 100644 index 0000000..b45f526 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resExtractedFactUnitName.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResExtractedFactUnitName = string | null; diff --git a/frontend/admin/src/api/generated/model/resFact.ts b/frontend/admin/src/api/generated/model/resFact.ts new file mode 100644 index 0000000..6e0f80c --- /dev/null +++ b/frontend/admin/src/api/generated/model/resFact.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResFactMsg } from './resFactMsg'; +import type { ResFactFact } from './resFactFact'; +import type { ResFactOutcome } from './resFactOutcome'; + +export interface ResFact { + result?: ErrorInfo; + msg?: ResFactMsg; + fact?: ResFactFact; + outcome?: ResFactOutcome; +} diff --git a/frontend/admin/src/api/generated/model/resFactFact.ts b/frontend/admin/src/api/generated/model/resFactFact.ts new file mode 100644 index 0000000..e09c9f5 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resFactFact.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { FactData } from './factData'; + +export type ResFactFact = FactData | null; diff --git a/frontend/admin/src/api/generated/model/resFactList.ts b/frontend/admin/src/api/generated/model/resFactList.ts new file mode 100644 index 0000000..ce221be --- /dev/null +++ b/frontend/admin/src/api/generated/model/resFactList.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResFactListMsg } from './resFactListMsg'; +import type { FactData } from './factData'; + +export interface ResFactList { + result?: ErrorInfo; + msg?: ResFactListMsg; + facts?: FactData[]; + publishable?: number; + pending_review?: number; +} diff --git a/frontend/admin/src/api/generated/model/resFactListMsg.ts b/frontend/admin/src/api/generated/model/resFactListMsg.ts new file mode 100644 index 0000000..3133f56 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resFactListMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResFactListMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resFactMsg.ts b/frontend/admin/src/api/generated/model/resFactMsg.ts new file mode 100644 index 0000000..a515fb4 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resFactMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResFactMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resFactOutcome.ts b/frontend/admin/src/api/generated/model/resFactOutcome.ts new file mode 100644 index 0000000..53f6ea7 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resFactOutcome.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { FactWriteOutcome } from './factWriteOutcome'; + +export type ResFactOutcome = FactWriteOutcome | null; diff --git a/frontend/admin/src/api/generated/model/resFaq.ts b/frontend/admin/src/api/generated/model/resFaq.ts new file mode 100644 index 0000000..5502505 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resFaq.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResFaqMsg } from './resFaqMsg'; +import type { ResFaqFaq } from './resFaqFaq'; + +export interface ResFaq { + result?: ErrorInfo; + msg?: ResFaqMsg; + faq?: ResFaqFaq; +} diff --git a/frontend/admin/src/api/generated/model/resFaqFaq.ts b/frontend/admin/src/api/generated/model/resFaqFaq.ts new file mode 100644 index 0000000..76fc798 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resFaqFaq.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { FaqData } from './faqData'; + +export type ResFaqFaq = FaqData | null; diff --git a/frontend/admin/src/api/generated/model/resFaqList.ts b/frontend/admin/src/api/generated/model/resFaqList.ts new file mode 100644 index 0000000..765d1d0 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resFaqList.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResFaqListMsg } from './resFaqListMsg'; +import type { FaqData } from './faqData'; + +export interface ResFaqList { + result?: ErrorInfo; + msg?: ResFaqListMsg; + faqs?: FaqData[]; + publishable?: number; + pending_review?: number; +} diff --git a/frontend/admin/src/api/generated/model/resFaqListMsg.ts b/frontend/admin/src/api/generated/model/resFaqListMsg.ts new file mode 100644 index 0000000..a3dbc55 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resFaqListMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResFaqListMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resFaqMsg.ts b/frontend/admin/src/api/generated/model/resFaqMsg.ts new file mode 100644 index 0000000..f3a9e7f --- /dev/null +++ b/frontend/admin/src/api/generated/model/resFaqMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResFaqMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resJob.ts b/frontend/admin/src/api/generated/model/resJob.ts new file mode 100644 index 0000000..2310d4b --- /dev/null +++ b/frontend/admin/src/api/generated/model/resJob.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResJobMsg } from './resJobMsg'; +import type { ResJobJob } from './resJobJob'; + +/** + * 잡 상태 폴링 응답. 수집·빌드는 몇 분 걸리므로 클라이언트가 이 엔드포인트를 폴링한다. + */ +export interface ResJob { + result?: ErrorInfo; + msg?: ResJobMsg; + job?: ResJobJob; +} diff --git a/frontend/admin/src/api/generated/model/resJobJob.ts b/frontend/admin/src/api/generated/model/resJobJob.ts new file mode 100644 index 0000000..138e47a --- /dev/null +++ b/frontend/admin/src/api/generated/model/resJobJob.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { JobData } from './jobData'; + +export type ResJobJob = JobData | null; diff --git a/frontend/admin/src/api/generated/model/resJobMsg.ts b/frontend/admin/src/api/generated/model/resJobMsg.ts new file mode 100644 index 0000000..b061d81 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resJobMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResJobMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resJobOps.ts b/frontend/admin/src/api/generated/model/resJobOps.ts new file mode 100644 index 0000000..c561af5 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resJobOps.ts @@ -0,0 +1,24 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResJobOpsMsg } from './resJobOpsMsg'; + +/** + * 운영 스냅샷 — 큐 지연·DEAD·좀비 감시용. + */ +export interface ResJobOps { + result?: ErrorInfo; + msg?: ResJobOpsMsg; + pending?: number; + running?: number; + done?: number; + dead?: number; + dead_1h?: number; + stuck_running?: number; + oldest_pending_sec?: number; + deadline_1h?: number; +} diff --git a/frontend/admin/src/api/generated/model/resJobOpsMsg.ts b/frontend/admin/src/api/generated/model/resJobOpsMsg.ts new file mode 100644 index 0000000..0c68f15 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resJobOpsMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResJobOpsMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resLink.ts b/frontend/admin/src/api/generated/model/resLink.ts new file mode 100644 index 0000000..766394b --- /dev/null +++ b/frontend/admin/src/api/generated/model/resLink.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResLinkMsg } from './resLinkMsg'; +import type { ResLinkLink } from './resLinkLink'; + +export interface ResLink { + result?: ErrorInfo; + msg?: ResLinkMsg; + link?: ResLinkLink; +} diff --git a/frontend/admin/src/api/generated/model/resLinkLink.ts b/frontend/admin/src/api/generated/model/resLinkLink.ts new file mode 100644 index 0000000..0fb6701 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resLinkLink.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { LinkData } from './linkData'; + +export type ResLinkLink = LinkData | null; diff --git a/frontend/admin/src/api/generated/model/resLinkList.ts b/frontend/admin/src/api/generated/model/resLinkList.ts new file mode 100644 index 0000000..18e360a --- /dev/null +++ b/frontend/admin/src/api/generated/model/resLinkList.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResLinkListMsg } from './resLinkListMsg'; +import type { LinkData } from './linkData'; + +export interface ResLinkList { + result?: ErrorInfo; + msg?: ResLinkListMsg; + links?: LinkData[]; + confirmed?: number; +} diff --git a/frontend/admin/src/api/generated/model/resLinkListMsg.ts b/frontend/admin/src/api/generated/model/resLinkListMsg.ts new file mode 100644 index 0000000..5b26d8f --- /dev/null +++ b/frontend/admin/src/api/generated/model/resLinkListMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResLinkListMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resLinkMsg.ts b/frontend/admin/src/api/generated/model/resLinkMsg.ts new file mode 100644 index 0000000..2f613bd --- /dev/null +++ b/frontend/admin/src/api/generated/model/resLinkMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResLinkMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resLocalContentList.ts b/frontend/admin/src/api/generated/model/resLocalContentList.ts new file mode 100644 index 0000000..0f05af2 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resLocalContentList.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResLocalContentListMsg } from './resLocalContentListMsg'; +import type { LocalContentData } from './localContentData'; + +export interface ResLocalContentList { + result?: ErrorInfo; + msg?: ResLocalContentListMsg; + contents?: LocalContentData[]; +} diff --git a/frontend/admin/src/api/generated/model/resLocalContentListMsg.ts b/frontend/admin/src/api/generated/model/resLocalContentListMsg.ts new file mode 100644 index 0000000..901a761 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resLocalContentListMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResLocalContentListMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resLogin.ts b/frontend/admin/src/api/generated/model/resLogin.ts new file mode 100644 index 0000000..edb1605 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resLogin.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResLoginMsg } from './resLoginMsg'; + +export interface ResLogin { + result?: ErrorInfo; + msg?: ResLoginMsg; + access_token?: string; + refresh_token?: string; + token_type?: string; +} diff --git a/frontend/admin/src/api/generated/model/resLoginMsg.ts b/frontend/admin/src/api/generated/model/resLoginMsg.ts new file mode 100644 index 0000000..1d86eb0 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resLoginMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResLoginMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resMe.ts b/frontend/admin/src/api/generated/model/resMe.ts new file mode 100644 index 0000000..c03cb26 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resMe.ts @@ -0,0 +1,25 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResMeMsg } from './resMeMsg'; +import type { ResMeName } from './resMeName'; +import type { ResMeEmail } from './resMeEmail'; +import type { ResMeContactNumber } from './resMeContactNumber'; +import type { UserRole } from './userRole'; +import type { ResMeCompany } from './resMeCompany'; + +export interface ResMe { + result?: ErrorInfo; + msg?: ResMeMsg; + user_id?: string; + id?: string; + name?: ResMeName; + email?: ResMeEmail; + contact_number?: ResMeContactNumber; + role?: UserRole; + company?: ResMeCompany; +} diff --git a/frontend/admin/src/api/generated/model/resMeCompany.ts b/frontend/admin/src/api/generated/model/resMeCompany.ts new file mode 100644 index 0000000..4a08cff --- /dev/null +++ b/frontend/admin/src/api/generated/model/resMeCompany.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { CompanyData } from './companyData'; + +export type ResMeCompany = CompanyData | null; diff --git a/frontend/admin/src/api/generated/model/resMeContactNumber.ts b/frontend/admin/src/api/generated/model/resMeContactNumber.ts new file mode 100644 index 0000000..934f45c --- /dev/null +++ b/frontend/admin/src/api/generated/model/resMeContactNumber.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResMeContactNumber = string | null; diff --git a/frontend/admin/src/api/generated/model/resMeEmail.ts b/frontend/admin/src/api/generated/model/resMeEmail.ts new file mode 100644 index 0000000..478aaf4 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resMeEmail.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResMeEmail = string | null; diff --git a/frontend/admin/src/api/generated/model/resMeMsg.ts b/frontend/admin/src/api/generated/model/resMeMsg.ts new file mode 100644 index 0000000..a4486c2 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resMeMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResMeMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resMeName.ts b/frontend/admin/src/api/generated/model/resMeName.ts new file mode 100644 index 0000000..1a77e03 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resMeName.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResMeName = string | null; diff --git a/frontend/admin/src/api/generated/model/resMediaList.ts b/frontend/admin/src/api/generated/model/resMediaList.ts new file mode 100644 index 0000000..53900b8 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resMediaList.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResMediaListMsg } from './resMediaListMsg'; +import type { MediaData } from './mediaData'; + +export interface ResMediaList { + result?: ErrorInfo; + msg?: ResMediaListMsg; + media?: MediaData[]; + publishable?: number; + pending_review?: number; + crawled?: number; +} diff --git a/frontend/admin/src/api/generated/model/resMediaListMsg.ts b/frontend/admin/src/api/generated/model/resMediaListMsg.ts new file mode 100644 index 0000000..3d8de8a --- /dev/null +++ b/frontend/admin/src/api/generated/model/resMediaListMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResMediaListMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resPlace.ts b/frontend/admin/src/api/generated/model/resPlace.ts new file mode 100644 index 0000000..8cb6581 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resPlace.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResPlaceMsg } from './resPlaceMsg'; +import type { ResPlacePlace } from './resPlacePlace'; + +export interface ResPlace { + result?: ErrorInfo; + msg?: ResPlaceMsg; + place?: ResPlacePlace; +} diff --git a/frontend/admin/src/api/generated/model/resPlaceList.ts b/frontend/admin/src/api/generated/model/resPlaceList.ts new file mode 100644 index 0000000..724fd05 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resPlaceList.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResPlaceListMsg } from './resPlaceListMsg'; +import type { PlaceData } from './placeData'; + +export interface ResPlaceList { + result?: ErrorInfo; + msg?: ResPlaceListMsg; + total?: number; + page?: number; + size?: number; + places?: PlaceData[]; +} diff --git a/frontend/admin/src/api/generated/model/resPlaceListMsg.ts b/frontend/admin/src/api/generated/model/resPlaceListMsg.ts new file mode 100644 index 0000000..7400c69 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resPlaceListMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResPlaceListMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resPlaceMsg.ts b/frontend/admin/src/api/generated/model/resPlaceMsg.ts new file mode 100644 index 0000000..2e72454 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resPlaceMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResPlaceMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resPlacePlace.ts b/frontend/admin/src/api/generated/model/resPlacePlace.ts new file mode 100644 index 0000000..d27c75f --- /dev/null +++ b/frontend/admin/src/api/generated/model/resPlacePlace.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { PlaceData } from './placeData'; + +export type ResPlacePlace = PlaceData | null; diff --git a/frontend/admin/src/api/generated/model/resPublishLogs.ts b/frontend/admin/src/api/generated/model/resPublishLogs.ts new file mode 100644 index 0000000..1d3462f --- /dev/null +++ b/frontend/admin/src/api/generated/model/resPublishLogs.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResPublishLogsMsg } from './resPublishLogsMsg'; +import type { PublishLogData } from './publishLogData'; + +export interface ResPublishLogs { + result?: ErrorInfo; + msg?: ResPublishLogsMsg; + logs?: PublishLogData[]; +} diff --git a/frontend/admin/src/api/generated/model/resPublishLogsMsg.ts b/frontend/admin/src/api/generated/model/resPublishLogsMsg.ts new file mode 100644 index 0000000..7f68688 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resPublishLogsMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResPublishLogsMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resRefreshToken.ts b/frontend/admin/src/api/generated/model/resRefreshToken.ts new file mode 100644 index 0000000..dd82f8d --- /dev/null +++ b/frontend/admin/src/api/generated/model/resRefreshToken.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResRefreshTokenMsg } from './resRefreshTokenMsg'; + +export interface ResRefreshToken { + result?: ErrorInfo; + msg?: ResRefreshTokenMsg; + access_token?: string; + token_type?: string; +} diff --git a/frontend/admin/src/api/generated/model/resRefreshTokenMsg.ts b/frontend/admin/src/api/generated/model/resRefreshTokenMsg.ts new file mode 100644 index 0000000..a12ede4 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resRefreshTokenMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResRefreshTokenMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resSeoAudit.ts b/frontend/admin/src/api/generated/model/resSeoAudit.ts new file mode 100644 index 0000000..9122c3d --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSeoAudit.ts @@ -0,0 +1,23 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResSeoAuditMsg } from './resSeoAuditMsg'; +import type { AuditCheckData } from './auditCheckData'; +import type { ResSeoAuditSummary } from './resSeoAuditSummary'; +import type { ResSeoAuditVisibility } from './resSeoAuditVisibility'; + +export interface ResSeoAudit { + result?: ErrorInfo; + msg?: ResSeoAuditMsg; + seo_score?: number; + aeo_score?: number; + overall_score?: number; + checks?: AuditCheckData[]; + summary?: ResSeoAuditSummary; + visibility?: ResSeoAuditVisibility; + disclaimer?: string; +} diff --git a/frontend/admin/src/api/generated/model/resSeoAuditMsg.ts b/frontend/admin/src/api/generated/model/resSeoAuditMsg.ts new file mode 100644 index 0000000..922a22e --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSeoAuditMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResSeoAuditMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resSeoAuditSummary.ts b/frontend/admin/src/api/generated/model/resSeoAuditSummary.ts new file mode 100644 index 0000000..95ccf88 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSeoAuditSummary.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResSeoAuditSummary = { [key: string]: unknown }; diff --git a/frontend/admin/src/api/generated/model/resSeoAuditVisibility.ts b/frontend/admin/src/api/generated/model/resSeoAuditVisibility.ts new file mode 100644 index 0000000..5182aa4 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSeoAuditVisibility.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResSeoAuditVisibility = {[key: string]: number}; diff --git a/frontend/admin/src/api/generated/model/resSite.ts b/frontend/admin/src/api/generated/model/resSite.ts new file mode 100644 index 0000000..1a2a3a2 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSite.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResSiteMsg } from './resSiteMsg'; +import type { ResSiteSite } from './resSiteSite'; +import type { ResSiteCurrentVersion } from './resSiteCurrentVersion'; +import type { RenderStatusData } from './renderStatusData'; + +export interface ResSite { + result?: ErrorInfo; + msg?: ResSiteMsg; + site?: ResSiteSite; + current_version?: ResSiteCurrentVersion; + needs_rebuild?: boolean; + render?: RenderStatusData; +} diff --git a/frontend/admin/src/api/generated/model/resSiteCurrentVersion.ts b/frontend/admin/src/api/generated/model/resSiteCurrentVersion.ts new file mode 100644 index 0000000..a4f3a23 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSiteCurrentVersion.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { SiteVersionData } from './siteVersionData'; + +export type ResSiteCurrentVersion = SiteVersionData | null; diff --git a/frontend/admin/src/api/generated/model/resSiteMsg.ts b/frontend/admin/src/api/generated/model/resSiteMsg.ts new file mode 100644 index 0000000..ef489a0 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSiteMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResSiteMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resSiteSite.ts b/frontend/admin/src/api/generated/model/resSiteSite.ts new file mode 100644 index 0000000..3d2e760 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSiteSite.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { SiteData } from './siteData'; + +export type ResSiteSite = SiteData | null; diff --git a/frontend/admin/src/api/generated/model/resSiteSlug.ts b/frontend/admin/src/api/generated/model/resSiteSlug.ts new file mode 100644 index 0000000..538e0ca --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSiteSlug.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResSiteSlugMsg } from './resSiteSlugMsg'; +import type { ResSiteSlugSite } from './resSiteSlugSite'; +import type { ResSiteSlugReason } from './resSiteSlugReason'; +import type { ResSiteSlugSuggestion } from './resSiteSlugSuggestion'; + +/** + * 주소 저장 결과. 거부됐으면 왜/대안을 check 와 같은 코드로 돌려준다. + */ +export interface ResSiteSlug { + result?: ErrorInfo; + msg?: ResSiteSlugMsg; + site?: ResSiteSlugSite; + reason?: ResSiteSlugReason; + suggestion?: ResSiteSlugSuggestion; +} diff --git a/frontend/admin/src/api/generated/model/resSiteSlugMsg.ts b/frontend/admin/src/api/generated/model/resSiteSlugMsg.ts new file mode 100644 index 0000000..8a62efd --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSiteSlugMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResSiteSlugMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resSiteSlugReason.ts b/frontend/admin/src/api/generated/model/resSiteSlugReason.ts new file mode 100644 index 0000000..70a14d6 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSiteSlugReason.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResSiteSlugReason = string | null; diff --git a/frontend/admin/src/api/generated/model/resSiteSlugSite.ts b/frontend/admin/src/api/generated/model/resSiteSlugSite.ts new file mode 100644 index 0000000..b954cfb --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSiteSlugSite.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { SiteData } from './siteData'; + +export type ResSiteSlugSite = SiteData | null; diff --git a/frontend/admin/src/api/generated/model/resSiteSlugSuggestion.ts b/frontend/admin/src/api/generated/model/resSiteSlugSuggestion.ts new file mode 100644 index 0000000..f9a3113 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSiteSlugSuggestion.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResSiteSlugSuggestion = string | null; diff --git a/frontend/admin/src/api/generated/model/resSiteVersions.ts b/frontend/admin/src/api/generated/model/resSiteVersions.ts new file mode 100644 index 0000000..d9a7237 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSiteVersions.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResSiteVersionsMsg } from './resSiteVersionsMsg'; +import type { SiteVersionData } from './siteVersionData'; + +export interface ResSiteVersions { + result?: ErrorInfo; + msg?: ResSiteVersionsMsg; + versions?: SiteVersionData[]; +} diff --git a/frontend/admin/src/api/generated/model/resSiteVersionsMsg.ts b/frontend/admin/src/api/generated/model/resSiteVersionsMsg.ts new file mode 100644 index 0000000..1c837b2 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSiteVersionsMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResSiteVersionsMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resSlugCheck.ts b/frontend/admin/src/api/generated/model/resSlugCheck.ts new file mode 100644 index 0000000..6a53f5d --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSlugCheck.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResSlugCheckMsg } from './resSlugCheckMsg'; +import type { ResSlugCheckReason } from './resSlugCheckReason'; +import type { ResSlugCheckSuggestion } from './resSlugCheckSuggestion'; + +/** + * 주소 사용 가능 확인. UI 가 타이핑 중에 호출한다. + */ +export interface ResSlugCheck { + result?: ErrorInfo; + msg?: ResSlugCheckMsg; + available?: boolean; + reason?: ResSlugCheckReason; + suggestion?: ResSlugCheckSuggestion; +} diff --git a/frontend/admin/src/api/generated/model/resSlugCheckMsg.ts b/frontend/admin/src/api/generated/model/resSlugCheckMsg.ts new file mode 100644 index 0000000..f25335b --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSlugCheckMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResSlugCheckMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resSlugCheckReason.ts b/frontend/admin/src/api/generated/model/resSlugCheckReason.ts new file mode 100644 index 0000000..d6e7a78 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSlugCheckReason.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResSlugCheckReason = string | null; diff --git a/frontend/admin/src/api/generated/model/resSlugCheckSuggestion.ts b/frontend/admin/src/api/generated/model/resSlugCheckSuggestion.ts new file mode 100644 index 0000000..a13e089 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSlugCheckSuggestion.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResSlugCheckSuggestion = string | null; diff --git a/frontend/admin/src/api/generated/model/resStartBuild.ts b/frontend/admin/src/api/generated/model/resStartBuild.ts new file mode 100644 index 0000000..ff52d77 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartBuild.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResStartBuildMsg } from './resStartBuildMsg'; +import type { ResStartBuildJobId } from './resStartBuildJobId'; +import type { ResStartBuildStatus } from './resStartBuildStatus'; + +export interface ResStartBuild { + result?: ErrorInfo; + msg?: ResStartBuildMsg; + job_id?: ResStartBuildJobId; + status?: ResStartBuildStatus; + created?: boolean; +} diff --git a/frontend/admin/src/api/generated/model/resStartBuildJobId.ts b/frontend/admin/src/api/generated/model/resStartBuildJobId.ts new file mode 100644 index 0000000..5e44adf --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartBuildJobId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResStartBuildJobId = string | null; diff --git a/frontend/admin/src/api/generated/model/resStartBuildMsg.ts b/frontend/admin/src/api/generated/model/resStartBuildMsg.ts new file mode 100644 index 0000000..1984e6c --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartBuildMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResStartBuildMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resStartBuildStatus.ts b/frontend/admin/src/api/generated/model/resStartBuildStatus.ts new file mode 100644 index 0000000..30a76ae --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartBuildStatus.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { JobStatus } from './jobStatus'; + +export type ResStartBuildStatus = JobStatus | null; diff --git a/frontend/admin/src/api/generated/model/resStartCollect.ts b/frontend/admin/src/api/generated/model/resStartCollect.ts new file mode 100644 index 0000000..9e121bb --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartCollect.ts @@ -0,0 +1,22 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResStartCollectMsg } from './resStartCollectMsg'; +import type { ResStartCollectJobId } from './resStartCollectJobId'; +import type { ResStartCollectStatus } from './resStartCollectStatus'; + +/** + * 수집 잡 적재 결과. 클라이언트는 job_id 로 GET /v1/job/{job_id} 를 폴링한다. + */ +export interface ResStartCollect { + result?: ErrorInfo; + msg?: ResStartCollectMsg; + job_id?: ResStartCollectJobId; + status?: ResStartCollectStatus; + created?: boolean; + confirmed_links?: number; +} diff --git a/frontend/admin/src/api/generated/model/resStartCollectJobId.ts b/frontend/admin/src/api/generated/model/resStartCollectJobId.ts new file mode 100644 index 0000000..cb9224d --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartCollectJobId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResStartCollectJobId = string | null; diff --git a/frontend/admin/src/api/generated/model/resStartCollectMsg.ts b/frontend/admin/src/api/generated/model/resStartCollectMsg.ts new file mode 100644 index 0000000..6cbaf37 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartCollectMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResStartCollectMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resStartCollectStatus.ts b/frontend/admin/src/api/generated/model/resStartCollectStatus.ts new file mode 100644 index 0000000..4490db5 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartCollectStatus.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { JobStatus } from './jobStatus'; + +export type ResStartCollectStatus = JobStatus | null; diff --git a/frontend/admin/src/api/generated/model/resStartCopy.ts b/frontend/admin/src/api/generated/model/resStartCopy.ts new file mode 100644 index 0000000..7793a52 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartCopy.ts @@ -0,0 +1,19 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResStartCopyMsg } from './resStartCopyMsg'; +import type { ResStartCopyJobId } from './resStartCopyJobId'; +import type { ResStartCopyStatus } from './resStartCopyStatus'; + +export interface ResStartCopy { + result?: ErrorInfo; + msg?: ResStartCopyMsg; + job_id?: ResStartCopyJobId; + status?: ResStartCopyStatus; + created?: boolean; + grounded_facts?: number; +} diff --git a/frontend/admin/src/api/generated/model/resStartCopyJobId.ts b/frontend/admin/src/api/generated/model/resStartCopyJobId.ts new file mode 100644 index 0000000..e25cbe1 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartCopyJobId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResStartCopyJobId = string | null; diff --git a/frontend/admin/src/api/generated/model/resStartCopyMsg.ts b/frontend/admin/src/api/generated/model/resStartCopyMsg.ts new file mode 100644 index 0000000..9098ea8 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartCopyMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResStartCopyMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resStartCopyStatus.ts b/frontend/admin/src/api/generated/model/resStartCopyStatus.ts new file mode 100644 index 0000000..426b2da --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartCopyStatus.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { JobStatus } from './jobStatus'; + +export type ResStartCopyStatus = JobStatus | null; diff --git a/frontend/admin/src/api/generated/model/resStartVision.ts b/frontend/admin/src/api/generated/model/resStartVision.ts new file mode 100644 index 0000000..9eb9fe4 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartVision.ts @@ -0,0 +1,19 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResStartVisionMsg } from './resStartVisionMsg'; +import type { ResStartVisionJobId } from './resStartVisionJobId'; +import type { ResStartVisionStatus } from './resStartVisionStatus'; + +export interface ResStartVision { + result?: ErrorInfo; + msg?: ResStartVisionMsg; + job_id?: ResStartVisionJobId; + status?: ResStartVisionStatus; + created?: boolean; + pending_media?: number; +} diff --git a/frontend/admin/src/api/generated/model/resStartVisionJobId.ts b/frontend/admin/src/api/generated/model/resStartVisionJobId.ts new file mode 100644 index 0000000..b80d41f --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartVisionJobId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResStartVisionJobId = string | null; diff --git a/frontend/admin/src/api/generated/model/resStartVisionMsg.ts b/frontend/admin/src/api/generated/model/resStartVisionMsg.ts new file mode 100644 index 0000000..1915ec6 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartVisionMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResStartVisionMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resStartVisionStatus.ts b/frontend/admin/src/api/generated/model/resStartVisionStatus.ts new file mode 100644 index 0000000..9d63ad8 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resStartVisionStatus.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { JobStatus } from './jobStatus'; + +export type ResStartVisionStatus = JobStatus | null; diff --git a/frontend/admin/src/api/generated/model/resSyncFestivals.ts b/frontend/admin/src/api/generated/model/resSyncFestivals.ts new file mode 100644 index 0000000..b04f96b --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSyncFestivals.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResSyncFestivalsMsg } from './resSyncFestivalsMsg'; + +export interface ResSyncFestivals { + result?: ErrorInfo; + msg?: ResSyncFestivalsMsg; + collected?: number; + skipped?: number; +} diff --git a/frontend/admin/src/api/generated/model/resSyncFestivalsMsg.ts b/frontend/admin/src/api/generated/model/resSyncFestivalsMsg.ts new file mode 100644 index 0000000..be86451 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resSyncFestivalsMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResSyncFestivalsMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resUnit.ts b/frontend/admin/src/api/generated/model/resUnit.ts new file mode 100644 index 0000000..d9af559 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resUnit.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResUnitMsg } from './resUnitMsg'; +import type { ResUnitUnit } from './resUnitUnit'; + +export interface ResUnit { + result?: ErrorInfo; + msg?: ResUnitMsg; + unit?: ResUnitUnit; +} diff --git a/frontend/admin/src/api/generated/model/resUnitList.ts b/frontend/admin/src/api/generated/model/resUnitList.ts new file mode 100644 index 0000000..0999bdf --- /dev/null +++ b/frontend/admin/src/api/generated/model/resUnitList.ts @@ -0,0 +1,15 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResUnitListMsg } from './resUnitListMsg'; +import type { UnitData } from './unitData'; + +export interface ResUnitList { + result?: ErrorInfo; + msg?: ResUnitListMsg; + units?: UnitData[]; +} diff --git a/frontend/admin/src/api/generated/model/resUnitListMsg.ts b/frontend/admin/src/api/generated/model/resUnitListMsg.ts new file mode 100644 index 0000000..417ce5c --- /dev/null +++ b/frontend/admin/src/api/generated/model/resUnitListMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResUnitListMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resUnitMsg.ts b/frontend/admin/src/api/generated/model/resUnitMsg.ts new file mode 100644 index 0000000..9b1f571 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resUnitMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResUnitMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resUnitUnit.ts b/frontend/admin/src/api/generated/model/resUnitUnit.ts new file mode 100644 index 0000000..e7b3068 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resUnitUnit.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { UnitData } from './unitData'; + +export type ResUnitUnit = UnitData | null; diff --git a/frontend/admin/src/api/generated/model/resVerifyCandidates.ts b/frontend/admin/src/api/generated/model/resVerifyCandidates.ts new file mode 100644 index 0000000..33889e8 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resVerifyCandidates.ts @@ -0,0 +1,27 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResVerifyCandidatesMsg } from './resVerifyCandidatesMsg'; +import type { ResVerifyCandidatesSource } from './resVerifyCandidatesSource'; +import type { ResVerifyCandidatesReason } from './resVerifyCandidatesReason'; +import type { PlaceCandidate } from './placeCandidate'; + +/** + * 동일 업소 후보 목록. + +★ 자동 판정을 신뢰하지 않는다. outcome 이 MATCHED 여도 후보를 전부 내려보내 + UI 가 사람에게 확인시킬 수 있게 한다 — 남의 가게가 섞이면 그게 제일 비싼 실수다. + */ +export interface ResVerifyCandidates { + result?: ErrorInfo; + msg?: ResVerifyCandidatesMsg; + source?: ResVerifyCandidatesSource; + outcome?: string; + reason?: ResVerifyCandidatesReason; + auto_selectable?: boolean; + candidates?: PlaceCandidate[]; +} diff --git a/frontend/admin/src/api/generated/model/resVerifyCandidatesMsg.ts b/frontend/admin/src/api/generated/model/resVerifyCandidatesMsg.ts new file mode 100644 index 0000000..612f18c --- /dev/null +++ b/frontend/admin/src/api/generated/model/resVerifyCandidatesMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResVerifyCandidatesMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resVerifyCandidatesReason.ts b/frontend/admin/src/api/generated/model/resVerifyCandidatesReason.ts new file mode 100644 index 0000000..ad4b404 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resVerifyCandidatesReason.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResVerifyCandidatesReason = string | null; diff --git a/frontend/admin/src/api/generated/model/resVerifyCandidatesSource.ts b/frontend/admin/src/api/generated/model/resVerifyCandidatesSource.ts new file mode 100644 index 0000000..7e113df --- /dev/null +++ b/frontend/admin/src/api/generated/model/resVerifyCandidatesSource.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ExternalPlaceSource } from './externalPlaceSource'; + +export type ResVerifyCandidatesSource = ExternalPlaceSource | null; diff --git a/frontend/admin/src/api/generated/model/resWeather.ts b/frontend/admin/src/api/generated/model/resWeather.ts new file mode 100644 index 0000000..4b4719c --- /dev/null +++ b/frontend/admin/src/api/generated/model/resWeather.ts @@ -0,0 +1,17 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ErrorInfo } from './errorInfo'; +import type { ResWeatherMsg } from './resWeatherMsg'; +import type { ResWeatherWeather } from './resWeatherWeather'; + +export interface ResWeather { + result?: ErrorInfo; + msg?: ResWeatherMsg; + weather?: ResWeatherWeather; + cached?: boolean; + stale?: boolean; +} diff --git a/frontend/admin/src/api/generated/model/resWeatherMsg.ts b/frontend/admin/src/api/generated/model/resWeatherMsg.ts new file mode 100644 index 0000000..c64419a --- /dev/null +++ b/frontend/admin/src/api/generated/model/resWeatherMsg.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ResWeatherMsg = string | null; diff --git a/frontend/admin/src/api/generated/model/resWeatherWeather.ts b/frontend/admin/src/api/generated/model/resWeatherWeather.ts new file mode 100644 index 0000000..48d8de8 --- /dev/null +++ b/frontend/admin/src/api/generated/model/resWeatherWeather.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { WeatherData } from './weatherData'; + +export type ResWeatherWeather = WeatherData | null; diff --git a/frontend/admin/src/api/generated/model/siteData.ts b/frontend/admin/src/api/generated/model/siteData.ts new file mode 100644 index 0000000..f3a3279 --- /dev/null +++ b/frontend/admin/src/api/generated/model/siteData.ts @@ -0,0 +1,23 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { SiteStatus } from './siteStatus'; +import type { SiteDataDomain } from './siteDataDomain'; +import type { SiteDataTemplateId } from './siteDataTemplateId'; +import type { SiteDataTheme } from './siteDataTheme'; +import type { SiteDataCurrentVersionId } from './siteDataCurrentVersionId'; +import type { SiteDataPublishedAt } from './siteDataPublishedAt'; + +export interface SiteData { + site_id: string; + place_id: string; + status: SiteStatus; + domain?: SiteDataDomain; + template_id?: SiteDataTemplateId; + theme?: SiteDataTheme; + current_version_id?: SiteDataCurrentVersionId; + published_at?: SiteDataPublishedAt; +} diff --git a/frontend/admin/src/api/generated/model/siteDataCurrentVersionId.ts b/frontend/admin/src/api/generated/model/siteDataCurrentVersionId.ts new file mode 100644 index 0000000..0c774b1 --- /dev/null +++ b/frontend/admin/src/api/generated/model/siteDataCurrentVersionId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type SiteDataCurrentVersionId = string | null; diff --git a/frontend/admin/src/api/generated/model/siteDataDomain.ts b/frontend/admin/src/api/generated/model/siteDataDomain.ts new file mode 100644 index 0000000..d981635 --- /dev/null +++ b/frontend/admin/src/api/generated/model/siteDataDomain.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type SiteDataDomain = string | null; diff --git a/frontend/admin/src/api/generated/model/siteDataPublishedAt.ts b/frontend/admin/src/api/generated/model/siteDataPublishedAt.ts new file mode 100644 index 0000000..7816415 --- /dev/null +++ b/frontend/admin/src/api/generated/model/siteDataPublishedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type SiteDataPublishedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/siteDataTemplateId.ts b/frontend/admin/src/api/generated/model/siteDataTemplateId.ts new file mode 100644 index 0000000..8fa345a --- /dev/null +++ b/frontend/admin/src/api/generated/model/siteDataTemplateId.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type SiteDataTemplateId = string | null; diff --git a/frontend/admin/src/api/generated/model/siteDataTheme.ts b/frontend/admin/src/api/generated/model/siteDataTheme.ts new file mode 100644 index 0000000..a06d868 --- /dev/null +++ b/frontend/admin/src/api/generated/model/siteDataTheme.ts @@ -0,0 +1,9 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { SiteDataThemeAnyOf } from './siteDataThemeAnyOf'; + +export type SiteDataTheme = SiteDataThemeAnyOf | null; diff --git a/frontend/admin/src/api/generated/model/siteDataThemeAnyOf.ts b/frontend/admin/src/api/generated/model/siteDataThemeAnyOf.ts new file mode 100644 index 0000000..d3e1b40 --- /dev/null +++ b/frontend/admin/src/api/generated/model/siteDataThemeAnyOf.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type SiteDataThemeAnyOf = { [key: string]: unknown }; diff --git a/frontend/admin/src/api/generated/model/siteStatus.ts b/frontend/admin/src/api/generated/model/siteStatus.ts new file mode 100644 index 0000000..9716066 --- /dev/null +++ b/frontend/admin/src/api/generated/model/siteStatus.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * sites.status 코드값. ★ 해지는 물리 삭제가 아니라 상태 전이로만 처리한다. + */ +export type SiteStatus = typeof SiteStatus[keyof typeof SiteStatus]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const SiteStatus = { + DRAFT: 1, + REVIEW: 2, + PUBLISHED: 3, + SUSPENDED: 4, + UNPUBLISHED: 5, +} as const; diff --git a/frontend/admin/src/api/generated/model/siteVersionData.ts b/frontend/admin/src/api/generated/model/siteVersionData.ts new file mode 100644 index 0000000..99a1757 --- /dev/null +++ b/frontend/admin/src/api/generated/model/siteVersionData.ts @@ -0,0 +1,20 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { BuildStatus } from './buildStatus'; +import type { SiteVersionDataBuildError } from './siteVersionDataBuildError'; +import type { SiteVersionDataBuiltAt } from './siteVersionDataBuiltAt'; +import type { SiteVersionDataCreatedAt } from './siteVersionDataCreatedAt'; + +export interface SiteVersionData { + site_version_id: string; + version: number; + build_status: BuildStatus; + unique_content_count?: number; + build_error?: SiteVersionDataBuildError; + built_at?: SiteVersionDataBuiltAt; + created_at?: SiteVersionDataCreatedAt; +} diff --git a/frontend/admin/src/api/generated/model/siteVersionDataBuildError.ts b/frontend/admin/src/api/generated/model/siteVersionDataBuildError.ts new file mode 100644 index 0000000..4451e85 --- /dev/null +++ b/frontend/admin/src/api/generated/model/siteVersionDataBuildError.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type SiteVersionDataBuildError = string | null; diff --git a/frontend/admin/src/api/generated/model/siteVersionDataBuiltAt.ts b/frontend/admin/src/api/generated/model/siteVersionDataBuiltAt.ts new file mode 100644 index 0000000..ecde8aa --- /dev/null +++ b/frontend/admin/src/api/generated/model/siteVersionDataBuiltAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type SiteVersionDataBuiltAt = string | null; diff --git a/frontend/admin/src/api/generated/model/siteVersionDataCreatedAt.ts b/frontend/admin/src/api/generated/model/siteVersionDataCreatedAt.ts new file mode 100644 index 0000000..648d227 --- /dev/null +++ b/frontend/admin/src/api/generated/model/siteVersionDataCreatedAt.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type SiteVersionDataCreatedAt = string | null; diff --git a/frontend/admin/src/api/generated/model/sourceType.ts b/frontend/admin/src/api/generated/model/sourceType.ts new file mode 100644 index 0000000..a2ad4d3 --- /dev/null +++ b/frontend/admin/src/api/generated/model/sourceType.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * facts.source_type / media.source_type / place_aliases.source_type 공용 코드값. +값이 어디서 왔는지 — 모든 사실은 출처를 갖는다. + */ +export type SourceType = typeof SourceType[keyof typeof SourceType]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const SourceType = { + OWNER: 1, + API: 2, + CRAWL: 3, + LLM: 4, +} as const; diff --git a/frontend/admin/src/api/generated/model/unitData.ts b/frontend/admin/src/api/generated/model/unitData.ts new file mode 100644 index 0000000..c36d26f --- /dev/null +++ b/frontend/admin/src/api/generated/model/unitData.ts @@ -0,0 +1,13 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export interface UnitData { + unit_id: string; + place_id: string; + name: string; + sort_order?: number; +} diff --git a/frontend/admin/src/api/generated/model/userRole.ts b/frontend/admin/src/api/generated/model/userRole.ts new file mode 100644 index 0000000..b1500c0 --- /dev/null +++ b/frontend/admin/src/api/generated/model/userRole.ts @@ -0,0 +1,21 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +/** + * users.role 코드값. +1=일반, 2=최고관리자(고객사 최상위), 3=개발자(우리 내부 운영 계정). +개발자 계정은 고객사에 존재를 노출하지 않는다 — 회원 목록에서 빼고 총계에도 넣지 않는다. + */ +export type UserRole = typeof UserRole[keyof typeof UserRole]; + + +// eslint-disable-next-line @typescript-eslint/no-redeclare +export const UserRole = { + USER: 1, + OWNER: 2, + DEVELOPER: 3, +} as const; diff --git a/frontend/admin/src/api/generated/model/validationError.ts b/frontend/admin/src/api/generated/model/validationError.ts new file mode 100644 index 0000000..bfd016e --- /dev/null +++ b/frontend/admin/src/api/generated/model/validationError.ts @@ -0,0 +1,16 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { ValidationErrorLocItem } from './validationErrorLocItem'; +import type { ValidationErrorCtx } from './validationErrorCtx'; + +export interface ValidationError { + loc: ValidationErrorLocItem[]; + msg: string; + type: string; + input?: unknown; + ctx?: ValidationErrorCtx; +} diff --git a/frontend/admin/src/api/generated/model/validationErrorCtx.ts b/frontend/admin/src/api/generated/model/validationErrorCtx.ts new file mode 100644 index 0000000..6fdaa69 --- /dev/null +++ b/frontend/admin/src/api/generated/model/validationErrorCtx.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ValidationErrorCtx = { [key: string]: unknown }; diff --git a/frontend/admin/src/api/generated/model/validationErrorLocItem.ts b/frontend/admin/src/api/generated/model/validationErrorLocItem.ts new file mode 100644 index 0000000..f4d5217 --- /dev/null +++ b/frontend/admin/src/api/generated/model/validationErrorLocItem.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type ValidationErrorLocItem = string | number; diff --git a/frontend/admin/src/api/generated/model/verifyCandidatesParams.ts b/frontend/admin/src/api/generated/model/verifyCandidatesParams.ts new file mode 100644 index 0000000..52dce97 --- /dev/null +++ b/frontend/admin/src/api/generated/model/verifyCandidatesParams.ts @@ -0,0 +1,13 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type VerifyCandidatesParams = { +/** + * 검색어. 비우면 등록된 상호명 + */ +query?: string | null; +}; diff --git a/frontend/admin/src/api/generated/model/weatherData.ts b/frontend/admin/src/api/generated/model/weatherData.ts new file mode 100644 index 0000000..7660333 --- /dev/null +++ b/frontend/admin/src/api/generated/model/weatherData.ts @@ -0,0 +1,18 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import type { WeatherDataWindSpeed } from './weatherDataWindSpeed'; +import type { WeatherDataTimezone } from './weatherDataTimezone'; + +export interface WeatherData { + temperature: number; + weather_code: number; + wind_speed?: WeatherDataWindSpeed; + observed_at: string; + timezone?: WeatherDataTimezone; + latitude: number; + longitude: number; +} diff --git a/frontend/admin/src/api/generated/model/weatherDataTimezone.ts b/frontend/admin/src/api/generated/model/weatherDataTimezone.ts new file mode 100644 index 0000000..e997a97 --- /dev/null +++ b/frontend/admin/src/api/generated/model/weatherDataTimezone.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type WeatherDataTimezone = string | null; diff --git a/frontend/admin/src/api/generated/model/weatherDataWindSpeed.ts b/frontend/admin/src/api/generated/model/weatherDataWindSpeed.ts new file mode 100644 index 0000000..a83253f --- /dev/null +++ b/frontend/admin/src/api/generated/model/weatherDataWindSpeed.ts @@ -0,0 +1,8 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ + +export type WeatherDataWindSpeed = number | null; diff --git a/frontend/admin/src/api/generated/place/place.ts b/frontend/admin/src/api/generated/place/place.ts new file mode 100644 index 0000000..ee2d808 --- /dev/null +++ b/frontend/admin/src/api/generated/place/place.ts @@ -0,0 +1,1346 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import { + useMutation, + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + MutationFunction, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseMutationOptions, + UseMutationResult, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + HTTPValidationError, + ListLinksParams, + ListPlacesParams, + ReqCreateLink, + ReqCreatePlace, + ReqCreateUnit, + ReqStartCollect, + ReqStartCopy, + ReqStartVision, + ReqUpdatePlace, + ReqVerifyPlace, + ReqVerifyPlaceByUrl, + ResJob, + ResLink, + ResLinkList, + ResPlace, + ResPlaceList, + ResStartCollect, + ResStartCopy, + ResStartVision, + ResUnit, + ResUnitList, + ResVerifyCandidates, + VerifyCandidatesParams +} from '.././model'; + +import { customFetch } from '../../mutator/custom-fetch'; + + +type SecondParameter unknown> = Parameters[1]; + + + +/** + * @summary 사업장 목록 + */ +export const listPlaces = ( + params?: ListPlacesParams, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/list`, method: 'GET', + params, signal + }, + options); + } + + + + +export const getListPlacesQueryKey = (params?: ListPlacesParams,) => { + return [ + `/v1/place/list`, ...(params ? [params]: []) + ] as const; + } + + +export const getListPlacesQueryOptions = >, TError = void | HTTPValidationError>(params?: ListPlacesParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListPlacesQueryKey(params); + + + + const queryFn: QueryFunction>> = ({ signal }) => listPlaces(params, requestOptions, signal); + + + + + + return { queryKey, queryFn, ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListPlacesQueryResult = NonNullable>> +export type ListPlacesQueryError = void | HTTPValidationError + + +export function useListPlaces>, TError = void | HTTPValidationError>( + params: undefined | ListPlacesParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListPlaces>, TError = void | HTTPValidationError>( + params?: ListPlacesParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListPlaces>, TError = void | HTTPValidationError>( + params?: ListPlacesParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 사업장 목록 + */ + +export function useListPlaces>, TError = void | HTTPValidationError>( + params?: ListPlacesParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListPlacesQueryOptions(params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * 상호명 하나로 시작한다. 주소·좌표는 동일 업소 검증(verify)이 채운다. + * @summary 사업장 등록 + */ +export const createPlace = ( + reqCreatePlace: ReqCreatePlace, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqCreatePlace, signal + }, + options); + } + + + +export const getCreatePlaceMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{data: ReqCreatePlace}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{data: ReqCreatePlace}, TContext> => { + +const mutationKey = ['createPlace']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {data: ReqCreatePlace}> = (props) => { + const {data} = props ?? {}; + + return createPlace(data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type CreatePlaceMutationResult = NonNullable>> + export type CreatePlaceMutationBody = ReqCreatePlace + export type CreatePlaceMutationError = void | HTTPValidationError + + /** + * @summary 사업장 등록 + */ +export const useCreatePlace = (options?: { mutation?:UseMutationOptions>, TError,{data: ReqCreatePlace}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {data: ReqCreatePlace}, + TContext + > => { + + const mutationOptions = getCreatePlaceMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * @summary 사업장 단건 + */ +export const getPlace = ( + placeId: string, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}`, method: 'GET', signal + }, + options); + } + + + + +export const getGetPlaceQueryKey = (placeId?: string,) => { + return [ + `/v1/place/${placeId}` + ] as const; + } + + +export const getGetPlaceQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetPlaceQueryKey(placeId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getPlace(placeId, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetPlaceQueryResult = NonNullable>> +export type GetPlaceQueryError = void | HTTPValidationError + + +export function useGetPlace>, TError = void | HTTPValidationError>( + placeId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetPlace>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetPlace>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 사업장 단건 + */ + +export function useGetPlace>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetPlaceQueryOptions(placeId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * @summary 사업장 수정 + */ +export const updatePlace = ( + placeId: string, + reqUpdatePlace: ReqUpdatePlace, + options?: SecondParameter,) => { + + + return customFetch( + {url: `/v1/place/${placeId}`, method: 'PATCH', + headers: {'Content-Type': 'application/json', }, + data: reqUpdatePlace + }, + options); + } + + + +export const getUpdatePlaceMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqUpdatePlace}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqUpdatePlace}, TContext> => { + +const mutationKey = ['updatePlace']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqUpdatePlace}> = (props) => { + const {placeId,data} = props ?? {}; + + return updatePlace(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type UpdatePlaceMutationResult = NonNullable>> + export type UpdatePlaceMutationBody = ReqUpdatePlace + export type UpdatePlaceMutationError = void | HTTPValidationError + + /** + * @summary 사업장 수정 + */ +export const useUpdatePlace = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqUpdatePlace}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqUpdatePlace}, + TContext + > => { + + const mutationOptions = getUpdatePlaceMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * @summary 사업장 삭제 + */ +export const deletePlace = ( + placeId: string, + options?: SecondParameter,) => { + + + return customFetch( + {url: `/v1/place/${placeId}`, method: 'DELETE' + }, + options); + } + + + +export const getDeletePlaceMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string}, TContext> => { + +const mutationKey = ['deletePlace']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string}> = (props) => { + const {placeId} = props ?? {}; + + return deletePlace(placeId,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type DeletePlaceMutationResult = NonNullable>> + + export type DeletePlaceMutationError = void | HTTPValidationError + + /** + * @summary 사업장 삭제 + */ +export const useDeletePlace = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string}, + TContext + > => { + + const mutationOptions = getDeletePlaceMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * @summary 진행 중인 수집 잡 + */ +export const getActiveCollect = ( + placeId: string, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/collect/active`, method: 'GET', signal + }, + options); + } + + + + +export const getGetActiveCollectQueryKey = (placeId?: string,) => { + return [ + `/v1/place/${placeId}/collect/active` + ] as const; + } + + +export const getGetActiveCollectQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetActiveCollectQueryKey(placeId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getActiveCollect(placeId, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetActiveCollectQueryResult = NonNullable>> +export type GetActiveCollectQueryError = void | HTTPValidationError + + +export function useGetActiveCollect>, TError = void | HTTPValidationError>( + placeId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetActiveCollect>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetActiveCollect>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 진행 중인 수집 잡 + */ + +export function useGetActiveCollect>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetActiveCollectQueryOptions(placeId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * 카카오 로컬 조회 결과를 박제해 동일 업소를 확정한다. ★ 이걸 통과해야 수집이 열린다. + * @summary 동일 업소 검증 + */ +export const verifyPlace = ( + placeId: string, + reqVerifyPlace: ReqVerifyPlace, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/verify`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqVerifyPlace, signal + }, + options); + } + + + +export const getVerifyPlaceMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqVerifyPlace}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqVerifyPlace}, TContext> => { + +const mutationKey = ['verifyPlace']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqVerifyPlace}> = (props) => { + const {placeId,data} = props ?? {}; + + return verifyPlace(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type VerifyPlaceMutationResult = NonNullable>> + export type VerifyPlaceMutationBody = ReqVerifyPlace + export type VerifyPlaceMutationError = void | HTTPValidationError + + /** + * @summary 동일 업소 검증 + */ +export const useVerifyPlace = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqVerifyPlace}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqVerifyPlace}, + TContext + > => { + + const mutationOptions = getVerifyPlaceMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * 사장님이 붙여넣은 네이버 플레이스 주소로 상호·주소·좌표를 읽어 확정하고, 그 URL 을 수집 채널로 등록·확정한다. ★ 상호 검색이 실패하는 가게(동명·지점명 표기 차이)를 위한 확실한 경로다. + * @summary 네이버 플레이스 URL 로 동일 업소 확정 + */ +export const verifyPlaceByUrl = ( + placeId: string, + reqVerifyPlaceByUrl: ReqVerifyPlaceByUrl, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/verify/by-url`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqVerifyPlaceByUrl, signal + }, + options); + } + + + +export const getVerifyPlaceByUrlMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqVerifyPlaceByUrl}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqVerifyPlaceByUrl}, TContext> => { + +const mutationKey = ['verifyPlaceByUrl']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqVerifyPlaceByUrl}> = (props) => { + const {placeId,data} = props ?? {}; + + return verifyPlaceByUrl(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type VerifyPlaceByUrlMutationResult = NonNullable>> + export type VerifyPlaceByUrlMutationBody = ReqVerifyPlaceByUrl + export type VerifyPlaceByUrlMutationError = void | HTTPValidationError + + /** + * @summary 네이버 플레이스 URL 로 동일 업소 확정 + */ +export const useVerifyPlaceByUrl = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqVerifyPlaceByUrl}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqVerifyPlaceByUrl}, + TContext + > => { + + const mutationOptions = getVerifyPlaceByUrlMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * @summary 하위 단위 목록(객실·메뉴·프로그램) + */ +export const listUnits = ( + placeId: string, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/unit/list`, method: 'GET', signal + }, + options); + } + + + + +export const getListUnitsQueryKey = (placeId?: string,) => { + return [ + `/v1/place/${placeId}/unit/list` + ] as const; + } + + +export const getListUnitsQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListUnitsQueryKey(placeId); + + + + const queryFn: QueryFunction>> = ({ signal }) => listUnits(placeId, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListUnitsQueryResult = NonNullable>> +export type ListUnitsQueryError = void | HTTPValidationError + + +export function useListUnits>, TError = void | HTTPValidationError>( + placeId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListUnits>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListUnits>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 하위 단위 목록(객실·메뉴·프로그램) + */ + +export function useListUnits>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListUnitsQueryOptions(placeId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * @summary 하위 단위 등록 + */ +export const createUnit = ( + placeId: string, + reqCreateUnit: ReqCreateUnit, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/unit`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqCreateUnit, signal + }, + options); + } + + + +export const getCreateUnitMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqCreateUnit}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqCreateUnit}, TContext> => { + +const mutationKey = ['createUnit']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqCreateUnit}> = (props) => { + const {placeId,data} = props ?? {}; + + return createUnit(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type CreateUnitMutationResult = NonNullable>> + export type CreateUnitMutationBody = ReqCreateUnit + export type CreateUnitMutationError = void | HTTPValidationError + + /** + * @summary 하위 단위 등록 + */ +export const useCreateUnit = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqCreateUnit}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqCreateUnit}, + TContext + > => { + + const mutationOptions = getCreateUnitMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * confirmed_only=true 면 크롤링 대상(확정된 URL)만. + * @summary 채널 URL 목록 + */ +export const listLinks = ( + placeId: string, + params?: ListLinksParams, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/link/list`, method: 'GET', + params, signal + }, + options); + } + + + + +export const getListLinksQueryKey = (placeId?: string, + params?: ListLinksParams,) => { + return [ + `/v1/place/${placeId}/link/list`, ...(params ? [params]: []) + ] as const; + } + + +export const getListLinksQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, + params?: ListLinksParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListLinksQueryKey(placeId,params); + + + + const queryFn: QueryFunction>> = ({ signal }) => listLinks(placeId,params, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListLinksQueryResult = NonNullable>> +export type ListLinksQueryError = void | HTTPValidationError + + +export function useListLinks>, TError = void | HTTPValidationError>( + placeId: string, + params: undefined | ListLinksParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListLinks>, TError = void | HTTPValidationError>( + placeId: string, + params?: ListLinksParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListLinks>, TError = void | HTTPValidationError>( + placeId: string, + params?: ListLinksParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 채널 URL 목록 + */ + +export function useListLinks>, TError = void | HTTPValidationError>( + placeId: string, + params?: ListLinksParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListLinksQueryOptions(placeId,params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * 등록만으로는 크롤링 대상이 되지 않는다 — 확정(confirm)이 따로 필요하다. + * @summary 채널 URL 등록 + */ +export const createLink = ( + placeId: string, + reqCreateLink: ReqCreateLink, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/link`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqCreateLink, signal + }, + options); + } + + + +export const getCreateLinkMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqCreateLink}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqCreateLink}, TContext> => { + +const mutationKey = ['createLink']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqCreateLink}> = (props) => { + const {placeId,data} = props ?? {}; + + return createLink(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type CreateLinkMutationResult = NonNullable>> + export type CreateLinkMutationBody = ReqCreateLink + export type CreateLinkMutationError = void | HTTPValidationError + + /** + * @summary 채널 URL 등록 + */ +export const useCreateLink = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqCreateLink}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqCreateLink}, + TContext + > => { + + const mutationOptions = getCreateLinkMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * ★ 확정된 URL 만 크롤링 대상이 된다. 사업장 검증이 끝나야 확정할 수 있다. + * @summary 채널 URL 확정 + */ +export const confirmLink = ( + placeId: string, + linkId: string, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/link/${linkId}/confirm`, method: 'POST', signal + }, + options); + } + + + +export const getConfirmLinkMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;linkId: string}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;linkId: string}, TContext> => { + +const mutationKey = ['confirmLink']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;linkId: string}> = (props) => { + const {placeId,linkId} = props ?? {}; + + return confirmLink(placeId,linkId,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type ConfirmLinkMutationResult = NonNullable>> + + export type ConfirmLinkMutationError = void | HTTPValidationError + + /** + * @summary 채널 URL 확정 + */ +export const useConfirmLink = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;linkId: string}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;linkId: string}, + TContext + > => { + + const mutationOptions = getConfirmLinkMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * 수집 파이프라인을 큐에 넣고 즉시 job_id 를 돌려준다. 한 건에 몇 분 걸리므로 GET /v1/job/{job_id} 로 진행 상태를 폴링한다. ★ 동일 업소 검증과 채널 URL 확정이 끝나야 시작할 수 있다. + * @summary 수집 시작(비동기) + */ +export const startCollect = ( + placeId: string, + reqStartCollect: ReqStartCollect, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/collect`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqStartCollect, signal + }, + options); + } + + + +export const getStartCollectMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqStartCollect}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqStartCollect}, TContext> => { + +const mutationKey = ['startCollect']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqStartCollect}> = (props) => { + const {placeId,data} = props ?? {}; + + return startCollect(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type StartCollectMutationResult = NonNullable>> + export type StartCollectMutationBody = ReqStartCollect + export type StartCollectMutationError = void | HTTPValidationError + + /** + * @summary 수집 시작(비동기) + */ +export const useStartCollect = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqStartCollect}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqStartCollect}, + TContext + > => { + + const mutationOptions = getStartCollectMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * Gemini Vision 으로 사진 분류 라벨과 alt 를 생성한다. 수집이 사진을 저장하면 자동으로 걸리며, 사장님이 직접 올린 사진이나 재분석(force)에 이 엔드포인트를 쓴다. ★ 신뢰도가 낮은 결과는 자동 반영되지 않고 사람 확인 큐에 남는다. + * @summary 사진 분석 시작(비동기) + */ +export const startVision = ( + placeId: string, + reqStartVision: ReqStartVision, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/vision`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqStartVision, signal + }, + options); + } + + + +export const getStartVisionMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqStartVision}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqStartVision}, TContext> => { + +const mutationKey = ['startVision']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqStartVision}> = (props) => { + const {placeId,data} = props ?? {}; + + return startVision(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type StartVisionMutationResult = NonNullable>> + export type StartVisionMutationBody = ReqStartVision + export type StartVisionMutationError = void | HTTPValidationError + + /** + * @summary 사진 분석 시작(비동기) + */ +export const useStartVision = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqStartVision}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqStartVision}, + TContext + > => { + + const mutationOptions = getStartVisionMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * 외부 장소 DB(카카오 키가 있으면 카카오, 없으면 네이버)에서 후보를 찾아 그대로 돌려준다. ★ 서버가 자동 확정하지 않는다 — UI 가 후보를 보여주고 사람이 고른 뒤 POST /verify 로 확정한다. auto_selectable=true 면 판정이 명확해 '이거 맞나요?' 한 번만 물어도 된다. + * @summary 동일 업소 후보 조회 + */ +export const verifyCandidates = ( + placeId: string, + params?: VerifyCandidatesParams, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/verify/candidates`, method: 'GET', + params, signal + }, + options); + } + + + + +export const getVerifyCandidatesQueryKey = (placeId?: string, + params?: VerifyCandidatesParams,) => { + return [ + `/v1/place/${placeId}/verify/candidates`, ...(params ? [params]: []) + ] as const; + } + + +export const getVerifyCandidatesQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, + params?: VerifyCandidatesParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getVerifyCandidatesQueryKey(placeId,params); + + + + const queryFn: QueryFunction>> = ({ signal }) => verifyCandidates(placeId,params, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type VerifyCandidatesQueryResult = NonNullable>> +export type VerifyCandidatesQueryError = void | HTTPValidationError + + +export function useVerifyCandidates>, TError = void | HTTPValidationError>( + placeId: string, + params: undefined | VerifyCandidatesParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useVerifyCandidates>, TError = void | HTTPValidationError>( + placeId: string, + params?: VerifyCandidatesParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useVerifyCandidates>, TError = void | HTTPValidationError>( + placeId: string, + params?: VerifyCandidatesParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 동일 업소 후보 조회 + */ + +export function useVerifyCandidates>, TError = void | HTTPValidationError>( + placeId: string, + params?: VerifyCandidatesParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getVerifyCandidatesQueryOptions(placeId,params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * 확인된 fact 만 근거로 소개문과 FAQ 를 작성한다. ★ 근거 없는 수치·시설 언급은 코드로 검증해 반려한다(LLM 은 사실을 만들지 않는다). 생성물도 미검증 상태로 들어가 사람이 승인해야 사이트에 나간다. + * @summary 소개문·FAQ 생성(비동기) + */ +export const startCopy = ( + placeId: string, + reqStartCopy: ReqStartCopy, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/copy`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqStartCopy, signal + }, + options); + } + + + +export const getStartCopyMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqStartCopy}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqStartCopy}, TContext> => { + +const mutationKey = ['startCopy']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqStartCopy}> = (props) => { + const {placeId,data} = props ?? {}; + + return startCopy(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type StartCopyMutationResult = NonNullable>> + export type StartCopyMutationBody = ReqStartCopy + export type StartCopyMutationError = void | HTTPValidationError + + /** + * @summary 소개문·FAQ 생성(비동기) + */ +export const useStartCopy = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqStartCopy}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqStartCopy}, + TContext + > => { + + const mutationOptions = getStartCopyMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + \ No newline at end of file diff --git a/frontend/admin/src/api/generated/site/site.ts b/frontend/admin/src/api/generated/site/site.ts new file mode 100644 index 0000000..9cdbd7c --- /dev/null +++ b/frontend/admin/src/api/generated/site/site.ts @@ -0,0 +1,852 @@ +/** + * Generated by orval v7.21.0 🍺 + * Do not edit manually. + * Web4Ai API + * OpenAPI spec version: 0.1.0 + */ +import { + useMutation, + useQuery +} from '@tanstack/react-query'; +import type { + DataTag, + DefinedInitialDataOptions, + DefinedUseQueryResult, + MutationFunction, + QueryClient, + QueryFunction, + QueryKey, + UndefinedInitialDataOptions, + UseMutationOptions, + UseMutationResult, + UseQueryOptions, + UseQueryResult +} from '@tanstack/react-query'; + +import type { + CheckSlugParams, + HTTPValidationError, + ReqSiteSlug, + ReqSiteStatus, + ReqSiteTemplate, + ReqSiteTheme, + ReqStartBuild, + ResPublishLogs, + ResSeoAudit, + ResSite, + ResSiteSlug, + ResSiteVersions, + ResSlugCheck, + ResStartBuild +} from '.././model'; + +import { customFetch } from '../../mutator/custom-fetch'; + + +type SecondParameter unknown> = Parameters[1]; + + + +/** + * 현재 발행 버전과 재빌드 필요 여부(needs_rebuild). 노출값이 바뀐 뒤 다시 빌드하지 않았으면 true — 이 사업장만 재빌드하면 된다. + * @summary 사이트 상태 + */ +export const getSite = ( + placeId: string, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/site`, method: 'GET', signal + }, + options); + } + + + + +export const getGetSiteQueryKey = (placeId?: string,) => { + return [ + `/v1/place/${placeId}/site` + ] as const; + } + + +export const getGetSiteQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetSiteQueryKey(placeId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getSite(placeId, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetSiteQueryResult = NonNullable>> +export type GetSiteQueryError = void | HTTPValidationError + + +export function useGetSite>, TError = void | HTTPValidationError>( + placeId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetSite>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetSite>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 사이트 상태 + */ + +export function useGetSite>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetSiteQueryOptions(placeId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * 현재 확인된 콘텐츠와 최신 빌드를 SEO·AEO 각각 100점으로 채점하고 개선 항목을 반환한다. 준비도 점수이며 실제 검색 순위나 AI 인용을 보장하지 않는다. + * @summary SEO/AEO 준비도 진단 + */ +export const getSeoAudit = ( + placeId: string, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/site/audit`, method: 'GET', signal + }, + options); + } + + + + +export const getGetSeoAuditQueryKey = (placeId?: string,) => { + return [ + `/v1/place/${placeId}/site/audit` + ] as const; + } + + +export const getGetSeoAuditQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getGetSeoAuditQueryKey(placeId); + + + + const queryFn: QueryFunction>> = ({ signal }) => getSeoAudit(placeId, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type GetSeoAuditQueryResult = NonNullable>> +export type GetSeoAuditQueryError = void | HTTPValidationError + + +export function useGetSeoAudit>, TError = void | HTTPValidationError>( + placeId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useGetSeoAudit>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useGetSeoAudit>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary SEO/AEO 준비도 진단 + */ + +export function useGetSeoAudit>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getGetSeoAuditQueryOptions(placeId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * 쓰고 싶은 주소를 미리 본다. 소문자 영문·숫자·하이픈 3~50자만 되고, 예약어와 남이 쓰는 주소는 막힌다. ★ 서버가 상호명으로 자동 확정하지 않는다 — 사람이 고른다. 못 쓰면 reason(INVALID_LENGTH·INVALID_FORMAT·RESERVED·TAKEN)과 대안 하나(suggestion)를 준다. 지금 자기가 쓰는 주소면 available=true 다. + * @summary 사이트 주소 사용 가능 확인 + */ +export const checkSlug = ( + placeId: string, + params: CheckSlugParams, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/site/slug/check`, method: 'GET', + params, signal + }, + options); + } + + + + +export const getCheckSlugQueryKey = (placeId?: string, + params?: CheckSlugParams,) => { + return [ + `/v1/place/${placeId}/site/slug/check`, ...(params ? [params]: []) + ] as const; + } + + +export const getCheckSlugQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, + params: CheckSlugParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getCheckSlugQueryKey(placeId,params); + + + + const queryFn: QueryFunction>> = ({ signal }) => checkSlug(placeId,params, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type CheckSlugQueryResult = NonNullable>> +export type CheckSlugQueryError = void | HTTPValidationError + + +export function useCheckSlug>, TError = void | HTTPValidationError>( + placeId: string, + params: CheckSlugParams, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useCheckSlug>, TError = void | HTTPValidationError>( + placeId: string, + params: CheckSlugParams, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useCheckSlug>, TError = void | HTTPValidationError>( + placeId: string, + params: CheckSlugParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 사이트 주소 사용 가능 확인 + */ + +export function useCheckSlug>, TError = void | HTTPValidationError>( + placeId: string, + params: CheckSlugParams, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getCheckSlugQueryOptions(placeId,params,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * 주소를 sites.domain 에 저장한다(사이트 행이 없으면 만든다). 검증은 check 와 같은 규칙으로 서버가 다시 한다 — 클라이언트 검증을 믿지 않는다. ★ 이미 발행된 사이트의 주소는 바꿀 수 없다(SITE_SLUG_LOCKED) — 색인된 주소가 바뀌면 AI 검색이 잡아 둔 페이지가 404 가 된다. + * @summary 사이트 주소 확정 + */ +export const setSlug = ( + placeId: string, + reqSiteSlug: ReqSiteSlug, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/site/slug`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqSiteSlug, signal + }, + options); + } + + + +export const getSetSlugMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqSiteSlug}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqSiteSlug}, TContext> => { + +const mutationKey = ['setSlug']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqSiteSlug}> = (props) => { + const {placeId,data} = props ?? {}; + + return setSlug(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type SetSlugMutationResult = NonNullable>> + export type SetSlugMutationBody = ReqSiteSlug + export type SetSlugMutationError = void | HTTPValidationError + + /** + * @summary 사이트 주소 확정 + */ +export const useSetSlug = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqSiteSlug}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqSiteSlug}, + TContext + > => { + + const mutationOptions = getSetSlugMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * 위저드에서 고른 템플릿을 sites.template_id 에 저장한다(사이트 행이 없으면 만든다). ★ 서버는 값을 검증하지 않는다 — 템플릿 목록은 프론트가 소유한다. 길이(100자)만 막는다. ★ 주소와 달리 발행 뒤에도 바꿀 수 있다: 디자인이 바뀌어도 URL 은 그대로라 색인이 깨지지 않는다. 이미 발행된 사이트면 재빌드가 필요하다는 표시로 content_updated_at 을 찍는다(needs_rebuild=true). + * @summary 템플릿(디자인) 선택 저장 + */ +export const setTemplate = ( + placeId: string, + reqSiteTemplate: ReqSiteTemplate, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/site/template`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqSiteTemplate, signal + }, + options); + } + + + +export const getSetTemplateMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqSiteTemplate}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqSiteTemplate}, TContext> => { + +const mutationKey = ['setTemplate']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqSiteTemplate}> = (props) => { + const {placeId,data} = props ?? {}; + + return setTemplate(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type SetTemplateMutationResult = NonNullable>> + export type SetTemplateMutationBody = ReqSiteTemplate + export type SetTemplateMutationError = void | HTTPValidationError + + /** + * @summary 템플릿(디자인) 선택 저장 + */ +export const useSetTemplate = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqSiteTemplate}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqSiteTemplate}, + TContext + > => { + + const mutationOptions = getSetTemplateMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * 에디터가 정한 색·서체·섹션(순서·on/off·배리에이션)을 sites.theme 에 저장한다(사이트 행이 없으면 만든다). body 최상위 키는 theme 하나다: {"theme":{"colors":{...},"fontStyle":"...","colorPaletteId":"...","sections":[{"id","name","enabled","locked","variantId"}]}}. ★ sections 의 배열 순서가 곧 섹션 순서다(별도 order 필드 없음). ★ 서버는 값을 해석하지 않는다 — 섹션 목록·배리에이션 키·색 토큰은 프론트가 소유한다. 직렬화 크기(64KB)만 막는다. ★ templateId 는 여기 담지 않는다 — sites.template_id 와 POST /template 이 담당한다. ★ colorPaletteId 는 에디터 복원 전용이라 저장·반환만 하고 발행 payload 에는 싣지 않는다. ★ 빈 값({})을 보내면 NULL 로 되돌아가 업종 기본 색·서체·섹션으로 떨어진다. ★ 템플릿과 같이 발행 뒤에도 바꿀 수 있다(디자인이 바뀌어도 URL 은 그대로다). 이미 발행된 사이트면 재빌드가 필요하다는 표시로 content_updated_at 을 찍는다(needs_rebuild=true). + * @summary 디자인(색·서체·섹션) 저장 + */ +export const setTheme = ( + placeId: string, + reqSiteTheme: ReqSiteTheme, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/site/theme`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqSiteTheme, signal + }, + options); + } + + + +export const getSetThemeMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqSiteTheme}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqSiteTheme}, TContext> => { + +const mutationKey = ['setTheme']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqSiteTheme}> = (props) => { + const {placeId,data} = props ?? {}; + + return setTheme(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type SetThemeMutationResult = NonNullable>> + export type SetThemeMutationBody = ReqSiteTheme + export type SetThemeMutationError = void | HTTPValidationError + + /** + * @summary 디자인(색·서체·섹션) 저장 + */ +export const useSetTheme = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqSiteTheme}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqSiteTheme}, + TContext + > => { + + const mutationOptions = getSetThemeMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * 스냅샷을 박제해 HTML + JSON-LD 를 만들고 발행 검수 게이트를 돌린다. publish=true 면 통과 시 바로 발행한다. ★ 게이트를 우회하는 옵션은 없다. + * @summary 정적 빌드(비동기) + */ +export const startBuild = ( + placeId: string, + reqStartBuild: ReqStartBuild, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/site/build`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqStartBuild, signal + }, + options); + } + + + +export const getStartBuildMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqStartBuild}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqStartBuild}, TContext> => { + +const mutationKey = ['startBuild']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqStartBuild}> = (props) => { + const {placeId,data} = props ?? {}; + + return startBuild(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type StartBuildMutationResult = NonNullable>> + export type StartBuildMutationBody = ReqStartBuild + export type StartBuildMutationError = void | HTTPValidationError + + /** + * @summary 정적 빌드(비동기) + */ +export const useStartBuild = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqStartBuild}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqStartBuild}, + TContext + > => { + + const mutationOptions = getStartBuildMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + /** + * @summary 빌드 버전 목록 + */ +export const listVersions = ( + placeId: string, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/site/version/list`, method: 'GET', signal + }, + options); + } + + + + +export const getListVersionsQueryKey = (placeId?: string,) => { + return [ + `/v1/place/${placeId}/site/version/list` + ] as const; + } + + +export const getListVersionsQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListVersionsQueryKey(placeId); + + + + const queryFn: QueryFunction>> = ({ signal }) => listVersions(placeId, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListVersionsQueryResult = NonNullable>> +export type ListVersionsQueryError = void | HTTPValidationError + + +export function useListVersions>, TError = void | HTTPValidationError>( + placeId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListVersions>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListVersions>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 빌드 버전 목록 + */ + +export function useListVersions>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListVersionsQueryOptions(placeId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * 발행 시도와 거부 사유. 게이트가 막았으면 무엇이 문제였는지 detail 에 남는다. + * @summary 발행 기록 + */ +export const listLogs = ( + placeId: string, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/site/log/list`, method: 'GET', signal + }, + options); + } + + + + +export const getListLogsQueryKey = (placeId?: string,) => { + return [ + `/v1/place/${placeId}/site/log/list` + ] as const; + } + + +export const getListLogsQueryOptions = >, TError = void | HTTPValidationError>(placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} +) => { + +const {query: queryOptions, request: requestOptions} = options ?? {}; + + const queryKey = queryOptions?.queryKey ?? getListLogsQueryKey(placeId); + + + + const queryFn: QueryFunction>> = ({ signal }) => listLogs(placeId, requestOptions, signal); + + + + + + return { queryKey, queryFn, enabled: !!(placeId), ...queryOptions} as UseQueryOptions>, TError, TData> & { queryKey: DataTag } +} + +export type ListLogsQueryResult = NonNullable>> +export type ListLogsQueryError = void | HTTPValidationError + + +export function useListLogs>, TError = void | HTTPValidationError>( + placeId: string, options: { query:Partial>, TError, TData>> & Pick< + DefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): DefinedUseQueryResult & { queryKey: DataTag } +export function useListLogs>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>> & Pick< + UndefinedInitialDataOptions< + Awaited>, + TError, + Awaited> + > , 'initialData' + >, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +export function useListLogs>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } +/** + * @summary 발행 기록 + */ + +export function useListLogs>, TError = void | HTTPValidationError>( + placeId: string, options?: { query?:Partial>, TError, TData>>, request?: SecondParameter} + , queryClient?: QueryClient + ): UseQueryResult & { queryKey: DataTag } { + + const queryOptions = getListLogsQueryOptions(placeId,options) + + const query = useQuery(queryOptions, queryClient) as UseQueryResult & { queryKey: DataTag }; + + query.queryKey = queryOptions.queryKey ; + + return query; +} + + + + +/** + * ★ 해지는 삭제가 아니라 상태 전이다. 색인된 페이지를 갑자기 404 로 만들면 AI 검색이 그 자리를 다시 OTA 로 채운다. + * @summary 발행 상태 전이(중지·재개·내림) + */ +export const changeStatus = ( + placeId: string, + reqSiteStatus: ReqSiteStatus, + options?: SecondParameter,signal?: AbortSignal +) => { + + + return customFetch( + {url: `/v1/place/${placeId}/site/status`, method: 'POST', + headers: {'Content-Type': 'application/json', }, + data: reqSiteStatus, signal + }, + options); + } + + + +export const getChangeStatusMutationOptions = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqSiteStatus}, TContext>, request?: SecondParameter} +): UseMutationOptions>, TError,{placeId: string;data: ReqSiteStatus}, TContext> => { + +const mutationKey = ['changeStatus']; +const {mutation: mutationOptions, request: requestOptions} = options ? + options.mutation && 'mutationKey' in options.mutation && options.mutation.mutationKey ? + options + : {...options, mutation: {...options.mutation, mutationKey}} + : {mutation: { mutationKey, }, request: undefined}; + + + + + const mutationFn: MutationFunction>, {placeId: string;data: ReqSiteStatus}> = (props) => { + const {placeId,data} = props ?? {}; + + return changeStatus(placeId,data,requestOptions) + } + + + + + return { mutationFn, ...mutationOptions }} + + export type ChangeStatusMutationResult = NonNullable>> + export type ChangeStatusMutationBody = ReqSiteStatus + export type ChangeStatusMutationError = void | HTTPValidationError + + /** + * @summary 발행 상태 전이(중지·재개·내림) + */ +export const useChangeStatus = (options?: { mutation?:UseMutationOptions>, TError,{placeId: string;data: ReqSiteStatus}, TContext>, request?: SecondParameter} + , queryClient?: QueryClient): UseMutationResult< + Awaited>, + TError, + {placeId: string;data: ReqSiteStatus}, + TContext + > => { + + const mutationOptions = getChangeStatusMutationOptions(options); + + return useMutation(mutationOptions, queryClient); + } + \ No newline at end of file diff --git a/frontend/admin/src/api/index.ts b/frontend/admin/src/api/index.ts new file mode 100644 index 0000000..22f4cd8 --- /dev/null +++ b/frontend/admin/src/api/index.ts @@ -0,0 +1,26 @@ +/** + * API 단일 입구. + * + * 알맹이는 전부 `generated/` — 백엔드 OpenAPI 에서 orval 이 뽑은 React Query 훅과 모델이다. + * **손으로 고치지 않는다.** 백엔드가 바뀌면 재생성한다: + * + * ```bash + * npm run orval -w admin # 백엔드가 떠 있을 때 + * ORVAL_INPUT=../../backend/openapi.json npm run orval -w admin # 서버 없이 + * ``` + * + * 이 파일이 하는 일은 재export 뿐이다 — 화면이 `@/api/generated/place/place` 같은 + * 태그 경로를 외우지 않게. 태그가 늘면 여기 한 줄만 는다. + */ +export * from './generated/auth/auth'; +export * from './generated/place/place'; +export * from './generated/fact/fact'; +export * from './generated/job/job'; +export * from './generated/site/site'; +export * from './generated/media/media'; +export * from './generated/faq/faq'; +export * from './generated/model'; + +// 잡 폴링(수집·비전·생성·빌드 공용). 생성물이 아니라 그 위에 얹은 얇은 유틸이다. +export * from './pollJob'; +export {ApiError, getAccessToken, setTokens, clearTokens} from './mutator/custom-fetch'; diff --git a/frontend/admin/src/api/mutator/custom-fetch.ts b/frontend/admin/src/api/mutator/custom-fetch.ts new file mode 100644 index 0000000..28cef81 --- /dev/null +++ b/frontend/admin/src/api/mutator/custom-fetch.ts @@ -0,0 +1,173 @@ +// Orval mutator (기본 client 방식). axios 인터셉터를 대체하는 단일 길목 — +// 토큰 주입 / 에러 throw / 401·434 처리 / baseURL 을 여기서 처리한다. +// +// orval.config.ts 의 override.mutator 가 이 함수를 모든 생성 API 호출에 꽂는다. +// httpClient: 'fetch' 를 쓰지 않으므로 orval 은 config-object 시그니처로 호출한다: +// customFetch({ url, method, params, data, signal, headers }, requestOptions) +// → 함수가 응답 본문(T)을 바로 반환하고, 상태코드별 ResponseXXX 유니온 타입은 생성되지 않는다. + +// baseURL — .env 의 VITE_API_BASE_URL 로 주입, 없으면 9800 폴백(o2o-web4ai 백엔드 기본 포트). +const BASE_URL = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9800'; + +const ACCESS_KEY = 'o2o-web4ai.accessToken'; +const REFRESH_KEY = 'o2o-web4ai.refreshToken'; + +let accessToken: string | null = readStoredToken(ACCESS_KEY); + +function readStoredToken(key: string): string | null { + try { + return localStorage.getItem(key); + } catch { + // 사파리 프라이빗 모드 등에서 localStorage 접근이 throw 한다. 메모리 토큰으로만 동작. + return null; + } +} + +export function setTokens(access: string | null, refresh?: string | null) { + accessToken = access; + try { + if (access) localStorage.setItem(ACCESS_KEY, access); + else localStorage.removeItem(ACCESS_KEY); + if (refresh !== undefined) { + if (refresh) localStorage.setItem(REFRESH_KEY, refresh); + else localStorage.removeItem(REFRESH_KEY); + } + } catch { + /* 저장 실패는 무시 — 이번 세션 동안 메모리 토큰으로 계속 간다. */ + } +} + +export function getAccessToken(): string | null { + return accessToken; +} + +export function clearTokens() { + accessToken = null; + try { + localStorage.removeItem(ACCESS_KEY); + localStorage.removeItem(REFRESH_KEY); + } catch { + /* noop */ + } +} + +// 동시 다발 434(액세스 토큰 만료)를 단 한 번의 refresh 로 합치기 위한 in-flight 프라미스. +let refreshInFlight: Promise | null = null; + +async function refreshAccessToken(): Promise { + if (refreshInFlight) return refreshInFlight; + refreshInFlight = (async () => { + try { + const refresh = readStoredToken(REFRESH_KEY); + if (!refresh) return null; + // refresh 토큰은 Authorization 헤더(Bearer)로 보낸다(백엔드 auth 규약과 동일). + const res = await fetch(`${BASE_URL}/v1/auth/refresh_token`, { + method: 'POST', + headers: {Authorization: `Bearer ${refresh}`}, + }); + if (!res.ok) return null; + const refreshed = await res.json().catch(() => null); + const newToken: string | undefined = refreshed?.access_token; + if (!newToken || refreshed?.result?.success === false) return null; + setTokens(newToken); + return newToken; + } catch { + return null; + } finally { + refreshInFlight = null; + } + })(); + return refreshInFlight; +} + +export class ApiError extends Error { + constructor( + public status: number, + public statusText: string, + public data: unknown, + ) { + super(`API ${status} ${statusText}`); + this.name = 'ApiError'; + } +} + +export type RequestConfig = { + url: string; + method: string; + params?: Record; + data?: unknown; + headers?: HeadersInit; + signal?: AbortSignal; + responseType?: string; +}; + +export const customFetch = async ( + config: RequestConfig, + options?: RequestInit, +): Promise => { + const {url, method, params, data, signal} = config; + + // 쿼리스트링 직렬화 (null/undefined 값은 제외) + const queryString = params + ? new URLSearchParams( + Object.entries(params) + .filter(([, v]) => v !== undefined && v !== null) + .map(([k, v]) => [k, String(v)]), + ).toString() + : ''; + const requestUrl = + (url.startsWith('http') ? url : `${BASE_URL}${url}`) + (queryString ? `?${queryString}` : ''); + + // 파일 업로드(FormData)는 ① 브라우저가 boundary 포함 Content-Type 을 직접 설정해야 하고 + // ② 본문을 JSON.stringify 하면 "{}" 가 되어 파일이 통째로 누락된다. 분기 처리. + const isFormData = typeof FormData !== 'undefined' && data instanceof FormData; + + // [요청 인터셉터] 토큰을 받아 헤더를 구성하고 한 번 호출(만료 재시도 시 새 토큰으로 재구성). + const doFetch = (token: string | null) => { + const headers = new Headers(config.headers); + if (options?.headers) { + new Headers(options.headers).forEach((v, k) => headers.set(k, v)); + } + if (isFormData) { + headers.delete('Content-Type'); // boundary 없는 multipart 헤더 제거 → 브라우저가 재설정 + } else if (data != null && !headers.has('Content-Type')) { + headers.set('Content-Type', 'application/json'); + } + if (token) headers.set('Authorization', `Bearer ${token}`); + return fetch(requestUrl, { + ...options, + method, + headers, + body: data != null ? (isFormData ? data : JSON.stringify(data)) : options?.body, + signal, + }); + }; + + let response = await doFetch(accessToken); + + // 434(액세스 토큰 만료) → refresh 로 재발급 후 1회 재시도. auth 엔드포인트 자신은 제외(무한루프 방지). + const isAuthEndpoint = + url.includes('/v1/auth/refresh_token') || url.includes('/v1/auth/login'); + if ((response.status === 434 || response.status === 401) && !isAuthEndpoint) { + const newToken = await refreshAccessToken(); + if (newToken) { + response = await doFetch(newToken); + } else { + clearTokens(); // refresh 실패 → 토큰 폐기(다음 로드/가드에서 로그인으로 유도) + } + } + + // [응답 인터셉터] 본문 파싱 (204/빈 응답 대응) + const isJson = response.headers.get('content-type')?.includes('application/json'); + const body = + response.status === 204 ? null : isJson ? await response.json() : await response.text(); + + // fetch 는 4xx/5xx 도 resolve 하므로 직접 throw → React Query 가 error 로 처리 + if (!response.ok) { + throw new ApiError(response.status, response.statusText, body); + } + + return body as T; +}; + +export default customFetch; diff --git a/frontend/admin/src/api/pollJob.ts b/frontend/admin/src/api/pollJob.ts new file mode 100644 index 0000000..e9283da --- /dev/null +++ b/frontend/admin/src/api/pollJob.ts @@ -0,0 +1,104 @@ +/** + * 잡 폴링 단일 구현. + * + * 수집·비전·생성·빌드는 전부 같은 모양이다 — `POST` 로 job_id 를 받고 + * `GET /v1/job/{job_id}` 를 DONE/DEAD 까지 물어본다(백엔드 README 의 "잡을 적재하고 즉시 응답"). + * 그래서 화면마다 while 루프를 다시 쓰지 않고 여기 한 곳만 둔다. + * + * ★ 폴링에는 React Query 훅을 쓰지 않는다. 훅은 렌더 트리에 묶여 있어서 + * "버튼을 누른 뒤 끝날 때까지"라는 명령형 흐름(진행 문구·단계 전환)을 표현하지 못한다. + * 대신 orval 이 만든 같은 `getJob` 함수를 쓴다 — 토큰·baseURL·401 재시도는 mutator 가 처리한다. + */ +import {JobStatus} from '@o2o/shared'; +import {getJob} from './generated/job/job'; +import type {JobData} from './generated/model'; + +/** 잡 폴링 간격. 수집·빌드는 분 단위로 도는 작업이라 더 촘촘히 물어봐도 얻는 게 없다. */ +export const JOB_POLL_MS = 2000; + +/** ★ 폴링 총 제한시간. 워커가 죽어 잡이 RUNNING 에 박제되면 여기서 끊는다 — 무한 폴링 금지. */ +export const JOB_POLL_TIMEOUT_MS = 3 * 60 * 1000; + +/** ★ 연속 실패 허용치. 잠깐 끊긴 건 넘기고, 계속 실패하면 제한시간을 다 기다리지 않고 접는다. */ +export const JOB_MAX_POLL_ERRORS = 3; + +/** + * 폴링이 끝난 이유. + * + * ★ `done` 이 "성공"은 아니다. 잡은 끝났다는 뜻일 뿐이고, 게이트 거부처럼 도메인 판정은 + * `job.result` 안에 있다(빌드는 build_status·gate). 호출측이 그걸 읽어야 한다. + */ +export type JobOutcome = + | {kind: 'done'; job: JobData} + | {kind: 'dead'; job: JobData} + /** 제한시간 초과. 잡은 서버에서 계속 돈다 — 화면만 풀어 준다. */ + | {kind: 'timeout'} + /** 언마운트·재시작으로 끊겼다. 조용히 끝낸다(토스트 금지). */ + | {kind: 'aborted'} + /** 연속 실패로 상태를 못 읽었다. 잡의 성패는 알 수 없다. */ + | {kind: 'unreachable'; error: unknown}; + +export interface PollJobOptions { + signal: AbortSignal; + intervalMs?: number; + timeoutMs?: number; + maxErrors?: number; + /** 폴링 1회마다 호출. 진행 문구·단계 표시를 여기서 갱신한다. */ + onTick?: (job: JobData) => void; +} + +/** 폴링 간격 대기. abort 되면 즉시 깨어난다 — 죽은 타이머를 남기지 않는다. */ +export function delay(ms: number, signal: AbortSignal) { + return new Promise((resolve) => { + if (signal.aborted) return resolve(); + const timer = setTimeout(resolve, ms); + signal.addEventListener( + 'abort', + () => { + clearTimeout(timer); + resolve(); + }, + {once: true}, + ); + }); +} + +export async function pollJob(jobId: string, options: PollJobOptions): Promise { + const { + signal, + intervalMs = JOB_POLL_MS, + timeoutMs = JOB_POLL_TIMEOUT_MS, + maxErrors = JOB_MAX_POLL_ERRORS, + onTick, + } = options; + + const deadline = Date.now() + timeoutMs; + let errors = 0; + let lastError: unknown; + + while (Date.now() < deadline) { + await delay(intervalMs, signal); + if (signal.aborted) return {kind: 'aborted'}; + + let job: JobData | undefined; + try { + const polled = await getJob(jobId, undefined, signal); + job = polled.job ?? undefined; + } catch (error) { + if (signal.aborted) return {kind: 'aborted'}; + lastError = error; + } + + // 한 번이라도 잡을 받아오면 카운터를 되돌린다 — 잠깐 끊긴 네트워크로 몇 분짜리 잡을 접으면 안 된다. + errors = job ? 0 : errors + 1; + if (errors >= maxErrors) return {kind: 'unreachable', error: lastError}; + if (!job) continue; + + onTick?.(job); + + if (job.status === JobStatus.DONE) return {kind: 'done', job}; + if (job.status === JobStatus.DEAD) return {kind: 'dead', job}; + } + + return {kind: 'timeout'}; +} diff --git a/frontend/admin/src/app/main.tsx b/frontend/admin/src/app/main.tsx new file mode 100644 index 0000000..867493b --- /dev/null +++ b/frontend/admin/src/app/main.tsx @@ -0,0 +1,14 @@ +import {StrictMode} from 'react'; +import {createRoot} from 'react-dom/client'; +import {RouterProvider} from 'react-router'; +import {Providers} from './provider'; +import {router} from './router'; +import '../index.css'; + +createRoot(document.getElementById('root')!).render( + + + + + , +); diff --git a/frontend/admin/src/app/provider.tsx b/frontend/admin/src/app/provider.tsx new file mode 100644 index 0000000..4ff0817 --- /dev/null +++ b/frontend/admin/src/app/provider.tsx @@ -0,0 +1,55 @@ +import {QueryClientProvider} from '@tanstack/react-query'; +import {useEffect, type ReactNode} from 'react'; +import {Toaster} from 'sonner'; +import {getAccessToken, me} from '@/api'; +import {queryClient} from '@/lib/query-client'; +import {toAuthUser, useAuthStore} from '@/stores/auth'; + +/** + * 저장된 액세스 토큰으로 세션을 복구한다. + * 실패해도 앱은 뜬다 — 빌더는 로그인 없이도 도는 화면이라, 인증 실패가 + * 전체를 막으면 데모조차 못 본다. 백엔드가 필요한 화면만 가드가 막는다. + */ +function useRestoreSession() { + const setUser = useAuthStore((s) => s.setUser); + const finishRestore = useAuthStore((s) => s.finishRestore); + + useEffect(() => { + let alive = true; + if (!getAccessToken()) { + finishRestore(); + return; + } + void me() + .then((res) => { + if (!alive || res.result?.success === false) return; + // ★ RemoveNoneResponse 라 신원 필드가 통째로 빠져 올 수 있다. + // 반쪽짜리 사용자를 세우면 화면은 로그인된 것처럼 굴면서 요청은 401 이 난다 — 세우지 않는다. + if (!res.user_id || !res.id) return; + setUser(toAuthUser(res)); + }) + .catch(() => { + /* 토큰이 죽었으면 비로그인 상태로 계속 간다. */ + }) + .finally(() => { + if (alive) finishRestore(); + }); + return () => { + alive = false; + }; + }, [setUser, finishRestore]); +} + +function SessionGate({children}: {children: ReactNode}) { + useRestoreSession(); + return <>{children}; +} + +export function Providers({children}: {children: ReactNode}) { + return ( + + {children} + + + ); +} diff --git a/frontend/admin/src/app/router.tsx b/frontend/admin/src/app/router.tsx new file mode 100644 index 0000000..123e822 --- /dev/null +++ b/frontend/admin/src/app/router.tsx @@ -0,0 +1,54 @@ +import {createBrowserRouter, Navigate, Outlet} from 'react-router'; +import {AppShell} from '@/components/layout/AppShell'; +import {RequireAuth} from '@/components/layout/RequireAuth'; +import {BuilderPage} from '@/pages/BuilderPage'; +import {DevShowcasePage} from '@/pages/DevShowcasePage'; +import {LoginPage} from '@/pages/LoginPage'; +import {NotFoundPage} from '@/pages/NotFoundPage'; +import {PlaceDetailPage} from '@/pages/PlaceDetailPage'; +import {PlaceListPage} from '@/pages/PlaceListPage'; +import {SeoAuditPage} from '@/pages/SeoAuditPage'; +import {LocalContentPage} from '@/pages/LocalContentPage'; + +export const router = createBrowserRouter([ + {path: '/login', element: }, + + // ★ 첫 화면은 업종 선택(위저드 1단계)이다. + // `?new=1` 을 붙이는 이유: 위저드 상태는 새로고침을 넘기려고 저장돼 있어서(stores/builder persist), + // 그냥 /builder 로 보내면 지난번에 만들다 만 **에디터**가 복원돼 뜬다. 처음 들어오는 사람에게는 + // 그게 "왜 자꾸 빌더로 튀냐"로 보인다. 그래서 진입 경로에서 한 번 비우고 시작한다. + {path: '/', element: }, + + /** + * 빌더는 로그인 화면을 앞에 세우지 않는다 — 위저드를 열자마자 로그인부터 만나면 + * 만들어 보기도 전에 막힌다. + * + * 대신 세션은 조용히 확보한다: + * 개발 → useDevAutoLogin() 이 .env 의 개발 계정으로 자동 로그인한다 + * 운영 → 이미 로그인돼 있으면 그대로 쓰고, 아니면 서버가 필요한 순간(2단계 검색)에만 알린다 + * + * 에디터(6단계)는 전체 화면이 필요해 AppShell 을 스스로 끄고 켠다 — BuilderPage 참조. + */ + {path: '/builder', element: }, + + { + element: ( + + + + + + ), + children: [ + {path: '/places', element: }, + {path: '/places/:placeId', element: }, + {path: '/places/:placeId/seo', element: }, + {path: '/local-content', element: }, + ], + }, + + // 개발 빌드에서만 열리는 컴포넌트 쇼케이스. 운영 번들에서는 라우트 자체가 없다. + ...(import.meta.env.DEV ? [{path: '/dev/showcase', element: }] : []), + + {path: '*', element: }, +]); diff --git a/frontend/admin/src/components/layout/AppShell.tsx b/frontend/admin/src/components/layout/AppShell.tsx new file mode 100644 index 0000000..1765d7a --- /dev/null +++ b/frontend/admin/src/components/layout/AppShell.tsx @@ -0,0 +1,120 @@ +import type {ReactNode} from 'react'; +import {Link, NavLink, useLocation} from 'react-router'; +import {Building2, CalendarDays, LayoutGrid, LogOut, Search, Wand2} from 'lucide-react'; +import {cn} from '@/lib/utils'; +import {useAuthStore} from '@/stores/auth'; + +/** + * 순서가 곧 흐름이다 — 사업장 목록이 허브이고, 빌더는 **새로 만드는 입구**다. + * + * ★ 빌더는 `?new=1` 로 간다. 그냥 `/builder` 로 보내면 저장된 위저드 상태가 복원돼 + * 지난번에 편집하던 가게의 에디터가 뜬다(BuilderPage 주석) — 새로 만들러 누른 사람에게는 + * 남의 화면이다. 이미 만든 가게를 고치는 길은 사업장 목록의 [사이트 편집] 하나뿐이다. + * ★ match 는 활성 표시용 경로다 — 쿼리스트링이 붙은 to 로는 pathname 을 비교할 수 없다. + */ +const NAV = [ + {to: '/places', match: '/places', label: '사업장', icon: Building2}, + {to: '/builder?new=1', match: '/builder', label: '새 사이트', icon: Wand2}, + {to: '/local-content', match: '/local-content', label: '지역 콘텐츠', icon: CalendarDays}, +]; + +export function AppShell({children}: {children: ReactNode}) { + const user = useAuthStore((s) => s.user); + const signOut = useAuthStore((s) => s.signOut); + const location = useLocation(); + + return ( +
    + + +
    +
    {children}
    +
    +
    + ); +} + +export function PageContainer({ + title, + description, + actions, + children, +}: { + title: string; + description?: string; + actions?: ReactNode; + children: ReactNode; +}) { + return ( +
    +
    +
    +

    {title}

    + {description &&

    {description}

    } +
    + {actions &&
    {actions}
    } +
    + {children} +
    + ); +} + +export function EmptyState({ + icon: Icon = LayoutGrid, + title, + description, + action, +}: { + icon?: typeof Search; + title: string; + description?: string; + action?: ReactNode; +}) { + return ( +
    + +

    {title}

    + {description &&

    {description}

    } + {action &&
    {action}
    } +
    + ); +} diff --git a/frontend/admin/src/components/layout/RequireAuth.tsx b/frontend/admin/src/components/layout/RequireAuth.tsx new file mode 100644 index 0000000..d714303 --- /dev/null +++ b/frontend/admin/src/components/layout/RequireAuth.tsx @@ -0,0 +1,25 @@ +import type {ReactNode} from 'react'; +import {Navigate, useLocation} from 'react-router'; +import {Loader2} from 'lucide-react'; +import {useAuthStore} from '@/stores/auth'; + +export function RequireAuth({children}: {children: ReactNode}) { + const location = useLocation(); + const isRestoring = useAuthStore((s) => s.isRestoring); + const user = useAuthStore((s) => s.user); + + // 복구가 끝나기 전에 판단하면, 새로고침할 때마다 로그인 화면이 한 번 번쩍인다. + if (isRestoring) { + return ( +
    + +
    + ); + } + + if (!user) { + return ; + } + + return <>{children}; +} diff --git a/frontend/admin/src/components/ui/badge.tsx b/frontend/admin/src/components/ui/badge.tsx new file mode 100644 index 0000000..0955ef3 --- /dev/null +++ b/frontend/admin/src/components/ui/badge.tsx @@ -0,0 +1,28 @@ +import {cva, type VariantProps} from 'class-variance-authority'; +import type {HTMLAttributes} from 'react'; +import {cn} from '@/lib/utils'; + +const badgeVariants = cva( + 'inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-xs tracking-tight whitespace-nowrap', + { + variants: { + variant: { + default: 'bg-muted text-foreground border-border', + outline: 'bg-transparent text-muted-foreground border-border', + warning: 'bg-warning/10 text-warning border-warning/30 font-medium', + success: 'bg-success/10 text-success border-success/30', + accent: 'bg-primary text-primary-foreground border-primary', + contrast: 'bg-foreground text-background border-foreground', + }, + }, + defaultVariants: {variant: 'default'}, + }, +); + +export interface BadgeProps + extends HTMLAttributes, + VariantProps {} + +export function Badge({className, variant, ...props}: BadgeProps) { + return ; +} diff --git a/frontend/admin/src/components/ui/button.tsx b/frontend/admin/src/components/ui/button.tsx new file mode 100644 index 0000000..500537c --- /dev/null +++ b/frontend/admin/src/components/ui/button.tsx @@ -0,0 +1,56 @@ +import {cva, type VariantProps} from 'class-variance-authority'; +import type {ButtonHTMLAttributes} from 'react'; +import {Loader2} from 'lucide-react'; +import {cn} from '@/lib/utils'; + +const buttonVariants = cva( + 'inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-md font-medium transition-colors outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 disabled:pointer-events-none disabled:opacity-40 select-none cursor-pointer [&_svg]:shrink-0', + { + variants: { + variant: { + primary: 'bg-primary text-primary-foreground hover:bg-primary/90', + secondary: 'bg-card text-foreground border border-border hover:bg-muted', + outline: 'bg-transparent text-foreground border border-border hover:bg-muted', + ghost: 'bg-transparent text-muted-foreground hover:bg-muted hover:text-foreground', + destructive: 'bg-destructive text-destructive-foreground hover:bg-destructive/90', + contrast: 'bg-foreground text-background hover:bg-foreground/90', + }, + size: { + sm: 'h-8 px-2.5 text-xs [&_svg]:size-3.5', + md: 'h-9 px-4 text-sm [&_svg]:size-4', + lg: 'h-11 px-6 text-base [&_svg]:size-4', + icon: 'h-8 w-8 [&_svg]:size-4', + }, + }, + defaultVariants: {variant: 'secondary', size: 'md'}, + }, +); + +export interface ButtonProps + extends ButtonHTMLAttributes, + VariantProps { + isLoading?: boolean; +} + +export function Button({ + className, + variant, + size, + isLoading = false, + disabled, + children, + ...props +}: ButtonProps) { + return ( + + ); +} + +export {buttonVariants}; diff --git a/frontend/admin/src/components/ui/card.tsx b/frontend/admin/src/components/ui/card.tsx new file mode 100644 index 0000000..bcd42cc --- /dev/null +++ b/frontend/admin/src/components/ui/card.tsx @@ -0,0 +1,27 @@ +import type {HTMLAttributes} from 'react'; +import {cn} from '@/lib/utils'; + +export function Card({className, ...props}: HTMLAttributes) { + return ( +
    + ); +} + +export function CardHeader({className, ...props}: HTMLAttributes) { + return
    ; +} + +export function CardTitle({className, ...props}: HTMLAttributes) { + return

    ; +} + +export function CardDescription({className, ...props}: HTMLAttributes) { + return

    ; +} + +export function CardContent({className, ...props}: HTMLAttributes) { + return

    ; +} diff --git a/frontend/admin/src/components/ui/dialog.tsx b/frontend/admin/src/components/ui/dialog.tsx new file mode 100644 index 0000000..2fec654 --- /dev/null +++ b/frontend/admin/src/components/ui/dialog.tsx @@ -0,0 +1,77 @@ +import {useEffect, type ReactNode} from 'react'; +import {X} from 'lucide-react'; +import {cn} from '@/lib/utils'; + +interface DialogProps { + open: boolean; + onClose: () => void; + title: string; + description?: string; + children: ReactNode; + /** 항상 아래에 붙어 있어야 하는 영역(주요 버튼). 본문이 길어도 잘리지 않는다. */ + footer?: ReactNode; + className?: string; +} + +export function Dialog({open, onClose, title, description, children, footer, className}: DialogProps) { + useEffect(() => { + if (!open) return; + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') onClose(); + }; + // 배경 스크롤 잠금 — 모달 뒤 페이지가 같이 움직이면 어디를 보는지 잃는다. + const previous = document.body.style.overflow; + document.body.style.overflow = 'hidden'; + window.addEventListener('keydown', onKeyDown); + return () => { + document.body.style.overflow = previous; + window.removeEventListener('keydown', onKeyDown); + }; + }, [open, onClose]); + + if (!open) return null; + + return ( +
    +
    +
    +
    +
    +

    {title}

    + {description && ( +

    {description}

    + )} +
    + +
    + {/* 본문만 스크롤한다 — footer 를 쓰는 화면은 버튼이 항상 아래에 붙어 있게 된다. */} +
    {children}
    + {footer && ( +
    {footer}
    + )} +
    +
    + ); +} diff --git a/frontend/admin/src/components/ui/input.tsx b/frontend/admin/src/components/ui/input.tsx new file mode 100644 index 0000000..a3ba57a --- /dev/null +++ b/frontend/admin/src/components/ui/input.tsx @@ -0,0 +1,14 @@ +import type {InputHTMLAttributes} from 'react'; +import {cn} from '@/lib/utils'; + +export function Input({className, ...props}: InputHTMLAttributes) { + return ( + + ); +} diff --git a/frontend/admin/src/components/ui/progress.tsx b/frontend/admin/src/components/ui/progress.tsx new file mode 100644 index 0000000..7876f55 --- /dev/null +++ b/frontend/admin/src/components/ui/progress.tsx @@ -0,0 +1,31 @@ +import {cn} from '@/lib/utils'; + +interface ProgressProps { + /** 0 ~ 100 */ + value: number; + className?: string; + 'aria-label'?: string; +} + +export function Progress({value, className, ...props}: ProgressProps) { + const clamped = Math.max(0, Math.min(100, value)); + return ( +
    +
    + {/* 0% 구간에서도 '진행 중'이 보이게 광택을 얹는다. */} +
    +
    +
    +
    + ); +} diff --git a/frontend/admin/src/components/ui/switch.tsx b/frontend/admin/src/components/ui/switch.tsx new file mode 100644 index 0000000..6879773 --- /dev/null +++ b/frontend/admin/src/components/ui/switch.tsx @@ -0,0 +1,51 @@ +import type {MouseEvent} from 'react'; +import {cn} from '@/lib/utils'; + +interface SwitchProps { + checked: boolean; + onCheckedChange: (checked: boolean) => void; + disabled?: boolean; + id?: string; + 'aria-label'?: string; + className?: string; +} + +export function Switch({ + checked, + onCheckedChange, + disabled = false, + id, + className, + ...props +}: SwitchProps) { + // 스위치는 클릭 가능한 행 안에 놓이는 일이 많다 — 토글이 행 선택까지 트리거하지 않게 막는다. + const handleClick = (event: MouseEvent) => { + event.stopPropagation(); + if (!disabled) onCheckedChange(!checked); + }; + + return ( + + ); +} diff --git a/frontend/admin/src/data/industryData.ts b/frontend/admin/src/data/industryData.ts new file mode 100644 index 0000000..8ac5e8c --- /dev/null +++ b/frontend/admin/src/data/industryData.ts @@ -0,0 +1,409 @@ +import type {IndustryData, IndustryType} from '@o2o/shared'; + +export const INDUSTRY_CONFIGS: Record = { + stay: { + id: 'stay', + name: '숙박', + subName: '펜션 · 스테이', + description: '감성 스테이, 풀빌라, 독채 펜션, 게스트하우스', + channels: [ + { id: 'stay_platforms', name: '야놀자 · 여기어때', checked: true }, + { id: 'naver_place', name: '네이버 플레이스', checked: true }, + { id: 'instagram', name: '인스타그램', checked: true }, + ], + sections: [ + { id: 'hero', type: 'hero', name: '히어로', isLocked: true, isEnabled: true, description: '상단 메인 비주얼과 대표 문구' }, + { id: 'intro', type: 'intro', name: '소개', isLocked: false, isEnabled: true, description: '스테이의 철학과 공간 스토리' }, + { id: 'rooms', type: 'rooms', name: '객실 안내', isLocked: false, isEnabled: true, description: '객실 타입, 구조, 비치 물품' }, + { id: 'info', type: 'info', name: '기본 정보', isLocked: true, isEnabled: true, description: '체크인, 주차, 시설 핵심 정보' }, + { id: 'rules', type: 'rules', name: '이용 규정', isLocked: false, isEnabled: true, description: '환불 규정, 입실 수칙 및 에티켓' }, + { id: 'booking', type: 'booking', name: '실시간 예약', isLocked: false, isEnabled: true, description: '예약 현황 및 예약 신청' }, + { id: 'photos', type: 'photos', name: '사진 갤러리', isLocked: false, isEnabled: true, description: '감성 인테리어와 외부 풍경' }, + { id: 'map', type: 'map', name: '오시는 길', isLocked: true, isEnabled: true, description: '위치 안내 및 대중교통 경로' }, + { id: 'weather', type: 'weather', name: '날씨', isLocked: false, isEnabled: true, description: '현재 기온과 사업장 주변 날씨' }, + { id: 'local', type: 'local', name: '지역 정보', isLocked: false, isEnabled: true, description: '주변 관광지 및 맛집 추천' }, + { id: 'faq', type: 'faq', name: '자주 묻는 질문', isLocked: false, isEnabled: true, description: '고객들이 자주 묻는 질문과 답변' }, + ], + templates: [ + { + id: 'stay-o2o-editorial', + industryId: 'stay', + name: 'O2O 에디토리얼', + tone: 'photo', + toneLabel: '차분한 모던', + description: '절제된 타이포그래피와 여백, 차분한 슬레이트 톤으로 신뢰감과 감성을 함께 전합니다.', + colors: { + primary: '#18181b', + secondary: '#52525b', + bg: '#ffffff', + card: '#fafafa', + text: '#09090b', + accent: '#2563eb', + }, + fontStyle: 'Modern Editorial', + }, + { + id: 'stay-quiet-margin', + industryId: 'stay', + name: '조용한 여백', + tone: 'photo', + toneLabel: '사진 중심', + description: '넓은 여백과 감성적인 사진 배치로 여유로운 휴식 분위기를 전달합니다.', + colors: { + primary: '#1e293b', + secondary: '#64748b', + bg: '#ffffff', + card: '#f8fafc', + text: '#0f172a', + accent: '#0284c7', + }, + fontStyle: 'Clean Minimalist', + }, + { + id: 'stay-warm-wood', + industryId: 'stay', + name: '따뜻한 목조', + tone: 'photo', + toneLabel: '사진 중심', + description: '아늑하고 내추럴한 톤으로 자연 친화적인 공간의 따스함을 극대화합니다.', + colors: { + primary: '#43302b', + secondary: '#786055', + bg: '#faf8f5', + card: '#f2ece4', + text: '#29201d', + accent: '#c27847', + }, + fontStyle: 'Warm Natural', + }, + { + id: 'stay-clear-info', + industryId: 'stay', + name: '또렷한 정보', + tone: 'info', + toneLabel: '정보 중심', + description: '객실 옵션, 구비 시설, 체크인 규정을 한눈에 파악할 수 있는 실용적인 구조입니다.', + colors: { + primary: '#0f172a', + secondary: '#475569', + bg: '#ffffff', + card: '#f1f5f9', + text: '#020617', + accent: '#2563eb', + }, + fontStyle: 'Crisp Modern', + }, + { + id: 'stay-booking-focus', + industryId: 'stay', + name: '예약 중심', + tone: 'book', + toneLabel: '예약·신청 강조', + description: '객실별 예약 버튼과 실시간 문의 CTA를 전면에 배치하여 전환율을 높입니다.', + colors: { + primary: '#18181b', + secondary: '#52525b', + bg: '#ffffff', + card: '#fafafa', + text: '#09090b', + accent: '#059669', + }, + fontStyle: 'Conversion Driven', + }, + ], + }, + + cafe: { + id: 'cafe', + name: '카페', + subName: '대형카페 · 로스터리', + description: '스페셜티 로스터리, 베이커리 카페, 오션·마운틴 뷰 대형 카페', + channels: [ + { id: 'naver_place', name: '네이버 플레이스', checked: true }, + { id: 'instagram', name: '인스타그램', checked: true }, + { id: 'kakao_map', name: '카카오맵', checked: true }, + ], + sections: [ + { id: 'hero', type: 'hero', name: '히어로', isLocked: true, isEnabled: true, description: '시그니처 비주얼과 카페 슬로건' }, + { id: 'intro', type: 'intro', name: '소개', isLocked: false, isEnabled: true, description: '로스팅 철학과 공간 스토리' }, + { id: 'menu', type: 'menu', name: '시그니처 메뉴', isLocked: false, isEnabled: true, description: '대표 원두, 음료, 시그니처 디저트' }, + { id: 'info', type: 'info', name: '기본 정보', isLocked: true, isEnabled: true, description: '영업시간, 좌석수, 편의시설 정보' }, + { id: 'space', type: 'space', name: '공간 · 좌석 안내', isLocked: false, isEnabled: true, description: '1/2층 공간 구성 및 야외 테라스석' }, + { id: 'photos', type: 'photos', name: '사진 갤러리', isLocked: false, isEnabled: true, description: '인테리어, 커피, 베이커리 비주얼' }, + { id: 'inquiry', type: 'inquiry', name: '대관 및 단체 문의', isLocked: false, isEnabled: true, description: '촬영 대관 및 단체 예약 접수' }, + { id: 'map', type: 'map', name: '오시는 길', isLocked: true, isEnabled: true, description: '드라이브 코스 및 주차 진입로 안내' }, + { id: 'weather', type: 'weather', name: '날씨', isLocked: false, isEnabled: true, description: '현재 기온과 매장 주변 날씨' }, + { id: 'local', type: 'local', name: '주변 나들이', isLocked: false, isEnabled: true, description: '양평 드라이브 코스 및 명소' }, + { id: 'faq', type: 'faq', name: '자주 묻는 질문', isLocked: false, isEnabled: true, description: '반려견 동반, 주차, 케어키즈존 안내' }, + ], + templates: [ + { + id: 'cafe-modern-espresso', + industryId: 'cafe', + name: '모던 에스프레소', + tone: 'photo', + toneLabel: '사진 중심', + description: '다크 차콜 톤과 고해상도 커피 샷으로 프로페셔널한 스페셜티 이미지를 완성합니다.', + colors: { + primary: '#1c1917', + secondary: '#78716c', + bg: '#ffffff', + card: '#fafaf9', + text: '#0c0a09', + accent: '#b45309', + }, + fontStyle: 'Sleek Roast', + }, + { + id: 'cafe-sun-terrace', + industryId: 'cafe', + name: '햇살과 테라스', + tone: 'photo', + toneLabel: '사진 중심', + description: '산뜻한 화이트와 그린 포인트로 자연 채광 가득한 힐링 테라스 분위기를 연출합니다.', + colors: { + primary: '#14532d', + secondary: '#4b5563', + bg: '#ffffff', + card: '#f0fdf4', + text: '#052e16', + accent: '#16a34a', + }, + fontStyle: 'Garden Terrace', + }, + { + id: 'cafe-roastery-story', + industryId: 'cafe', + name: '감성 로스터리', + tone: 'info', + toneLabel: '정보 중심', + description: '원두 컵노트, 로스팅 프로파일, 브루잉 가이드를 체계적으로 정리해 전달합니다.', + colors: { + primary: '#332924', + secondary: '#6c584c', + bg: '#fcfaf8', + card: '#f4ede6', + text: '#201815', + accent: '#8c5e3d', + }, + fontStyle: 'Artisan Roast', + }, + { + id: 'cafe-quick-order', + industryId: 'cafe', + name: '퀵 오더 & 예약', + tone: 'book', + toneLabel: '예약·신청 강조', + description: '시그니처 원두 패키지 스마트스토어 링크 및 단체 대관 접수를 최우선으로 노출합니다.', + colors: { + primary: '#0f172a', + secondary: '#475569', + bg: '#ffffff', + card: '#f8fafc', + text: '#020617', + accent: '#ea580c', + }, + fontStyle: 'Dynamic Commerce', + }, + ], + }, + + restaurant: { + id: 'restaurant', + name: '음식점', + subName: '식당 · 주점', + description: '한식 다이닝, 일식 오마카세, 이탈리안 비스트로, 고기집', + channels: [ + { id: 'naver_place', name: '네이버 플레이스', checked: true }, + { id: 'catchtable', name: '캐치테이블', checked: true }, + { id: 'instagram', name: '인스타그램', checked: true }, + ], + sections: [ + { id: 'hero', type: 'hero', name: '히어로', isLocked: true, isEnabled: true, description: '대표 요리 비주얼 및 다이닝 소개' }, + { id: 'intro', type: 'intro', name: '소개', isLocked: false, isEnabled: true, description: '셰프의 조리 철학과 식재료 원산지 이야기' }, + { id: 'menu', type: 'menu', name: '코스 및 메뉴', isLocked: false, isEnabled: true, description: '점심/저녁 코스, 단품 요리, 주류 페어링' }, + { id: 'info', type: 'info', name: '기본 정보', isLocked: true, isEnabled: true, description: '영업시간, 휴무일, 주차, 예약 안내' }, + { id: 'booking', type: 'booking', name: '예약 · 포장 안내', isLocked: false, isEnabled: true, description: '캐치테이블 실시간 룸 예약 및 포장' }, + { id: 'photos', type: 'photos', name: '사진 갤러리', isLocked: false, isEnabled: true, description: '플레이팅, 룸 인테리어, 정갈한 상차림' }, + { id: 'inquiry', type: 'inquiry', name: '단체 행사 문의', isLocked: false, isEnabled: true, description: '상견례, 돌잔치, 기업 대관 문의' }, + { id: 'map', type: 'map', name: '오시는 길', isLocked: true, isEnabled: true, description: '지하철역 출구 및 발렛부스 위치' }, + { id: 'weather', type: 'weather', name: '날씨', isLocked: false, isEnabled: true, description: '현재 기온과 매장 주변 날씨' }, + { id: 'local', type: 'local', name: '주변 안내', isLocked: false, isEnabled: true, description: '청담 명품거리 및 갤러리 안내' }, + { id: 'faq', type: 'faq', name: '자주 묻는 질문', isLocked: false, isEnabled: true, description: '콜키지 정책, 알러지 케어, 주차 안내' }, + ], + templates: [ + { + id: 'rest-neat-table', + industryId: 'restaurant', + name: '정갈한 한상', + tone: 'photo', + toneLabel: '사진 중심', + description: '단아한 여백과 요리 고유의 색감을 살려 프리미엄 다이닝의 격을 높입니다.', + colors: { + primary: '#1c1917', + secondary: '#57534e', + bg: '#ffffff', + card: '#fafaf9', + text: '#0c0a09', + accent: '#b45309', + }, + fontStyle: 'Sophisticated Table', + }, + { + id: 'rest-modern-dining', + industryId: 'restaurant', + name: '모던 다이닝', + tone: 'photo', + toneLabel: '사진 중심', + description: '세련된 다크 모던 톤으로 주류 페어링과 비스트로의 트렌디함을 강조합니다.', + colors: { + primary: '#09090b', + secondary: '#52525b', + bg: '#ffffff', + card: '#f4f4f5', + text: '#09090b', + accent: '#e11d48', + }, + fontStyle: 'Chic Bistro', + }, + { + id: 'rest-taste-origin', + industryId: 'restaurant', + name: '맛과 원산지', + tone: 'info', + toneLabel: '정보 중심', + description: '계절 코스 구성, 식재료 산지 지도, 조리 과정을 상세히 기록하여 신뢰도를 높입니다.', + colors: { + primary: '#1e293b', + secondary: '#475569', + bg: '#ffffff', + card: '#f1f5f9', + text: '#0f172a', + accent: '#0d9488', + }, + fontStyle: 'Artisan Story', + }, + { + id: 'rest-booking-type', + industryId: 'restaurant', + name: '테이블 예약형', + tone: 'book', + toneLabel: '예약·신청 강조', + description: '시간대별 룸 예약 위젯과 잔여석 상태를 직관적으로 노출합니다.', + colors: { + primary: '#0f172a', + secondary: '#334155', + bg: '#ffffff', + card: '#f8fafc', + text: '#020617', + accent: '#2563eb', + }, + fontStyle: 'Direct Reserve', + }, + ], + }, + + tour: { + id: 'tour', + name: '관광 · 체험', + subName: '체험공간 · 전시', + description: '원데이 클래스, 도자기·목공 공방, 사설 갤러리, 팜스테이', + channels: [ + { id: 'naver_place', name: '네이버 플레이스', checked: true }, + { id: 'frip', name: '프립 (체험 플랫폼)', checked: true }, + { id: 'instagram', name: '인스타그램', checked: true }, + ], + sections: [ + { id: 'hero', type: 'hero', name: '히어로', isLocked: true, isEnabled: true, description: '대표 프로그램 비주얼 및 감성 슬로건' }, + { id: 'intro', type: 'intro', name: '소개', isLocked: false, isEnabled: true, description: '스튜디오 역사와 작가진 소개' }, + { id: 'programs', type: 'programs', name: '체험 프로그램', isLocked: false, isEnabled: true, description: '물레 체험, 핸드빌딩, 키즈 클래스' }, + { id: 'info', type: 'info', name: '기본 정보', isLocked: true, isEnabled: true, description: '운영시간, 입장료, 주차, 예약 방식' }, + { id: 'exhibition', type: 'exhibition', name: '관람 및 갤러리 안내', isLocked: false, isEnabled: true, description: '전시 일정 및 도자기 아트숍' }, + { id: 'photos', type: 'photos', name: '사진 갤러리', isLocked: false, isEnabled: true, description: '체험 모습, 완성 작품, 공방 풍경' }, + { id: 'inquiry', type: 'inquiry', name: '단체 및 출강 문의', isLocked: false, isEnabled: true, description: '기업 워크숍, 학교 단체 체험 접수' }, + { id: 'map', type: 'map', name: '오시는 길', isLocked: true, isEnabled: true, description: '이천 예스파크 진입로 및 주차장' }, + { id: 'weather', type: 'weather', name: '날씨', isLocked: false, isEnabled: true, description: '현재 기온과 체험장 주변 날씨' }, + { id: 'local', type: 'local', name: '주변 관광 코스', isLocked: false, isEnabled: true, description: '도예마을 맛집 및 주변 힐링 스팟' }, + { id: 'faq', type: 'faq', name: '자주 묻는 질문', isLocked: false, isEnabled: true, description: '작품 수령 기간, 복장, 환불 규정' }, + ], + templates: [ + { + id: 'tour-visual-tour', + industryId: 'tour', + name: '비주얼 투어', + tone: 'photo', + toneLabel: '사진 중심', + description: '체험 현장의 생생한 사진과 감각적인 그리드로 방문 욕구를 자극합니다.', + colors: { + primary: '#0f172a', + secondary: '#475569', + bg: '#ffffff', + card: '#f8fafc', + text: '#020617', + accent: '#0284c7', + }, + fontStyle: 'Visual Journey', + }, + { + id: 'tour-gallery-archive', + industryId: 'tour', + name: '갤러리 아카이브', + tone: 'photo', + toneLabel: '사진 중심', + description: '단아한 미술관 도록 스타일로 공예품과 전시 작품의 미학을 돋보이게 합니다.', + colors: { + primary: '#27272a', + secondary: '#71717a', + bg: '#fafafa', + card: '#f4f4f5', + text: '#18181b', + accent: '#d97706', + }, + fontStyle: 'Art Museum', + }, + { + id: 'tour-detailed-guide', + industryId: 'tour', + name: '상세 안내형', + tone: 'info', + toneLabel: '정보 중심', + description: '연령대별 추천 코스, 단계별 커리큘럼, 준비물 안내를 명확하게 정리합니다.', + colors: { + primary: '#1e293b', + secondary: '#64748b', + bg: '#ffffff', + card: '#f1f5f9', + text: '#0f172a', + accent: '#4f46e5', + }, + fontStyle: 'Curriculum Guide', + }, + { + id: 'tour-ticket-booking', + industryId: 'tour', + name: '티켓 예매형', + tone: 'book', + toneLabel: '예약·신청 강조', + description: '클래스 날짜 선택과 즉시 티켓 결제 연동에 최적화된 고전환 레이아웃입니다.', + colors: { + primary: '#0f172a', + secondary: '#334155', + bg: '#ffffff', + card: '#f8fafc', + text: '#020617', + accent: '#059669', + }, + fontStyle: 'Instant Booking', + }, + ], + }, +}; + +/** + * 업종을 아직 모를 때 떨어질 자리. + * + * ★ 스토어의 초기 업종이자, 서버 category 를 못 알아봤을 때의 기본값이다(placeAdapter). + * 두 곳이 다른 값을 쓰면 "빌더가 처음 보여준 화면"과 "사업장을 열었을 때 화면"의 + * 섹션·문구가 달라진다 — 사장님 눈에는 값이 바뀐 것으로 보인다. + */ +export const FALLBACK_INDUSTRY: IndustryType = 'stay'; diff --git a/frontend/admin/src/features/builder/CanvasView.tsx b/frontend/admin/src/features/builder/CanvasView.tsx new file mode 100644 index 0000000..7588037 --- /dev/null +++ b/frontend/admin/src/features/builder/CanvasView.tsx @@ -0,0 +1,220 @@ +import {useState, type CSSProperties} from 'react'; +import {Bed, Calendar, Home, MapPin, Monitor, Smartphone, Sparkles, Tablet} from 'lucide-react'; +import type {SectionItem, ViewportMode} from '@o2o/shared'; +import {publishUrlString, toSlug} from '@o2o/shared'; +import {deriveSurfaces} from '@/lib/color'; +import {cn} from '@/lib/utils'; +import {useBuilderStore, useCurrentTemplate} from '@/stores/builder'; +import {resolveVariant} from './canvas/registry'; + +// ★ 호스트를 상수로 박지 않는다. PublishModal 과 **다른 주소**를 보여주면 사장님은 +// 미리보기에서 본 주소와 발행 후 안내받는 주소가 달라 어느 쪽이 진짜인지 알 수 없다. +// 같은 규칙(VITE_PUBLISH_HOST → 없으면 현재 호스트)을 쓴다. +const PUBLISH_HOST = import.meta.env.VITE_PUBLISH_HOST ?? window.location.host; + +const VIEWPORT_FRAME: Record = { + pc: 'w-full max-w-5xl shadow-md', + tablet: 'w-[768px] max-w-full border-x border-border shadow-lg', + mobile: 'w-[390px] max-w-full overflow-hidden rounded-lg border-x border-border shadow-xl', +}; + +const VIEWPORT_TOOLBAR: {id: ViewportMode; label: string; icon: typeof Monitor}[] = [ + {id: 'pc', label: 'PC (100%)', icon: Monitor}, + {id: 'tablet', label: '태블릿 (768px)', icon: Tablet}, + {id: 'mobile', label: '모바일 (390px)', icon: Smartphone}, +]; + +const MOBILE_TABS = [ + {key: 'home', label: '홈', anchor: 'canvas-section-hero', icon: Home}, + {key: 'rooms', label: '객실', anchor: 'canvas-section-rooms', icon: Bed}, + {key: 'guide', label: '가이드', anchor: 'canvas-section-local', icon: Sparkles}, + {key: 'map', label: '위치', anchor: 'canvas-section-map', icon: MapPin}, +]; + +export function CanvasView() { + const industry = useBuilderStore((s) => s.industry); + const storeName = useBuilderStore((s) => s.storeName); + const location = useBuilderStore((s) => s.location); + const weatherLocation = useBuilderStore((s) => s.weatherLocation); + const sections = useBuilderStore((s) => s.sections); + const infoFields = useBuilderStore((s) => s.infoFields); + const photos = useBuilderStore((s) => s.photos); + const selectedSectionId = useBuilderStore((s) => s.selectedSectionId); + const viewport = useBuilderStore((s) => s.viewport); + const isPreviewMode = useBuilderStore((s) => s.isPreviewMode); + const setViewport = useBuilderStore((s) => s.setViewport); + const selectSection = useBuilderStore((s) => s.selectSection); + const setRightTab = useBuilderStore((s) => s.setRightTab); + + const template = useCurrentTemplate(); + const [activeMobileTab, setActiveMobileTab] = useState('home'); + + const scrollToSection = (anchor: string, tabKey: string) => { + setActiveMobileTab(tabKey); + document.getElementById(anchor)?.scrollIntoView({behavior: 'smooth', block: 'start'}); + }; + + // 템플릿 색은 CSS 변수로 내려보낸다 — 관리자 토큰(--primary 등)과 이름이 겹치지 않게 --tpl-* 접두어. + // ★ 면 토큰(--tpl-surface / -alt / inverse / border)은 템플릿 색에서 유도한다. + // 이걸 안 내려보내면 SectionFrame 이 폴백(고정 stone 색)으로 떨어져서, + // 템플릿을 바꿔도 화면 면적의 대부분이 그대로다 — 쇼케이스와 같은 식(lib/color.ts)을 쓴다. + const surfaces = deriveSurfaces(template.colors); + + const themeVars = { + '--tpl-surface': surfaces.surface, + '--tpl-surface-alt': surfaces.surfaceAlt, + '--tpl-inverse': surfaces.inverse, + '--tpl-border': surfaces.border, + '--tpl-primary': template.colors.primary, + '--tpl-secondary': template.colors.secondary, + '--tpl-bg': template.colors.bg, + '--tpl-card': template.colors.card, + '--tpl-text': template.colors.text, + '--tpl-accent': template.colors.accent, + } as CSSProperties; + + /** + * 섹션 하나를 그린다. + * + * 어떤 레이아웃으로 그릴지는 레지스트리가 정한다 — 여기에 switch 를 두면 + * 배리에이션을 하나 추가할 때마다 이 파일을 같이 고쳐야 한다. + */ + const renderSection = (section: SectionItem) => { + if (!section.isEnabled) return null; + + const variant = resolveVariant(section, industry); + // 아직 배리에이션이 없는 섹션 타입 — 캔버스를 깨뜨리지 않고 조용히 건너뛴다. + if (!variant) return null; + + const {Component} = variant; + + return ( + { + selectSection(section.id); + setRightTab('content'); + }} + /> + ); + }; + + return ( +
    + {!isPreviewMode && ( +
    + {/* ★ min-w-0 — 이 줄이 안 줄어들면 캔버스 칸 전체의 최소 너비가 올라가고, + 그 여파로 오른쪽 패널이 화면 밖으로 밀린다(EditorLayout 주석 참조). */} +
    + 미리보기 해상도: +
    + {VIEWPORT_TOOLBAR.map(({id, label, icon: Icon}) => ( + + ))} +
    +
    + +
    + + 실시간 동기화 캔버스 +
    +
    + )} + +
    +
    + {viewport !== 'pc' && ( +
    + + + + + + + {publishUrlString(toSlug(storeName) || 'my-store', PUBLISH_HOST)} + + {viewport.toUpperCase()} +
    + )} + + {/* 섹션은 좌측 패널이 정한 순서 그대로 그린다. */} +
    + {sections.map((section) => renderSection(section))} +
    + +
    +
    +

    + {storeName} +

    +

    + {infoFields.find((f) => f.id === 'address')?.value || location} +

    +

    + © {new Date().getFullYear()} {storeName}. Powered by Web4Ai. +

    +
    +
    + + {viewport === 'mobile' && ( + + )} +
    +
    +
    + ); +} diff --git a/frontend/admin/src/features/builder/EditorHeader.tsx b/frontend/admin/src/features/builder/EditorHeader.tsx new file mode 100644 index 0000000..0a476ce --- /dev/null +++ b/frontend/admin/src/features/builder/EditorHeader.tsx @@ -0,0 +1,96 @@ +import {Eye, Pencil, Send} from 'lucide-react'; +import {Link} from 'react-router'; +import {SiteStatus} from '@o2o/shared'; +import {getAccessToken, useGetSite} from '@/api'; +import {Badge} from '@/components/ui/badge'; +import {Button} from '@/components/ui/button'; +import {INDUSTRY_CONFIGS} from '@/data/industryData'; +import {useBuilderStore, useUnverifiedFields} from '@/stores/builder'; + +export function EditorHeader() { + const industry = useBuilderStore((s) => s.industry); + const storeName = useBuilderStore((s) => s.storeName); + const isPreviewMode = useBuilderStore((s) => s.isPreviewMode); + const togglePreview = useBuilderStore((s) => s.togglePreview); + const openPublishModal = useBuilderStore((s) => s.openPublishModal); + const reset = useBuilderStore((s) => s.reset); + const placeId = useBuilderStore((s) => s.placeId); + + const unverifiedCount = useUnverifiedFields().length; + + /** + * 한 번이라도 발행했는가 — 버튼 문구가 [사이트 발행] 인지 [사이트 재발행] 인지를 가른다. + * + * ★ usePlaceSync 가 이미 읽는 같은 쿼리다(같은 키 → 같은 캐시). 여기서 다시 부른다고 + * 요청이 한 번 더 나가지 않는다. + */ + const siteQuery = useGetSite(placeId ?? '', { + query: {enabled: Boolean(placeId) && Boolean(getAccessToken())}, + }); + const isRepublish = siteQuery.data?.site?.status === SiteStatus.PUBLISHED; + + return ( +
    +
    + {/* ★ 실사업장을 편집 중이면 로고는 사업장 목록으로 간다. + 예전엔 여기서도 reset() 을 불렀는데, 그러면 편집하던 가게를 떠나 데모 위저드로 + 떨어진다 — 사장님 눈에는 자기 가게가 사라진 것으로 보인다. */} + {placeId ? ( + + + + ) : ( + + )} + + + +
    + + {storeName} + + {INDUSTRY_CONFIGS[industry].name} + {unverifiedCount > 0 && ( + + 확인 필요 {unverifiedCount} + + )} +
    +
    + +
    + + + {/* 발행 = 빌드다. 누르면 HTML 을 다시 굽는다(usePublishSite 주석 참고). */} + +
    +
    + ); +} + +function LogoMark() { + return ( + Web4Ai + ); +} diff --git a/frontend/admin/src/features/builder/EditorLayout.tsx b/frontend/admin/src/features/builder/EditorLayout.tsx new file mode 100644 index 0000000..3eecc0a --- /dev/null +++ b/frontend/admin/src/features/builder/EditorLayout.tsx @@ -0,0 +1,108 @@ +import {useState} from 'react'; +import {Eye, Image as ImageIcon, Layers} from 'lucide-react'; +import {cn} from '@/lib/utils'; +import {useBuilderStore, useUnverifiedFields} from '@/stores/builder'; +import {CanvasView} from './CanvasView'; +import {EditorHeader} from './EditorHeader'; +import {RightTabsPanel} from './RightTabsPanel'; +import {SectionListPanel} from './SectionListPanel'; +import {PublishModal} from '@/features/publish/PublishModal'; + +type NarrowTab = 'sections' | 'canvas' | 'assets'; + +const NARROW_TABS: {id: NarrowTab; label: string; icon: typeof Layers}[] = [ + {id: 'sections', label: '섹션', icon: Layers}, + {id: 'canvas', label: '미리보기', icon: Eye}, + {id: 'assets', label: '에셋 / 정보', icon: ImageIcon}, +]; + +export function EditorLayout() { + const isPreviewMode = useBuilderStore((s) => s.isPreviewMode); + const unverifiedCount = useUnverifiedFields().length; + + // 1024px 미만에서는 3열이 안 들어간다 — 탭으로 하나씩 보여준다. + const [narrowTab, setNarrowTab] = useState('canvas'); + + return ( +
    + + + {!isPreviewMode && ( +
    + {NARROW_TABS.map(({id, label, icon: Icon}) => ( + + ))} +
    + )} + +
    + {isPreviewMode ? ( + + ) : ( + <> + {/* ★ shrink-0 — 가운데가 넓어져도 이 패널은 절대 줄지 않는다. */} +
    + { + if (window.innerWidth < 1024) setNarrowTab('canvas'); + }} + /> +
    + + {/* + ★ min-w-0 이 반드시 있어야 한다. + flex 아이템의 기본값은 `min-width: auto` 라 **콘텐츠 최소 너비 아래로 줄지 않는다**. + 캔버스 툴바(해상도 버튼 + 동기화 표시)가 그 최소 너비를 밀어올리면 이 칸이 + 남은 공간을 다 먹고, 오른쪽 패널이 통째로 화면 밖으로 밀려난다 + (바깥이 overflow-hidden 이라 스크롤도 안 생겨 그냥 사라진다 — 실제로 그랬다). + */} +
    + +
    + + {/* ★ shrink-0 — 오른쪽 패널이 잘리던 자리. 폭을 양보하지 않는다. */} +
    + +
    + + )} +
    + + +
    + ); +} diff --git a/frontend/admin/src/features/builder/FaqPanel.tsx b/frontend/admin/src/features/builder/FaqPanel.tsx new file mode 100644 index 0000000..e9826e8 --- /dev/null +++ b/frontend/admin/src/features/builder/FaqPanel.tsx @@ -0,0 +1,214 @@ +import {useState} from 'react'; +import {useQueryClient} from '@tanstack/react-query'; +import {Check, Loader2, MessageCircleQuestion, Plus, Sparkles, X} from 'lucide-react'; +import {FactStatus, PUBLISHABLE_FACT_STATUSES} from '@o2o/shared'; +import {getListFaqsQueryKey, useCreateFaq, useListFaqs, useTransitionFaq} from '@/api'; +import {Badge} from '@/components/ui/badge'; +import {Button} from '@/components/ui/button'; +import {Input} from '@/components/ui/input'; +import {cn} from '@/lib/utils'; +import {useBuilderStore} from '@/stores/builder'; + +/** + * FAQ 관리 패널. + * + * ★ 왜 별도 탭인가 + * FAQ 는 AI 검색이 가장 잘 인용하는 형식이다(FAQPage 구조화 데이터). 그런데 지금까지 + * 관리자에는 FAQ 를 **볼 자리조차** 없었다 — COPY 잡이 만들어 둔 FAQ 가 `UNVERIFIED` 로 + * 쌓여 있는데 승인할 화면이 없으니 영원히 발행되지 않았다. 실제로 8건이 대기 중인 + * 사업장이 있고, FAQ 가 나가는 사업장은 한 곳뿐이었다. + * + * ★ 이 패널이 하는 일은 둘이다. + * 1) 사장님이 **직접 질문·답변을 쓴다** → 서버가 OWNER 출처로 바로 노출값(VERIFIED)에 넣는다. + * 쓴 사람이 곧 출처이자 책임 주체이기 때문이다(fact 직접 입력과 같은 규칙). + * 2) LLM 이 만들어 둔 대기 FAQ 를 **승인한다** → VERIFIED 로 전이시켜 사이트에 내보낸다. + */ +export function FaqPanel() { + const placeId = useBuilderStore((s) => s.placeId); + + if (!placeId) { + return ( +
    + +

    데모에서는 FAQ 를 저장할 수 없습니다

    +

    + FAQ 는 서버(사업장)에 저장됩니다. 실제 사업장으로 들어오면 이곳에서 추가·승인할 수 있습니다. +

    +
    + ); + } + + return ; +} + +function FaqEditor({placeId}: {placeId: string}) { + const queryClient = useQueryClient(); + const [question, setQuestion] = useState(''); + const [answer, setAnswer] = useState(''); + // 어떤 항목에 요청이 나가 있는지 — 버튼마다 따로 표시해야 어느 줄이 움직이는지 보인다. + const [busyId, setBusyId] = useState(null); + + const listQuery = useListFaqs(placeId); + const createFaq = useCreateFaq(); + const transitionFaq = useTransitionFaq(); + + /** 목록을 다시 읽는다. 추가·승인 뒤 화면이 옛 상태로 남으면 사장님이 같은 걸 두 번 누른다. */ + const refresh = () => + queryClient.invalidateQueries({queryKey: getListFaqsQueryKey(placeId)}); + + const faqs = listQuery.data?.faqs ?? []; + const publishable = listQuery.data?.publishable ?? 0; + const pending = listQuery.data?.pending_review ?? 0; + + const submit = async () => { + const q = question.trim(); + const a = answer.trim(); + if (!q || !a) return; + await createFaq.mutateAsync({placeId, data: {question: q, answer: a}}); + setQuestion(''); + setAnswer(''); + await refresh(); + }; + + const approve = async (faqId: string) => { + setBusyId(faqId); + try { + await transitionFaq.mutateAsync({placeId, faqId, data: {status: FactStatus.VERIFIED}}); + await refresh(); + } finally { + setBusyId(null); + } + }; + + const reject = async (faqId: string) => { + setBusyId(faqId); + try { + await transitionFaq.mutateAsync({placeId, faqId, data: {status: FactStatus.REJECTED}}); + await refresh(); + } finally { + setBusyId(null); + } + }; + + return ( +
    +
    + 자주 묻는 질문 + + 노출 {publishable}건{pending > 0 && ` · 대기 ${pending}건`} + +
    + + {/* ── 새 FAQ 직접 추가 ───────────────────────────────── */} +
    +
    + 질문·답변 추가 +
    + setQuestion(event.target.value)} + placeholder="질문 (예: 주차할 수 있나요?)" + className="text-xs" + /> +