구조: 사장님(solution)과 내부 운영(admin)을 두 앱으로 가른다

최상단을 프로젝트 단위로 평평하게 둔다 — o2o-negosium 과 같은 규약이고, 이 레포만
다르게 갈 이유가 없다. negodata/{backend,front} 가 프로젝트 안에서 f/b 를 가르는 선례,
lps-admin/ 이 백엔드 없이 프론트만 가진 최상단 폴더의 선례다.

  backend/ frontend/{admin,site,shared}  →  solution/{backend,front,site,shared} + admin/

## 왜

내부 라우트(/local-content, /places/:id/seo)의 이름과 화면 코드가 사장님 번들에
그대로 실려 나가고 있었다. UserRole.DEVELOPER 주석의 "고객사에 존재를 노출하지 않는다"를
번들이 깨고 있었다 — 라우트 가드는 화면을 가리지 번들은 못 가린다.
번들을 갈라 확인했다: 사장님 dist 에서 local-content · /places · SeoAudit 이 전부 0건이다.

그 과정에서 두 곳이 더 새고 있었다.
- AppShell 의 NAV 배열이 내부 메뉴를 하드코딩하고 있었다. 앱을 가른 뒤에도 dist 에
  local-content 가 남아서 찾았다. 메뉴는 이제 앱이 prop 으로 들고 온다.
- EditorHeader·BuilderPage·LoginPage 가 /places 로 링크하고 있었다. 그 화면이 admin 으로
  나갔으니 사장님 앱에서는 404 다. 링크를 걷어내고 LoginPage 기본 도착지는 '/' 로 바꿨다
  (앱마다 홈이 다르고 각 라우터의 '/' 가 이미 그걸 안다).

## admin 에 백엔드를 두지 않았다

내부 화면이 부르는 훅이 전부 router/v1/{place,fact,local,validator} 에 이미 있다.
자체 백엔드를 두면 place·fact·link 를 같은 DB 에 대고 두 번 구현하게 된다.
대가는 solution/backend 가 죽으면 admin 도 멈추는 것 — 내부 도구라 감수한다.

## admin 의 `@` 는 solution/front/src 를 가리킨다

내부 화면이 쓰는 API 클라이언트·UI·수집 배선이 solution 에 한 벌만 있고 그 파일들끼리도
`@/...` 로 서로를 부른다. admin 에서 `@` 를 자기 src 로 잡으면 그 참조가 전부 깨진다
(실측 TS2307 14건). 복제하는 길도 있지만 RecollectPanel 주석이 금지한다 —
"수집 경로를 두 벌 만들면 확정 게이트"가 갈라진다.
admin 자기 파일만 `@admin` 이고, 의존 방향은 admin → solution 한 쪽뿐이다.

admin 이 여는 빌더는 다른 오리진이라 절대 URL + 새 탭이다(admin/src/lib/solutionUrl.ts).
react-router Link 로 두면 admin 안에서 라우트를 찾다 404 다.

## 그 밖

- npm 워크스페이스 루트를 레포 루트로 올렸다(admin 이 solution 밖이라).
- docker-compose 를 255→174줄로 줄이고 admin(:3002) 서비스를 넣었다. ADMIN_BIND 기본값은
  127.0.0.1 — 0.0.0.0 으로 열면 앱을 가른 의미가 없다.
- 발행 호스트를 프론트 .env 에 따로 적지 않는다. compose 가 루트의 SITE_PUBLIC_HOST 를
  VITE_PUBLISH_HOST 로 흘려보낸다 — 두 곳에 적으면 canonical 과 화면 주소가 조용히 갈라진다.
- nginx/site.conf 를 git 에서 빼고 .example 만 남겼다(.env·*.toml 과 같은 규약).
  compose 가 bind mount 하므로 클론 직후 복사해야 한다 — 없으면 Docker 가 그 자리에
  디렉토리를 만들어 nginx 가 설정 없이 뜬다.
- config.test.toml.example 을 추가했다. 없으면 클론한 사람이 pytest 를 아예 못 돌린다
  (conftest import 단계에서 죽는다). 외부 API 키는 전부 빈값이다 —
  APP_ENV=test 가 .env 를 안 읽는 이유를 여기서 우회하면 안 된다.
- 경로가 한 칸 깊어져 test_schema_ddl(parents[2]→[3]) 과 test_site_theme 을 고쳤다.

검증: front·admin·site 전부 lint 0 / build 0. 백엔드 514 passed.
남은 4건(test_build_publish 3 · test_snapshot 1)은 이 변경 전부터 실패하던 것으로,
손대지 않은 메인 체크아웃에서 같은 4건이 같게 실패하는 것을 확인했다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019uYhHQdssRubirPirrdJJC
This commit is contained in:
minaChoiandClaude Opus 5 committed 2026-08-31 15:12:09 +09:00
1 parent 139d460839
commit 9d25ed613e
714 files changed
+782 -440

No files matched your search

@@ -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"<loc>\s*([^<\s]+)\s*</loc>", res.text)
if "<urlset" not in res.text:
report(FAIL, "루트 사이트맵", "urlset 형식이 아니다")
return locs
if len(locs) > 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'<script[^>]+type="application/ld\+json"[^>]*>(.*?)</script>', 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)[^>]*>.*?</\1>", " ", 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()
+134
View File
@@ -0,0 +1,134 @@
"""생성 사이트 데모 — 실 DB 에 데이터가 갖춰진 사업장을 만들고 빌드해서 HTML 을 파일로 뽑는다.
python scripts/demo_build.py (backend/ 에서 실행)
★ 실 DB(web4ai_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 을 쓰는 것까지가 백엔드의 일이고,
# 그걸 정적 페이지로 굽는 것은 solution/site 의 렌더러다(그게 방문자가 보는 유일한 페이지).
print(f"\npayload: {r.get('payload_path')}")
print(f"페이지: {r.get('routes')}개 · JSON-LD 노드 {len(r.get('mismatches') or []) == 0 and '검증 통과' or '불일치'}")
print("정적 파일: solution/site/out/s/<slug>/ (렌더러가 굽는다)")
await engine.dispose()
asyncio.run(main())
+154
View File
@@ -0,0 +1,154 @@
"""파이프라인 데모 — 실 DB(web4ai_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("&amp;", "&")
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())
@@ -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()
+89
View File
@@ -0,0 +1,89 @@
"""발행된 사이트 **전부**를 Azure Blob(`$web`)에 다시 올린다.
python scripts/republish_all.py (backend/ 에서 실행)
python scripts/republish_all.py --dry-run (올리지 않고 목록만 본다)
★ 왜 필요한가 — 렌더러(solution/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()