Compare commits
26
Commits
Docs
...
2026fde80f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2026fde80f | ||
|
|
e8cda02a4b | ||
|
|
5ef3e5a7de | ||
|
|
1bcee68432 | ||
|
|
38fbe0ee7b | ||
|
|
8410380769 | ||
|
|
b94daa9dcf | ||
|
|
e8e695c5a9 | ||
|
|
d6a6c8e229 | ||
|
|
48109fdc99 | ||
|
|
22b7623aeb | ||
|
|
139a672138 | ||
|
|
94a083c895 | ||
|
|
969fb6773c | ||
|
|
4debeaed3a | ||
|
|
e6ffdad888 | ||
|
|
23162783f9 | ||
|
|
c250b656fd | ||
|
|
db58e94540 | ||
|
|
43483c6c38 | ||
|
|
df6c9bbb54 | ||
|
|
fceadd68ce | ||
|
|
9fe7f3f7f5 | ||
|
|
36b9e25b92 | ||
|
|
45cc80b60a | ||
|
|
9b4fe4030b |
No files matched your search
+14
-15
@@ -1,29 +1,28 @@
|
||||
# ★ 빌드 컨텍스트가 레포 루트다(solution/backend/Dockerfile 주석 참조).
|
||||
# 컨텍스트가 넓어진 만큼 여기서 확실히 잘라내야 이미지가 붓지 않는다.
|
||||
**/__pycache__/
|
||||
*.pyc
|
||||
**/.pytest_cache/
|
||||
# 빌드 컨텍스트는 레포 루트고, 백엔드 이미지와 solution-site 이미지가 이것을 **같이** 쓴다.
|
||||
# ★ nginx/Dockerfile.dockerignore 는 BuildKit 전용이다. 이 머신엔 buildx 가 없어 레거시
|
||||
# 빌더가 돌고, 그러면 이 파일만 읽힌다 — 여기서 프론트 소스를 자르면 nginx 빌드가 죽는다.
|
||||
# (백엔드 이미지는 COPY 대상이 solution/backend·admin/backend 뿐이라 영향이 없다.)
|
||||
.git/
|
||||
.venv/
|
||||
**/.venv/
|
||||
node_modules/
|
||||
**/node_modules/
|
||||
**/dist/
|
||||
**/.vite/
|
||||
**/__pycache__/
|
||||
*.pyc
|
||||
**/.pytest_cache/
|
||||
.venv/
|
||||
**/.venv/
|
||||
|
||||
# 발행 산출물은 볼륨에서 온다. 이미지에 구우면 사이트가 늘 때마다 이미지가 붓는다.
|
||||
solution/site/out/
|
||||
solution/site/payloads/
|
||||
|
||||
# 프론트·문서는 백엔드 이미지에 들어갈 이유가 없다.
|
||||
solution/frontend/
|
||||
solution/site/
|
||||
solution/shared/
|
||||
admin/frontend/
|
||||
docs/
|
||||
nginx/
|
||||
postgres-init/
|
||||
**/*.md
|
||||
solution/backend/tests/
|
||||
solution/backend/loadtest/
|
||||
|
||||
# 시크릿 — 이미지에 굽지 않는다. Dockerfile 이 example 을 복사해 넣고 실값은 compose env 로 준다.
|
||||
# 시크릿 — 이미지에 굽지 않는다. 백엔드는 example 사본 + compose env, 프론트는 build args.
|
||||
**/config.local.toml
|
||||
**/config.test.toml
|
||||
.env
|
||||
|
||||
+49
-66
@@ -1,83 +1,66 @@
|
||||
# o2o-web4ai 환경변수 템플릿.
|
||||
# cp .env.example .env 후 값을 채운다. .env 는 커밋되지 않는다(.gitignore).
|
||||
#
|
||||
# 우선순위: 실제 환경변수(docker-compose 등) > .env > config/config.{APP_ENV}.toml
|
||||
# DB 접속·JWT 는 config.local.toml 이 기본값이다. 여기 값을 채우면 그쪽을 덮어쓴다.
|
||||
# 외부 API 키는 toml 을 비워두고 여기서만 관리하는 것을 권장한다.
|
||||
# cp .env.example .env 후 값을 채운다. .env 는 커밋되지 않는다.
|
||||
# 우선순위: 실제 환경변수(compose) > .env > 코드 기본값(config_models.py)
|
||||
|
||||
# ── 실행 ─────────────────────────────────────────────────
|
||||
# ── 공통 solution/backend · admin/backend (server_configs 가 읽는다)
|
||||
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=web4ai_db
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=5432
|
||||
DB_USER=postgres
|
||||
DB_PASSWORD=
|
||||
DB_NAME=web4ai_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 가 늘어난다)
|
||||
COLLECT_USE_PERPLEXITY=0 # Perplexity 채널 발견. 0=끔(기본)
|
||||
NAVER_CLIENT_ID=
|
||||
NAVER_CLIENT_SECRET=
|
||||
|
||||
KAKAO_REST_API_KEY=
|
||||
|
||||
# 사진 분류 + 카피 작성 (Google AI Studio)
|
||||
# https://aistudio.google.com/apikey
|
||||
KAKAO_REST_API_KEY= # 미발급. 없으면 네이버 지역검색을 쓴다
|
||||
GEMINI_API_KEY=
|
||||
TOUR_API_KEY= # 디코딩된 키(인코딩 키는 이중 인코딩된다)
|
||||
|
||||
# 축제 · 관광지 (한국관광공사 TourAPI, data.go.kr)
|
||||
# ★ TourAPI 는 자체 areaCode/sigunguCode 체계를 쓴다 — 카카오 행정구역 코드와 다르므로 매핑이 필요하다.
|
||||
# 디코딩된 서비스키를 넣는다(인코딩 키를 넣으면 %2B 등이 이중 인코딩된다).
|
||||
TOUR_API_KEY=
|
||||
# 구글 로그인. 비우면 구글 로그인만 꺼진다(서버는 뜨고, 화면에 버튼도 안 뜬다).
|
||||
# Google Cloud Console > API 및 서비스 > 사용자 인증 정보 > OAuth 2.0 클라이언트 ID(웹 애플리케이션)
|
||||
# "승인된 JavaScript 원본" 에 화면 주소를 등록해야 브라우저에서 토큰이 나온다(리디렉션 URI 는 필요 없다).
|
||||
# ★ 백엔드(aud 대조)와 프론트(버튼)가 **같은 값**을 써야 한다 — compose 가 이 하나를
|
||||
# VITE_GOOGLE_CLIENT_ID 로 흘려보낸다. 두 곳에 따로 적지 않는다.
|
||||
# ★ 바꾸면 프론트를 다시 구워야 한다: ./deploy.sh solution-site
|
||||
GOOGLE_CLIENT_ID=
|
||||
|
||||
# Open-Meteo(날씨)는 API 키가 필요 없다. 좌표만 있으면 된다.
|
||||
# ── 발행 호스트 ──
|
||||
# 커스텀 도메인이 없는 사이트의 공개 주소(`https://<이 값>/s/<slug>`).
|
||||
# canonical·og:url·sitemap·IndexNow 가 전부 이 값을 쓴다. 비우면 w4ai.o2o.kr.
|
||||
# ★ 프론트(admin)의 VITE_PUBLISH_HOST 와 **같은 값**이어야 화면과 발행본이 갈리지 않는다.
|
||||
# CORS 허용 오리진. 쉼표로 여럿.
|
||||
# 서버에 올리면 반드시 적는다. 안 적으면 화면은 뜨고 API 만 막힌다.
|
||||
# CLIENT_URL=http://172.30.1.36:30031,http://localhost:3002
|
||||
# LANDING_URL=
|
||||
|
||||
# ── solution/frontend 브라우저가 부르는 주소 (compose 가 VITE_* 로 주입)
|
||||
# ★ 브라우저가 부르는 주소다. 서버에 올리면 localhost 는 즉시 틀린다.
|
||||
# PUBLIC_API_BASE_URL=http://localhost:9800
|
||||
# PUBLIC_WEB_BASE_URL=http://localhost:3000
|
||||
|
||||
# ── solution/site 발행물 — solution/backend 도 같이 본다
|
||||
# canonical·og:url·sitemap·IndexNow 가 전부 SITE_PUBLIC_HOST 를 쓴다.
|
||||
SITE_PUBLIC_HOST=w4ai.o2o.kr
|
||||
INDEXNOW_KEY= # 비우면 색인 통보를 건너뛴다(발행은 정상)
|
||||
AZURE_STORAGE_CONNECTION_STRING= # 비우면 로컬 발행만 한다
|
||||
AZURE_STORAGE_CONTAINER=
|
||||
AZURE_STORAGE_PREFIX=
|
||||
|
||||
# Azure Blob 정적 사이트 발행. 비우면 기존 로컬 out/ 발행만 사용한다.
|
||||
AZURE_STORAGE_CONNECTION_STRING=
|
||||
AZURE_STORAGE_CONTAINER=$web
|
||||
AZURE_STORAGE_PREFIX=ai-for-web
|
||||
# ── compose 포트 매핑
|
||||
# 비우면 로컬 기본값. 서버 값은 docs/SERVERS.md
|
||||
# SITE_HTTP_PORT=80 # 발행 사이트
|
||||
# WEB_PORT=3000 # 사장님 앱
|
||||
# API_PORT=9800 # 사장님 API
|
||||
# ADMIN_PORT=3002 # 내부 화면 (bind 127.0.0.1)
|
||||
# ADMIN_API_PORT_PUBLIC=9801 # 내부 API (bind 127.0.0.1)
|
||||
|
||||
# ── 색인 통보(IndexNow) ──
|
||||
# 발행 즉시 네이버·Bing·Yandex 에 URL 을 알린다. 비우면 통보를 건너뛴다(발행은 정상).
|
||||
# 구글은 IndexNow 를 지원하지 않는다 — 구글 쪽은 Search Console 사이트맵 제출이 별도 경로다.
|
||||
# 값은 8~128자의 영문·숫자·하이픈 아무 문자열이면 된다(비밀이 아니다. 공개되어야 작동한다):
|
||||
# python3 -c "import uuid; print(uuid.uuid4().hex)"
|
||||
INDEXNOW_KEY=
|
||||
# 자동 로그인 — 위저드 앞에 로그인 화면을 세우지 않으려고 세션을 미리 잡는다.
|
||||
# ⚠️ 이 값은 **프론트 번들에 구워진다.** 페이지를 연 사람은 누구나 JS 에서 읽는다 —
|
||||
# 내부 테스트 호스트에서만 채우고, 사장님에게 여는 순간 비운다(lib/autoSession.ts).
|
||||
# ★ 바꾸면 재빌드해야 한다: ./deploy.sh solution-site
|
||||
AUTO_LOGIN_ID=
|
||||
AUTO_LOGIN_PW=
|
||||
@@ -9,7 +9,9 @@
|
||||
| 어떻게 도나 · 앱 경계 | [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) |
|
||||
| **다음에 뭘 만드나** (우선순위 P0~P4) | [docs/DEVELOPMENT_DIRECTION.md](docs/DEVELOPMENT_DIRECTION.md) |
|
||||
| 미결 사항 · 코드가 그걸 어떻게 격리했나 | [docs/DECISIONS.md](docs/DECISIONS.md) |
|
||||
| 최근에 뭘 왜 바꿨나 | [docs/DEVLOG.md](docs/DEVLOG.md) |
|
||||
| 서버에 올릴 때 | [docs/DEPLOY.md](docs/DEPLOY.md) |
|
||||
| **어느 서버**에 올리나 (킹서버) | [docs/SERVERS.md](docs/SERVERS.md) |
|
||||
|
||||
---
|
||||
|
||||
@@ -32,11 +34,15 @@
|
||||
- **★ 프론트(`solution/site`)를 배포하면 반드시 전체 재굽기 + 전체 재업로드.**
|
||||
`azure_static.publish(slug)` 는 공용 자산 + `s/<slug>` 만 올린다 —
|
||||
**렌더러를 고쳐도 다른 사이트에는 반영되지 않는다.**
|
||||
→ `docker compose restart web` 후 `python scripts/republish_all.py`
|
||||
→ `docker compose restart solution-frontend` 후 `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 를 다시 만들어야 한다.
|
||||
- **`GOOGLE_CLIENT_ID` 도 두 곳에 있고 같아야 한다.** 백엔드(`GOOGLE_CLIENT_ID`) ↔ 프론트
|
||||
(`VITE_GOOGLE_CLIENT_ID`, compose 가 루트 값을 흘려보낸다). 백엔드는 이 값으로 구글 토큰의
|
||||
수신자(`aud`)를 대조한다 — **이 검사가 유일하게 "남의 앱에 발급된 진짜 구글 토큰"을 막는다.**
|
||||
어긋나면 버튼은 뜨는데 로그인만 계속 거부된다. 비우면 구글 로그인만 꺼진다(서버는 뜬다).
|
||||
- **`AZURE_STORAGE_PREFIX` 와 루트 절대경로는 충돌한다.** HTML 이 `/assets/…` 를 가리키는데
|
||||
블롭은 `ai-for-web/assets/…` 에 놓인다. 접두사를 쓰려면 오리진 경로를 `/ai-for-web` 로 잡는
|
||||
CDN 을 앞에 세워야 한다. 아니면 비워라.
|
||||
@@ -75,8 +81,8 @@ admin/ 우리 — backend(진입점만, :9801) · frontend(운영 화면)
|
||||
|
||||
| | 포트 | 진입점 | 권한 |
|
||||
|---|---|---|---|
|
||||
| 사장님 API | 9800 | `solution/backend/web_main.py` | 엔드포인트별 |
|
||||
| 내부 API | 9801 | `admin/backend/main.py` → `app.py` | **앱 전체 role >= DEVELOPER** |
|
||||
| 솔루션 API | 9800 | `solution/backend/web_main.py` | 엔드포인트별 |
|
||||
| 어드민 API | 9801 | `admin/backend/main.py` → `app.py` | **앱 전체 role >= DEVELOPER** |
|
||||
|
||||
`services`·`crud`·`models` 은 그대로 공유한다. admin 화면이 부르는 게 사장님 빌더와 거의
|
||||
같아서(place·fact, admin 전용은 `local-content` 하나) 도메인을 복제하지 않고 **같은 router
|
||||
@@ -90,12 +96,19 @@ admin/ 우리 — backend(진입점만, :9801) · frontend(운영 화면)
|
||||
## 실행
|
||||
|
||||
```bash
|
||||
docker compose up -d # api :9800 · api-admin :9801 · 워커 · web :3000 · admin :3002 · nginx :80
|
||||
docker compose logs -f worker
|
||||
docker compose up -d # api :9800 · 워커 · 프리렌더 · nginx :80
|
||||
docker compose --profile dev up -d # + 사장님 앱 HMR :3000 (로컬 전용)
|
||||
docker compose logs -f solution-worker
|
||||
```
|
||||
|
||||
- 사장님 앱 `:3000`(API :9800) · 내부 운영 `:3002`(API :9801, 로컬호스트에만 열림)
|
||||
- 발행 사이트: `http://localhost:3000/s/<slug>` (빌더 Vite 가 :3001 정적서버로 프록시)
|
||||
★ **운영에는 dev 서버를 띄우지 않는다.** `docker compose up -d` 가 올리는 nginx(`:80`)가
|
||||
사장님 앱(구운 번들) · 발행 사이트 · API 를 **한 오리진**으로 준다. `solution-frontend`
|
||||
(Vite dev, `:3000`)는 `--profile dev` 로만 뜨고 HMR 이 필요할 때만 쓴다.
|
||||
|
||||
- 한 오리진: `http://localhost/` 앱 · `http://localhost/s/<slug>` 발행 사이트 · `/v1/...` API
|
||||
- 내부 운영 `:3002`(API :9801, 로컬호스트에만 열림) — `--profile admin`
|
||||
- ★ **`VITE_*` 는 번들에 구워진다.** 주소를 바꾸면 `.env` 만 고쳐선 안 되고
|
||||
`./deploy.sh solution-site` 로 **다시 구워야** 한다
|
||||
- **클론 직후 1회**: `cp .env.example .env` · `cp nginx/site.conf.example nginx/site.conf`
|
||||
(후자를 빼먹으면 Docker 가 그 자리에 디렉토리를 만들어 nginx 가 설정 없이 뜬다)
|
||||
- DB 는 compose 밖이다 (호스트 PostgreSQL, `host.docker.internal`).
|
||||
@@ -119,7 +132,145 @@ Vite 앱은 구조상 **자기 디렉토리의 `.env` 만** 읽는다 — 그래
|
||||
★ **두 곳에 같은 값을 적지 않는다.** 발행 호스트는 compose 가 루트의 `SITE_PUBLIC_HOST` 를
|
||||
`VITE_PUBLISH_HOST` 로 흘려보낸다. 각자 적으면 canonical 과 화면 주소가 조용히 갈라진다.
|
||||
|
||||
## 커밋
|
||||
## 브랜치 · 커밋
|
||||
|
||||
- 한 커밋 = 한 가지 변경. 문서와 그 문서가 설명하는 코드는 같은 커밋에 둔다.
|
||||
- 커밋 메시지는 한국어로, **무엇을 왜 바꿨는지**. 파일 목록은 `git` 이 이미 안다.
|
||||
`o2o-negosium` 과 같은 규약이다.
|
||||
|
||||
**브랜치는 영문**이다. 한국어 브랜치를 올리지 않는다(워크트리 도구가 한글 이름을 자동으로
|
||||
만드는데 그대로 push 되기 쉽다).
|
||||
|
||||
```
|
||||
feature/<주제> feat/<주제> 새 기능
|
||||
fix/<주제> 버그
|
||||
chore/<주제> 잡일·설정
|
||||
docs/<주제> 문서
|
||||
design/<주제> 디자인
|
||||
```
|
||||
|
||||
**커밋 제목: `[type] scope: 요약 — 부연`**
|
||||
|
||||
```
|
||||
[feat] lps/enuri: 오퍼 항목의 판매몰명 식별 — 이미지 CDN 도메인 매핑
|
||||
[fix] negosium/front: 복기 구멍을 블록 경계에서 끊고 시트 여닫이에 고정
|
||||
[chore] lps: 구 IQR 이상치 제거 코드 삭제 — 죽은 경로 정리
|
||||
```
|
||||
|
||||
- type: `feat` `fix` `chore` `docs`
|
||||
- **scope 는 코드 경로**다 — `lps/ai` · `negodata/front` · `postgres-init`.
|
||||
이 레포라면 `solution/backend` · `site` · `admin/front` · `deploy`.
|
||||
여러 곳이면 쉼표(`negosium/front,landing`)
|
||||
- **요약은 명사형으로 끝낸다** — "분리" "추가" "갱신". "~한다" 로 쓰지 않는다
|
||||
- 부연은 `—` 뒤에 붙인다
|
||||
|
||||
**본문은 세 덩이다.**
|
||||
|
||||
```
|
||||
[fix] lps: 행(hang)·병목 가드 — 페이지 상호작용 80s 상한 + AI 호출 타임아웃
|
||||
|
||||
crash 로 굳은 페이지는 content() 가 CDP 응답을 상한 없이 기다린다 —
|
||||
실측(gmarket): 무로그 4분 행 → 잡 데드라인 300s 소진 → 사용자 체감 +5분.
|
||||
|
||||
- browser.py: goto+렌더대기+content 를 _fetch_page 로 묶어 80s 단일 상한
|
||||
- ai/keyword: timeout=45s 명시 — SDK 기본(600s)이 잡 데드라인보다 크다
|
||||
|
||||
테스트 4건 추가, 전체 270 passed
|
||||
```
|
||||
|
||||
1. **왜** — 실측값·밟은 함정. 코드를 읽으면 아는 "무엇" 은 쓰지 않는다
|
||||
2. **변경 항목** — 파일/모듈별 불릿, 항목마다 근거
|
||||
3. **검증** — `tsc·eslint·vite build 통과` · `전체 N passed`
|
||||
|
||||
한 커밋 = 한 가지 변경. 문서와 그 문서가 설명하는 코드는 같은 커밋에 둔다.
|
||||
|
||||
## 레포 구조
|
||||
|
||||
```
|
||||
solution/ 사장님 — backend · frontend(빌더) · site(발행물) · shared(계약)
|
||||
admin/ 우리 — backend(진입점만, :9801) · frontend(운영 화면)
|
||||
```
|
||||
|
||||
최상단은 **프로젝트 단위**다(`o2o-negosium` 과 같은 규약). `frontend/` `backend/` 를 최상단
|
||||
묶음 폴더로 쓰지 않는다. 근거와 경계는 [ARCHITECTURE.md 4절](docs/ARCHITECTURE.md).
|
||||
|
||||
★ **의존 방향은 `admin` → `solution` 한 쪽뿐이다.** admin 의 `@` 별칭이 `solution/frontend/src` 를
|
||||
가리키고, API 도 solution 백엔드를 본다. 반대 방향이 생기면 가른 의미가 사라진다.
|
||||
|
||||
★ **백엔드는 코드 한 벌, 진입점 둘이다.**
|
||||
|
||||
| | 포트 | 진입점 | 권한 |
|
||||
|---|---|---|---|
|
||||
| 솔루션 API | 9800 | `solution/backend/web_main.py` | 엔드포인트별 |
|
||||
| 어드민 API | 9801 | `admin/backend/main.py` → `app.py` | **앱 전체 role >= DEVELOPER** |
|
||||
|
||||
`services`·`crud`·`models` 은 그대로 공유한다. admin 화면이 부르는 게 사장님 빌더와 거의
|
||||
같아서(place·fact, admin 전용은 `local-content` 하나) 도메인을 복제하지 않고 **같은 router
|
||||
객체를 다시 마운트하면서 앱 단위로 권한만 덧건다.**
|
||||
경로 접두어(`/v1/admin/...`)가 아니라 **포트**를 가른 이유: 접두어는 같은 프로세스라
|
||||
사장님이 닿는 서버에 내부 엔드포인트가 존재한다. 포트를 가르면 아예 없다.
|
||||
`ADMIN_API_BIND` 기본값이 `127.0.0.1` 인 것도 같은 이유다 — 0.0.0.0 으로 열면 무의미하다.
|
||||
⚠️ 단 `/v1/admin/local-content` 는 아직 :9800 에도 마운트돼 있다 — 남은 구멍이다
|
||||
([ARCHITECTURE.md 4절](docs/ARCHITECTURE.md)).
|
||||
|
||||
## 실행
|
||||
|
||||
```bash
|
||||
docker compose up -d # api :9800 · 워커 · 프리렌더 · nginx :80
|
||||
docker compose --profile dev up -d # + 사장님 앱 HMR :3000 (로컬 전용)
|
||||
docker compose logs -f solution-worker
|
||||
```
|
||||
|
||||
★ **운영에는 dev 서버를 띄우지 않는다.** `docker compose up -d` 가 올리는 nginx(`:80`)가
|
||||
사장님 앱(구운 번들) · 발행 사이트 · API 를 **한 오리진**으로 준다. `solution-frontend`
|
||||
(Vite dev, `:3000`)는 `--profile dev` 로만 뜨고 HMR 이 필요할 때만 쓴다.
|
||||
|
||||
- 한 오리진: `http://localhost/` 앱 · `http://localhost/s/<slug>` 발행 사이트 · `/v1/...` API
|
||||
- 내부 운영 `:3002`(API :9801, 로컬호스트에만 열림) — `--profile admin`
|
||||
- ★ **`VITE_*` 는 번들에 구워진다.** 주소를 바꾸면 `.env` 만 고쳐선 안 되고
|
||||
`./deploy.sh solution-site` 로 **다시 구워야** 한다
|
||||
- **클론 직후 1회**: `cp .env.example .env` · `cp nginx/site.conf.example nginx/site.conf`
|
||||
(후자를 빼먹으면 Docker 가 그 자리에 디렉토리를 만들어 nginx 가 설정 없이 뜬다)
|
||||
- DB 는 compose 밖이다 (호스트 PostgreSQL, `host.docker.internal`).
|
||||
스키마는 `postgres-init/init-data/init.sql` **한 벌**이다 — 누적 ALTER 파일은 없다
|
||||
- npm 워크스페이스 루트는 **레포 루트**다. `npm install` 은 루트에서 한 번.
|
||||
`npm run dev:frontend` / `dev:admin` / `dev:site`
|
||||
- 백엔드 스크립트는 `solution/backend/` 에서 `.venv/bin/python scripts/<name>.py`
|
||||
- 테스트: `solution/backend/` 에서 `.venv/bin/pytest`. **`APP_ENV=test` 면 `.env` 를 읽지 않는다** —
|
||||
실키가 테스트로 새어 외부 API 요금이 나가는 경로를 막아 뒀다
|
||||
|
||||
## .env 는 어디에 두나
|
||||
|
||||
**루트 `.env` 가 단일 출처다.** compose 가 이 파일만 읽고(`${...}` 치환 + `env_file`),
|
||||
Vite 앱은 구조상 **자기 디렉토리의 `.env` 만** 읽는다 — 그래서 나뉘어 있는 것이지 취향이 아니다.
|
||||
|
||||
| 파일 | 담는 것 |
|
||||
|---|---|
|
||||
| `.env` | DB · JWT · 외부 API 키 · `SITE_PUBLIC_HOST` · `INDEXNOW_KEY` |
|
||||
| `solution/frontend/.env` · `admin/frontend/.env` | 그 앱에만 있는 `VITE_*`. admin 은 API 가 :9801 이다 |
|
||||
|
||||
★ **두 곳에 같은 값을 적지 않는다.** 발행 호스트는 compose 가 루트의 `SITE_PUBLIC_HOST` 를
|
||||
`VITE_PUBLISH_HOST` 로 흘려보낸다. 각자 적으면 canonical 과 화면 주소가 조용히 갈라진다.
|
||||
|
||||
## 브랜치 · 커밋
|
||||
|
||||
`o2o-negosium` 과 같은 규약이다.
|
||||
|
||||
**브랜치는 영문**이다. 한국어 브랜치를 올리지 않는다(워크트리 도구가 한글 이름을 자동으로
|
||||
만들 수 있는데, 그대로 push 하면 안 된다).
|
||||
|
||||
```
|
||||
feature/<주제> 새 기능 fix/<주제> 버그
|
||||
chore/<주제> 잡일·설정 docs/<주제> 문서
|
||||
```
|
||||
|
||||
**커밋 메시지는 `type(scope): 한국어 설명`.**
|
||||
|
||||
```
|
||||
feat(site): 발행 모달에 커스텀 도메인 안내를 붙인다
|
||||
fix(backend/config): 배포 주소에서 CORS 가 막히던 것
|
||||
chore(deploy): 포트를 .env 로 뽑는다
|
||||
```
|
||||
|
||||
- type: `feat` `fix` `chore` `docs` `refactor`
|
||||
- scope: 건드린 자리(`backend` `site` `admin/front` `lps` `postgres-init` …). 애매하면 생략한다
|
||||
- 한 커밋 = 한 가지 변경. 문서와 그 문서가 설명하는 코드는 같은 커밋에 둔다
|
||||
- 본문에는 **왜** 를 적는다. 파일 목록은 `git` 이 이미 안다
|
||||
@@ -16,16 +16,16 @@
|
||||
cp .env.example .env # DB_*, JWT_*, 외부 API 키
|
||||
cp nginx/site.conf.example nginx/site.conf # 빼먹으면 nginx 가 설정 없이 뜬다
|
||||
docker compose up -d
|
||||
docker compose logs -f worker
|
||||
docker compose logs -f solution-worker
|
||||
```
|
||||
|
||||
| | 주소 | 공개 |
|
||||
|---|---|---|
|
||||
| 사장님 앱 (빌더) | http://localhost:3000 | 외부 |
|
||||
| 발행된 사이트 | http://localhost:3000/s/`<slug>` · 운영은 :80 | 외부 |
|
||||
| 사장님 API 문서 | http://localhost:9800/docs | 외부 |
|
||||
| 솔루션 API 문서 | http://localhost:9800/docs | 외부 |
|
||||
| **내부 운영 화면** | http://localhost:3002 | **127.0.0.1 만** |
|
||||
| **내부 API 문서** | http://localhost:9801/docs | **127.0.0.1 만** |
|
||||
| **어드민 API 문서** | http://localhost:9801/docs | **127.0.0.1 만** |
|
||||
|
||||
내부 두 개를 `0.0.0.0` 으로 열면 앱을 가른 의미가 없다 (`ADMIN_BIND` · `ADMIN_API_BIND`).
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""내부 운영 API. 사장님 API(:9800)와 프로세스·포트가 갈린다.
|
||||
"""어드민 API. 솔루션 API(:9800)와 프로세스·포트가 갈린다.
|
||||
|
||||
도메인 코드는 solution/backend 것을 PYTHONPATH 로 쓴다 — admin 전용 라우터가 0개라
|
||||
(전부 place·fact) 새로 쓰면 같은 테이블을 두 벌 구현하는 것뿐이다.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# 내부 운영 API 서버 (:9801). 근거는 app.py 주석.
|
||||
# 어드민 API 서버 (:9801). 근거는 app.py 주석.
|
||||
# PYTHONPATH=../../solution/backend python main.py
|
||||
|
||||
import os
|
||||
|
||||
@@ -23,7 +23,8 @@ const ADMIN_NAV: NavItem[] = [
|
||||
* 그 예외가 기본값이 된다. 사장님 앱과 앱을 가른 이유가 이 규칙을 지키기 위해서다.
|
||||
*/
|
||||
export const router = createBrowserRouter([
|
||||
{path: '/login', element: <LoginPage />},
|
||||
// selfServe=false: 내부 운영 계정은 우리가 만들어 준다 — 가입 링크도 구글 로그인도 두지 않는다.
|
||||
{path: '/login', element: <LoginPage selfServe={false} />},
|
||||
|
||||
{path: '/', element: <Navigate to="/places" replace />},
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ const CATEGORY_LABEL: Record<number, string> = {
|
||||
[PlaceCategory.LODGING]: '숙박',
|
||||
[PlaceCategory.CAFE]: '카페',
|
||||
[PlaceCategory.RESTAURANT]: '음식점',
|
||||
[PlaceCategory.TOUR_ACTIVITY]: '관광체험',
|
||||
[PlaceCategory.CLINIC]: '피부과·성형외과',
|
||||
};
|
||||
|
||||
const STATUS_LABEL: Record<number, string> = {
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
#!/usr/bin/env bash
|
||||
# 배포 — 코드를 당기고, 지정한 서비스만 다시 빌드해 갈아끼운다.
|
||||
#
|
||||
# ./deploy.sh 전체
|
||||
# ./deploy.sh solution-backend 그 서비스만
|
||||
# ./deploy.sh solution-backend solution-worker 여럿
|
||||
#
|
||||
# 서비스명 대신 컨테이너명(o2o-web4ai-solution-backend)으로 불러도 받는다.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
PREFIX=o2o-web4ai
|
||||
# api·worker·api-admin 은 이미지 한 벌(o2o-web4ai-backend)을 나눠 쓴다.
|
||||
BACKEND_SVCS=(solution-backend solution-worker admin-backend)
|
||||
BRANCH=${DEPLOY_BRANCH:-main}
|
||||
|
||||
PULL=1
|
||||
ONLY=0
|
||||
TARGETS=()
|
||||
|
||||
usage() {
|
||||
cat <<'USAGE'
|
||||
사용법: ./deploy.sh [옵션] [서비스...]
|
||||
|
||||
옵션
|
||||
--no-pull 코드를 당기지 않는다(디스크에 있는 코드 그대로 빌드)
|
||||
--only 백엔드 형제 서비스를 함께 갈아끼우지 않는다 (아래 ★ 참고)
|
||||
-h, --help
|
||||
|
||||
환경변수
|
||||
DEPLOY_BRANCH 기본 main. 다른 브랜치를 배포할 때만 쓴다
|
||||
|
||||
서비스: solution-backend · solution-worker · solution-prerender · solution-site
|
||||
admin-backend · admin-frontend (프로필 admin, 기본 기동에서 빠져 있다)
|
||||
solution-frontend (프로필 dev, 로컬 HMR 전용 — 운영에서 띄우지 않는다)
|
||||
o2o-web4ai-solution-backend 처럼 컨테이너명으로 적어도 된다
|
||||
|
||||
★ solution-backend·solution-worker·admin-backend 는 이미지가 한 벌이다. 하나를 빌드하면 나머지도 새 이미지로
|
||||
갈아끼워야 한다 — 안 그러면 옛 코드로 도는 컨테이너가 남는데, 셋 다 "살아 있음" 이라
|
||||
화면상으로는 배포가 끝난 것처럼 보인다. --only 는 그걸 알고 건너뛸 때만 쓴다.
|
||||
USAGE
|
||||
}
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--no-pull) PULL=0 ;;
|
||||
--only) ONLY=1 ;;
|
||||
-h|--help) usage; exit 0 ;;
|
||||
-*) echo "모르는 옵션: $1" >&2; usage >&2; exit 2 ;;
|
||||
*) TARGETS+=("${1#"$PREFIX"-}") ;; # 컨테이너명으로 불러도 받는다
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
ALL_SVCS=$(docker compose config --services)
|
||||
for t in ${TARGETS+"${TARGETS[@]}"}; do
|
||||
grep -qx "$t" <<<"$ALL_SVCS" || {
|
||||
echo "그런 서비스가 없다: $t" >&2
|
||||
echo "있는 것: $(tr '\n' ' ' <<<"$ALL_SVCS")" >&2
|
||||
exit 2
|
||||
}
|
||||
done
|
||||
|
||||
# ── 코드 ────────────────────────────────────────────────────────────
|
||||
# 배포 서버의 작업트리는 main 의 **사본**이지 작업 공간이 아니다. 그래서 머지(pull)가 아니라
|
||||
# origin/$BRANCH 로 하드 리셋한다 — 밖에서 force-push 가 나도 --ff-only 로 막히지 않고,
|
||||
# 서버에서 누가 손댄 흔적이 다음 배포까지 살아남지 않는다.
|
||||
#
|
||||
# ★ fetch 가 실패하면 **리셋하지 않는다.** 이 서버엔 gitea 자격증명이 없어 fetch 가 죽는데,
|
||||
# 그 상태의 origin/$BRANCH 는 마지막으로 fetch 된 낡은 ref 다.
|
||||
# 실측(2026-09-01 킹서버): HEAD=9b4fe40 인데 origin/main=4871e50 — 믿고 리셋하면 한 커밋
|
||||
# 롤백된다. 그러고도 빌드는 성공하고 컨테이너는 뜬다. 조용히 틀리는 종류다.
|
||||
#
|
||||
# ★ git clean 은 하지 않는다. .env 와 nginx/site.conf 는 추적되지 않는 파일이고 서버마다
|
||||
# 다르다 — reset --hard 는 이 둘을 건드리지 않지만 clean 은 지운다.
|
||||
if [ "$PULL" = 1 ]; then
|
||||
echo "▶ git fetch origin $BRANCH"
|
||||
if git fetch --prune origin "$BRANCH" 2>&1; then
|
||||
DIRTY=$(git status --porcelain)
|
||||
if [ -n "$DIRTY" ]; then
|
||||
echo " ! 작업트리 변경을 버린다:"
|
||||
sed 's/^/ /' <<<"$DIRTY"
|
||||
fi
|
||||
echo "▶ git reset --hard origin/$BRANCH"
|
||||
git reset --hard "origin/$BRANCH"
|
||||
else
|
||||
echo " ! fetch 실패 — 리셋을 건너뛰고 디스크에 있는 코드 그대로 간다." >&2
|
||||
echo " origin/$BRANCH 가 낡았을 수 있어 그걸로 리셋하면 배포가 조용히 롤백된다." >&2
|
||||
echo " (밖에서 밀어넣었으면 이대로 두면 되고, 자동화하려면 gitea 배포키를 건다)" >&2
|
||||
fi
|
||||
fi
|
||||
echo "▶ 지금 코드: $(git log --oneline -1)"
|
||||
|
||||
# ── 대상 정하기 ─────────────────────────────────────────────────────
|
||||
if [ ${#TARGETS[@]} -eq 0 ]; then
|
||||
SVCS=() # 빈 인자 = compose 가 전부로 해석한다
|
||||
echo "▶ 대상: 전체"
|
||||
else
|
||||
SVCS=("${TARGETS[@]}")
|
||||
# 백엔드 하나를 건드리면 같은 이미지를 쓰는 형제도 함께 갈아끼운다.
|
||||
if [ "$ONLY" = 0 ]; then
|
||||
for t in "${TARGETS[@]}"; do
|
||||
for b in "${BACKEND_SVCS[@]}"; do [ "$t" = "$b" ] || continue
|
||||
for sib in "${BACKEND_SVCS[@]}"; do
|
||||
printf '%s\n' "${SVCS[@]}" | grep -qx "$sib" || {
|
||||
SVCS+=("$sib")
|
||||
echo " + $sib — 같은 이미지를 쓴다(옛 코드로 남지 않게 함께 간다)"
|
||||
}
|
||||
done
|
||||
done
|
||||
done
|
||||
fi
|
||||
echo "▶ 대상: ${SVCS[*]}"
|
||||
fi
|
||||
|
||||
# ── 빌드 · 교체 ─────────────────────────────────────────────────────
|
||||
# build 절이 없는 서비스(node:24-alpine · nginx:alpine)는 build 가 조용히 건너뛴다.
|
||||
echo "▶ build"
|
||||
docker compose build ${SVCS+"${SVCS[@]}"}
|
||||
|
||||
echo "▶ up -d"
|
||||
docker compose up -d --force-recreate ${SVCS+"${SVCS[@]}"}
|
||||
|
||||
echo
|
||||
docker compose ps
|
||||
echo
|
||||
echo "로그: ./log.sh"
|
||||
+103
-34
@@ -5,15 +5,15 @@ name: o2o-web4ai
|
||||
# DB 는 compose 밖이다(호스트 PostgreSQL).
|
||||
# ★ 컨테이너 이름이 negosium-db 인 건 베낀 흔적이 아니다 — web4ai 는 DB 인스턴스를 따로 띄우지
|
||||
# 않고, negosium 이 쓰는 postgres(5432) 안에 web4ai_db 라는 database 만 새로 만들어 쓴다
|
||||
# (DECISIONS.md 3절). 그래서 아래 명령의 컨테이너 이름이 negosium-db 다.
|
||||
# 최초 1회:
|
||||
# docker exec -i -e PGPASSWORD=password negosium-db \
|
||||
# (DECISIONS.md 3절). 그래서 아래 명령의 컨테이너 이름이 우리 것이 아니다.
|
||||
# 최초 1회 — 컨테이너 이름은 환경마다 다르다(로컬 negosium-db · 킹서버 king_postgres_container):
|
||||
# docker exec -i -e PGPASSWORD=password <postgres 컨테이너> \
|
||||
# psql -h 127.0.0.1 -U postgres -d postgres -v ON_ERROR_STOP=1 < postgres-init/init-data/init.sql
|
||||
|
||||
x-common-env: &common-env
|
||||
APP_ENV: local
|
||||
PYTHONUNBUFFERED: "1"
|
||||
# 이미지 안 config.local.toml 은 플레이스홀더다 — 아래 값이 없으면 접속·서명이 실패한다.
|
||||
# 설정 파일은 없다 — 값은 전부 여기(=최상위 .env)서 온다. 비우면 config_models 의 기본값이다.
|
||||
DB_HOST: ${DB_HOST:-host.docker.internal}
|
||||
DB_PORT: ${DB_PORT:-5432}
|
||||
DB_USER: ${DB_USER:-postgres}
|
||||
@@ -21,6 +21,9 @@ x-common-env: &common-env
|
||||
DB_NAME: ${DB_NAME:-web4ai_db}
|
||||
JWT_ACCESS_SECRET: ${JWT_ACCESS_SECRET:-}
|
||||
JWT_REFRESH_SECRET: ${JWT_REFRESH_SECRET:-}
|
||||
# ★ 프론트(VITE_GOOGLE_CLIENT_ID)와 같은 값이어야 한다 — 백엔드는 이 값으로 구글 토큰의
|
||||
# 수신자(aud)를 대조한다. 어긋나면 버튼은 뜨는데 로그인만 계속 거부된다.
|
||||
GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}
|
||||
# ★ 프론트(VITE_PUBLISH_HOST)와 같은 값이어야 한다. canonical·og:url·sitemap 이 전부 이걸 쓴다.
|
||||
SITE_PUBLIC_HOST: ${SITE_PUBLIC_HOST:-w4ai.o2o.kr}
|
||||
SITE_PAYLOAD_DIR: /app/out/payloads
|
||||
@@ -29,12 +32,12 @@ x-common-env: &common-env
|
||||
INDEXNOW_KEY: ${INDEXNOW_KEY:-}
|
||||
|
||||
services:
|
||||
api:
|
||||
solution-backend:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: solution/backend/Dockerfile
|
||||
image: o2o-web4ai-backend
|
||||
container_name: o2o-web4ai-api
|
||||
container_name: o2o-web4ai-solution-backend
|
||||
command: ["python", "web_main.py"]
|
||||
env_file:
|
||||
- .env
|
||||
@@ -45,7 +48,7 @@ services:
|
||||
volumes:
|
||||
- ./solution/site/payloads:/app/out/payloads
|
||||
ports:
|
||||
- "${API_BIND:-0.0.0.0}:9800:9800"
|
||||
- "${API_BIND:-0.0.0.0}:${API_PORT:-9800}:9800"
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
restart: unless-stopped
|
||||
@@ -53,11 +56,12 @@ services:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
worker:
|
||||
solution-worker:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: solution/backend/Dockerfile
|
||||
image: o2o-web4ai-backend
|
||||
container_name: o2o-web4ai-solution-worker
|
||||
command: ["python", "worker_main.py"]
|
||||
env_file:
|
||||
- .env
|
||||
@@ -77,18 +81,21 @@ services:
|
||||
- "host.docker.internal:host-gateway"
|
||||
stop_grace_period: 300s
|
||||
depends_on:
|
||||
- api
|
||||
- solution-backend
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# 내부 운영 API(:9801). 진입점은 admin/backend/{main,app}.py 이고 도메인 코드는
|
||||
# 어드민 API(:9801). 진입점은 admin/backend/{main,app}.py 이고 도메인 코드는
|
||||
# solution/backend 것을 PYTHONPATH 로 그대로 쓴다 — place·fact 를 두 번 구현하지 않으면서
|
||||
# 프로세스와 포트만 가른다. 여기 붙는 모든 엔드포인트는 role >= DEVELOPER 다.
|
||||
api-admin:
|
||||
admin-backend:
|
||||
image: o2o-web4ai-backend
|
||||
container_name: o2o-web4ai-api-admin
|
||||
container_name: o2o-web4ai-admin-backend
|
||||
# ★ 기본으로 뜨지 않는다. 어드민 화면을 안 쓰는 동안은 이 API 도 부를 사람이 없다.
|
||||
# 켤 때: docker compose --profile admin up -d
|
||||
profiles: ["admin"]
|
||||
working_dir: /app/admin/backend
|
||||
command: ["python", "main.py"]
|
||||
env_file:
|
||||
@@ -109,20 +116,24 @@ services:
|
||||
- ./solution/site/payloads:/app/out/payloads
|
||||
ports:
|
||||
# ★ 내부망에만 연다. 0.0.0.0 으로 열면 API 를 가른 의미가 없다.
|
||||
- "${ADMIN_API_BIND:-127.0.0.1}:9801:9801"
|
||||
- "${ADMIN_API_BIND:-127.0.0.1}:${ADMIN_API_PORT_PUBLIC:-9801}:9801"
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
depends_on:
|
||||
- api
|
||||
- solution-backend
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# 사장님 앱(:3000) + 발행 사이트 프리렌더·정적서버(:3001, `/s/*` 프록시)
|
||||
web:
|
||||
# 발행 사이트를 굽는다. **굽기만 한다** — 서빙은 solution-site(nginx)가 맡는다.
|
||||
#
|
||||
# ★ 사장님 앱 dev 서버는 여기서 빠졌다. 운영에 `vite dev` 를 띄우면 요청마다 트랜스파일하고
|
||||
# 기동이 npm install 네트워크에 의존하고 /src 원본이 그대로 나간다. 번들은 solution-site
|
||||
# 이미지가 굽는다(nginx/Dockerfile). 로컬에서 HMR 이 필요하면 `--profile dev`.
|
||||
solution-prerender:
|
||||
image: node:24-alpine
|
||||
container_name: o2o-web4ai-web
|
||||
container_name: o2o-web4ai-solution-prerender
|
||||
working_dir: /app
|
||||
command:
|
||||
- sh
|
||||
@@ -132,11 +143,8 @@ services:
|
||||
# ★ `-d node_modules` 로 판단하면 안 된다. 익명 볼륨은 빈 디렉토리로 이미 존재해서
|
||||
# 설치를 건너뛰고 `vite: not found`(exit 127)로 죽는다.
|
||||
[ -x node_modules/.bin/vite ] || npm install
|
||||
node solution/site/scripts/serve-sites.mjs &
|
||||
node solution/site/scripts/watch-payloads.mjs &
|
||||
exec npm run dev -w @o2o/frontend
|
||||
exec node solution/site/scripts/watch-payloads.mjs
|
||||
environment:
|
||||
PORT: 3001
|
||||
INDEXNOW_KEY: ${INDEXNOW_KEY:-}
|
||||
# ★ 발행 호스트를 프론트 .env 에 따로 적지 않는다 — 루트 .env 의 SITE_PUBLIC_HOST 를
|
||||
# 그대로 흘려보낸다. 두 곳에 적으면 canonical 과 화면 주소가 조용히 갈라진다.
|
||||
@@ -155,17 +163,61 @@ services:
|
||||
- /app/admin/frontend/node_modules
|
||||
# ★ 산출물은 named volume. 호스트 경로면 재배포로 코드를 갈아엎는 순간 전 사이트가 404 다.
|
||||
- site-out:/app/solution/site/out
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# 사장님 앱 dev 서버 + 발행본 정적서버(:3001). **로컬 전용**이다 — `--profile dev`.
|
||||
# 운영에서 이게 뜨면 안 된다(위 solution-prerender 주석).
|
||||
solution-frontend:
|
||||
image: node:24-alpine
|
||||
container_name: o2o-web4ai-solution-frontend
|
||||
profiles: ["dev"]
|
||||
working_dir: /app
|
||||
command:
|
||||
- sh
|
||||
- -c
|
||||
- |
|
||||
cd /app
|
||||
[ -x node_modules/.bin/vite ] || npm install
|
||||
node solution/site/scripts/serve-sites.mjs &
|
||||
exec npm run dev -w @o2o/frontend
|
||||
environment:
|
||||
PORT: 3001
|
||||
INDEXNOW_KEY: ${INDEXNOW_KEY:-}
|
||||
VITE_PUBLISH_HOST: ${SITE_PUBLIC_HOST:-w4ai.o2o.kr}
|
||||
# ★ 이 둘은 **브라우저가** 부르는 주소다. 컨테이너 안에서 보는 주소가 아니라
|
||||
# 화면을 연 사람이 닿을 수 있는 주소여야 한다 — localhost 는 서버에 올리는 순간 틀린다.
|
||||
VITE_API_BASE_URL: ${PUBLIC_API_BASE_URL:-http://localhost:9800}
|
||||
VITE_SITE_PREVIEW_URL: ${PUBLIC_WEB_BASE_URL:-http://localhost:3000}
|
||||
VITE_AUTO_LOGIN_ID: ${AUTO_LOGIN_ID:-}
|
||||
VITE_AUTO_LOGIN_PW: ${AUTO_LOGIN_PW:-}
|
||||
# 백엔드와 같은 값을 흘려보낸다(루트 .env 가 단일 출처).
|
||||
VITE_GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}
|
||||
volumes:
|
||||
- ./package.json:/app/package.json
|
||||
- ./package-lock.json:/app/package-lock.json
|
||||
- ./tsconfig.base.json:/app/tsconfig.base.json
|
||||
- ./solution:/app/solution
|
||||
- ./admin:/app/admin
|
||||
- /app/node_modules
|
||||
- /app/solution/site/node_modules
|
||||
- /app/solution/frontend/node_modules
|
||||
- /app/admin/frontend/node_modules
|
||||
- site-out:/app/solution/site/out
|
||||
ports:
|
||||
- "3000:3000"
|
||||
- "${WEB_BIND:-0.0.0.0}:${WEB_PORT:-3000}:3000"
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# 내부 운영 앱(:3002). 사장님 번들과 갈라 두는 것이 이 서비스의 존재 이유다.
|
||||
admin:
|
||||
admin-frontend:
|
||||
image: node:24-alpine
|
||||
container_name: o2o-web4ai-admin
|
||||
container_name: o2o-web4ai-admin-frontend
|
||||
profiles: ["admin"]
|
||||
working_dir: /app
|
||||
command:
|
||||
- sh
|
||||
@@ -175,8 +227,11 @@ services:
|
||||
[ -x node_modules/.bin/vite ] || npm install
|
||||
exec npm run dev -w @o2o/admin
|
||||
environment:
|
||||
# ★ 내부 API(:9801)를 본다. :9800 을 보면 API 를 가른 의미가 없다.
|
||||
# ★ 어드민 API(:9801)를 본다. :9800 을 보면 API 를 가른 의미가 없다.
|
||||
VITE_API_BASE_URL: ${ADMIN_API_BASE_URL:-http://localhost:9801}
|
||||
# 사장님 앱은 다른 오리진이라 절대 URL 로 연다(admin/frontend/src/lib/solutionUrl.ts).
|
||||
# 이걸 안 넘기면 "빌더 열기" 가 서버에서 localhost:3000 을 가리켜 죽은 링크가 된다.
|
||||
VITE_SOLUTION_URL: ${PUBLIC_WEB_BASE_URL:-http://localhost:3000}
|
||||
volumes:
|
||||
- ./package.json:/app/package.json
|
||||
- ./package-lock.json:/app/package-lock.json
|
||||
@@ -189,27 +244,41 @@ services:
|
||||
- /app/admin/frontend/node_modules
|
||||
ports:
|
||||
# ★ 운영에서는 내부망에만 연다. 0.0.0.0 으로 열면 앱을 가른 의미가 없다.
|
||||
- "${ADMIN_BIND:-127.0.0.1}:3002:3002"
|
||||
depends_on:
|
||||
- web
|
||||
- "${ADMIN_BIND:-127.0.0.1}:${ADMIN_PORT:-3002}:3002"
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options: { max-size: "10m", max-file: "5" }
|
||||
|
||||
# 발행 사이트 정적 서빙. 굽는 쪽(web)과 분리 — 볼륨 하나를 사이에 두고 서로를 모른다.
|
||||
nginx:
|
||||
image: nginx:alpine
|
||||
container_name: o2o-web4ai-nginx
|
||||
# 공개 진입점 하나. 사장님 앱(구운 번들) · 발행 사이트(볼륨) · API 프록시를 한 오리진으로 준다.
|
||||
solution-site:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: nginx/Dockerfile
|
||||
args:
|
||||
# ★ VITE_* 는 **번들에 구워진다.** .env 를 고쳐도 재빌드 전엔 안 바뀐다
|
||||
# → 주소를 바꿨으면 `./deploy.sh solution-site`.
|
||||
VITE_API_BASE_URL: ${PUBLIC_API_BASE_URL:-http://localhost:9800}
|
||||
VITE_PUBLISH_HOST: ${SITE_PUBLIC_HOST:-w4ai.o2o.kr}
|
||||
VITE_SITE_PREVIEW_URL: ${PUBLIC_WEB_BASE_URL:-http://localhost:3000}
|
||||
# ⚠️ 비어 있으면 자동 로그인은 아예 꺼진다(기본값 없음). 채우면 번들에 구워진다.
|
||||
VITE_AUTO_LOGIN_ID: ${AUTO_LOGIN_ID:-}
|
||||
VITE_AUTO_LOGIN_PW: ${AUTO_LOGIN_PW:-}
|
||||
# 비어 있으면 구글 로그인 버튼이 안 뜬다. 백엔드 GOOGLE_CLIENT_ID 와 같은 값이다.
|
||||
VITE_GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}
|
||||
image: o2o-web4ai-solution-site
|
||||
container_name: o2o-web4ai-solution-site
|
||||
volumes:
|
||||
- site-out:/srv/sites:ro
|
||||
# ★ 클론 직후: cp nginx/site.conf.example nginx/site.conf
|
||||
# 파일이 없으면 Docker 가 그 자리에 디렉토리를 만들어 nginx 가 설정 없이 뜬다.
|
||||
- ./nginx/site.conf:/etc/nginx/conf.d/default.conf:ro
|
||||
ports:
|
||||
- "80:80"
|
||||
# ★ :80 이 비어 있다는 보장이 없다(킹서버는 호스트 nginx 가 물고 있다).
|
||||
# 앞단 프록시를 세울 거면 여기서 포트만 옮기고 프록시가 이쪽을 가리키게 한다.
|
||||
- "${SITE_HTTP_BIND:-0.0.0.0}:${SITE_HTTP_PORT:-80}:80"
|
||||
depends_on:
|
||||
- web
|
||||
- solution-prerender
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
|
||||
+18
-11
@@ -35,7 +35,7 @@ BUILD 잡 (worker) ─ services/build_service.py:99 run_build()
|
||||
├ 1차 게이트 (DB 사실 기준) → publish_gate.evaluate()
|
||||
├ site_payload.emit_payload() → out/payloads/<slug>.json ★ 백엔드의 유일한 산출물
|
||||
│
|
||||
│ ┌ [별도 컨테이너 o2o-web4ai-web]
|
||||
│ ┌ [별도 컨테이너 o2o-web4ai-solution-frontend]
|
||||
│ │ scripts/watch-payloads.mjs — payloads/ 2초 폴링, 바뀐 것만
|
||||
│ │ └ node dist/prerender/prerender.js --payload=<file>
|
||||
│ │ → out/s/<slug>/** + out/assets, out/fonts, out/robots.txt …
|
||||
@@ -45,9 +45,16 @@ BUILD 잡 (worker) ─ services/build_service.py:99 run_build()
|
||||
├ render_report.wait_for() → .status/<slug>.json 폴링
|
||||
├ 2차 게이트 (**실제 구워진 HTML** 기준: JSON-LD 불일치 · 고유 콘텐츠 수)
|
||||
├ azure_static.publish(slug) → Azure Blob `$web` (설정됐을 때만 — 3절)
|
||||
├ site_thumbnail.store(slug, …) → Blob `<prefix>/thumbs/<slug>.<ext>` → sites.thumbnail_url
|
||||
└ indexnow.submit(slug) → 네이버·Bing·Yandex 통보 (구글 미지원)
|
||||
```
|
||||
|
||||
썸네일은 **스크린샷이 아니라 그 사이트의 대표 사진(og:image)** 이다 — 헤드리스 브라우저는
|
||||
영구 금지고([DECISIONS 1-1](DECISIONS.md)) 워커·프리렌더 이미지에 Chromium 이 없다.
|
||||
대표 사진 선정은 `site_payload.primary_media()` 한 곳뿐이라 og:image 와 항상 같은 사진이다.
|
||||
★ 블롭 경로가 `s/<slug>/` **밖**인 이유: `azure_static._remove_stale_site_files()` 가 매 발행마다
|
||||
사이트 경로를 프리렌더 산출물로 통째로 교체한다 — 그 안에 두면 다음 발행에서 조용히 사라진다.
|
||||
|
||||
게이트가 **두 번** 도는 게 핵심이다. 1차는 DB 의 사실을, 2차는 **정말로 그렇게 구워졌는지**를 본다.
|
||||
1차만 있으면 "데이터는 맞는데 HTML 은 틀린" 상태를 발행한다.
|
||||
|
||||
@@ -59,7 +66,7 @@ Azure Blob 업로드 경로(`azure_static.py`)는 코드에 있고 동작하지
|
||||
클라우드는 고도화 시점에 붙인다.
|
||||
|
||||
```
|
||||
프리렌더(o2o-web4ai-web) ──쓴다──▶ named volume `site-out` ◀──읽는다(ro)── nginx(:80)
|
||||
프리렌더(o2o-web4ai-solution-frontend) ──쓴다──▶ named volume `site-out` ◀──읽는다(ro)── nginx(:80)
|
||||
```
|
||||
|
||||
굽는 쪽과 서빙하는 쪽이 **볼륨 하나를 사이에 두고 서로를 모른다.** 그래서 재배포로 코드를
|
||||
@@ -106,7 +113,7 @@ o2o-web4ai/
|
||||
│ └─ shared/ frontend·site·백엔드 계약 (SitePayload · slug · 토큰)
|
||||
│
|
||||
├─ admin/ 우리 — 전체 사이트 운영
|
||||
│ ├─ backend/ 내부 API 진입점(:9801). 도메인 코드는 solution/backend
|
||||
│ ├─ backend/ 어드민 API 진입점(:9801). 도메인 코드는 solution/backend
|
||||
│ └─ frontend/ 내부 운영 화면
|
||||
│
|
||||
├─ docs/ nginx/ postgres-init/ docker-compose.yml package.json(워크스페이스 루트)
|
||||
@@ -147,8 +154,8 @@ negosium 대응: `negodata/{backend, front}` 가 프로젝트 안에서 f/b 를
|
||||
|
||||
| | 포트 | 진입점 | 권한 |
|
||||
|---|---|---|---|
|
||||
| 사장님 API | 9800 | `solution/backend/web_main.py` | 엔드포인트별 |
|
||||
| 내부 API | **9801** | `admin/backend/main.py` → `app.py` | **앱 전체 `role >= DEVELOPER`** |
|
||||
| 솔루션 API | 9800 | `solution/backend/web_main.py` | 엔드포인트별 |
|
||||
| 어드민 API | **9801** | `admin/backend/main.py` → `app.py` | **앱 전체 `role >= DEVELOPER`** |
|
||||
|
||||
`services`·`crud`·`models` 은 공유한다 — `admin/backend` 는 진입점 두 파일뿐이고,
|
||||
도메인 코드는 `PYTHONPATH=/app/solution/backend` 로 그대로 import 한다. admin 화면이 부르는
|
||||
@@ -276,12 +283,12 @@ DB 에 HTML 컬럼은 없다 (`site_versions.snapshot` JSONB 가 원본).
|
||||
|
||||
| 컨테이너 | 무엇 | 포트 |
|
||||
|---|---|---|
|
||||
| `o2o-web4ai-api` | 사장님 API (`solution/backend/web_main.py`) | 9800 |
|
||||
| `o2o-web4ai-api-admin` | 내부 API (`admin/backend/main.py`) — 앱 전체 `role >= DEVELOPER` | 9801 (기본 `127.0.0.1`) |
|
||||
| `o2o-web4ai-worker` | 잡 러너 (BUILD·수집·생성) + 스케줄러 | — |
|
||||
| `o2o-web4ai-web` | 사장님 빌더 Vite + `watch-payloads` 프리렌더 + `serve-sites`(개발용 :3001) | 3000 |
|
||||
| `o2o-web4ai-admin` | 내부 운영 화면 Vite | 3002 (기본 `127.0.0.1`) |
|
||||
| `o2o-web4ai-nginx` | **발행 사이트 정적 서빙** — `site-out` 볼륨을 읽기 전용으로 | 80 |
|
||||
| `o2o-web4ai-solution-backend` | 솔루션 API (`solution/backend/web_main.py`) | 9800 |
|
||||
| `o2o-web4ai-admin-frontend-backend` | 어드민 API (`admin/backend/main.py`) — 앱 전체 `role >= DEVELOPER` | 9801 (기본 `127.0.0.1`) |
|
||||
| `o2o-web4ai-solution-worker` | 잡 러너 (BUILD·수집·생성) + 스케줄러 | — |
|
||||
| `o2o-web4ai-solution-frontend` | 사장님 빌더 Vite + `watch-payloads` 프리렌더 + `serve-sites`(개발용 :3001) | 3000 |
|
||||
| `o2o-web4ai-admin-frontend` | 내부 운영 화면 Vite | 3002 (기본 `127.0.0.1`) |
|
||||
| `o2o-web4ai-solution-site` | **발행 사이트 정적 서빙** — `site-out` 볼륨을 읽기 전용으로 | 80 |
|
||||
|
||||
DB(PostgreSQL)는 **compose 밖**이다 — 호스트에서 돌고 `host.docker.internal` 로 붙는다.
|
||||
데이터 수명이 컨테이너 수명과 달라야 해서다.
|
||||
+13
-2
@@ -15,7 +15,7 @@
|
||||
|---|---|---|
|
||||
| 야놀자 · 여기어때 | **불가** | 풀 브라우저 헤더로도 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 차단 |
|
||||
| 카카오맵 | **불가** | 상세는 SPA 셸(3.6KB), 어드민 API 406 차단 |
|
||||
| **사장님이 확정한 자체 홈페이지** | **가능** | 사장님 동의 기반. → `StaticHtmlAdapter` 등록(2026-08-28) |
|
||||
|
||||
**추가 결론 (2026-08-31)** — TourAPI 어댑터를 붙여 같은 표본으로 대조한 결과
|
||||
@@ -65,6 +65,17 @@
|
||||
| 코드 격리 | `site` 에 발행 상태를 두고, 해지 처리는 **삭제가 아니라 상태 전이**로만 구현한다. 물리 삭제 경로를 만들지 않는다 |
|
||||
| 반영됨 (2026-08-26) | `SiteStatus.SUSPENDED`(해지 유예 — 페이지 살아 있음) / `UNPUBLISHED`(내림)를 분리했다. `PublishAction.SUSPEND`·`RESUME` 으로 `publish_logs` 에 남는다. 유예 기간 길이만 정하면 된다 |
|
||||
|
||||
### 1-5. 계정 연결 — 같은 사람의 id/pw 계정과 구글 계정을 이을 것인가
|
||||
|
||||
| 항목 | 내용 |
|
||||
|---|---|
|
||||
| 상태 | **미결** (2026-09-02 구글 로그인 붙이면서 생김) |
|
||||
| 필요한 결론 | 이미 id/pw 로 가입한 사람이 같은 이메일의 구글로 로그인했을 때, 같은 계정으로 이을 것인가. 이으려면 **먼저 가입한 쪽의 소유 증명**(비밀번호 재입력 또는 이메일 인증)을 어디에 둘 것인가 |
|
||||
| 왜 지금 안 푸나 | 이메일만 보고 자동으로 이으면 **계정 선점**이 된다 — 공격자가 남의 이메일로 id/pw 계정을 먼저 만들어 두면, 그 사람이 구글로 로그인하는 순간 공격자가 비밀번호를 아는 계정 안으로 들어간다. 소유 증명 절차 없이 열 수 있는 문이 아니다 |
|
||||
| 코드 격리 | `company.users.provider`(AuthProvider) 로 계정마다 수단을 하나만 둔다. 이메일이 이미 쓰이고 있으면 **잇지도 만들지도 않고** `ACCOUNT_PROVIDER_CONFLICT` 로 거절하고, 화면은 "처음 가입할 때 쓴 방법으로 로그인" 을 안내한다. 반대 방향(구글 계정에 비밀번호 설정)도 `update_me` 에서 같은 코드로 막는다 |
|
||||
| 결론이 "잇는다" 일 때 | `provider`·`provider_uid` 를 users 에서 별도 테이블(`user_identities`)로 빼고, 계정 하나에 수단 여러 개를 매단다. 지금 구조가 그 이행을 막지 않는다 |
|
||||
| 확정 사항 | **구글 ID 토큰의 `aud`(우리 client_id)와 `email_verified` 검증은 결론과 무관하게 필수다.** `tests/test_google_identity.py` 가 이 둘을 고정한다 |
|
||||
|
||||
---
|
||||
|
||||
## 2. 이식하면서 내린 결정 (2026-08-26)
|
||||
@@ -115,7 +126,7 @@
|
||||
| 테이블명 | 복수형 (`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 를 때리고 요금이 나간다 |
|
||||
| 설정 주입 | 레포 최상위 `.env` + `pydantic-settings` | FastAPI 공식 방식(BaseSettings + env_file). 우선순위 = 실제 환경변수 > `.env` > 코드 기본값. toml 층은 없앴다(2026-09-01) — 키를 손으로 나열하다 `client_url` 이 빠져 배포 주소의 CORS 가 막혔다. **`APP_ENV=test` 면 `.env` 를 읽지 않는다** |
|
||||
| 키 출처 | Perplexity·Gemini 는 `o2o-infinith-backend/.env` 값 재사용. **TourAPI 는 2026-08-31 활용신청 승인**, 카카오는 여전히 **미발급** | 카카오 키가 없으면 `kakao` 어댑터만 비활성이고 주변 정보 블록이 비어 뜬다 |
|
||||
|
||||
### 아직 테이블이 없는 것
|
||||
|
||||
+48
-11
@@ -77,9 +77,9 @@ site-out/
|
||||
**규칙: `solution/site` 를 배포하면 반드시 전체 재굽기 + 전체 재업로드.**
|
||||
|
||||
```bash
|
||||
docker compose restart web # 기동하며 전체 재굽기
|
||||
docker compose logs -f web # "[watch] 기동" 배치가 끝날 때까지 대기
|
||||
docker compose exec worker python scripts/republish_all.py
|
||||
docker compose restart solution-frontend # 기동하며 전체 재굽기
|
||||
docker compose logs -f solution-frontend # "[watch] 기동" 배치가 끝날 때까지 대기
|
||||
docker compose exec solution-worker python scripts/republish_all.py
|
||||
```
|
||||
|
||||
## 3. 서버에 올리는 순서 (지금 밟는 경로)
|
||||
@@ -104,14 +104,28 @@ docker compose exec worker python scripts/republish_all.py
|
||||
프리렌더만 다시 돌리면 옛 주소가 그대로 나온다. 반드시 **백엔드에서 재발행**해 payload 를
|
||||
다시 만들어야 한다.
|
||||
|
||||
### 0단계-b — 구글 로그인도 주소가 정해져야 켜진다
|
||||
|
||||
`GOOGLE_CLIENT_ID` 하나를 루트 `.env` 에 적으면 compose 가 백엔드와 프론트
|
||||
(`VITE_GOOGLE_CLIENT_ID`) 양쪽에 흘려보낸다. **두 곳에 따로 적지 않는다.**
|
||||
|
||||
- Google Cloud Console > 사용자 인증 정보 > **OAuth 2.0 클라이언트 ID(웹 애플리케이션)**
|
||||
- **승인된 JavaScript 원본**에 화면을 여는 주소를 그대로 넣는다(포트까지). 리디렉션 URI 는
|
||||
쓰지 않는다 — 브라우저가 ID 토큰을 바로 받는 방식(GIS)이다.
|
||||
- 주소가 바뀌면 원본 목록도 같이 고친다. 안 고치면 **버튼은 뜨는데 눌러도 아무 일이 없다.**
|
||||
- 비워 두면 구글 로그인만 꺼진다(버튼 자체가 안 뜬다). id/pw 로그인·가입은 그대로 된다.
|
||||
|
||||
★ `VITE_*` 라서 **번들에 구워진다** — 값을 넣거나 바꾸면 `./deploy.sh solution-site` 로 다시 굽는다.
|
||||
|
||||
### 1단계 — 서버에서 "굽기"만 재현 (Azure 끔)
|
||||
배포 대상 서버(접속·경로·이미 물린 포트)는 [SERVERS.md](SERVERS.md) 가 단일 출처다.
|
||||
```bash
|
||||
# 서버에서
|
||||
cp .env.example .env # DB_*, JWT_*, 외부 API 키 채우기
|
||||
# AZURE_STORAGE_CONNECTION_STRING 은 비워 둔다 ← 이번 단계에서는 안 올린다
|
||||
# INDEXNOW_KEY 도 비워 둔다 ← 없는 주소를 색인 통보하지 않는다
|
||||
docker compose up -d
|
||||
docker compose logs -f worker
|
||||
docker compose logs -f solution-worker
|
||||
```
|
||||
확인: 사이트 1개 발행 → `curl -I http://<서버>:3000/s/<slug>` 200 ·
|
||||
`out/s/<slug>/index.html` 생성 · `out/payloads/.status/<slug>.json` 의 `ok: true`.
|
||||
@@ -119,7 +133,7 @@ docker compose logs -f worker
|
||||
여기서 막히면 Azure 문제가 아니다. **DB 연결 / payload 디렉토리 마운트 / node_modules** 셋 중 하나다.
|
||||
|
||||
### 2단계 — 정적 서빙을 nginx 로 교체 (구현됨)
|
||||
`serve-sites.mjs` 는 개발용이다. 운영은 `o2o-web4ai-nginx` 컨테이너가 맡는다(`nginx/site.conf`).
|
||||
`serve-sites.mjs` 는 개발용이다. 운영은 `o2o-web4ai-solution-site` 컨테이너가 맡는다(`nginx/site.conf`).
|
||||
|
||||
★ **산출물은 named volume `site-out` 에 있다.** 프리렌더가 쓰고 nginx·워커가 읽는다.
|
||||
호스트 경로가 등장하지 않으므로 재배포로 코드를 갈아엎어도 사이트가 죽지 않는다.
|
||||
@@ -127,7 +141,7 @@ docker compose logs -f worker
|
||||
|
||||
```bash
|
||||
docker compose up -d # nginx 포함 전부
|
||||
docker compose exec nginx ls /usr/share/nginx/html/s # 들여다볼 때
|
||||
docker compose exec solution-site ls /usr/share/nginx/html/s # 들여다볼 때
|
||||
```
|
||||
|
||||
확인은 스크립트가 한다. 색인을 기다리지 않고 **지금 볼 수 있는 것만** 본다 —
|
||||
@@ -136,7 +150,7 @@ docker compose exec nginx ls /usr/share/nginx/html/s # 들여다볼 때
|
||||
브라우저로는 절대 안 보인다).
|
||||
|
||||
```bash
|
||||
docker compose exec worker python scripts/check_search_ready.py https://<도메인>
|
||||
docker compose exec solution-worker python scripts/check_search_ready.py https://<도메인>
|
||||
```
|
||||
|
||||
`/s/<slug>` (끝 슬래시 없음)이 열리는지도 이 스크립트가 본다 — 사장님이 주소창에 치는 형태가 그거다.
|
||||
@@ -145,6 +159,29 @@ docker compose exec worker python scripts/check_search_ready.py https://<도메
|
||||
`nginx/site.conf` 에 443 과 인증서 볼륨을 추가한다. Blob 단독으로는 커스텀 도메인 TLS 가
|
||||
안 되지만 nginx 는 Let's Encrypt 로 끝난다 — CDN 을 억지로 끼울 이유가 없다.
|
||||
|
||||
### 2-2단계 — 검색엔진 소유확인
|
||||
|
||||
★ **오리진이 하나라 루트에서 한 번만 하면 `/s/<slug>` 전부가 딸려온다.** 사장님이 늘어도
|
||||
반복하지 않는다 — 오리진을 안 가른 이유가 이거다.
|
||||
|
||||
| | 방식 | 어디에 사는가 |
|
||||
|---|---|---|
|
||||
| 구글 Search Console | DNS TXT (도메인 속성) | DNS. **이 레포 밖이고 재배포와 무관하다** |
|
||||
| Bing Webmaster | `BingSiteAuth.xml` | `solution/frontend/public/` → 이미지에 구워진다 |
|
||||
| 네이버 서치어드바이저 | 메타태그 / HTML 파일 (**DNS TXT 를 안 받는다**) | 아직 안 붙였다 |
|
||||
|
||||
★ **파일 방식은 재배포가 필요하다.** `public/` 은 `solution-site` 이미지에 구워지므로
|
||||
`docker cp` 로 밀어 넣으면 컨테이너 재생성 때 사라진다 — 검색엔진은 인증을 주기적으로
|
||||
재확인하므로 그때 조용히 풀린다.
|
||||
|
||||
★ **확인은 상태코드가 아니라 내용으로 한다.** `location /` 이 `try_files $uri … /index.html`
|
||||
이라 파일명이 한 글자만 틀려도 404 가 아니라 **빌더 앱 HTML 이 200 으로** 나간다.
|
||||
검색엔진은 "확인 실패" 만 뱉고 이유를 안 알려준다.
|
||||
|
||||
```bash
|
||||
curl -s https://<도메인>/BingSiteAuth.xml # HTML 이 나오면 파일이 없는 것이다
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 나중에 — Azure Blob 을 켤 때
|
||||
@@ -161,8 +198,8 @@ 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 # 전체 업로드
|
||||
docker compose exec solution-worker python scripts/republish_all.py --dry-run # 대상 확인
|
||||
docker compose exec solution-worker python scripts/republish_all.py # 전체 업로드
|
||||
```
|
||||
확인: `https://<account>.z*.web.core.windows.net/s/<slug>` 가 **CSS 까지 입혀서** 뜨는지.
|
||||
스타일이 없으면 접두사/경로 문제다(2절 참고).
|
||||
@@ -171,12 +208,12 @@ docker compose exec worker python scripts/republish_all.py # 전체
|
||||
1. DNS 를 Blob 정적 웹사이트(또는 앞단 CDN)로 연결
|
||||
2. HTTPS 확인 — 커스텀 도메인 + TLS 는 Blob 단독으로는 안 되고 CDN/Front Door 가 필요하다
|
||||
3. `SITE_PUBLIC_HOST` 가 실제 도메인과 같은지 재확인 → 다르면 고치고 **전체 재발행**
|
||||
4. 그 다음에야 `INDEXNOW_KEY` 를 채운다. 백엔드와 `o2o-web4ai-web` 이 **같은 값**이어야 한다
|
||||
4. 그 다음에야 `INDEXNOW_KEY` 를 채운다. 백엔드와 `o2o-web4ai-solution-frontend` 이 **같은 값**이어야 한다
|
||||
(프리렌더가 루트에 `<key>.txt` 를 굽고 검색엔진이 대조한다 — 어긋나면 403)
|
||||
5. `https://<도메인>/<key>.txt` 와 `https://<도메인>/robots.txt` 가 열리는지 확인
|
||||
6. 구글은 IndexNow 미지원 → Search Console 에 `https://<도메인>/sitemap.xml` 수동 제출
|
||||
|
||||
## 5. 되돌리기
|
||||
`out/` 은 재생성물이라 백업이 필요 없다. 문제가 생기면
|
||||
`docker compose restart web` → 전체 재굽기 → `republish_all.py`.
|
||||
`docker compose restart solution-frontend` → 전체 재굽기 → `republish_all.py`.
|
||||
지켜야 할 건 **DB 와 `out/payloads/`** 뿐이다.
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
# 개발 일지
|
||||
|
||||
무엇을 왜 바꿨는지 날짜순으로 남긴다. 새 항목을 **위에** 추가한다.
|
||||
결론과 배경은 각 문서가 단일 출처다 — 여기에는 요약과 링크만 둔다.
|
||||
|
||||
---
|
||||
|
||||
## 2026-09-03 — 상호명 검색을 로그인 앞으로 · 업종은 LLM 없이 정한다
|
||||
|
||||
**왜**
|
||||
랜딩 첫 화면에서 상호명을 치게 하려면 검색이 로그인 앞에 있어야 하는데,
|
||||
후보 조회는 `place_id` 와 토큰을 둘 다 요구했다(`place.py` 확정 경로). 로그인 관문을
|
||||
에디터 진입 하나로 되돌려 놓고도 API 는 그대로였다.
|
||||
그리고 업종은 사장님에게 고르게 하고 있었는데 — 경계(베이커리 카페, 브런치집)에서 멈춘다.
|
||||
|
||||
**한 일**
|
||||
- `GET /v1/place/search` 신설(인증 없음). 사업장을 만들지도, 우리 DB 를 읽지도 않는다.
|
||||
확정 경로(`/{place_id}/verify/candidates`)는 인증을 그대로 둔다 — 남의 place_id 존재
|
||||
여부까지 열 이유가 없다
|
||||
- `place_category.guess_category()`: 카카오 `category_group_code`(AD5·CE7·FD6) 우선,
|
||||
없으면 분류 문자열. **LLM 호출 0건** — 상호명 검색 응답에 이미 들어 있던 값이다
|
||||
- 못 정하면 `None`. 억지로 고르지 않는다 — 업종은 수집 스키마와 JSON-LD 타입을 통째로
|
||||
정해서 틀리면 되돌리는 비용이 크다. HP8(병원)은 피부과·성형외과일 때만 받는다
|
||||
- `rate_limit`: 인증 없이 유료 외부 API 를 부르는 경로라 IP 당 분당 20회.
|
||||
프로세스 메모리라 완전하지 않다(앞단 nginx 가 제대로 된 자리)
|
||||
|
||||
**검증** — 전체 562 passed. 공개 응답에 place_id·전화·좌표가 안 나가는 것,
|
||||
검색만으로 사업장이 생기지 않는 것을 테스트로 고정.
|
||||
|
||||
## 2026-09-03 — 발행하면 썸네일이 남는다 (랜딩 쇼케이스용)
|
||||
|
||||
**왜**
|
||||
랜딩에 "이렇게 만들어졌습니다" 를 보여줄 그림이 없었다. 사이트는 발행되는데 그 결과물을
|
||||
가리킬 이미지가 어디에도 저장되지 않아, 쇼케이스를 만들려면 매번 사람이 캡처를 떠야 했다.
|
||||
|
||||
**썸네일은 스크린샷이 아니라 그 사이트의 대표 사진이다**
|
||||
헤드리스 브라우저는 봇 탐지 우회 우려로 영구 금지고([DECISIONS 1-1](DECISIONS.md)),
|
||||
워커(python:3.12-slim)·프리렌더(node:24-alpine) 어디에도 Chromium 이 없다. 넣으면 이미지가
|
||||
수백 MB 늘고 금지해 둔 도구를 상비하게 된다. 대신 `og:image` 로 나가는 **대표 사진**을 그대로
|
||||
옮긴다 — 검색 결과에 뜨는 그림과 쇼케이스 카드가 같아진다. 대표 사진 선정 규칙은
|
||||
`site_payload.primary_media()` 한 곳뿐이라 두 곳이 갈릴 수 없다.
|
||||
|
||||
**한 일**
|
||||
- `services/site_thumbnail.py` 신설. 대표 사진을 httpx 로 받아(10초 상한 · 리다이렉트 3회 ·
|
||||
image/* 만 · 5MB 상한) `<prefix>/thumbs/<slug>.<ext>` 로 올린다. 기존
|
||||
`AZURE_STORAGE_CONNECTION_STRING` 을 그대로 쓴다 — 새 자격증명 체계를 들이지 않았다.
|
||||
★ 사이트 경로(`s/<slug>/`) 안에 두지 않는다: `azure_static._remove_stale_site_files()` 가
|
||||
매 발행마다 그 경로를 통째로 교체하므로 다음 발행에서 조용히 사라진다.
|
||||
- `build_service`: `azure_static.publish()` 직후 · IndexNow 통보 전에 저장하고,
|
||||
발행 상태 전이 UPDATE 에 `thumbnail_url` 을 실어 보낸다(UPDATE 는 그대로 한 번).
|
||||
실패해도 발행을 되돌리지 않는다 — 정적 파일은 이미 올라갔다(`emit_payload` 와 같은 원칙).
|
||||
못 만들면 키를 넣지 않아 지난 발행의 그림이 남는다.
|
||||
- `GET /v1/showcase` 신설(**인증 없음**, 랜딩이 부른다). 발행된 사이트만 최신순,
|
||||
기본 12건·상한 48건. 나가는 것은 상호명·업종·지역(시·군·구까지)·발행 주소·썸네일뿐이다 —
|
||||
place_id·company_id·전화번호·상세 주소는 싣지 않는다. 무엇을 내보낼지 고르는 자리를
|
||||
`services/showcase_service.py` 한 곳에 모아 경계를 눈에 보이게 뒀다.
|
||||
어드민 진입점(:9801)에는 마운트하지 않는다.
|
||||
|
||||
**곁가지로 고친 것 — 브랜치에 이미 깨져 있던 테스트 4건**
|
||||
- `conftest.fake_renderer` 가 늘 `ok=True` 를 돌려줬다. 진짜 렌더러는 고유 콘텐츠 0건이면
|
||||
페이지를 쓰지 않는데(prerender.ts `NoUniqueContentError`), 대역이 그 실패를 흉내내지 않아
|
||||
백엔드가 그 사유를 NO_UNIQUE_CONTENT 로 되짚는 경로가 통째로 안 돌고 있었다.
|
||||
- `test_snapshot` 이 "region_code 가 없으면 지역 정보 없음" 을 기대했다. 지금은 도로명주소에서
|
||||
유도한다(`snapshot._local_contents`) — 유도 동작에 테스트가 없었다. 둘로 갈라 채웠다.
|
||||
|
||||
**검증** — `pytest` 전체 552 passed.
|
||||
|
||||
## 2026-09-02 — 직접 쓴 소개문이 발행에서 사라지던 구멍
|
||||
|
||||
**왜**
|
||||
에디터의 소개 섹션 본문은 `sites.theme` 에 저장됐지만 발행 payload 경계에서 버려졌고,
|
||||
프리렌더도 고유 콘텐츠로 세지 않았다. 사장님이 소개를 써도 발행 화면은 0건이라며 거부했다.
|
||||
|
||||
**한 일**
|
||||
- `SectionSetting.body` 계약을 추가하고 저장값을 payload 까지 전달
|
||||
- 소개 본문을 발행 HTML에 표시하고, 켜진 소개 섹션의 8자 이상 본문만 고유 콘텐츠로 계수
|
||||
- 고유 콘텐츠 0건과 JSON-LD 불일치, 계수 실패를 서로 다른 발행 사유로 분리
|
||||
|
||||
**검증** — 직접 입력 소개문만 있는 발행 경로 회귀 테스트 추가.
|
||||
|
||||
## 2026-09-02 — 템플릿이 색만 바꾸던 걸 끝냈다 (5개 → 3개)
|
||||
|
||||
**왜**
|
||||
업종마다 템플릿이 다섯이었는데 넷이 "흰 바탕 + 고딕 + 둥근 모서리"에 색조만 달랐다.
|
||||
고르는 화면의 미리보기도 회색 막대 세 줄 + 색 동그라미라 다섯 장이 전부 같은 그림이었다 —
|
||||
사장님은 뭐가 다른지 알 수 없으니 아무거나 골랐다. 사용자 말: "가라 UI 로 되어 있어서 뭐가뭔지 모르겠음".
|
||||
|
||||
**한 일**
|
||||
- `TemplateItem.look`(`TemplateLook`) 신설: 제목·본문 서체, 모서리, 테두리 두께, 그림자,
|
||||
제목 자간·굵기, 섹션 여백. **CSS 에 그대로 들어가는 문자열**로 들고 있다 — 숫자로 두면
|
||||
쓰는 쪽에서 단위를 빠뜨린 곳이 조용히 0 이 된다.
|
||||
- 업종당 **3개**로 정리: 심플(고딕·둥근·그림자) · 매거진(명조 제목·각짐·그림자 없음·여백 큼) ·
|
||||
레트로(간판체·2px 테두리·오프셋 그림자·갱지). `templatesFor()` 팩토리 하나가 찍어내고
|
||||
**업종은 accent 하나만 바꾼다** — 생김새는 업종이 아니라 취향의 문제다.
|
||||
`industryData.ts` 537줄 → 237줄.
|
||||
- 고르는 화면의 미리보기를 **그 템플릿의 서체·모서리·테두리·그림자로 실제로 그린다**(`TemplatePreview`).
|
||||
|
||||
**핵심 수법 — Tailwind 테마 변수를 캔버스 안에서만 덮는다**
|
||||
`.site-canvas` 에 `--radius-*` · `--shadow-*` 를 내려보내면, 변이 파일 40여 개에 흩어진
|
||||
`rounded-*` · `shadow-*` 를 **한 줄도 안 고치고** 전부 템플릿을 따르게 된다.
|
||||
배수는 Tailwind 기본 비율을 그대로 옮겨, 기준값 0.75rem 이면 지금까지와 픽셀 단위로 같고 0 이면 전부 각진다.
|
||||
|
||||
**밟은 함정**
|
||||
- `.site-canvas` 는 이미 `--tpl-font-heading/body` 를 **읽고 있었는데 아무도 넣지 않았다.**
|
||||
서체가 갈리지 않던 진짜 이유가 이 빠진 고리였다.
|
||||
- 간판체(Gugi)는 굵기가 한 벌뿐이라 `font-weight:700` 을 주면 브라우저가 가짜 볼드를 씌워 획이 뭉갠다.
|
||||
→ `--tpl-heading-weight` 로 템플릿이 400 을 지정할 수 있게 했다.
|
||||
- `Noto Serif KR` 을 안 불러오고 있었다. 매거진 제목이 Batang 으로 떨어지는데 맥에는 그 서체가 없다.
|
||||
- 옛 템플릿 id(`stay-warm-wood` 등)가 DB 에 남아 있어도 `resolveTemplate` 이 첫 템플릿으로 떨어뜨린다.
|
||||
|
||||
**검증** — `tsc·eslint·vite build` 통과(frontend·admin·site). 템플릿 12벌의 look 전량 대조,
|
||||
옛 id 폴백·레트로만 아이템을 데려오는지 확인.
|
||||
|
||||
---
|
||||
|
||||
## 2026-09-01 — 붙여넣기 아이템 셋: 가요 다방 · 오늘의 한 장 · 반나절 산책
|
||||
|
||||
**한 일**
|
||||
- 섹션 타입 3개 추가(`songs` · `daily` · `course`). 데이터가 수집(fact)이 아니라
|
||||
**사장님이 붙여넣은 JSON** 에서 온다 — 새 갈래다.
|
||||
- `canvas/dataSpec.ts` 신설: 스키마·예시·프롬프트가 한 표에 모인다. 배리에이션 레지스트리와 같은 결이라
|
||||
여기 한 줄을 더하면 캔버스·[콘텐츠] 탭·프롬프트가 동시에 는다.
|
||||
- `SectionItem.data?: string` 추가. **파싱본이 아니라 원문 문자열**을 담는다.
|
||||
- [콘텐츠] 탭에 JSON 칸 + [프롬프트 복사] [프롬프트 보기] [예시 넣기] [줄맞춤].
|
||||
- 업종 시드 넷 모두에 세 섹션을 **꺼진 채로** 넣었다.
|
||||
|
||||
**왜 이 모양인가**
|
||||
`gunsan_365_story_db.xlsx`(365행)를 분석한 결과 **고유 주제는 52개고 한 주제가 7회씩 돈다**
|
||||
(접미사 10개만 회전). 날짜 축으로 카드를 늘어놓으면 이레마다 같은 카드가 돌아온다 —
|
||||
그래서 묶는 축을 주제로 잡고, 날짜는 일력 한 장에만 썼다.
|
||||
같은 시트 `DB_Guide` 가 **가사·현대문학 원문 전재를 금지**해서 가요 스키마에 `lyrics` 필드를
|
||||
아예 두지 않았다. 없는 칸은 채울 수 없다.
|
||||
|
||||
**밟은 함정**
|
||||
- **테마 상한 64KB**(`site_service._THEME_MAX_BYTES`). 세 섹션이 각자 JSON 을 채우면 넘고,
|
||||
거절은 발행 직전에야 드러난다. → `SECTION_DATA_MAX_CHARS`(12,000자)로 화면에서 먼저 끊는다.
|
||||
- **`JSON.parse` 오류 메시지가 두 형식이다.** `position N (line L column C)` 형과, 위치 없이
|
||||
깨진 조각만 인용하는 형. 앞의 것만 보면 후자에서 위치를 통째로 잃는다 — 조각을 원문에서 되찾아 센다.
|
||||
- 파싱은 **절대 throw 하지 않는다.** 편집 중인 JSON 은 늘 깨져 있고, 깨진 순간 캔버스가 죽으면 못 고친다.
|
||||
|
||||
**섹션 관리에 붙인 것**
|
||||
- 좌측 패널 하단 **[+ 섹션 추가]** → 목록에서 골라 넣는다. 시드에 박아 두지 않는 이유는,
|
||||
붙여넣기 아이템은 내용이 없으면 빈 칸이라 아무도 안 쓰는 항목이 늘 붙어 있게 되기 때문이다.
|
||||
- 나중에 넣은 섹션만 휴지통으로 뺄 수 있다(업종 기본 섹션은 스위치로 끈다).
|
||||
- **레트로 템플릿**(업종마다 하나: 옛 항구 · 옛 다방 · 노포 · 시간여행)을 고르면 세 아이템이 함께 들어온다.
|
||||
`TemplateItem.defaultSectionTypes` 가 그 계약이고, **넣기만 하고 빼지 않는다** —
|
||||
템플릿을 눌러 보다 넣어 둔 섹션이 사라지면 사장님은 자기가 지웠다고 생각한다.
|
||||
- 저장 payload 에 `type` 을 실었다. 시드에 없는 섹션은 복원 때 `id` 로 못 찾아 **통째로 버려졌다**
|
||||
(사장님이 채운 JSON 까지 같이). 이제 `type` 으로 되살린다.
|
||||
|
||||
**아직 안 한 것**
|
||||
- 발행 사이트(`solution/site`)는 `variantId` 도 `data` 도 아직 안 읽는다. 지금은 빌더 캔버스 전용이다.
|
||||
- 프롬프트는 상호·주소를 박아 내보낸다(빈칸을 남기면 사장님이 못 채우고 그대로 보낸다).
|
||||
|
||||
**검증** — `tsc --noEmit` · `eslint` · `vite build` 통과(frontend·admin). 세 배리에이션 SSR 렌더 확인,
|
||||
파서 경계 12건 + 추가·삭제·템플릿·저장복원 왕복 12건 확인.
|
||||
|
||||
---
|
||||
|
||||
## 2026-09-01 — 설정을 `.env` 하나로 모았다
|
||||
|
||||
**한 일**
|
||||
- 백엔드 설정을 toml → `pydantic-settings`(FastAPI 공식 방식)로 옮겼다.
|
||||
- `config_loader.py` · `config.local.toml.example` · `config.test.toml.example` 삭제.
|
||||
- `server_configs.py` 107줄 → 26줄. `_apply_*_env_override` 함수 4개 제거.
|
||||
- 호출부 21개 파일은 안 건드렸다 — 같은 이름을 그대로 내보낸다.
|
||||
|
||||
**왜**
|
||||
키마다 `if os.environ.get(...)` 를 손으로 나열하는 구조였다. 하나 빠뜨리면 조용히 틀리는데,
|
||||
실제로 `client_url` 이 빠져 있어 **배포 주소의 API 호출이 전부 CORS 로 막혔다**.
|
||||
`BaseSettings` 는 필드를 선언하면 환경변수가 자동으로 들어와 이 사고가 구조적으로 안 난다.
|
||||
|
||||
**하는 김에 잡은 잠재 버그**
|
||||
- `.env` 경로가 세 단계라 `solution/.env`(없는 파일)를 보고 있었다. 백엔드를 `solution/` 아래로
|
||||
옮길 때 안 고쳐진 자리다. toml 이 값을 들고 있어 로컬에서 안 드러났고, 도커는 compose 가
|
||||
환경변수를 직접 넣어 역시 멀쩡했다. toml 을 없앤 지금은 유일한 공급원이라 치명적이었다.
|
||||
- 환경변수 이름을 `validation_alias` 로 못 박았다. 안 그러면 `port` 필드가 흔한 `PORT` 를
|
||||
주워 먹어 엉뚱한 포트로 뜬다.
|
||||
|
||||
**결과** — 백엔드 설정 파일은 최상위 `.env` 하나뿐이다. → [DECISIONS.md](DECISIONS.md)
|
||||
|
||||
---
|
||||
|
||||
## 2026-08-31 — 킹서버 최초 배포
|
||||
|
||||
**한 일**
|
||||
- `~/data2/o2o-web4ai` 에 배포. DB(`web4ai_db`) 생성 + `init.sql` 적용.
|
||||
- 컴포즈 포트를 전부 `.env` 변수로 뽑았다. 로컬 기본값은 그대로다.
|
||||
- `deploy.sh` · `log.sh` 추가.
|
||||
|
||||
**왜 포트를 뽑았나**
|
||||
킹서버는 `:80` 을 호스트 nginx 가 이미 물고 있다. 사내망에 열려 있는 건 30xxx 대역뿐이라
|
||||
그 안에서 자리를 잡아야 했다. → [SERVERS.md](SERVERS.md)
|
||||
|
||||
**밟은 함정**
|
||||
- `PUBLIC_API_BASE_URL` 은 **브라우저가** 부르는 주소다. `localhost` 로 두면 화면은 뜨고
|
||||
API 만 죽는다 — 콘솔을 열기 전엔 안 보인다.
|
||||
- 내부 화면의 "빌더 열기" 가 `VITE_SOLUTION_URL` 미주입으로 죽은 링크였다. 로컬에서는
|
||||
기본값이 맞는 주소라 서버에 올리기 전까지 드러나지 않았다.
|
||||
- `deploy.sh api` 는 worker·api-admin 도 함께 갈아끼운다. 셋이 이미지 한 벌을 나눠 쓰는데
|
||||
하나만 바꾸면 옛 코드로 도는 컨테이너가 남고, `ps` 로는 셋 다 살아 있어 구분이 안 된다.
|
||||
|
||||
**남은 것** — `w4ai.o2o.kr` DNS + 앞단(59.14.81.3) 포워딩. 서버에 sudo 가 없어 인프라 몫이다.
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
# 킹서버 — 배포 대상 정의
|
||||
|
||||
배포 **절차**는 [DEPLOY.md](DEPLOY.md) 3절이다. 이 문서는 그 절차가 "서버에서" 라고만 부르는
|
||||
**그 서버가 무엇인지**만 적는다. 값은 2026-08-31 에 직접 붙어서 확인한 것이다.
|
||||
|
||||
## 접속
|
||||
|
||||
```bash
|
||||
ssh King_admin # ~/.ssh/config 에 정의됨
|
||||
```
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| 호스트명 | `king` (`172.30.1.36`) — **사설 IP다. 직접 못 닿는다** |
|
||||
| 계정 | `o2oadmin` |
|
||||
| 경유 | `ProxyJump Confluence` = `59.14.81.3:14444` |
|
||||
|
||||
★ `~/.ssh/config` 는 레포 밖이다. 새로 합류하면 아래를 직접 넣어야 붙는다.
|
||||
|
||||
```
|
||||
Host King_admin
|
||||
HostName 172.30.1.36
|
||||
User o2oadmin
|
||||
ProxyJump Confluence
|
||||
|
||||
Host Confluence
|
||||
HostName 59.14.81.3
|
||||
Port 14444
|
||||
User o2oadmin
|
||||
```
|
||||
|
||||
## 무엇이 올라가 있나
|
||||
|
||||
Ubuntu 18.04.6 LTS · 24 core · RAM 125G · Docker 24.0.2 · Docker Compose v2.20.3.
|
||||
컨테이너 34개가 이미 돈다 (negosium · iquote · triple-pick · infinith · gitea · persona 등).
|
||||
**우리만 쓰는 서버가 아니다** — 포트와 디스크를 남의 것과 나눠 쓴다.
|
||||
|
||||
## 어디에 두나 — `/home/o2oadmin/data2/o2o-web4ai`
|
||||
|
||||
레포는 홈이 아니라 **`data2` 밑**에 둔다. 홈이 있는 루트 디스크와 다른 물리 디스크다.
|
||||
|
||||
```
|
||||
/ 1.8T 중 228G 남음 (87% 사용) ← 여기에 두면 곧 찬다
|
||||
/mnt/data2 3.6T 중 2.7T 남음 (22% 사용) ← 다른 o2o 프로젝트가 전부 여기 있다
|
||||
```
|
||||
|
||||
`o2o-negosium` · `o2o-iquote` · `o2o-triple-pick` 이 모두 `/home/o2oadmin/data2/<레포명>` 이다.
|
||||
같은 규약을 따른다. (`git remote` 는 `https://gitea.o2o.kr/castad/o2o-web4ai.git` — gitea 도
|
||||
이 서버의 컨테이너다.)
|
||||
|
||||
## 포트 — 이 서버에서 우리가 잡은 자리
|
||||
|
||||
★ **`:80` 은 호스트 nginx 가 이미 물고 있다**(bible-chatbot·o2sound-voucher 를 라우팅 중).
|
||||
그래서 컴포즈의 포트를 전부 `.env` 로 뽑아 두고, 킹서버에서는 30xxx 대역을 쓴다.
|
||||
로컬 기본값은 그대로다 — `.env` 를 안 채우면 예전과 똑같이 뜬다.
|
||||
|
||||
| 서비스 | 컨테이너 포트 | 킹서버 | bind | 누가 보나 |
|
||||
|---|---|---|---|---|
|
||||
| `solution-site` (**공개 진입점**) | 80 | **30030** | 0.0.0.0 | 방문자·사장님 |
|
||||
| `solution-backend` (솔루션 API) | 9800 | 30032 | **127.0.0.1** | nginx 만 |
|
||||
| `solution-prerender` (굽기) | — | — | — | — |
|
||||
| `solution-worker` (잡 러너) | — | — | — | — |
|
||||
| `admin-frontend` (어드민 화면) | 3002 | 3002 | **127.0.0.1** | 우리 |
|
||||
| `admin-backend` (어드민 API) | 9801 | 9801 | **127.0.0.1** | 우리 |
|
||||
|
||||
★ **밖으로 열린 포트는 30030 하나다.** 사장님 앱 · 발행 사이트 · API 가 전부 그 뒤에 있다
|
||||
(`nginx/site.conf`). API 를 따로 열지 않는 이유: 같은 오리진이면 CORS 가 아예 없고,
|
||||
`robots.txt`·`sitemap.xml` 은 RFC 9309 상 **오리진 루트에서만** 읽힌다.
|
||||
|
||||
| 경로 | 어디로 |
|
||||
|---|---|
|
||||
| `/` | 사장님 앱 — 이미지에 구워 넣은 정적 번들(`/srv/app`) |
|
||||
| `/s/<slug>` · `/assets/` · `/robots.txt` · `/sitemap.xml` | `site-out` 볼륨 |
|
||||
| `/v1/...` · `/healthz` · `/docs` | `solution-backend:9800` |
|
||||
|
||||
★ 어드민 둘은 **기본 기동에서 빠져 있다**(compose 프로필). 켤 때는
|
||||
`docker compose --profile admin up -d`.
|
||||
|
||||
내부 둘은 로컬호스트에만 연다 — 포트를 가른 이유가 그거다([AGENTS.md](../AGENTS.md)).
|
||||
밖에서 볼 땐 터널을 판다:
|
||||
|
||||
```bash
|
||||
ssh -N -L 3002:127.0.0.1:3002 -L 9801:127.0.0.1:9801 King_admin
|
||||
# → http://localhost:3002
|
||||
```
|
||||
|
||||
★ **30xxx 는 사내망(172.30.1.x)에서만 닿는다.** 밖에서는 안 열린다 —
|
||||
`59.14.81.3:30010` 같은 이웃 프로젝트 포트도 바깥에서 막혀 있는 걸 확인했다.
|
||||
공개하려면 앞단(59.14.81.3)에 포워딩/프록시를 걸어야 하고, 그건 이 레포 밖이다.
|
||||
|
||||
★ **`PUBLIC_API_BASE_URL` 은 브라우저가 부르는 주소다.** 컨테이너 안 주소가 아니다.
|
||||
비워 두면 `http://localhost:9800` 이라 **서버에 올리는 순간 틀린다** —
|
||||
화면은 뜨는데 API 만 안 되고, 콘솔을 열기 전에는 안 보인다.
|
||||
|
||||
## 배포 · 로그
|
||||
|
||||
레포 루트에 스크립트 두 개가 있다. 서버에서 실행한다.
|
||||
|
||||
```bash
|
||||
cd ~/data2/o2o-web4ai
|
||||
./deploy.sh # 전체 (git pull → build → up -d)
|
||||
./deploy.sh api # 그 서비스만
|
||||
./log.sh # 1=전체, 2번부터 개별 컨테이너
|
||||
./log.sh 1 # 메뉴 없이 바로
|
||||
```
|
||||
|
||||
★ `deploy.sh api` 는 worker·api-admin 도 함께 갈아끼운다. 셋이 이미지 한 벌을 나눠 쓰기 때문이다 —
|
||||
안 그러면 옛 코드로 도는 컨테이너가 남는데 셋 다 "살아 있음" 이라 눈으로는 구분이 안 된다.
|
||||
|
||||
★ 서버에 gitea 자격증명이 없어 `git pull` 이 실패한다. 밖에서 밀어넣고 `./deploy.sh --no-pull`
|
||||
로 돌리거나, gitea 에 배포키를 등록해 원격을 SSH 로 바꾼다.
|
||||
|
||||
## DB
|
||||
|
||||
호스트에 PostgreSQL 15(pgvecto)가 `king_postgres_container` 로 떠 있고 `5432` 가 호스트에 열려 있다.
|
||||
컴포즈가 `DB_HOST` 기본값을 `host.docker.internal` 로 두고 `extra_hosts: host-gateway` 를
|
||||
붙여 두었으므로 **컴포즈를 고치지 않고 그대로 닿는다.** DB 는 만들어야 한다 —
|
||||
`postgres-init/init-data/init.sql` 한 벌이 스키마 전부다.
|
||||
|
||||
## 공개 주소 — `https://w4ai.o2o.kr` (2026-09-01 연결됨)
|
||||
|
||||
```
|
||||
DNS A w4ai.o2o.kr → 59.14.81.3
|
||||
└ 앞단 Apache(2.4.18) → http://172.30.1.36:30030 → solution-site
|
||||
```
|
||||
|
||||
`59.14.81.3` 은 사내망 입구다(`gitea.o2o.kr` 과 같은 IP). 킹서버의 `172.30.1.36` 은 **사설
|
||||
IP라 DNS 에 못 적는다** — 앞단 vhost 와 인증서는 이 레포 밖이고 인프라 담당이 잡는다.
|
||||
|
||||
이 값이 `SITE_PUBLIC_HOST` 이고 canonical·og:url·sitemap·IndexNow 에 전부 들어간다.
|
||||
바꾸면 **payload JSON 에 구워진 `origin` 까지 재발행**해야 한다([DEPLOY.md 0단계](DEPLOY.md)).
|
||||
|
||||
★ **`.env` 를 고쳐도 화면 주소는 안 바뀐다.** `VITE_*` 는 `solution-site` 이미지의 번들에
|
||||
구워진다 — `./deploy.sh solution-site` 로 다시 굽는다.
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env bash
|
||||
# 로그 보기.
|
||||
#
|
||||
# ./log.sh 메뉴에서 고른다
|
||||
# ./log.sh 1 1번 = 전체 로그
|
||||
# ./log.sh 4 4번 컨테이너
|
||||
# ./log.sh solution-backend 이름으로 바로
|
||||
#
|
||||
# -n <줄> 처음에 보여줄 줄 수 (기본 200)
|
||||
# --no-f 따라가지 않고 지금까지만 찍고 끝낸다
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
TAIL=200
|
||||
FOLLOW=1
|
||||
PICK=""
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
-n) TAIL="$2"; shift ;;
|
||||
--no-f|--no-follow) FOLLOW=0 ;;
|
||||
-h|--help) awk 'NR>1 && /^#/ {sub(/^# ?/, ""); print; next} NR>1 {exit}' "$0"; exit 0 ;;
|
||||
-*) echo "모르는 옵션: $1" >&2; exit 2 ;;
|
||||
*) PICK="$1" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
# 번호가 흔들리면 손이 기억한 번호가 다른 컨테이너를 연다 — 순서를 코드로 못 박는다.
|
||||
ORDER=(solution-backend solution-worker solution-frontend solution-site admin-backend admin-frontend)
|
||||
AVAILABLE=$(docker compose config --services)
|
||||
SVCS=()
|
||||
for s in "${ORDER[@]}"; do grep -qx "$s" <<<"$AVAILABLE" && SVCS+=("$s"); done
|
||||
# compose 에 서비스가 늘면 뒤에 붙는다(빠뜨리지 않으려고).
|
||||
while read -r s; do
|
||||
[ -n "$s" ] || continue
|
||||
printf '%s\n' "${SVCS[@]}" | grep -qx "$s" || SVCS+=("$s")
|
||||
done <<<"$AVAILABLE"
|
||||
|
||||
# 살아 있는지 한눈에 — 죽은 걸 고르고 "로그가 안 나온다" 하는 자리를 없앤다.
|
||||
# ★ --format '{{.Service}}' 은 쓰지 않는다. compose v2.20 이 커스텀 템플릿을 파싱하지 못해
|
||||
# 전부 "미기동" 으로 보인다(명령은 성공해서 틀린 줄 모른다).
|
||||
RUNNING=$(docker compose ps --services --filter status=running 2>/dev/null || true)
|
||||
status() {
|
||||
grep -qx "$1" <<<"$RUNNING" && printf '실행중' || printf '멈춤'
|
||||
}
|
||||
|
||||
menu() {
|
||||
echo
|
||||
echo " o2o-web4ai 로그"
|
||||
echo " ─────────────────────────────"
|
||||
printf " 1) %-18s %s\n" "전체" ""
|
||||
local i=2
|
||||
for s in "${SVCS[@]}"; do
|
||||
printf " %2d) %-18s %s\n" "$i" "$s" "[$(status "$s")]"
|
||||
i=$((i + 1))
|
||||
done
|
||||
echo " q) 나가기"
|
||||
echo
|
||||
}
|
||||
|
||||
resolve() { # 번호 또는 이름 → docker compose logs 인자
|
||||
local pick="$1"
|
||||
if [ "$pick" = "1" ]; then TARGET=(); return; fi
|
||||
if [[ "$pick" =~ ^[0-9]+$ ]]; then
|
||||
local idx=$((pick - 2))
|
||||
[ "$idx" -ge 0 ] && [ "$idx" -lt "${#SVCS[@]}" ] || { echo "그런 번호가 없다: $pick" >&2; return 1; }
|
||||
TARGET=("${SVCS[$idx]}"); return
|
||||
fi
|
||||
local name="${pick#o2o-web4ai-}"
|
||||
printf '%s\n' "${SVCS[@]}" | grep -qx "$name" || { echo "그런 컨테이너가 없다: $pick" >&2; return 1; }
|
||||
TARGET=("$name")
|
||||
}
|
||||
|
||||
if [ -z "$PICK" ]; then
|
||||
menu
|
||||
read -rp " 번호: " PICK
|
||||
[ "$PICK" = "q" ] && exit 0
|
||||
fi
|
||||
|
||||
TARGET=()
|
||||
resolve "$PICK" || exit 2
|
||||
|
||||
ARGS=(--tail="$TAIL")
|
||||
[ "$FOLLOW" = 1 ] && ARGS+=(-f)
|
||||
echo "▶ docker compose logs ${ARGS[*]} ${TARGET[*]:-(전체)}"
|
||||
exec docker compose logs "${ARGS[@]}" ${TARGET+"${TARGET[@]}"}
|
||||
@@ -0,0 +1,46 @@
|
||||
# 공개 진입점 이미지 — 사장님 앱 정적 번들을 구워 넣고, nginx 가 그것과 발행 사이트를 함께 준다.
|
||||
#
|
||||
# ★ 왜 dev 서버를 안 띄우나
|
||||
# 운영에 `vite dev` 를 두면 요청마다 트랜스파일하고, 기동이 `npm install` 네트워크에 의존하고,
|
||||
# `/src/*` 원본과 소스맵이 그대로 나간다. 실측(킹서버): 컨테이너 기동에 npm install 이 걸려
|
||||
# 재기동 시간이 네트워크 상태에 좌우됐다.
|
||||
#
|
||||
# ★ 발행 사이트(`/s/...`)는 이 이미지에 안 들어간다. named volume(site-out)에서 읽는다 —
|
||||
# 사이트가 늘 때마다 이미지를 다시 굽지 않는다.
|
||||
|
||||
FROM node:24-alpine AS build
|
||||
WORKDIR /app
|
||||
|
||||
# 의존성 레이어를 소스와 분리한다. 소스만 바뀌면 npm ci 를 건너뛴다.
|
||||
COPY package.json package-lock.json tsconfig.base.json ./
|
||||
COPY solution/shared/package.json solution/shared/
|
||||
COPY solution/frontend/package.json solution/frontend/
|
||||
COPY solution/site/package.json solution/site/
|
||||
COPY admin/frontend/package.json admin/frontend/
|
||||
RUN npm ci
|
||||
|
||||
COPY solution ./solution
|
||||
COPY admin ./admin
|
||||
|
||||
# ★ VITE_* 는 **빌드 시점에 번들로 구워진다.** 런타임 환경변수로는 못 바꾼다 —
|
||||
# 주소를 바꾸면 이 이미지를 다시 빌드해야 한다(`./deploy.sh solution-site`).
|
||||
ARG VITE_API_BASE_URL
|
||||
ARG VITE_PUBLISH_HOST
|
||||
ARG VITE_SITE_PREVIEW_URL
|
||||
# ⚠️ 자동 로그인 계정. **번들에 그대로 구워져** 페이지를 연 사람이 JS 에서 읽을 수 있다 —
|
||||
# 내부 테스트 호스트에서만 채우고, 사장님에게 여는 순간 비운다(lib/autoSession).
|
||||
ARG VITE_AUTO_LOGIN_ID
|
||||
ARG VITE_AUTO_LOGIN_PW
|
||||
# 구글 OAuth 클라이언트 ID. 비밀이 아니라 번들에 들어가도 된다 — 다만 백엔드 GOOGLE_CLIENT_ID 와
|
||||
# 같은 값이어야 한다(백엔드가 이 값으로 토큰의 aud 를 대조한다).
|
||||
ARG VITE_GOOGLE_CLIENT_ID
|
||||
ENV VITE_API_BASE_URL=$VITE_API_BASE_URL \
|
||||
VITE_PUBLISH_HOST=$VITE_PUBLISH_HOST \
|
||||
VITE_SITE_PREVIEW_URL=$VITE_SITE_PREVIEW_URL \
|
||||
VITE_AUTO_LOGIN_ID=$VITE_AUTO_LOGIN_ID \
|
||||
VITE_AUTO_LOGIN_PW=$VITE_AUTO_LOGIN_PW \
|
||||
VITE_GOOGLE_CLIENT_ID=$VITE_GOOGLE_CLIENT_ID
|
||||
RUN npm run build -w @o2o/frontend
|
||||
|
||||
FROM nginx:alpine
|
||||
COPY --from=build /app/solution/frontend/dist /srv/app
|
||||
@@ -0,0 +1,29 @@
|
||||
# ★ 루트 `.dockerignore` 는 **백엔드 이미지용**이라 solution/frontend·site·shared 를 통째로
|
||||
# 잘라낸다. 같은 컨텍스트를 쓰는 이 이미지가 그걸 물려받으면 COPY 가 "not found" 로 죽는다.
|
||||
# BuildKit 은 `<Dockerfile 경로>.dockerignore` 를 먼저 보므로 여기서 따로 잡는다.
|
||||
.git/
|
||||
node_modules/
|
||||
**/node_modules/
|
||||
**/dist/
|
||||
**/.vite/
|
||||
|
||||
# 파이썬 백엔드는 이 이미지에 들어갈 이유가 없다.
|
||||
solution/backend/
|
||||
postgres-init/
|
||||
**/__pycache__/
|
||||
*.pyc
|
||||
**/.pytest_cache/
|
||||
.venv/
|
||||
**/.venv/
|
||||
|
||||
# 발행 산출물은 볼륨에서 온다. 이미지에 구우면 사이트가 늘 때마다 이미지가 붓는다.
|
||||
solution/site/out/
|
||||
solution/site/payloads/
|
||||
|
||||
docs/
|
||||
**/*.md
|
||||
|
||||
# 시크릿 — 이미지에 굽지 않는다. VITE_* 는 build args 로 준다.
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
@@ -1,79 +0,0 @@
|
||||
# 발행 사이트 정적 서빙.
|
||||
#
|
||||
# ★ 산출물은 named volume(site-out)으로 들어온다. 프리렌더 컨테이너가 쓰고 여기서 읽기만 한다 —
|
||||
# 호스트 경로가 등장하지 않으므로 재배포로 코드를 갈아엎어도 사이트가 죽지 않는다.
|
||||
#
|
||||
# ★ 규칙은 하나뿐이다: 디렉토리 요청 → index.html.
|
||||
# `/s/butter` (끝 슬래시 없음)가 사장님이 주소창에 치는 형태다. 이게 404 면
|
||||
# "발행했는데 안 나온다"가 된다.
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name _;
|
||||
|
||||
# ★ nginx 이미지의 기본 문서 루트(/usr/share/nginx/html)를 쓰지 않는다.
|
||||
# named volume 을 거기 마운트하면 Docker 가 **이미지에 들어 있던 index.html 을
|
||||
# 빈 볼륨으로 복사한다** — 그러면 오리진 루트가 "Welcome to nginx!" 를 띄우고,
|
||||
# 그게 크롤러에 잡힌다. 빈 경로에 마운트하면 복사될 것이 없다.
|
||||
root /srv/sites;
|
||||
|
||||
# index 지시를 끈다. 오리진 루트에는 페이지가 없다(사이트는 /s/<slug> 아래에 있다).
|
||||
index index.html;
|
||||
|
||||
charset utf-8;
|
||||
server_tokens off;
|
||||
|
||||
# 텍스트 산출물은 압축이 크게 먹는다(HTML 55KB → 10KB 안팎).
|
||||
gzip on;
|
||||
gzip_comp_level 6;
|
||||
gzip_min_length 1024;
|
||||
gzip_vary on;
|
||||
gzip_types
|
||||
text/plain text/css text/xml
|
||||
application/javascript application/json application/xml
|
||||
image/svg+xml;
|
||||
|
||||
# ── 공용 번들 ──────────────────────────────────────────────
|
||||
# 파일명에 해시가 박혀 있다. 내용이 바뀌면 이름이 바뀌므로 영구 캐시가 안전하다.
|
||||
# ★ expires 와 add_header 를 함께 쓰면 Cache-Control 헤더가 두 줄로 나간다.
|
||||
# 합쳐서 읽히긴 하지만 의도가 흐려지므로 add_header 하나로 통일한다.
|
||||
location /assets/ {
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
access_log off;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location /fonts/ {
|
||||
add_header Cache-Control "public, max-age=604800";
|
||||
access_log off;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# ── 크롤러가 읽는 파일 ─────────────────────────────────────
|
||||
# 발행하면 곧바로 반영되어야 한다. 길게 캐시하면 새 사업장이 사이트맵에 들어가도
|
||||
# 크롤러가 옛 파일을 계속 본다.
|
||||
location = /robots.txt {
|
||||
add_header Cache-Control "public, max-age=300, must-revalidate";
|
||||
}
|
||||
|
||||
location = /sitemap.xml {
|
||||
add_header Cache-Control "public, max-age=300, must-revalidate";
|
||||
}
|
||||
|
||||
# ── 발행 사이트 ────────────────────────────────────────────
|
||||
location / {
|
||||
# $uri/ 를 거치면 nginx 가 끝 슬래시로 301 을 내보낸다. 크롤러가 리다이렉트를
|
||||
# 한 번 더 타야 하므로 index.html 을 바로 준다.
|
||||
try_files $uri $uri/index.html =404;
|
||||
add_header Cache-Control "public, max-age=300, must-revalidate";
|
||||
}
|
||||
|
||||
# 발행되지 않은 주소. 사장님이 오타를 냈을 때 흰 화면 대신 이유를 보여준다.
|
||||
error_page 404 /404.html;
|
||||
location = /404.html {
|
||||
internal;
|
||||
return 404 '<!doctype html><html lang="ko"><meta charset="utf-8"><title>페이지를 찾을 수 없습니다</title><body style="font-family:system-ui;padding:3rem;text-align:center"><h1>페이지를 찾을 수 없습니다</h1><p>주소를 다시 확인해 주세요.</p></body></html>';
|
||||
add_header Content-Type "text/html; charset=utf-8";
|
||||
}
|
||||
}
|
||||
+76
-19
@@ -1,11 +1,17 @@
|
||||
# 발행 사이트 정적 서빙.
|
||||
# 공개 진입점 하나. 사장님 앱 · 발행 사이트 · API 가 **같은 오리진**을 쓴다.
|
||||
#
|
||||
# ★ 산출물은 named volume(site-out)으로 들어온다. 프리렌더 컨테이너가 쓰고 여기서 읽기만 한다 —
|
||||
# / → 사장님 앱 (이미지에 구워 넣은 정적 번들, /srv/app)
|
||||
# /s/<slug> → 발행 사이트 (site-out 볼륨에서 정적)
|
||||
# /assets/ → 발행본 공용 번들 (정적)
|
||||
# /robots.txt · /sitemap.xml → 크롤러가 읽는 파일 (정적)
|
||||
# /v1/... /healthz → API(solution-backend:9800)
|
||||
#
|
||||
# ★ 오리진을 가르지 않는 이유: robots.txt·sitemap.xml 은 RFC 9309 상 **오리진 루트에서만**
|
||||
# 읽힌다. 앱과 사이트를 다른 호스트에 두면 인증서도 DNS 도 두 벌이 되고 CORS 가 붙는다.
|
||||
# 개발에서는 Vite 프록시가 같은 일을 한다(solution/frontend/vite.config.ts).
|
||||
#
|
||||
# ★ 산출물은 named volume(site-out)으로 들어온다. 프리렌더가 쓰고 여기서 읽기만 한다 —
|
||||
# 호스트 경로가 등장하지 않으므로 재배포로 코드를 갈아엎어도 사이트가 죽지 않는다.
|
||||
#
|
||||
# ★ 규칙은 하나뿐이다: 디렉토리 요청 → index.html.
|
||||
# `/s/butter` (끝 슬래시 없음)가 사장님이 주소창에 치는 형태다. 이게 404 면
|
||||
# "발행했는데 안 나온다"가 된다.
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
@@ -18,11 +24,14 @@ server {
|
||||
# 그게 크롤러에 잡힌다. 빈 경로에 마운트하면 복사될 것이 없다.
|
||||
root /srv/sites;
|
||||
|
||||
# index 지시를 끈다. 오리진 루트에는 페이지가 없다(사이트는 /s/<slug> 아래에 있다).
|
||||
index index.html;
|
||||
|
||||
charset utf-8;
|
||||
server_tokens off;
|
||||
client_max_body_size 20m;
|
||||
|
||||
# ★ Docker 내장 DNS. 업스트림을 변수로 두면 nginx 가 **기동할 때** 이름을 풀지 않는다 —
|
||||
# 안 그러면 solution-backend 가 아직 안 떴을 때 nginx 자체가 죽는다.
|
||||
resolver 127.0.0.11 valid=10s ipv6=off;
|
||||
set $api http://solution-backend:9800;
|
||||
|
||||
# 텍스트 산출물은 압축이 크게 먹는다(HTML 55KB → 10KB 안팎).
|
||||
gzip on;
|
||||
@@ -34,19 +43,33 @@ server {
|
||||
application/javascript application/json application/xml
|
||||
image/svg+xml;
|
||||
|
||||
# ── 공용 번들 ──────────────────────────────────────────────
|
||||
# ── 발행 사이트 ────────────────────────────────────────────
|
||||
# ^~ 로 잡아 아래 정규식 location 들이 끼어들지 못하게 한다.
|
||||
location ^~ /s/ {
|
||||
# $uri/ 를 거치면 nginx 가 끝 슬래시로 301 을 내보낸다. 크롤러가 리다이렉트를
|
||||
# 한 번 더 타야 하므로 index.html 을 바로 준다.
|
||||
try_files $uri $uri/index.html =404;
|
||||
add_header Cache-Control "public, max-age=300, must-revalidate";
|
||||
}
|
||||
|
||||
# 파일명에 해시가 박혀 있다. 내용이 바뀌면 이름이 바뀌므로 영구 캐시가 안전하다.
|
||||
# ★ expires 와 add_header 를 함께 쓰면 Cache-Control 헤더가 두 줄로 나간다.
|
||||
# 합쳐서 읽히긴 하지만 의도가 흐려지므로 add_header 하나로 통일한다.
|
||||
location /assets/ {
|
||||
location ^~ /assets/ {
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
access_log off;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location /fonts/ {
|
||||
# ★ 빌더와 발행본이 `/fonts/` 를 **각자** 쓴다(vite.config.ts 주석). 발행본을 먼저 보고
|
||||
# 없으면 빌더 것으로 떨어뜨린다 — 한쪽만 잡으면 다른 쪽 폰트가 조용히 404 다.
|
||||
location ^~ /fonts/ {
|
||||
root /srv/sites;
|
||||
add_header Cache-Control "public, max-age=604800";
|
||||
access_log off;
|
||||
try_files $uri @app_fonts;
|
||||
}
|
||||
location @app_fonts {
|
||||
root /srv/app;
|
||||
access_log off;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
@@ -55,18 +78,52 @@ server {
|
||||
# 크롤러가 옛 파일을 계속 본다.
|
||||
location = /robots.txt {
|
||||
add_header Cache-Control "public, max-age=300, must-revalidate";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location = /sitemap.xml {
|
||||
add_header Cache-Control "public, max-age=300, must-revalidate";
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# ── 발행 사이트 ────────────────────────────────────────────
|
||||
# ── API ────────────────────────────────────────────────────
|
||||
# 앱과 같은 오리진이라 프리플라이트가 아예 발생하지 않는다.
|
||||
location ~ ^/(v1/|healthz$|openapi\.json$|docs|redoc) {
|
||||
proxy_pass $api;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
|
||||
# 발행·수집 잡은 분 단위다. 기본 60s 면 게이트웨이가 먼저 끊는다.
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
}
|
||||
|
||||
# IndexNow 키 파일. 프리렌더가 루트에 <key>.txt 를 굽고 검색엔진이 대조한다.
|
||||
# ★ `{8,128}` 같은 수량자는 못 쓴다 — nginx 는 `{`·`}` 를 블록 구분자로 먼저 읽는다.
|
||||
location ~ ^/[A-Za-z0-9_-]+\.txt$ {
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# ── 사장님 앱 (그 외 전부) ─────────────────────────────────
|
||||
# 해시가 박힌 번들. 내용이 바뀌면 이름이 바뀌므로 영구 캐시가 안전하다.
|
||||
# ★ 발행본 `/assets/` 와 겹치지 않게 빌더만 `builder-assets` 로 뺐다
|
||||
# (solution/frontend/vite.config.ts 의 build.assetsDir).
|
||||
location ^~ /builder-assets/ {
|
||||
root /srv/app;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
access_log off;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# SPA 다. 없는 경로는 index.html 로 넘겨 클라이언트 라우터가 받게 한다.
|
||||
# ★ index.html 은 캐시하지 않는다 — 여기에 번들 해시가 박혀 있어서, 캐시되면
|
||||
# 새로 배포해도 브라우저가 옛 번들 주소를 계속 부른다(404 → 흰 화면).
|
||||
location / {
|
||||
# $uri/ 를 거치면 nginx 가 끝 슬래시로 301 을 내보낸다. 크롤러가 리다이렉트를
|
||||
# 한 번 더 타야 하므로 index.html 을 바로 준다.
|
||||
try_files $uri $uri/index.html =404;
|
||||
add_header Cache-Control "public, max-age=300, must-revalidate";
|
||||
root /srv/app;
|
||||
try_files $uri $uri/index.html /index.html;
|
||||
add_header Cache-Control "no-cache";
|
||||
}
|
||||
|
||||
# 발행되지 않은 주소. 사장님이 오타를 냈을 때 흰 화면 대신 이유를 보여준다.
|
||||
|
||||
@@ -68,14 +68,16 @@ CREATE TABLE IF NOT EXISTS company.companies (
|
||||
CREATE TABLE IF NOT EXISTS company.users (
|
||||
user_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), -- 유저 식별자(PK)
|
||||
company_id uuid NOT NULL, -- 소속 회사(company.companies.company_id)
|
||||
id VARCHAR(20) NOT NULL, -- 로그인 ID
|
||||
password VARCHAR(255) NOT NULL, -- 해시된 비밀번호이어야 함
|
||||
id VARCHAR(64) NOT NULL, -- 로그인 ID (구글 계정은 google_<sub>)
|
||||
password VARCHAR(255) NULL, -- bcrypt 해시. 소셜 계정은 NULL
|
||||
name VARCHAR(50) NULL, -- 이름
|
||||
email VARCHAR(255) NULL, -- 이메일
|
||||
contact_number VARCHAR(20) NULL, -- 연락처
|
||||
last_accessed_at TIMESTAMPTZ NOT NULL DEFAULT now(), -- 마지막 접속 시각
|
||||
status SMALLINT NOT NULL DEFAULT 1, -- 상태: 1=active(활성), 2=inactive(비활성)
|
||||
role SMALLINT NOT NULL DEFAULT 1, -- 권한(UserRole): 1=user(일반), 2=owner(최고관리자), 3=developer(내부 운영)
|
||||
provider SMALLINT NOT NULL DEFAULT 1, -- 로그인 수단(AuthProvider): 1=local(id/pw), 2=google
|
||||
provider_uid VARCHAR(255) NULL, -- 구글 sub — 이메일이 바뀌어도 유지되는 유일 키
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), -- 생성 시각(UTC)
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), -- 수정 시각(UTC, 앱에서 갱신)
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE -- 소프트 삭제 여부
|
||||
@@ -89,7 +91,7 @@ CREATE TABLE IF NOT EXISTS place.places (
|
||||
company_id uuid NOT NULL, -- 테넌트(company.companies.company_id)
|
||||
owner_user_id uuid NULL, -- 사장님 계정(company.users.user_id)
|
||||
name VARCHAR(200) NOT NULL, -- 상호명(입력값)
|
||||
category SMALLINT NOT NULL, -- 업종(PlaceCategory): 1=숙박 2=카페 3=음식점 4=관광체험
|
||||
category SMALLINT NOT NULL, -- 업종(PlaceCategory): 1=숙박 2=카페 3=음식점 4=피부과·성형외과
|
||||
status SMALLINT NOT NULL DEFAULT 1, -- 상태(PlaceStatus): 1=draft 2=collecting 3=review 4=published 5=suspended
|
||||
external_source SMALLINT NULL, -- 검증에 쓴 외부 장소 DB(ExternalPlaceSource): 1=kakao 2=naver
|
||||
external_place_id VARCHAR(64) NULL, -- 외부 고유 장소 id — ★ 카카오는 주고 네이버는 안 준다
|
||||
@@ -274,6 +276,7 @@ CREATE TABLE IF NOT EXISTS site.sites (
|
||||
status SMALLINT NOT NULL DEFAULT 1, -- 상태(SiteStatus): 1=draft 2=review 3=published 4=suspended 5=unpublished
|
||||
current_version_id uuid NULL, -- 현재 발행 버전(site.site_versions.site_version_id)
|
||||
published_at TIMESTAMPTZ NULL, -- 최초/최근 발행 시각
|
||||
thumbnail_url VARCHAR(500) NULL, -- 발행 썸네일(Azure Blob 공개 URL). 발행에 성공한 뒤에만 채워진다 — 쇼케이스·사이트 목록 카드가 읽는다
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE
|
||||
@@ -356,6 +359,8 @@ CREATE INDEX IF NOT EXISTS idx_users_company_id ON company.users (company_id);
|
||||
|
||||
-- 소프트 삭제를 쓰므로 자연키 유니크는 부분 인덱스(deleted = FALSE)로 건다.
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_users_id ON company.users (id) WHERE deleted = FALSE;
|
||||
-- 같은 구글 계정으로 두 번 가입되지 않게. provider 를 키에 넣어 수단이 늘어도 이 인덱스가 그대로 쓰인다.
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_users_provider_uid ON company.users (provider, provider_uid) WHERE deleted = FALSE AND provider_uid IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_companies_biz_number ON company.companies (business_number) WHERE deleted = FALSE AND business_number IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_companies_code ON company.companies (code) WHERE deleted = FALSE;
|
||||
|
||||
@@ -430,3 +435,10 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_jobs_dedupe_active ON job.jobs (dedupe_key)
|
||||
ALTER TABLE place.places
|
||||
ADD COLUMN IF NOT EXISTS content_updated_at TIMESTAMPTZ NULL, -- 2026-08-27 노출값 변경 시각(개별 재빌드 판별)
|
||||
ADD COLUMN IF NOT EXISTS external_source SMALLINT NULL; -- 2026-08-27 검증 소스(kakao/naver)
|
||||
|
||||
-- 2026-09-02 구글 로그인. 소셜 계정은 비밀번호가 없고(NULL), 로그인 아이디가 google_<sub> 라 20자를 넘는다.
|
||||
ALTER TABLE company.users
|
||||
ADD COLUMN IF NOT EXISTS provider SMALLINT NOT NULL DEFAULT 1,
|
||||
ADD COLUMN IF NOT EXISTS provider_uid VARCHAR(255) NULL;
|
||||
ALTER TABLE company.users ALTER COLUMN id TYPE VARCHAR(64);
|
||||
ALTER TABLE company.users ALTER COLUMN password DROP NOT NULL;
|
||||
@@ -20,8 +20,6 @@ RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY solution/backend ./solution/backend
|
||||
COPY admin/backend ./admin/backend
|
||||
|
||||
# 시크릿 든 config.local.toml 은 .dockerignore 로 제외됨 → example(플레이스홀더)로 대체.
|
||||
RUN cp solution/backend/config/config.local.toml.example solution/backend/config/config.local.toml
|
||||
|
||||
ENV APP_ENV=local
|
||||
# ★ 내부 API(admin/backend)가 common·router·services 를 그대로 import 하는 경로.
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
|
||||
**수집 → 생성 → 빌드 → 발행 파이프라인이 API 로 다 열렸다.** 프론트(`solution/frontend`)가 이 API 를 붙여 쓴다.
|
||||
|
||||
★ **코드는 한 벌인데 진입점이 둘이다** — 사장님 API `web_main.py`(:9800, 엔드포인트별 권한)와
|
||||
내부 API `admin/backend/main.py`(:9801, 앱 전체 `role >= DEVELOPER`). 같은 router 객체를 다시
|
||||
★ **코드는 한 벌인데 진입점이 둘이다** — 솔루션 API `web_main.py`(:9800, 엔드포인트별 권한)와
|
||||
어드민 API `admin/backend/main.py`(:9801, 앱 전체 `role >= DEVELOPER`). 같은 router 객체를 다시
|
||||
마운트하고 앱 단위로 권한만 덧건다. 왜 경로 접두어가 아니라 포트인지는
|
||||
[../../docs/ARCHITECTURE.md 4절](../../docs/ARCHITECTURE.md).
|
||||
|
||||
@@ -39,7 +39,7 @@ 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)
|
||||
└── clinic.json 피부과·성형외과 필드 24 (critical 17)
|
||||
```
|
||||
|
||||
**업종 추가 = JSON 파일 1개 + `PlaceCategory` 코드 1줄.** 로직은 건드리지 않는다.
|
||||
@@ -88,9 +88,9 @@ o2o-web4ai/
|
||||
├── .env.example # 외부 API 키·DB 접속 주입 템플릿 (cp .env.example .env)
|
||||
├── postgres-init/
|
||||
│ └── init-data/init.sql # 스키마 DDL 한 벌 (재실행 안전. 누적 ALTER 파일은 없다)
|
||||
├── admin/backend/ # 내부 API 진입점(:9801). 도메인 코드는 아래를 그대로 import 한다
|
||||
├── admin/backend/ # 어드민 API 진입점(:9801). 도메인 코드는 아래를 그대로 import 한다
|
||||
└── solution/backend/
|
||||
├── web_main.py # 사장님 API 진입점 :9800 (uvicorn)
|
||||
├── web_main.py # 솔루션 API 진입점 :9800 (uvicorn)
|
||||
├── worker_main.py # 잡 러너 + 스케줄러
|
||||
├── config/ # 환경설정 (APP_ENV 별 toml 로드)
|
||||
├── conftest.py, tests/ # pytest (test DB 자동 create/drop) — 아래 '테스트'
|
||||
@@ -196,9 +196,9 @@ POST /v1/place/{id}/site/slug {slug} → sites.domain 에 저장(사
|
||||
|
||||
| 무엇 | 어디 | 커밋 |
|
||||
|---|---|---|
|
||||
| DB 접속 · JWT · 포트 | `solution/backend/config/config.local.toml` | ✗ (`*.toml` ignore) |
|
||||
| DB 접속 · JWT · 포트 | 레포 최상위 `.env` | ✗ (ignore) |
|
||||
| 외부 API 키 | 레포 최상위 `.env` | ✗ |
|
||||
| 템플릿 | `config/config.local.toml.example` · `.env.example` | ✓ |
|
||||
| 템플릿 | `.env.example` | ✓ |
|
||||
|
||||
우선순위: **실제 환경변수(docker-compose) > `.env` > `config.{APP_ENV}.toml`**
|
||||
|
||||
@@ -219,7 +219,7 @@ psql -h 127.0.0.1 -p 5432 -U postgres -f ../../postgres-init/init-data/init.sql
|
||||
cd ../.. # 레포 루트
|
||||
cp .env.example .env # 최초 1회, 외부 API 키 채우기
|
||||
cd solution/backend
|
||||
cp config/config.local.toml.example config/config.local.toml # 최초 1회, DB·JWT 채우기
|
||||
cp .env.example .env # 레포 최상위. 최초 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
|
||||
@@ -244,7 +244,7 @@ python -m pytest tests/test_auth.py # 파일 하나만
|
||||
venv 를 활성화하지 않으면 `.venv/bin/python -m pytest` 로 직접 지정한다. 정상이면 마지막 줄에 `NN passed`.
|
||||
|
||||
동작 방식 (전부 [conftest.py](conftest.py) 가 자동 처리):
|
||||
- `APP_ENV` 를 `test` 로 자동 설정 → `config/config.test.toml`([예제](config/config.test.toml.example)) 의 **`web4ai_test_db`** 사용(dev DB 와 완전 분리).
|
||||
- `APP_ENV` 를 `test` 로 자동 설정 → DB 이름 기본값이 **`web4ai_test_db`** 로 갈린다(dev DB 와 완전 분리, `config_models.py`).
|
||||
- **세션 시작 시 test DB 를 새로 만들고(CREATE), 끝나면 내린다(DROP).** 매번 현재 모델로 새로 빌드돼 스키마가 낡을 일이 없다.
|
||||
- 테이블은 `create_all` 로 자동 생성, 매 테스트 전 `TRUNCATE` 로 비워 격리.
|
||||
- 안전가드: 이름에 `test` 없는 DB 는 만들지도 지우지도 않는다(실 DB 보호).
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"category": "clinic",
|
||||
"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": "specialties", "label": "진료과목", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false },
|
||||
{ "key": "medical_staff", "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": "consultation_fee", "label": "상담료", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false },
|
||||
{ "key": "insurance_covered", "label": "보험 적용 안내", "type": "text", "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": "night_clinic", "label": "야간진료", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false },
|
||||
{ "key": "weekend_clinic", "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": "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": "price_adult", "label": "시술 비용", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
|
||||
{ "key": "anesthesia", "label": "마취 방식", "type": "text", "scope": "unit", "required": false, "critical": true, "allow_llm": false },
|
||||
{ "key": "downtime", "label": "회복 기간", "type": "text", "scope": "unit", "required": false, "critical": true, "allow_llm": false },
|
||||
{ "key": "session_count", "label": "권장 횟수", "type": "text", "scope": "unit", "required": false, "critical": true, "allow_llm": false },
|
||||
{ "key": "aftercare", "label": "시술 후 주의사항", "type": "text", "scope": "unit", "required": false, "critical": true, "allow_llm": false },
|
||||
{ "key": "program_intro", "label": "시술 설명", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": true }
|
||||
]
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
{
|
||||
"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 }
|
||||
]
|
||||
}
|
||||
@@ -6,6 +6,7 @@ from sqlalchemy.dialects.postgresql import UUID, JSONB
|
||||
from sqlalchemy.sql import text
|
||||
|
||||
from common.enums import (
|
||||
AuthProvider,
|
||||
DBType,
|
||||
UserStatus,
|
||||
UserRole,
|
||||
@@ -68,14 +69,22 @@ class users(MainTableMixin, MAIN_BASE):
|
||||
|
||||
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 확장)
|
||||
# 20자였다. 구글 계정의 로그인 아이디를 `google_<sub>`(최대 28자)로 만들면서 넓혔다 —
|
||||
# sub 를 잘라 쓰면 앞자리가 같은 두 계정이 한 아이디로 겹친다.
|
||||
id = Column(String(64), nullable=False, unique=True, index=True) # 로그인 아이디
|
||||
# 소셜 계정은 비밀번호가 없다(NULL). 더미 해시를 넣으면 "비번이 있는 계정" 처럼 보여
|
||||
# id/pw 로그인 경로가 그 계정을 상대로 계속 시도된다.
|
||||
password = Column(String(255), nullable=True) # 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)
|
||||
# server_default 를 함께 준다 — ORM default 는 raw INSERT(테스트 시드·수동 SQL)에 안 먹어서
|
||||
# 컬럼이 NOT NULL 이면 그 경로가 통째로 깨진다(init.sql 의 DEFAULT 1 과 같은 값).
|
||||
provider = Column(SmallInteger, nullable=False, server_default=text("1"), default=AuthProvider.LOCAL.value)
|
||||
provider_uid = Column(String(255), nullable=True) # 구글 sub — 이메일이 바뀌어도 같은 사람인지 판단하는 유일한 키
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -160,7 +169,7 @@ class place_links(MainTableMixin, MAIN_BASE):
|
||||
|
||||
|
||||
class units(MainTableMixin, MAIN_BASE):
|
||||
"""업종별 하위 단위 — 숙박=객실, 카페·음식점=메뉴, 관광체험=프로그램.
|
||||
"""업종별 하위 단위 — 숙박=객실, 카페·음식점=메뉴, 피부과·성형외과=프로그램.
|
||||
가변 필드는 facts(scope=unit)로 들어가고, 여기에는 목록 렌더에 필요한 뼈대만 둔다."""
|
||||
|
||||
__tablename__ = "units"
|
||||
@@ -396,6 +405,9 @@ class sites(MainTableMixin, MAIN_BASE):
|
||||
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)
|
||||
# 발행 썸네일(Azure Blob 공개 URL). ★ 발행에 성공한 뒤에만 채운다 — 굽다 만 사이트의 그림을
|
||||
# 쇼케이스에 걸면 없는 페이지로 보낸다. 만들지 못하면 NULL 이고, 화면은 글자 카드로 떨어진다.
|
||||
thumbnail_url = Column(String(500), nullable=True)
|
||||
|
||||
|
||||
class site_versions(MainTableMixin, MAIN_BASE):
|
||||
|
||||
@@ -52,6 +52,9 @@ class ErrorType(Enum):
|
||||
ACCOUNT_BLOCKED_USER = auto()
|
||||
ACCOUNT_NOT_FOUND = auto()
|
||||
ACCOUNT_FORBIDDEN = auto() # 최고관리자 외 접근 / 다른 회사·최고관리자 대상 변경 시도
|
||||
ACCOUNT_PROVIDER_CONFLICT = auto() # 이미 다른 로그인 수단으로 가입된 이메일 — 자동 연결하지 않는다(DECISIONS 1절)
|
||||
OAUTH_NOT_CONFIGURED = auto() # GOOGLE_CLIENT_ID 미설정 — 구글 로그인만 꺼진다
|
||||
OAUTH_INVALID_TOKEN = auto() # 구글 ID 토큰 서명·수신자·만료 검증 실패
|
||||
|
||||
# 사업장(places) 관련 에러
|
||||
PLACE_NOT_FOUND = 1200
|
||||
@@ -153,6 +156,17 @@ class UserRole(CodeEnum):
|
||||
DEVELOPER = 3 # 개발자(내부 운영): 최고관리자 권한 전부 + 고객사에 보이지 않음
|
||||
|
||||
|
||||
class AuthProvider(CodeEnum):
|
||||
"""users.provider 코드값. 이 계정이 무엇으로 신원을 증명하는가.
|
||||
|
||||
한 계정은 수단 하나다 — 같은 이메일이라도 id/pw 계정과 구글 계정을 자동으로 잇지 않는다.
|
||||
이으려면 "먼저 가입한 쪽의 소유"를 증명받아야 하는데, 그 증명 없이 이메일만 보고 이으면
|
||||
남이 먼저 만들어 둔 계정에 내 구글 로그인이 들어간다(계정 선점). 보류 사유는 DECISIONS.md 1절."""
|
||||
|
||||
LOCAL = 1 # id/pw
|
||||
GOOGLE = 2 # 구글 ID 토큰
|
||||
|
||||
|
||||
class CompanyStatus(CodeEnum):
|
||||
"""companies.status 코드값."""
|
||||
|
||||
@@ -167,7 +181,7 @@ class PlaceCategory(CodeEnum):
|
||||
LODGING = 1 # 숙박
|
||||
CAFE = 2 # 카페
|
||||
RESTAURANT = 3 # 음식점
|
||||
TOUR_ACTIVITY = 4 # 관광체험
|
||||
CLINIC = 4 # 피부과·성형외과
|
||||
|
||||
|
||||
class ExternalPlaceSource(CodeEnum):
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""IP 단위 호출 제한 — 프로세스 메모리에만 있는 아주 단순한 것.
|
||||
|
||||
★ 한계를 먼저 적는다. 프로세스가 여럿이면 한도가 그 수만큼 곱해지고, 재시작하면 리셋된다.
|
||||
제대로 하려면 앞단(nginx `limit_req`)이나 공유 저장소가 필요하다.
|
||||
|
||||
★ 그런데도 두는 이유: 이걸 쓰는 곳이 **인증 없이 유료 외부 API 를 부르는 경로**다.
|
||||
방어가 0 이면 새로고침을 누르고 있는 것만으로 요금이 나간다
|
||||
(카카오 키워드 검색은 무료 한도를 넘기면 건당 2원 — services/external/kakao.py 주석).
|
||||
"""
|
||||
|
||||
import time
|
||||
from collections import defaultdict, deque
|
||||
|
||||
_hits: dict[str, deque] = defaultdict(deque)
|
||||
|
||||
|
||||
def allow(key: str, limit: int, window_sec: float) -> bool:
|
||||
"""key 가 window_sec 안에서 limit 번을 넘지 않았으면 True(그리고 1회로 센다)."""
|
||||
now = time.monotonic()
|
||||
bucket = _hits[key]
|
||||
while bucket and now - bucket[0] > window_sec:
|
||||
bucket.popleft()
|
||||
if len(bucket) >= limit:
|
||||
return False
|
||||
bucket.append(now)
|
||||
# 안 쓰는 키가 쌓이는 걸 막는다. 호출이 뜸하면 자연히 비워진다.
|
||||
if not bucket:
|
||||
_hits.pop(key, None)
|
||||
return True
|
||||
|
||||
|
||||
def reset():
|
||||
"""테스트 전용 — 프로세스 상태를 비운다."""
|
||||
_hits.clear()
|
||||
@@ -1,52 +0,0 @@
|
||||
# 복사해서 사용: cp config.local.toml.example config.local.toml
|
||||
# 실제 config.local.toml 은 시크릿 포함이라 커밋하지 않는다(.gitignore: *.toml).
|
||||
# 모든 서버는 APP_ENV=local 로 띄우며 이 파일을 읽는다.
|
||||
[WebServerConfig]
|
||||
server_name = "Web4aiServer"
|
||||
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 = "web4ai_db"
|
||||
write_host = "127.0.0.1"
|
||||
write_port = 5432
|
||||
write_id = "<DB_USER>"
|
||||
write_pw = "<DB_PASSWORD>"
|
||||
read_host = "127.0.0.1"
|
||||
read_port = 5432
|
||||
read_id = "<DB_USER>"
|
||||
read_pw = "<DB_PASSWORD>"
|
||||
show_log = false
|
||||
pool_size = 10
|
||||
max_overflow = 20
|
||||
sslmode = "" # 로컬: "" / 관리형 DB: "require"|"verify-ca"|"verify-full"
|
||||
|
||||
[JwtToken]
|
||||
access_key = "<JWT_ACCESS_SECRET>"
|
||||
refresh_key = "<JWT_REFRESH_SECRET>"
|
||||
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 = "" # 공공데이터포털 전국문화축제표준데이터 일반 인증키
|
||||
@@ -1,51 +0,0 @@
|
||||
# 복사해서 사용: cp config.test.toml.example config.test.toml
|
||||
# 실제 config.test.toml 은 커밋하지 않는다(.gitignore: *.toml).
|
||||
#
|
||||
# ★ 이 파일이 없으면 `.venv/bin/pytest` 가 conftest import 단계에서 죽는다
|
||||
# (server_configs 가 config.<APP_ENV>.toml 을 읽는다). 그래서 템플릿을 둔다.
|
||||
# ★ DB 이름을 dev 와 절대 같게 두지 말 것 — 픽스처가 TRUNCATE 를 돌린다.
|
||||
# conftest 의 안전가드가 이름을 확인하지만, 여기서부터 갈라 두는 게 먼저다.
|
||||
[WebServerConfig]
|
||||
server_name = "O2oSiteServerTest"
|
||||
port = 9800
|
||||
process_count = 1
|
||||
is_ssl = false
|
||||
is_test = true
|
||||
client_url = "http://localhost:3000"
|
||||
landing_url = ""
|
||||
|
||||
[LogConfig]
|
||||
print_console = false
|
||||
log_level = "warning"
|
||||
|
||||
[MainDBConfig]
|
||||
db_type = "postgresql"
|
||||
name = "web4ai_test_db" # ★ dev(web4ai_db)와 다른 DB. 픽스처가 매번 지웠다 만든다
|
||||
write_host = "127.0.0.1"
|
||||
write_port = 5432
|
||||
write_id = "postgres"
|
||||
write_pw = "password"
|
||||
read_host = "127.0.0.1"
|
||||
read_port = 5432
|
||||
read_id = "postgres"
|
||||
read_pw = "password"
|
||||
show_log = false
|
||||
pool_size = 5
|
||||
max_overflow = 10
|
||||
sslmode = ""
|
||||
|
||||
[JwtToken]
|
||||
access_key = "test-access-key-not-a-secret"
|
||||
refresh_key = "test-refresh-key-not-a-secret"
|
||||
access_expire_min = 30
|
||||
refresh_expire_day = 7
|
||||
|
||||
# ★ 전부 빈값으로 둔다. APP_ENV=test 는 .env 를 읽지 않는데(실키가 테스트로 새는 경로 차단),
|
||||
# 여기에 실키를 적으면 그 차단을 우회해 외부 API 요금이 나간다.
|
||||
[ExternalApiConfig]
|
||||
perplexity_api_key = ""
|
||||
kakao_rest_api_key = ""
|
||||
naver_client_id = ""
|
||||
naver_client_secret = ""
|
||||
gemini_api_key = ""
|
||||
tour_api_key = ""
|
||||
@@ -1,37 +0,0 @@
|
||||
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)
|
||||
@@ -1,66 +1,164 @@
|
||||
from config.config_loader import ConfigModel
|
||||
"""설정 모델 — 값은 전부 환경변수(최상위 .env 포함)에서 온다.
|
||||
|
||||
★ 환경변수 이름은 validation_alias 로 못 박는다. 필드명만 두면 `port` 가 흔한 `PORT` 를
|
||||
주워 먹어 엉뚱한 포트로 뜬다.
|
||||
"""
|
||||
|
||||
from functools import lru_cache
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
import os
|
||||
|
||||
# 레포 최상위 .env. 여기서 네 단계 위다 — 세 단계로 두면 solution/.env(없는 파일)를 본다.
|
||||
_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
||||
_DOTENV = os.path.join(_REPO_ROOT, ".env")
|
||||
|
||||
APP_ENV = os.environ.get("APP_ENV", "local")
|
||||
|
||||
# ★ APP_ENV=test 면 .env 를 읽지 않는다. 실키가 새면 테스트가 실제 외부 API 를 때린다.
|
||||
_ENV_FILE = None if APP_ENV == "test" else _DOTENV
|
||||
|
||||
# ★ 테스트는 별도 DB. conftest 가 "이름에 test 없으면 중단" 으로 dev DB 를 지킨다.
|
||||
_DEFAULT_DB_NAME = "web4ai_test_db" if APP_ENV == "test" else "web4ai_db"
|
||||
|
||||
_BASE = SettingsConfigDict(env_file=_ENV_FILE, env_file_encoding="utf-8", extra="ignore", case_sensitive=False)
|
||||
|
||||
|
||||
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 WebServerConfig(BaseSettings):
|
||||
model_config = _BASE
|
||||
|
||||
server_name: str = Field("Web4aiServer", validation_alias="WEB_SERVER_NAME")
|
||||
port: int = Field(9800, validation_alias="WEB_SERVER_PORT")
|
||||
process_count: int = Field(1, validation_alias="WEB_PROCESS_COUNT")
|
||||
is_ssl: bool = Field(False, validation_alias="WEB_IS_SSL")
|
||||
is_test: bool = Field(False, validation_alias="WEB_IS_TEST")
|
||||
# CORS 허용 오리진(쉼표로 여럿). vite 는 3000 이 막히면 3001, 3002… 로 옮겨 뜬다.
|
||||
client_url: str = Field(
|
||||
"http://localhost:3000,http://localhost:3001,http://localhost:3002,"
|
||||
"http://localhost:3003,http://localhost:3004,http://localhost:3005",
|
||||
validation_alias="CLIENT_URL",
|
||||
)
|
||||
landing_url: str = Field("", validation_alias="LANDING_URL")
|
||||
|
||||
|
||||
class LogConfig(ConfigModel):
|
||||
print_console: bool = True
|
||||
log_level: str = "debug"
|
||||
class LogConfig(BaseSettings):
|
||||
model_config = _BASE
|
||||
|
||||
print_console: bool = Field(True, validation_alias="LOG_PRINT_CONSOLE")
|
||||
log_level: str = Field("debug", validation_alias="LOG_LEVEL")
|
||||
|
||||
|
||||
# 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 MainDBConfig(BaseSettings):
|
||||
"""DB read/write 분리. 읽기 접속을 안 주면 쓰기와 같은 곳을 본다(복제 없는 환경이 기본)."""
|
||||
|
||||
model_config = _BASE
|
||||
|
||||
db_type: str = Field("postgresql", validation_alias="DB_TYPE")
|
||||
name: str = Field(_DEFAULT_DB_NAME, validation_alias="DB_NAME")
|
||||
|
||||
write_host: str = Field("127.0.0.1", validation_alias="DB_HOST")
|
||||
write_port: int = Field(5432, validation_alias="DB_PORT")
|
||||
write_id: str = Field("postgres", validation_alias="DB_USER")
|
||||
write_pw: str = Field("", validation_alias="DB_PASSWORD")
|
||||
|
||||
read_host: Optional[str] = Field(None, validation_alias="DB_READ_HOST")
|
||||
read_port: Optional[int] = Field(None, validation_alias="DB_READ_PORT")
|
||||
read_id: Optional[str] = Field(None, validation_alias="DB_READ_USER")
|
||||
read_pw: Optional[str] = Field(None, validation_alias="DB_READ_PASSWORD")
|
||||
|
||||
show_log: bool = Field(False, validation_alias="DB_SHOW_LOG")
|
||||
# 동시 커넥션 상한 = (pool_size + max_overflow) x 엔진수(R/W=2) x 워커수.
|
||||
# PostgreSQL max_connections 를 넘기면 안 된다.
|
||||
pool_size: int = Field(10, validation_alias="DB_POOL_SIZE")
|
||||
max_overflow: int = Field(20, validation_alias="DB_MAX_OVERFLOW")
|
||||
# ""/"disable"=로컬 · "require"|"verify-ca"|"verify-full"=관리형 DB
|
||||
sslmode: str = Field("", validation_alias="DB_SSLMODE")
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _read_falls_back_to_write(self):
|
||||
if self.read_host is None:
|
||||
self.read_host = self.write_host
|
||||
if self.read_port is None:
|
||||
self.read_port = self.write_port
|
||||
if self.read_id is None:
|
||||
self.read_id = self.write_id
|
||||
if self.read_pw is None:
|
||||
self.read_pw = self.write_pw
|
||||
return self
|
||||
|
||||
|
||||
class JwtToken(ConfigModel):
|
||||
access_key: str = ""
|
||||
refresh_key: str = ""
|
||||
access_expire_min: int = 30
|
||||
refresh_expire_day: int = 7
|
||||
class JwtToken(BaseSettings):
|
||||
model_config = _BASE
|
||||
|
||||
access_key: str = Field("", validation_alias="JWT_ACCESS_SECRET")
|
||||
refresh_key: str = Field("", validation_alias="JWT_REFRESH_SECRET")
|
||||
access_expire_min: int = Field(30, validation_alias="JWT_ACCESS_EXPIRE_MIN")
|
||||
refresh_expire_day: int = Field(7, validation_alias="JWT_REFRESH_EXPIRE_DAY")
|
||||
|
||||
|
||||
# 외부 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 = "" # 공공데이터포털 일반 인증키(전국문화축제표준데이터)
|
||||
class GoogleOAuthConfig(BaseSettings):
|
||||
"""구글 로그인. client_id 가 비면 그 로그인 수단만 꺼진다 — 다른 외부 키들과 같은 규칙이다.
|
||||
|
||||
★ client_id 는 비밀이 아니다(프론트 번들에 그대로 들어간다). 서버가 이 값을 갖는 이유는
|
||||
숨기려는 게 아니라 **수신자(aud) 대조** 때문이다 — 남의 앱에 발급된 구글 토큰을 그대로
|
||||
들고 와도 우리 계정이 되지 않게 막는 유일한 검사다.
|
||||
★ client_secret 은 쓰지 않는다. 프론트가 ID 토큰을 받아 오는 방식(GIS)이라 코드 교환이 없다."""
|
||||
|
||||
model_config = _BASE
|
||||
|
||||
client_id: str = Field("", validation_alias="GOOGLE_CLIENT_ID")
|
||||
|
||||
|
||||
class ExternalApiConfig(BaseSettings):
|
||||
"""키가 비면 그 어댑터만 비활성이다 — 부팅이 외부 계약에 묶이면 안 된다."""
|
||||
|
||||
model_config = _BASE
|
||||
|
||||
perplexity_api_key: str = Field("", validation_alias="PERPLEXITY_API_KEY")
|
||||
# 동일 업소 검증 — 둘 다 있으면 카카오 우선.
|
||||
# 카카오: 15건 · 전화번호 O · 고유 id O · 행정구역 코드 O
|
||||
# 네이버: 5건 · 전화번호 X · 고유 id 불확실 · 행정구역 코드 X → AMBIGUOUS 가 는다
|
||||
kakao_rest_api_key: str = Field("", validation_alias="KAKAO_REST_API_KEY")
|
||||
naver_client_id: str = Field("", validation_alias="NAVER_CLIENT_ID")
|
||||
naver_client_secret: str = Field("", validation_alias="NAVER_CLIENT_SECRET")
|
||||
gemini_api_key: str = Field("", validation_alias="GEMINI_API_KEY")
|
||||
# 3.7 기본: 라벨이 틀리면 사람 확인 큐 비용이 모델 값 차이(1건 $0.045 vs $0.018)보다 크다.
|
||||
gemini_vision_model: str = Field("gemini-3.7-flash", validation_alias="GEMINI_VISION_MODEL")
|
||||
gemini_text_model: str = Field("gemini-3.7-flash", validation_alias="GEMINI_TEXT_MODEL")
|
||||
# 이 값 미만이면 자동 반영하지 않고 사람 확인 큐(PENDING_REVIEW)에 남긴다.
|
||||
vision_confidence_threshold: float = Field(0.7, validation_alias="VISION_CONFIDENCE_THRESHOLD")
|
||||
tour_api_key: str = Field("", validation_alias="TOUR_API_KEY")
|
||||
|
||||
|
||||
# .env 를 요청마다 다시 읽지 않는다. 새 코드는 Depends(get_*) 로 주입받는다.
|
||||
@lru_cache
|
||||
def get_web_server_config() -> WebServerConfig:
|
||||
return WebServerConfig()
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_log_config() -> LogConfig:
|
||||
return LogConfig()
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_main_db_config() -> MainDBConfig:
|
||||
return MainDBConfig()
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_jwt_token_config() -> JwtToken:
|
||||
return JwtToken()
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_external_api_config() -> ExternalApiConfig:
|
||||
return ExternalApiConfig()
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_google_oauth_config() -> GoogleOAuthConfig:
|
||||
return GoogleOAuthConfig()
|
||||
@@ -1,107 +1,30 @@
|
||||
import os
|
||||
"""설정 싱글턴 — 호출부 21개 파일이 이 이름들을 가져다 쓴다."""
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from config.config_models import (
|
||||
APP_ENV, # 재export — 테스트가 "지금 어느 환경으로 도는가" 를 여기서 읽는다(tests/test_config.py)
|
||||
ExternalApiConfig,
|
||||
GoogleOAuthConfig,
|
||||
JwtToken,
|
||||
LogConfig,
|
||||
MainDBConfig,
|
||||
WebServerConfig,
|
||||
get_external_api_config,
|
||||
get_google_oauth_config,
|
||||
get_jwt_token_config,
|
||||
get_log_config,
|
||||
get_main_db_config,
|
||||
get_web_server_config,
|
||||
)
|
||||
|
||||
from config.config_loader import Configs
|
||||
from config.config_models import WebServerConfig, LogConfig, MainDBConfig, JwtToken, ExternalApiConfig
|
||||
web_server_config: WebServerConfig = get_web_server_config()
|
||||
log_config: LogConfig = get_log_config()
|
||||
main_db_config: MainDBConfig = get_main_db_config()
|
||||
jwt_token_config: JwtToken = get_jwt_token_config()
|
||||
external_api_config: ExternalApiConfig = get_external_api_config()
|
||||
google_oauth_config: GoogleOAuthConfig = get_google_oauth_config()
|
||||
|
||||
# 레포 최상위 .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 로 주입하지 않으면 "<JWT_ACCESS_SECRET>" 이라는 공개된 문자열이 서명 키가 된다.
|
||||
# 운영에서는 반드시 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("<"):
|
||||
# 부팅은 막지 않는다 — 토큰이 필요 없는 로컬 작업까지 못 하게 되면 곤란하다.
|
||||
if not jwt_token_config.access_key or not jwt_token_config.refresh_key:
|
||||
from common.logger import LOG
|
||||
|
||||
LOG.w(
|
||||
"[보안] JWT 시크릿이 플레이스홀더입니다 — JWT_ACCESS_SECRET / JWT_REFRESH_SECRET 를 env 로 주입하세요. "
|
||||
"이 상태로 운영에 띄우면 서명 키가 공개값입니다."
|
||||
)
|
||||
LOG.w("[보안] JWT 시크릿이 비어 있습니다 — .env 에 JWT_ACCESS_SECRET / JWT_REFRESH_SECRET 를 넣으세요.")
|
||||
@@ -1,4 +1,4 @@
|
||||
# 테스트는 APP_ENV=test 로 실행한다 (config.test.toml → web4ai_test_db, dev DB 와 분리).
|
||||
# 테스트는 APP_ENV=test 로 실행한다 (DB 이름 기본값이 web4ai_test_db 로 갈린다, dev DB 와 분리).
|
||||
# 이 픽스처들은 TRUNCATE 를 하므로 dev DB(web4ai_db)와 절대 공유하면 안 된다(아래 db_engine 안전가드 참고).
|
||||
# config.server_configs 가 import 되는 순간 config.<APP_ENV>.toml 을 읽으므로 가장 먼저 설정.
|
||||
import os
|
||||
@@ -73,13 +73,13 @@ async def db_engine(_test_db_lifecycle):
|
||||
"""테스트용 스키마를 보장하고, 매 테스트 시작 시 테이블을 비워 격리한다.
|
||||
|
||||
⚠ 이 픽스처는 TRUNCATE 한다 → dev DB(web4ai_db)를 가리키면 실데이터가 날아간다.
|
||||
그래서 test 전용 DB(이름에 'test')가 아니면 즉시 중단한다(config.test.toml / APP_ENV=test).
|
||||
그래서 test 전용 DB(이름에 'test')가 아니면 즉시 중단한다(APP_ENV=test).
|
||||
앱(DB_SESSION_MNG)도 APP_ENV=test 면 같은 test DB 에 접속하므로 여기서 만든 스키마를 공유한다.
|
||||
"""
|
||||
# 안전가드: dev DB 오염 방지. web4ai_test_db 이외엔 절대 실행하지 않는다.
|
||||
assert "test" in main_db_config.name, (
|
||||
f"테스트가 비-test DB('{main_db_config.name}')를 가리킵니다. "
|
||||
"APP_ENV=test(config.test.toml)로 실행하세요. dev DB 보호를 위해 중단합니다."
|
||||
"APP_ENV=test 로 실행하세요. dev DB 보호를 위해 중단합니다."
|
||||
)
|
||||
engine = create_async_engine(
|
||||
_write_url(main_db_config),
|
||||
@@ -201,6 +201,12 @@ def fake_renderer(monkeypatch, tmp_path_factory):
|
||||
return len(str(value or "").strip()) >= MIN_UNIQUE_TEXT
|
||||
|
||||
count = 0
|
||||
intro = next(
|
||||
(s for s in (payload.get("theme") or {}).get("sections") or [] if s.get("id") == "intro"),
|
||||
None,
|
||||
)
|
||||
if intro and intro.get("enabled") and long(intro.get("body")):
|
||||
count += 1
|
||||
facts = list(payload.get("facts") or [])
|
||||
for unit in payload.get("units") or []:
|
||||
facts.extend(unit.get("facts") or [])
|
||||
@@ -220,6 +226,28 @@ def fake_renderer(monkeypatch, tmp_path_factory):
|
||||
if payload["site"]["version"] != site_version:
|
||||
return None
|
||||
place = payload.get("place") or {}
|
||||
count = _count(payload)
|
||||
# ★ 고유 콘텐츠 0건이면 렌더러는 **페이지를 쓰지 않는다**
|
||||
# (prerender.ts NoUniqueContentError — 백엔드가 나중에 거부해도 그 전에 디스크에
|
||||
# 나가 있으면 크롤러가 읽는다). 대역이 늘 ok=True 를 주면 백엔드가 그 실패를
|
||||
# NO_UNIQUE_CONTENT 로 되짚는 경로가 통째로 테스트되지 않는다.
|
||||
# mismatches 는 비워 둔다 — 사유가 JSONLD_MISMATCH 로 섞이면 화면 문구가 틀린다.
|
||||
if count <= 0:
|
||||
return {
|
||||
"schemaVersion": 1,
|
||||
"slug": slug,
|
||||
"siteId": payload["site"]["siteId"],
|
||||
"placeId": payload["site"]["placeId"],
|
||||
"siteVersion": site_version,
|
||||
"ok": False,
|
||||
"renderedAt": "2026-01-01T00:00:00.000Z",
|
||||
"routes": 0,
|
||||
"bundle": "test.js",
|
||||
"uniqueContentCount": count,
|
||||
"jsonld": None,
|
||||
"mismatches": [],
|
||||
"error": "고유 콘텐츠가 0건이다 — 이 가게에만 있는 내용이 없으면 발행하지 않는다",
|
||||
}
|
||||
return {
|
||||
"schemaVersion": 1,
|
||||
"slug": slug,
|
||||
@@ -230,7 +258,7 @@ def fake_renderer(monkeypatch, tmp_path_factory):
|
||||
"renderedAt": "2026-01-01T00:00:00.000Z",
|
||||
"routes": 3,
|
||||
"bundle": "test.js",
|
||||
"uniqueContentCount": _count(payload),
|
||||
"uniqueContentCount": count,
|
||||
"jsonld": [{"@type": "LodgingBusiness", "name": place.get("name"),
|
||||
"telephone": place.get("phone")}],
|
||||
"mismatches": [],
|
||||
|
||||
@@ -5,8 +5,8 @@ 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.database.model.models import places, publish_logs, site_versions, sites
|
||||
from common.enums import BuildStatus, ErrorType, SiteStatus
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
|
||||
@@ -57,6 +57,10 @@ class ISiteCRUD(ABC):
|
||||
async def list_logs(self, cdb: AsyncSession, site_id, limit: int) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def list_published(self, cdb: AsyncSession, limit: int) -> Tuple[ErrorType, list]:
|
||||
pass
|
||||
|
||||
|
||||
class SiteCRUD(ISiteCRUD):
|
||||
async def get_site_by_place(self, cdb: AsyncSession, place_id) -> Tuple[ErrorType, sites]:
|
||||
@@ -196,3 +200,27 @@ class SiteCRUD(ISiteCRUD):
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, []
|
||||
|
||||
async def list_published(self, cdb: AsyncSession, limit: int = 12) -> Tuple[ErrorType, list]:
|
||||
"""발행된 사이트 + 그 사업장을 최신순으로. 랜딩 쇼케이스가 읽는 목록이다.
|
||||
|
||||
★ 회사 스코프가 없는 **유일한** 사이트 조회다(비로그인 API 가 쓴다). 그래서 행을 통째로
|
||||
돌려주고, 무엇이 밖으로 나갈지는 services/showcase_service 한 곳에서만 고른다 —
|
||||
여기서 열을 골라 두면 나중에 필드를 늘릴 때 공개 여부를 판단할 자리가 사라진다."""
|
||||
try:
|
||||
query = (
|
||||
select(sites, places)
|
||||
.join(places, places.place_id == sites.place_id)
|
||||
.where(
|
||||
sites.status == SiteStatus.PUBLISHED.value,
|
||||
sites.deleted == False, # noqa: E712
|
||||
places.deleted == False, # noqa: E712
|
||||
)
|
||||
.order_by(sites.published_at.desc().nulls_last(), sites.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, []
|
||||
@@ -19,6 +19,14 @@ class IUserCRUD(ABC):
|
||||
async def get_user_by_login_id(self, cdb: AsyncSession, login_id: str) -> Tuple[ErrorType, users]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_user_by_provider_uid(self, cdb: AsyncSession, provider: int, provider_uid: str) -> Tuple[ErrorType, users]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_user_by_email(self, cdb: AsyncSession, email: str) -> Tuple[ErrorType, users]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def is_user(self, cdb: AsyncSession, login_id: str) -> ErrorType:
|
||||
pass
|
||||
@@ -31,6 +39,10 @@ class IUserCRUD(ABC):
|
||||
async def update_last_accessed(self, cdb: AsyncSession, user_id) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def add_company(self, cdb: AsyncSession, company: companies) -> ErrorType:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_company(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, companies]:
|
||||
pass
|
||||
@@ -66,6 +78,45 @@ class UserCRUD(IUserCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def get_user_by_provider_uid(self, cdb: AsyncSession, provider: int, provider_uid: str) -> Tuple[ErrorType, users]:
|
||||
"""소셜 계정 조회 키는 provider_uid(구글 sub) 다 — 이메일이 아니다.
|
||||
구글은 이메일 변경을 허용하고, 이메일로 찾으면 그때 같은 사람에게 계정이 하나 더 생긴다."""
|
||||
try:
|
||||
query = (
|
||||
select(users)
|
||||
.where(users.provider == provider, users.provider_uid == provider_uid, users.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, "get_user_by_provider_uid 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 get_user_by_email(self, cdb: AsyncSession, email: str) -> Tuple[ErrorType, users]:
|
||||
"""이메일로 1건. "이미 다른 수단으로 가입돼 있다" 판정에만 쓴다.
|
||||
이메일에는 유니크 제약이 없다(옛 데이터) — 여러 건이면 가장 먼저 만들어진 것을 본다."""
|
||||
try:
|
||||
query = (
|
||||
select(users)
|
||||
.where(func.lower(users.email) == email.strip().lower(), users.deleted == False) # noqa: E712
|
||||
.order_by(users.created_at.asc())
|
||||
.limit(1)
|
||||
)
|
||||
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, "get_user_by_email 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
|
||||
@@ -94,6 +145,13 @@ class UserCRUD(IUserCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
|
||||
async def add_company(self, cdb: AsyncSession, company: companies) -> ErrorType:
|
||||
try:
|
||||
return await DB_SESSION_MNG.insert(cdb, company)
|
||||
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
|
||||
|
||||
@@ -10,5 +10,5 @@ pydantic>=2.0
|
||||
python-multipart
|
||||
httpx
|
||||
apscheduler>=3.10
|
||||
python-dotenv # 레포 최상위 .env 로드(외부 API 키·DB 접속 주입)
|
||||
pydantic-settings # 환경변수·.env 로드 (FastAPI 공식 설정 방식)
|
||||
azure-storage-blob>=12.19
|
||||
@@ -17,6 +17,7 @@ import router.v1.faq.faq
|
||||
import router.v1.media.media
|
||||
import router.v1.job.job
|
||||
import router.v1.site.site
|
||||
import router.v1.site.showcase
|
||||
import router.v1.local.local
|
||||
|
||||
API_SERVER_START_TIME = GTime.UTCStr()
|
||||
@@ -87,5 +88,7 @@ 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)
|
||||
# ★ 인증 없는 공개 목록. 랜딩이 부른다 — 어드민 진입점(:9801)에는 붙이지 않는다.
|
||||
app.include_router(router.v1.site.showcase.router)
|
||||
app.include_router(router.v1.local.local.router)
|
||||
app.include_router(router.v1.local.local.weather_router)
|
||||
@@ -4,7 +4,7 @@ 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
|
||||
from .protocol import Req_GoogleLogin, Req_Login, Req_Signup, Req_UpdateMe, Res_Login, Res_Me, Res_RefreshToken
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
@@ -17,6 +17,26 @@ 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="/signup",
|
||||
response_model=Res_Login,
|
||||
summary="회원가입",
|
||||
description="id/pw 로 가입한다. 회사(테넌트) 1개가 함께 생기고, 성공하면 곧바로 로그인 토큰을 발급한다.",
|
||||
)
|
||||
async def signup(req: Req_Signup, service: AuthService = Depends()):
|
||||
return RemoveNoneResponse(await service.signup(req))
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/google",
|
||||
response_model=Res_Login,
|
||||
summary="구글 로그인",
|
||||
description="구글 ID 토큰(GIS credential)을 검증하고 JWT 토큰을 발급한다. 처음 온 계정은 그 자리에서 만든다.",
|
||||
)
|
||||
async def google_login(req: Req_GoogleLogin, service: AuthService = Depends()):
|
||||
return RemoveNoneResponse(await service.google_login(req))
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/refresh_token",
|
||||
dependencies=[Depends(IsValidRefreshToken)],
|
||||
|
||||
@@ -2,7 +2,7 @@ from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import UserRole
|
||||
from common.enums import AuthProvider, UserRole
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
@@ -16,6 +16,29 @@ class Req_Login(AuthProtocol):
|
||||
password: str = ""
|
||||
|
||||
|
||||
class Req_Signup(AuthProtocol):
|
||||
"""id/pw 가입. 가입 = 새 테넌트(회사) 1개 + 그 회사의 첫 계정 1개다.
|
||||
|
||||
★ 이메일을 필수로 받는 이유: 같은 이메일이 이미 구글로 가입돼 있는지 판단할 근거가 없으면
|
||||
한 사람에게 계정이 둘 생긴다. 지금 이메일 인증 절차는 없다 — 소유 증명이 아니라
|
||||
**중복 판정용** 이다."""
|
||||
|
||||
id: str = ""
|
||||
password: str = ""
|
||||
name: Optional[str] = None
|
||||
email: str = ""
|
||||
company_name: Optional[str] = None # 상호. 비우면 이름 → 아이디 순으로 채운다
|
||||
|
||||
|
||||
class Req_GoogleLogin(AuthProtocol):
|
||||
"""구글 로그인. 프론트(GIS)가 받은 ID 토큰을 그대로 넘긴다.
|
||||
|
||||
필드 이름이 `credential` 인 이유는 GIS 콜백이 주는 이름 그대로이기 때문이다 —
|
||||
`access_token`/`id_token` 으로 바꿔 부르면 우리 토큰과 헷갈린다."""
|
||||
|
||||
credential: str = ""
|
||||
|
||||
|
||||
class Res_Login(Res_WebPacketProtocol):
|
||||
access_token: str = ""
|
||||
refresh_token: str = ""
|
||||
@@ -47,4 +70,7 @@ class Res_Me(Res_WebPacketProtocol):
|
||||
email: Optional[str] = None
|
||||
contact_number: Optional[str] = None
|
||||
role: UserRole = UserRole.USER
|
||||
# 이 계정이 무엇으로 로그인하는가. 구글 계정에는 바꿀 비밀번호가 없어서(update_me 가 막는다)
|
||||
# 내 정보 화면이 붙을 때 이 값으로 갈라야 한다.
|
||||
provider: AuthProvider = AuthProvider.LOCAL
|
||||
company: Optional[CompanyData] = Field(default=None)
|
||||
@@ -1,7 +1,7 @@
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from fastapi import APIRouter, Depends, Query, Request
|
||||
|
||||
from common.enums import PlaceCategory, PlaceStatus
|
||||
from common.models.gmodel import PageParams, UserInfo
|
||||
@@ -22,6 +22,7 @@ from .protocol import (
|
||||
Res_LinkList,
|
||||
Res_Place,
|
||||
Res_PlaceList,
|
||||
Res_PlaceSearch,
|
||||
Res_StartCollect,
|
||||
Res_StartCopy,
|
||||
Res_StartVision,
|
||||
@@ -46,6 +47,26 @@ async def list_places(
|
||||
return RemoveNoneResponse(await service.list_places(user_info, pg, search, category, status))
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/search",
|
||||
response_model=Res_PlaceSearch,
|
||||
summary="상호명 공개 검색",
|
||||
description="상호명으로 외부 장소 DB(카카오 → 없으면 네이버)를 찾아 후보를 그대로 돌려준다. "
|
||||
"★ 인증이 없다 — 랜딩 첫 화면이 부른다. 사업장을 만들지도, 우리 DB 를 읽지도 않는다. "
|
||||
"★ 응답의 category 는 외부 분류에서 **추정한 기본값**이다. None 이면 못 정한 것이고, "
|
||||
"값이 있어도 확정이 아니다 — 화면은 언제나 바꿀 수 있게 둔다.",
|
||||
)
|
||||
async def search_places_public(
|
||||
request: Request,
|
||||
service: PlaceService = Depends(),
|
||||
q: str = Query(..., min_length=2, max_length=100, description="상호명"),
|
||||
):
|
||||
# ★ 이 라우트는 반드시 `/{place_id}` **앞에** 있어야 한다. FastAPI 는 등록 순서로 매칭해서,
|
||||
# 뒤에 두면 "search" 가 place_id 로 잡혀 422 가 난다 — 조용히 틀리는 종류다.
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
return RemoveNoneResponse(await service.search_places_public(q, client_ip))
|
||||
|
||||
|
||||
@router.post(
|
||||
path="",
|
||||
response_model=Res_Place,
|
||||
|
||||
@@ -208,6 +208,33 @@ class Res_VerifyCandidates(Res_WebPacketProtocol):
|
||||
candidates: list[PlaceCandidate] = []
|
||||
|
||||
|
||||
# ---- 공개 상호명 검색 (랜딩 첫 화면) ----------------------------------------
|
||||
class PlaceSearchItem(WebPacketProtocol):
|
||||
"""공개 검색 결과 1건.
|
||||
|
||||
★ 외부 장소 DB 가 공개적으로 주는 값만 담는다. 우리 DB 값(place_id·company_id·소유자)은
|
||||
하나도 나가지 않는다 — 로그인 없이 열려 있는 응답이라 여기에 우리 것을 실으면 그대로 샌다.
|
||||
★ 좌표·전화번호도 뺐다. 랜딩이 하는 일은 '어느 가게인지 고르게 하는 것'뿐이고,
|
||||
확정과 수집은 로그인 뒤 기존 경로(POST /place → verify)가 그대로 한다."""
|
||||
|
||||
name: str = ""
|
||||
road_address: Optional[str] = None
|
||||
category_name: Optional[str] = None # 외부 DB 의 분류 문자열(예: "숙박>펜션")
|
||||
# 추정 업종. ★ None 이면 못 정한 것이다 — 화면이 사장님에게 직접 고르게 한다.
|
||||
# 값이 있어도 확정이 아니다. 화면은 언제나 바꿀 수 있게 둔다(경계 업종이 실제로 있다).
|
||||
category: Optional[PlaceCategory] = None
|
||||
|
||||
|
||||
class Res_PlaceSearch(Res_WebPacketProtocol):
|
||||
"""상호명 공개 검색 결과.
|
||||
|
||||
★ 인증이 없다. 랜딩 첫 화면에서 상호명을 치면 바로 부른다 —
|
||||
만들어 보기도 전에 로그인을 요구하지 않기로 한 결정(로그인 관문은 에디터 진입 하나)의 연장이다."""
|
||||
|
||||
source: Optional[ExternalPlaceSource] = None
|
||||
items: list[PlaceSearchItem] = []
|
||||
|
||||
|
||||
class Req_StartCopy(PlaceProtocol):
|
||||
"""소개문·FAQ 생성 시작.
|
||||
|
||||
|
||||
@@ -4,7 +4,15 @@ from typing import Any, Optional
|
||||
|
||||
from pydantic import ConfigDict
|
||||
|
||||
from common.enums import BuildStatus, JobStatus, PublishAction, PublishRejectReason, PublishResult, SiteStatus
|
||||
from common.enums import (
|
||||
BuildStatus,
|
||||
JobStatus,
|
||||
PlaceCategory,
|
||||
PublishAction,
|
||||
PublishRejectReason,
|
||||
PublishResult,
|
||||
SiteStatus,
|
||||
)
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
@@ -54,6 +62,8 @@ class SiteData(WebPacketProtocol):
|
||||
theme: Optional[dict[str, Any]] = None
|
||||
current_version_id: Optional[uuid.UUID] = None
|
||||
published_at: Optional[datetime] = None
|
||||
# 발행 썸네일(Azure Blob 공개 URL). 대표 사진을 옮긴 것이고, 만들지 못했으면 없다.
|
||||
thumbnail_url: Optional[str] = None
|
||||
|
||||
|
||||
class PublishLogData(WebPacketProtocol):
|
||||
@@ -88,8 +98,8 @@ class Req_SiteTheme(SiteProtocol):
|
||||
|
||||
★ 그래서 필드를 펼치지 않고 dict 하나로 받는다. 계약은 이렇다:
|
||||
{"theme": {"colors": {...}, "fontStyle": "...", "colorPaletteId": "...", "sections": [...]}}
|
||||
sections 는 {id, name, enabled, locked, variantId?} 의 목록이고 **배열 순서가 곧 섹션 순서**다
|
||||
(별도 order 필드가 없다). variantId 는 고른 게 있을 때만 키가 붙는다.
|
||||
sections 는 {id, name, enabled, locked, variantId?, body?} 의 목록이고 **배열 순서가 곧 섹션 순서**다
|
||||
(별도 order 필드가 없다). variantId 와 직접 입력 본문 body 는 값이 있을 때만 키가 붙는다.
|
||||
pydantic 으로 모양을 고정하면 프론트가 항목을 추가한 순간 백엔드가 그걸 조용히 떨어뜨린다 —
|
||||
서버는 배달부지 심판이 아니다.
|
||||
|
||||
@@ -192,3 +202,24 @@ class Req_SiteStatus(SiteProtocol):
|
||||
색인된 페이지를 갑자기 404 로 만들면 그 자리를 다시 OTA 가 가져간다."""
|
||||
|
||||
action: PublishAction = PublishAction.SUSPEND
|
||||
|
||||
|
||||
class ShowcaseItem(WebPacketProtocol):
|
||||
"""랜딩 쇼케이스 카드 한 장. **로그인 없이 나가는 값이다.**
|
||||
|
||||
★ 여기 있는 것은 전부 이미 발행된 페이지에 적혀 있는 것뿐이다.
|
||||
place_id·company_id·전화번호·상세 주소는 절대 싣지 않는다 — 사이트 한 곳을 여는 것과
|
||||
발행 업소 명단을 통째로 긁는 것은 다른 일이다. 지역도 시·군·구까지만 준다."""
|
||||
|
||||
name: str
|
||||
category: PlaceCategory
|
||||
# "강원특별자치도 양양군" 수준. 주소를 못 읽으면 없다.
|
||||
region: Optional[str] = None
|
||||
# 발행 주소. 랜딩과 발행본이 한 오리진이라 루트 상대경로로 준다(`/s/<slug>`).
|
||||
url: str
|
||||
# 없으면 화면이 글자 카드로 떨어진다(썸네일은 발행의 부수 효과라 실패할 수 있다).
|
||||
thumbnail_url: Optional[str] = None
|
||||
|
||||
|
||||
class Res_Showcase(Res_WebPacketProtocol):
|
||||
items: list[ShowcaseItem] = []
|
||||
@@ -0,0 +1,24 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from router.v1.validator.dependencies import RemoveNoneResponse
|
||||
from services.showcase_service import ShowcaseService
|
||||
from .protocol import Res_Showcase
|
||||
|
||||
# 발행 사이트 쇼케이스. ★ 인증이 없다 — 랜딩(비로그인)이 부른다.
|
||||
# ★ :9801(어드민 진입점)에는 마운트하지 않는다. 내부 화면이 쓸 목록이 아니다.
|
||||
router = APIRouter(prefix="/v1/showcase", tags=["Showcase"], responses={404: {"description": "Not found"}})
|
||||
|
||||
|
||||
@router.get(
|
||||
path="",
|
||||
response_model=Res_Showcase,
|
||||
summary="발행 사이트 쇼케이스(공개)",
|
||||
description="실제로 발행된 사이트를 최신순으로 준다. 상호명·업종·지역(시·군·구까지)·발행 주소·썸네일뿐이다 — "
|
||||
"로그인 없이 나가므로 사업장 식별자·전화번호·상세 주소는 싣지 않는다. "
|
||||
"썸네일은 그 사이트의 대표 사진이고, 만들지 못한 사이트는 키가 없다.",
|
||||
)
|
||||
async def list_showcase(
|
||||
service: ShowcaseService = Depends(),
|
||||
limit: int = Query(12, ge=1, le=48, description="가져올 개수"),
|
||||
):
|
||||
return RemoveNoneResponse(await service.list(limit))
|
||||
@@ -106,7 +106,7 @@ async def set_template(
|
||||
description="에디터가 정한 색·서체·섹션(순서·on/off·배리에이션)을 sites.theme 에 저장한다"
|
||||
"(사이트 행이 없으면 만든다). body 최상위 키는 theme 하나다: "
|
||||
"{\"theme\":{\"colors\":{...},\"fontStyle\":\"...\",\"colorPaletteId\":\"...\","
|
||||
"\"sections\":[{\"id\",\"name\",\"enabled\",\"locked\",\"variantId\"}]}}. "
|
||||
"\"sections\":[{\"id\",\"name\",\"enabled\",\"locked\",\"variantId\",\"body\"}]}}. "
|
||||
"★ sections 의 배열 순서가 곧 섹션 순서다(별도 order 필드 없음). "
|
||||
"★ 서버는 값을 해석하지 않는다 — 섹션 목록·배리에이션 키·색 토큰은 프론트가 소유한다. "
|
||||
"직렬화 크기(64KB)만 막는다. "
|
||||
|
||||
@@ -1,14 +1,23 @@
|
||||
import re
|
||||
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.database.model.models import companies, users
|
||||
from common.enums import AuthProvider, CompanyStatus, 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.auth.protocol import (
|
||||
CompanyData,
|
||||
Req_GoogleLogin,
|
||||
Req_Signup,
|
||||
Req_UpdateMe,
|
||||
Res_Login,
|
||||
Res_Me,
|
||||
Res_RefreshToken,
|
||||
)
|
||||
from router.v1.validator.dependencies import (
|
||||
CreateAccessToken,
|
||||
CreateRefreshToken,
|
||||
@@ -16,6 +25,35 @@ from router.v1.validator.dependencies import (
|
||||
GetHashedPW,
|
||||
VerifyPW,
|
||||
)
|
||||
from services.external.google_identity import (
|
||||
GoogleAccount,
|
||||
GoogleNotConfigured,
|
||||
GoogleTokenInvalid,
|
||||
verify_id_token,
|
||||
)
|
||||
|
||||
# 로그인 아이디: 영문으로 시작하는 4~20자. 대소문자를 구분하지 않고 저장은 입력 그대로 한다.
|
||||
_LOGIN_ID_RE = re.compile(r"^[a-zA-Z][a-zA-Z0-9._-]{3,19}$")
|
||||
# 형식만 본다 — 이메일 소유 증명은 여기 없다(Req_Signup 주석).
|
||||
_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
||||
_MIN_PASSWORD_LEN = 8
|
||||
|
||||
# 구글 계정의 로그인 아이디 접두어. 사람이 이 접두어로 가입해 두면 같은 이름의 구글 계정이
|
||||
# 영영 못 만들어진다(유니크 충돌) — 가입 단계에서 막는다.
|
||||
_SOCIAL_ID_PREFIX = "google_"
|
||||
|
||||
|
||||
def _google_login_id(sub: str) -> str:
|
||||
"""구글 계정의 로그인 아이디. sub 를 그대로 붙인다 — 자르면 앞자리가 같은 두 계정이 겹친다."""
|
||||
return f"{_SOCIAL_ID_PREFIX}{sub}"
|
||||
|
||||
|
||||
def _fit(value: str | None, limit: int) -> str | None:
|
||||
"""컬럼 길이에 맞춰 자른다. 구글 표시 이름이나 사장님 입력이 길면 INSERT 가 통째로 터지는데,
|
||||
그건 "이름이 길다" 가 아니라 "가입이 안 된다" 로 보인다. 표시용 값이라 자르는 편이 낫다."""
|
||||
if value is None:
|
||||
return None
|
||||
return value[:limit]
|
||||
|
||||
|
||||
class AuthService:
|
||||
@@ -41,6 +79,29 @@ class AuthService:
|
||||
role=user.role,
|
||||
)
|
||||
|
||||
async def _finish_login(self, user: users) -> Res_Login:
|
||||
"""신원이 확인된 뒤의 마지막 단계 — id/pw 와 구글이 공유한다.
|
||||
|
||||
상태 확인 → 우리 토큰 발급 → 마지막 접속 갱신. 어느 수단으로 들어왔든 여기서부터는
|
||||
같은 세션이다(구글 토큰을 세션으로 들고 다니지 않는다)."""
|
||||
res = Res_Login()
|
||||
|
||||
if user.status != UserStatus.ACTIVE.value:
|
||||
res.result.SetResult(ErrorType.ACCOUNT_BLOCKED_USER)
|
||||
return res
|
||||
|
||||
user_info = self._user_info(user)
|
||||
res.access_token = CreateAccessToken(user_info)
|
||||
res.refresh_token = CreateRefreshToken(user_info)
|
||||
|
||||
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
|
||||
|
||||
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()
|
||||
@@ -57,31 +118,172 @@ class AuthService:
|
||||
return res
|
||||
user: users
|
||||
|
||||
# 2) 비밀번호 검증
|
||||
# 2) 소셜 계정에는 대조할 비밀번호가 없다.
|
||||
# 여기서 끊지 않으면 VerifyPW 가 None 해시를 만나 500 이 난다.
|
||||
# '아이디/비번 오류' 로 뭉개지 않는 이유: 화면이 "구글로 로그인하세요" 를 안내해야 한다.
|
||||
if user.provider != AuthProvider.LOCAL.value or not user.password:
|
||||
res.result.SetResult(ErrorType.ACCOUNT_PROVIDER_CONFLICT)
|
||||
return res
|
||||
|
||||
# 3) 비밀번호 검증
|
||||
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
|
||||
return await self._finish_login(user)
|
||||
|
||||
# 4) 토큰 발급
|
||||
user_info = self._user_info(user)
|
||||
res.access_token = CreateAccessToken(user_info)
|
||||
res.refresh_token = CreateRefreshToken(user_info)
|
||||
# ---- 가입 --------------------------------------------------------------
|
||||
async def _create_account(
|
||||
self,
|
||||
*,
|
||||
login_id: str,
|
||||
password_hash: str | None,
|
||||
name: str | None,
|
||||
email: str | None,
|
||||
company_name: str,
|
||||
provider: AuthProvider,
|
||||
provider_uid: str | None,
|
||||
) -> tuple[ErrorType, users]:
|
||||
"""회사 1개 + 그 회사의 첫 계정 1개를 한 트랜잭션으로 만든다.
|
||||
|
||||
# 5) 마지막 접속 시간 갱신 (Write DB, 트랜잭션)
|
||||
★ 가입은 곧 새 테넌트다. users.company_id 가 NOT NULL 이고 모든 도메인(사업장·사이트)이
|
||||
company_id 로 스코프되므로, 회사 없는 계정은 아무것도 만들지 못한다.
|
||||
★ uuid 를 여기서 미리 만든다. 모델 default 는 flush 시점에 적용돼서, 그 전에
|
||||
company.company_id 를 읽으면 None 이다 — 그대로 넣으면 NOT NULL 위반이다."""
|
||||
company_uuid = uuid.uuid4()
|
||||
company = companies(
|
||||
company_id=company_uuid,
|
||||
name=_fit(company_name, 100),
|
||||
email=_fit(email, 255),
|
||||
status=CompanyStatus.ACTIVE.value,
|
||||
)
|
||||
user = users(
|
||||
user_id=uuid.uuid4(),
|
||||
company_id=company_uuid,
|
||||
id=login_id,
|
||||
password=password_hash,
|
||||
name=_fit(name, 50),
|
||||
email=_fit(email, 255),
|
||||
status=UserStatus.ACTIVE.value,
|
||||
role=UserRole.USER.value,
|
||||
provider=provider.value,
|
||||
provider_uid=provider_uid,
|
||||
)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[users.DBType()],
|
||||
[lambda s: self.user_crud.update_last_accessed(s, user.user_id)],
|
||||
[
|
||||
lambda s: self.user_crud.add_company(s, company),
|
||||
lambda s: self.user_crud.add_user(s, user),
|
||||
],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def _email_taken(self, email: str) -> bool:
|
||||
err_type, existing = await DB_SESSION_MNG.execute_lambda(
|
||||
users.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.get_user_by_email(s, email),
|
||||
)
|
||||
return err_type == ErrorType.SUCCESS and existing is not None
|
||||
|
||||
async def signup(self, req: Req_Signup) -> Res_Login:
|
||||
"""id/pw 가입. 성공하면 곧바로 로그인 상태로 만든다(토큰을 실어 보낸다) —
|
||||
가입 직후 로그인 화면으로 되돌리면 방금 정한 비밀번호를 또 치게 된다."""
|
||||
res = Res_Login()
|
||||
login_id = req.id.strip()
|
||||
email = (req.email or "").strip().lower()
|
||||
name = (req.name or "").strip() or None
|
||||
|
||||
if not _LOGIN_ID_RE.match(login_id) or login_id.lower().startswith(_SOCIAL_ID_PREFIX):
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
if len(req.password) < _MIN_PASSWORD_LEN:
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
if not _EMAIL_RE.match(email):
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
|
||||
# 아이디 중복. is_user 는 "없으면 SUCCESS" 다 — 있으면 DB_ALREADY_SAME_KEY 를 준다.
|
||||
dup = await DB_SESSION_MNG.execute_lambda(
|
||||
users.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.is_user(s, login_id),
|
||||
)
|
||||
if dup != ErrorType.SUCCESS:
|
||||
res.result.SetResult(ErrorType.ACCOUNT_ALREADY_EXIST)
|
||||
return res
|
||||
|
||||
# 이메일 중복 — 구글로 이미 가입한 사람이 같은 이메일로 계정을 하나 더 만드는 걸 막는다.
|
||||
if await self._email_taken(email):
|
||||
res.result.SetResult(ErrorType.ACCOUNT_ALREADY_EXIST)
|
||||
return res
|
||||
|
||||
err_type, user = await self._create_account(
|
||||
login_id=login_id,
|
||||
password_hash=await GetHashedPW(req.password),
|
||||
name=name,
|
||||
email=email,
|
||||
company_name=(req.company_name or "").strip() or name or login_id,
|
||||
provider=AuthProvider.LOCAL,
|
||||
provider_uid=None,
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
return res
|
||||
LOG.i(f"SIGNUP : id={login_id}")
|
||||
return await self._finish_login(user)
|
||||
|
||||
# ---- 구글 로그인 --------------------------------------------------------
|
||||
async def google_login(self, req: Req_GoogleLogin) -> Res_Login:
|
||||
"""구글 ID 토큰 → 우리 세션. 처음 온 계정이면 그 자리에서 만든다(별도 가입 절차 없음)."""
|
||||
res = Res_Login()
|
||||
|
||||
try:
|
||||
account: GoogleAccount = await verify_id_token(req.credential)
|
||||
except GoogleNotConfigured:
|
||||
res.result.SetResult(ErrorType.OAUTH_NOT_CONFIGURED)
|
||||
return res
|
||||
except GoogleTokenInvalid:
|
||||
res.result.SetResult(ErrorType.OAUTH_INVALID_TOKEN)
|
||||
return res
|
||||
|
||||
# 1) 이미 있는 구글 계정인가 — 판정 키는 sub 다(이메일이 바뀌어도 같은 사람).
|
||||
err_type, user = await DB_SESSION_MNG.execute_lambda(
|
||||
users.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.get_user_by_provider_uid(s, AuthProvider.GOOGLE.value, account.sub),
|
||||
)
|
||||
if err_type == ErrorType.SUCCESS and user is not None:
|
||||
LOG.i(f"LOGIN(google) : sub={account.sub}")
|
||||
return await self._finish_login(user)
|
||||
|
||||
# 2) 같은 이메일이 다른 수단으로 이미 가입돼 있으면 **잇지 않는다.**
|
||||
# 자동으로 이으면, 남의 이메일로 먼저 만들어 둔 id/pw 계정에 그 사람의 구글 로그인이
|
||||
# 그대로 들어간다(계정 선점). 소유 증명 없이 잇는 건 로그인 하나를 통째로 넘기는 것이다.
|
||||
if account.email and await self._email_taken(account.email):
|
||||
res.result.SetResult(ErrorType.ACCOUNT_PROVIDER_CONFLICT)
|
||||
return res
|
||||
|
||||
# 3) 첫 방문 — 계정과 회사를 만든다.
|
||||
err_type, user = await self._create_account(
|
||||
login_id=_google_login_id(account.sub),
|
||||
password_hash=None,
|
||||
name=account.name or None,
|
||||
email=account.email or None,
|
||||
company_name=account.name or account.email or _google_login_id(account.sub),
|
||||
provider=AuthProvider.GOOGLE,
|
||||
provider_uid=account.sub,
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
LOG.i(f"SIGNUP(google) : sub={account.sub}")
|
||||
return await self._finish_login(user)
|
||||
|
||||
async def get_me(self, user_info: UserInfo) -> Res_Me:
|
||||
res = Res_Me()
|
||||
@@ -113,6 +315,7 @@ class AuthService:
|
||||
res.email = user.email
|
||||
res.contact_number = user.contact_number
|
||||
res.role = UserRole(user.role)
|
||||
res.provider = AuthProvider(user.provider)
|
||||
res.company = company
|
||||
return res
|
||||
|
||||
@@ -122,6 +325,22 @@ class AuthService:
|
||||
|
||||
# 비밀번호: 값 있으면 해시 교체, 비었으면 변경 안 함.
|
||||
if data.get("password"):
|
||||
# 구글 계정에 비밀번호를 심으면 id/pw 로도 열리는 반쪽 계정이 된다 —
|
||||
# 로그인 수단이 둘인데 어느 쪽도 상대를 모르는 상태다. 받지 않는다.
|
||||
if len(data["password"]) < _MIN_PASSWORD_LEN:
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
err_type, me = 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_NOT_FOUND)
|
||||
return res
|
||||
if me.provider != AuthProvider.LOCAL.value:
|
||||
res.result.SetResult(ErrorType.ACCOUNT_PROVIDER_CONFLICT)
|
||||
return res
|
||||
data["password"] = await GetHashedPW(data["password"])
|
||||
else:
|
||||
data.pop("password", None)
|
||||
|
||||
@@ -29,7 +29,7 @@ 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 import azure_static, indexnow, publish_gate, render_report, site_payload, site_thumbnail
|
||||
from services.site_payload import emit_payload
|
||||
from services.snapshot import build_snapshot
|
||||
|
||||
@@ -200,7 +200,10 @@ async def run_build(job: dict) -> dict:
|
||||
)
|
||||
|
||||
mismatches = list(report.get("mismatches") or [])
|
||||
unique_count = report.get("uniqueContentCount") or 0
|
||||
# ★ None(재지 못했다)과 0(재 봤더니 0건)을 뭉개지 않는다. 게이트는 raw 를 보고,
|
||||
# 기록·화면에는 0 으로 떨어뜨린다. 뭉개면 디스크 오류가 NO_UNIQUE_CONTENT 로 둔갑한다.
|
||||
unique_count_raw = report.get("uniqueContentCount")
|
||||
unique_count = unique_count_raw or 0
|
||||
jsonld = report.get("jsonld") or []
|
||||
result["unique_content_count"] = unique_count
|
||||
result["mismatches"] = mismatches[:20]
|
||||
@@ -211,17 +214,29 @@ async def run_build(job: dict) -> dict:
|
||||
# 대개 게이트 사유(고유 콘텐츠 0건·구조화 데이터 불일치)이기 때문이다.
|
||||
# 여기서 사유를 정확히 골라야 publish_logs 에 '무엇을 고쳐야 하는지' 가 남는다 —
|
||||
# 전부 "렌더 실패"로 뭉뚱그리면 운영자가 손댈 곳을 알 수 없다.
|
||||
gate = publish_gate.evaluate(PlaceCategory(place.category), snapshot["facts"], unique_count, mismatches)
|
||||
gate = publish_gate.evaluate(
|
||||
PlaceCategory(place.category), snapshot["facts"], unique_count_raw, 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 파손). 재시도가 의미 있는 쪽이다.
|
||||
# ★ 렌더러가 거부한 이유에 사유 코드를 붙인다. evaluate() 는 얇은 콘텐츠로 막지
|
||||
# 않지만 렌더러는 스팸 판정을 피하려 페이지 쓰기를 거부한다 — 그 사유를 "렌더 실패"
|
||||
# 로 뭉개면 화면이 NO_UNIQUE_CONTENT 문구를 못 고르고, 사장님은 손댈 곳을 모른다.
|
||||
thin = publish_gate.check_unique_content(unique_count_raw)
|
||||
if not thin.passed:
|
||||
# 위에서 evaluate 결과로 채워 둔 gate 를 덮는다 — 화면(GateRejectCard)은 이 값으로
|
||||
# 문구를 고르는데, passed=True 인 채로 두면 "서버 검수를 통과하지 못했습니다" 만 뜬다.
|
||||
result["gate"] = {"passed": False, **thin.as_log()}
|
||||
return await _fail(f"{thin.reason.name}: {thin.as_log()}", thin, stamp)
|
||||
# 나머지는 게이트로 설명되지 않는 실패(디스크·번들·payload 파손). 재시도가 의미 있다.
|
||||
return await _fail(str(report.get("error") or "렌더 실패"), None, stamp)
|
||||
|
||||
# DB 발행 상태를 바꾸기 전에 정적 파일을 외부 저장소에 올린다.
|
||||
thumbnail_url = None
|
||||
if want_publish:
|
||||
try:
|
||||
azure_result = await azure_static.publish(slug)
|
||||
@@ -229,6 +244,11 @@ async def run_build(job: dict) -> dict:
|
||||
return await _fail(str(ex), None, stamp)
|
||||
if azure_result:
|
||||
result["azure"] = azure_result
|
||||
# ★ 페이지가 실제로 올라간 뒤에 썸네일을 남긴다 — 없는 페이지의 그림을 쇼케이스에 걸지 않는다.
|
||||
# 실패해도 발행은 성공이다(스크린샷이 아니라 대표 사진이라, 없으면 글자 카드로 떨어진다).
|
||||
thumbnail_url = await site_thumbnail.store(slug, snapshot)
|
||||
if thumbnail_url:
|
||||
result["thumbnail_url"] = thumbnail_url
|
||||
# ★ 정적 파일이 올라간 **뒤에** 통보한다. 먼저 알리면 크롤러가 옛 파일을 가져간다.
|
||||
# 실패해도 발행은 성공이다 — 색인 통보는 부수 효과이고, 다음 발행에서 다시 보낸다.
|
||||
indexnow_result = await indexnow.submit(slug)
|
||||
@@ -255,13 +275,17 @@ async def run_build(job: dict) -> dict:
|
||||
result["routes"] = report.get("routes")
|
||||
|
||||
if want_publish:
|
||||
# 썸네일은 발행 상태 전이와 같은 UPDATE 에 싣는다 — 못 만들었으면 키를 넣지 않아
|
||||
# 지난 발행의 그림이 그대로 남는다(NULL 로 밀어 카드를 비우지 않는다).
|
||||
site_update = {
|
||||
"status": SiteStatus.PUBLISHED.value,
|
||||
"current_version_id": version.site_version_id,
|
||||
"published_at": now,
|
||||
**({"thumbnail_url": thumbnail_url} if thumbnail_url else {}),
|
||||
}
|
||||
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},
|
||||
),
|
||||
lambda s: _site_crud.update_site(s, site.site_id, site_update),
|
||||
)
|
||||
# ★ 사업장 상태도 같이 올린다. 여기서 안 올리면 places.status 는 영원히 REVIEW 라,
|
||||
# 발행을 마친 가게가 사업장 목록에서 '발행 전'으로 남는다 — 사장님은 목록만 보고
|
||||
@@ -277,6 +301,8 @@ async def run_build(job: dict) -> dict:
|
||||
site.status = SiteStatus.PUBLISHED.value
|
||||
site.current_version_id = version.site_version_id
|
||||
site.published_at = now
|
||||
if thumbnail_url:
|
||||
site.thumbnail_url = thumbnail_url
|
||||
result["published"] = True
|
||||
LOG.i(f"[build] place={place_id} v{version_no} 발행 완료 "
|
||||
f"(고유 콘텐츠 {unique_count}건 · {report.get('routes')} 페이지)")
|
||||
|
||||
@@ -29,7 +29,7 @@ _CATEGORY_BY_NAME = {
|
||||
"lodging": PlaceCategory.LODGING,
|
||||
"cafe": PlaceCategory.CAFE,
|
||||
"restaurant": PlaceCategory.RESTAURANT,
|
||||
"tour_activity": PlaceCategory.TOUR_ACTIVITY,
|
||||
"clinic": PlaceCategory.CLINIC,
|
||||
}
|
||||
|
||||
_CHANNEL_BY_NAME = {c.name.lower(): c for c in LinkChannel}
|
||||
@@ -86,16 +86,18 @@ _PLACE_FACTS = {
|
||||
("signature_menu", "한우 물회"),
|
||||
("price_range", "15,000~30,000원"),
|
||||
],
|
||||
PlaceCategory.TOUR_ACTIVITY: [
|
||||
("operating_hours", "09:00~18:00"),
|
||||
("closed_days", "매주 수요일"),
|
||||
PlaceCategory.CLINIC: [
|
||||
("operating_hours", "평일 10:00~19:00, 토 10:00~14:00"),
|
||||
("closed_days", "일요일·공휴일"),
|
||||
("specialties", "피부과, 성형외과"),
|
||||
("medical_staff", "피부과 전문의 2인, 성형외과 전문의 1인"),
|
||||
("reservation_required", "true"),
|
||||
("reservation_channel", "네이버 예약"),
|
||||
("cancel_policy", "체험 3일 전까지 100% 환불, 당일 취소 불가"),
|
||||
("age_limit", "만 7세 이상"),
|
||||
("safety_notice", "구명조끼 착용 필수, 음주 후 참여 불가"),
|
||||
("weather_dependent", "우천 시 당일 오전 8시에 개별 안내"),
|
||||
("what_to_bring", "여벌 옷, 수건"),
|
||||
("reservation_channel", "네이버 예약, 전화"),
|
||||
("consultation_fee", "초진 상담료 없음"),
|
||||
("insurance_covered", "질환 치료는 보험 적용, 미용 시술은 비급여"),
|
||||
("cancel_policy", "예약 1일 전까지 변경 가능, 당일 취소는 재예약 제한"),
|
||||
("night_clinic", "목요일 21:00까지"),
|
||||
("weekend_clinic", "토요일 14:00까지"),
|
||||
("parking", "true"),
|
||||
],
|
||||
}
|
||||
@@ -130,19 +132,21 @@ _UNIT_FACTS = {
|
||||
"한우 물회": [("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"),
|
||||
PlaceCategory.CLINIC: {
|
||||
"레이저 토닝": [
|
||||
("program_name", "레이저 토닝"),
|
||||
("program_duration", "30"),
|
||||
("price_adult", "100000"),
|
||||
("anesthesia", "마취 없음"),
|
||||
("downtime", "당일 일상생활 가능"),
|
||||
("session_count", "5회 권장"),
|
||||
],
|
||||
"패들보드 체험": [
|
||||
("program_name", "패들보드 체험"),
|
||||
("program_duration", "90"),
|
||||
("program_capacity", "6"),
|
||||
("price_adult", "55000"),
|
||||
"보톡스": [
|
||||
("program_name", "보톡스"),
|
||||
("program_duration", "20"),
|
||||
("price_adult", "150000"),
|
||||
("anesthesia", "연고 마취"),
|
||||
("downtime", "1~2일 미세 부기"),
|
||||
],
|
||||
},
|
||||
}
|
||||
@@ -168,11 +172,11 @@ _MEDIA = {
|
||||
("한우 물회", "한우 물회"),
|
||||
("성게 비빔밥", "성게 비빔밥"),
|
||||
],
|
||||
PlaceCategory.TOUR_ACTIVITY: [
|
||||
("해변 전경", None),
|
||||
("장비 보관소", None),
|
||||
("서핑 강습", "서핑 입문 클래스"),
|
||||
("패들보드", "패들보드 체험"),
|
||||
PlaceCategory.CLINIC: [
|
||||
("병원 외관", None),
|
||||
("상담실", None),
|
||||
("레이저 장비", "레이저 토닝"),
|
||||
("시술실", "보톡스"),
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
"""구글 ID 토큰 검증 — "이 토큰이 정말 구글이 **우리 앱에** 발급한 것인가" 만 본다.
|
||||
|
||||
프론트(Google Identity Services)가 받아 온 ID 토큰을 그대로 우리 백엔드로 보내면,
|
||||
여기서 구글 공개키로 서명을 확인하고 신원(sub·email)을 꺼낸다. 그 뒤로는 우리 JWT 다 —
|
||||
구글 토큰을 세션으로 들고 다니지 않는다.
|
||||
|
||||
★ 왜 client_secret 이 없나
|
||||
코드 교환(authorization code flow)을 하지 않기 때문이다. GIS 는 브라우저에서 ID 토큰을
|
||||
바로 준다. 서버가 할 일은 교환이 아니라 **검증**이고, 검증에 필요한 건 공개키와 client_id 뿐이다.
|
||||
|
||||
★ 반드시 남겨야 할 검사 세 가지 (하나만 빠져도 조용히 뚫린다)
|
||||
1. 서명 — 구글 JWKS 의 공개키로. 이게 없으면 아무나 JSON 을 만들어 보낸다.
|
||||
2. aud — 우리 client_id 와 같아야 한다. 없으면 **다른 서비스에 발급된 진짜 구글 토큰**을
|
||||
그대로 들고 와서 우리 계정이 된다(가장 흔한 구멍이다).
|
||||
3. iss — accounts.google.com. 서명과 함께 발급자를 못 박는다.
|
||||
email_verified 도 함께 본다 — 미인증 이메일을 신원으로 쓰면 이메일 기반 판단이 전부 흔들린다.
|
||||
|
||||
★ 공개키는 돌아간다(rotation). kid 가 캐시에 없으면 한 번 다시 받는다 —
|
||||
TTL 만 믿고 있으면 키가 바뀐 직후 몇 분 동안 전원 로그인 실패다.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
|
||||
import httpx
|
||||
from jose import jwt, JWTError
|
||||
|
||||
from common.logger import LOG
|
||||
from config.server_configs import google_oauth_config
|
||||
|
||||
# 구글 공개키(JWKS). OpenID discovery 를 매번 타지 않고 고정 주소를 쓴다 — 구글이 바꾸지 않는 주소다.
|
||||
_JWKS_URL = "https://www.googleapis.com/oauth2/v3/certs"
|
||||
|
||||
# 구글은 두 표기를 모두 쓴다. 한쪽만 받으면 어느 날 갑자기 전원 로그인 실패다.
|
||||
_ISSUERS = ("accounts.google.com", "https://accounts.google.com")
|
||||
|
||||
# 캐시 수명. 구글 응답의 Cache-Control 은 보통 수 시간이라 1시간은 넉넉히 보수적이다.
|
||||
_JWKS_TTL_SEC = 3600
|
||||
|
||||
_HTTP_TIMEOUT_SEC = 5.0
|
||||
|
||||
_jwks: dict | None = None
|
||||
_jwks_at: float = 0.0
|
||||
# 토큰이 동시에 여러 개 들어와도 JWKS 는 한 번만 받는다.
|
||||
_jwks_lock = asyncio.Lock()
|
||||
|
||||
|
||||
class GoogleNotConfigured(RuntimeError):
|
||||
"""GOOGLE_CLIENT_ID 미설정 — 구글 로그인만 꺼진다. 서버는 뜬다."""
|
||||
|
||||
|
||||
class GoogleTokenInvalid(RuntimeError):
|
||||
"""서명·수신자(aud)·발급자(iss)·만료 중 하나라도 어긋났다."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class GoogleAccount:
|
||||
"""ID 토큰에서 꺼낸 신원. 여기 없는 값은 쓰지 않는다."""
|
||||
|
||||
sub: str # 구글 계정의 영구 식별자. 이메일이 바뀌어도 유지된다 — 계정 매칭 키는 이것뿐이다.
|
||||
email: str
|
||||
name: str
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
return bool(google_oauth_config.client_id)
|
||||
|
||||
|
||||
async def _fetch_jwks() -> dict:
|
||||
async with httpx.AsyncClient(timeout=_HTTP_TIMEOUT_SEC) as client:
|
||||
res = await client.get(_JWKS_URL)
|
||||
res.raise_for_status()
|
||||
return res.json()
|
||||
|
||||
|
||||
async def _get_jwks(*, force: bool = False) -> dict:
|
||||
global _jwks, _jwks_at
|
||||
async with _jwks_lock:
|
||||
fresh = _jwks is not None and (time.monotonic() - _jwks_at) < _JWKS_TTL_SEC
|
||||
if fresh and not force:
|
||||
return _jwks
|
||||
try:
|
||||
_jwks = await _fetch_jwks()
|
||||
_jwks_at = time.monotonic()
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(f"[GOOGLE] JWKS 조회 실패: {ex}")
|
||||
# 낡은 캐시라도 있으면 그걸로 간다 — 구글이 잠깐 안 될 때 로그인 전체가 죽는 것보다 낫다.
|
||||
if _jwks is None:
|
||||
raise GoogleTokenInvalid("JWKS unavailable") from ex
|
||||
return _jwks
|
||||
|
||||
|
||||
def _has_kid(jwks: dict, kid: str | None) -> bool:
|
||||
return any(key.get("kid") == kid for key in (jwks.get("keys") or []))
|
||||
|
||||
|
||||
async def verify_id_token(id_token: str) -> GoogleAccount:
|
||||
if not is_configured():
|
||||
raise GoogleNotConfigured("GOOGLE_CLIENT_ID 가 비어 있다")
|
||||
if not id_token:
|
||||
raise GoogleTokenInvalid("empty token")
|
||||
|
||||
try:
|
||||
kid = jwt.get_unverified_header(id_token).get("kid")
|
||||
except JWTError as ex:
|
||||
raise GoogleTokenInvalid("malformed token") from ex
|
||||
|
||||
jwks = await _get_jwks()
|
||||
# 키 회전 직후: 캐시에 없는 kid 면 한 번만 다시 받는다.
|
||||
if not _has_kid(jwks, kid):
|
||||
jwks = await _get_jwks(force=True)
|
||||
|
||||
try:
|
||||
claims = jwt.decode(
|
||||
id_token,
|
||||
jwks,
|
||||
algorithms=["RS256"],
|
||||
audience=google_oauth_config.client_id,
|
||||
issuer=_ISSUERS,
|
||||
# at_hash 는 access_token 과 짝일 때만 의미가 있다. GIS 크리덴셜에는 access_token 이
|
||||
# 없으므로 켜 두면 "access_token 이 없다"는 이유로 정상 토큰이 거부된다.
|
||||
options={"verify_at_hash": False},
|
||||
)
|
||||
except JWTError as ex:
|
||||
# 이유를 사용자에게 흘리지 않는다 — 로그에만 남긴다.
|
||||
LOG.w(f"[GOOGLE] ID 토큰 거부: {ex}")
|
||||
raise GoogleTokenInvalid(str(ex)) from ex
|
||||
|
||||
sub = str(claims.get("sub") or "")
|
||||
email = str(claims.get("email") or "")
|
||||
if not sub:
|
||||
raise GoogleTokenInvalid("no sub")
|
||||
# 미인증 이메일은 신원으로 쓸 수 없다 — 남의 주소를 적어 둔 계정일 수 있다.
|
||||
if not claims.get("email_verified"):
|
||||
raise GoogleTokenInvalid("email not verified")
|
||||
|
||||
return GoogleAccount(sub=sub, email=email, name=str(claims.get("name") or ""))
|
||||
+4
@@ -97,6 +97,9 @@ class KakaoPlace:
|
||||
latitude: Optional[float] # y
|
||||
longitude: Optional[float] # x
|
||||
category_name: Optional[str]
|
||||
# ★ 업종 자동 판별의 입력. 한글 분류(category_name)는 카카오가 언제든 바꾸지만 이 코드는 안 바뀐다 —
|
||||
# AD5 숙박 · CE7 카페 · FD6 음식점 · HP8 병원. 매핑은 services/place_category.py 가 소유한다.
|
||||
category_group_code: Optional[str]
|
||||
place_url: Optional[str]
|
||||
|
||||
@classmethod
|
||||
@@ -110,6 +113,7 @@ class KakaoPlace:
|
||||
latitude=_to_float(doc.get("y")), # ★ y = 위도
|
||||
longitude=_to_float(doc.get("x")), # ★ x = 경도
|
||||
category_name=(doc.get("category_name") or None),
|
||||
category_group_code=(doc.get("category_group_code") or None),
|
||||
place_url=(doc.get("place_url") or None),
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""외부 장소 DB 의 분류 → 우리 업종(PlaceCategory).
|
||||
|
||||
★ 업종 판별에 LLM 을 부르지 않는다. 상호명으로 카카오·네이버를 부르는 건 어차피 하는 일이고,
|
||||
그 응답에 분류가 함께 온다(`category_name`, 카카오는 `category_group_code` 까지).
|
||||
지금까지 받아 놓고 쓰지 않았을 뿐이다 — 여기서 그 값을 업종으로 옮긴다.
|
||||
|
||||
★ 못 정하면 None 이다. 억지로 하나를 고르지 않는다. 업종은 수집 스키마와 JSON-LD 타입을
|
||||
통째로 정하는 값이라, 틀린 업종으로 시작하면 되돌리는 비용이 크다.
|
||||
None 이면 화면이 사장님에게 직접 묻는다.
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from common.enums import PlaceCategory
|
||||
|
||||
# 카카오 category_group_code. 한글 분류 문자열은 카카오가 언제든 바꾸지만 이 코드는 안 바뀐다.
|
||||
# ★ HP8(병원)은 여기 없다 — 병원 전체가 아니라 피부과·성형외과만 열려 있어서,
|
||||
# 코드만으로는 우리 업종인지 알 수 없다. 아래 키워드로 한 번 더 좁힌다.
|
||||
_BY_GROUP_CODE = {
|
||||
"AD5": PlaceCategory.LODGING,
|
||||
"CE7": PlaceCategory.CAFE,
|
||||
"FD6": PlaceCategory.RESTAURANT,
|
||||
}
|
||||
_HOSPITAL_GROUP_CODE = "HP8"
|
||||
|
||||
# 분류 문자열 키워드. 네이버는 group_code 를 주지 않아 이 경로만 탄다.
|
||||
# ★ 순서가 결과를 바꾼다. 카카오·네이버 모두 카페를 "음식점 > 카페" 아래 두기 때문에
|
||||
# CAFE 를 RESTAURANT 보다 먼저 봐야 한다. 뒤집으면 카페가 전부 음식점이 된다.
|
||||
_KEYWORDS: list[tuple[PlaceCategory, tuple[str, ...]]] = [
|
||||
# ★ "피부"·"성형" 이 아니라 "피부과"·"성형외과" 다. 앞의 둘로 보면 피부관리실(에스테틱)이
|
||||
# 병원으로 걸린다 — 의료 광고 규제가 걸리는 업종이라 잘못 붙이면 가장 비싸다.
|
||||
(PlaceCategory.CLINIC, ("피부과", "성형외과")),
|
||||
(PlaceCategory.LODGING, ("숙박", "펜션", "호텔", "모텔", "리조트", "게스트하우스", "민박")),
|
||||
(PlaceCategory.CAFE, ("카페", "커피", "베이커리", "제과", "디저트")),
|
||||
(PlaceCategory.RESTAURANT, ("음식점", "한식", "일식", "중식", "양식", "분식",
|
||||
"주점", "술집", "치킨", "횟집", "뷔페", "패스트푸드")),
|
||||
]
|
||||
|
||||
|
||||
def guess_category(
|
||||
category_name: Optional[str], group_code: Optional[str] = None
|
||||
) -> Optional[PlaceCategory]:
|
||||
"""분류 문자열(+ 카카오 그룹코드)로 업종을 추정한다. 모르면 None.
|
||||
|
||||
category_name 예 — 카카오 "가정,생활 > 숙박 > 펜션" · 네이버 "숙박>펜션"
|
||||
"""
|
||||
text = (category_name or "").replace(" ", "")
|
||||
code = (group_code or "").strip().upper()
|
||||
|
||||
if code == _HOSPITAL_GROUP_CODE:
|
||||
# 병원이라는 것까지만 안다. 진료과가 문자열에 없으면 우리 업종인지 알 수 없다.
|
||||
return PlaceCategory.CLINIC if _match(text) is PlaceCategory.CLINIC else None
|
||||
|
||||
if code in _BY_GROUP_CODE:
|
||||
by_code = _BY_GROUP_CODE[code]
|
||||
# ★ 그룹코드를 문자열로 덮는 경우가 하나 있다: 카카오가 베이커리·브런치 가게를
|
||||
# FD6(음식점)으로 주면서 분류 문자열엔 "카페"를 다는 일이 있다. 어느 쪽이 맞는지는
|
||||
# 실측하지 않았다 — 사장님이 바꿀 수 있으니 이름이 더 구체적인 쪽을 기본값으로 둔다.
|
||||
if by_code is PlaceCategory.RESTAURANT and _match(text) is PlaceCategory.CAFE:
|
||||
return PlaceCategory.CAFE
|
||||
return by_code
|
||||
|
||||
return _match(text)
|
||||
|
||||
|
||||
def _match(text: str) -> Optional[PlaceCategory]:
|
||||
for category, words in _KEYWORDS:
|
||||
if any(word in text for word in words):
|
||||
return category
|
||||
return None
|
||||
@@ -28,8 +28,10 @@ from router.v1.place.protocol import (
|
||||
Res_LinkList,
|
||||
Res_Place,
|
||||
Res_PlaceList,
|
||||
Res_PlaceSearch,
|
||||
Res_VerifyCandidates,
|
||||
PlaceCandidate,
|
||||
PlaceSearchItem,
|
||||
Res_StartCollect,
|
||||
Res_StartCopy,
|
||||
Res_StartVision,
|
||||
@@ -37,6 +39,12 @@ from router.v1.place.protocol import (
|
||||
Res_UnitList,
|
||||
)
|
||||
from router.v1.job.protocol import JobData, Res_Job
|
||||
|
||||
# 공개 검색이 한 번에 가져오는 후보 수. 카카오 키워드 검색은 무료 한도를 넘기면 건당 과금이라
|
||||
# 확정 경로(15건)보다 좁게 잡는다 — 랜딩에서 사람이 훑는 목록은 다섯이면 충분하다.
|
||||
_PUBLIC_SEARCH_SIZE = 5
|
||||
# IP 당 분당 허용 횟수. 사람이 상호명을 고쳐 가며 치는 속도를 넘지 않게 잡았다.
|
||||
_PUBLIC_SEARCH_PER_MIN = 20
|
||||
# 도로명주소 → 지역 캐시 키. 외부 장소 DB 는 행정구역 코드를 주지 않으므로 여기서 만든다.
|
||||
from services.external.naver import region_key
|
||||
from services.job_service import enqueue_job
|
||||
@@ -582,6 +590,74 @@ class PlaceService:
|
||||
return res
|
||||
|
||||
# ---- 동일 업소 후보 조회 (UI 가 사람에게 고르게 한다) ----
|
||||
# ---- 공개 상호명 검색 (랜딩 첫 화면) ----
|
||||
async def search_places_public(self, query: str, client_ip: str) -> Res_PlaceSearch:
|
||||
"""상호명으로 외부 장소 DB 를 찾아 그대로 돌려준다. **인증도, 사업장 행도 없다.**
|
||||
|
||||
★ find_candidates 와 무엇이 다른가: 저쪽은 이미 만들어진 사업장의 신원을 확정하는
|
||||
경로라 place_id 와 로그인이 필요하다. 여기는 아직 아무것도 만들지 않은 사람이
|
||||
"내 가게가 있나" 를 보는 경로다 — 만들어 보기도 전에 로그인을 요구하지 않기로 한
|
||||
결정(로그인 관문은 에디터 진입 하나)이 API 까지 내려온 것이다.
|
||||
|
||||
★ pick_match 를 돌리지 않는다. 자동 판정은 확정 경로에서만 의미가 있고,
|
||||
여기서는 사람이 목록에서 고르는 게 전부다.
|
||||
|
||||
★ DB 를 읽지도 쓰지도 않는다. 나가는 값은 외부 장소 DB 가 공개적으로 주는 것뿐이다.
|
||||
"""
|
||||
from common.enums import ExternalPlaceSource
|
||||
from common.utils import rate_limit
|
||||
from services.external import kakao as kakao_client
|
||||
from services.external import naver as naver_client
|
||||
from services.place_category import guess_category
|
||||
|
||||
res = Res_PlaceSearch()
|
||||
q = (query or "").strip()
|
||||
if len(q) < 2:
|
||||
res.result.SetResult(ErrorType.INVALID_REQUEST_DATA)
|
||||
return res
|
||||
|
||||
# ★ 인증이 없는데 유료 외부 API 를 부른다 — 방어가 0 이면 새로고침만으로 요금이 나간다.
|
||||
# 프로세스 메모리 기반이라 완전하지 않다(common/utils/rate_limit.py 주석).
|
||||
if not rate_limit.allow(f"place-search:{client_ip}", _PUBLIC_SEARCH_PER_MIN, 60.0):
|
||||
res.result.SetResult(ErrorType.HTTP_TO_MANY_REQUEST)
|
||||
return res
|
||||
|
||||
kakao = kakao_client.KakaoLocalClient()
|
||||
try:
|
||||
if kakao.enabled:
|
||||
res.source = ExternalPlaceSource.KAKAO
|
||||
rows = await kakao.search_keyword(q, size=_PUBLIC_SEARCH_SIZE)
|
||||
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
|
||||
rows = await client.search_local(q, display=_PUBLIC_SEARCH_SIZE)
|
||||
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"[search] 공개 검색 실패 q={q!r}: {type(ex).__name__}: {ex}")
|
||||
res.result.SetResult(ErrorType.LOCAL_FETCH_FAILED)
|
||||
return res
|
||||
|
||||
res.items = [
|
||||
PlaceSearchItem(
|
||||
name=row.name,
|
||||
road_address=row.road_address or row.address,
|
||||
category_name=row.category_name,
|
||||
# 네이버는 그룹코드를 주지 않는다 — 그때는 분류 문자열만으로 추정한다.
|
||||
category=guess_category(row.category_name, getattr(row, "category_group_code", None)),
|
||||
)
|
||||
for row in rows
|
||||
]
|
||||
if not res.items:
|
||||
res.result.SetResult(ErrorType.PLACE_VERIFY_NO_CANDIDATE)
|
||||
return res
|
||||
|
||||
async def find_candidates(self, user_info: UserInfo, place_id: str, query: str | None = None) -> Res_VerifyCandidates:
|
||||
"""외부 장소 DB 에서 이 상호명의 후보를 찾아 그대로 내려준다.
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ _CATEGORY_LABEL = {
|
||||
PlaceCategory.LODGING: "숙박업소",
|
||||
PlaceCategory.CAFE: "카페",
|
||||
PlaceCategory.RESTAURANT: "음식점",
|
||||
PlaceCategory.TOUR_ACTIVITY: "관광·체험 시설",
|
||||
PlaceCategory.CLINIC: "관광·체험 시설",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ _LABELS = {
|
||||
PlaceCategory.LODGING: ["외관", "침실", "거실", "욕실", "주방", "수영장", "바비큐장", "주차장", "전망", "부대시설"],
|
||||
PlaceCategory.CAFE: ["외관", "내부", "좌석", "메뉴", "디저트", "음료", "테라스", "주차장"],
|
||||
PlaceCategory.RESTAURANT: ["외관", "내부", "좌석", "메뉴", "음식", "룸", "주차장"],
|
||||
PlaceCategory.TOUR_ACTIVITY: ["외관", "시설", "장비", "활동", "안전장비", "주차장", "매표소"],
|
||||
PlaceCategory.CLINIC: ["외관", "시설", "장비", "활동", "안전장비", "주차장", "매표소"],
|
||||
}
|
||||
_DEFAULT_LABELS = ["외관", "내부", "시설", "기타"]
|
||||
|
||||
|
||||
@@ -63,11 +63,20 @@ def check_required_fields(category: PlaceCategory, facts: list) -> GateResult:
|
||||
return GateResult(True)
|
||||
|
||||
|
||||
def check_unique_content(unique_content_count: int) -> GateResult:
|
||||
"""고유 콘텐츠 품질 진단용. 발행 게이트에서는 더 이상 호출하지 않는다.
|
||||
def check_unique_content(unique_content_count: int | None) -> GateResult:
|
||||
"""렌더러가 '고유 콘텐츠 0건' 으로 거부했을 때 사유 코드를 붙이는 자리.
|
||||
|
||||
evaluate() 는 이걸 부르지 않는다(얇은 콘텐츠로 발행을 막지 않기로 했다).
|
||||
부르는 곳은 build_service — 렌더 보고서가 실패로 왔을 때 그 이유를 되짚는다.
|
||||
|
||||
이 가게에만 있는 것(소개문·FAQ·객실 설명·사진 alt·템플릿 아닌 fact 값)이 0이면
|
||||
같은 템플릿 대량 생성으로 보인다. 그건 스팸 판정 대상이고, 판정되면 사이트가 통째로 무의미해진다."""
|
||||
같은 템플릿 대량 생성으로 보인다. 그건 스팸 판정 대상이고, 판정되면 사이트가 통째로 무의미해진다.
|
||||
|
||||
★ None 은 '0건' 이 아니라 '재지 못했다' 다. 렌더러가 디스크·번들 문제로 죽으면 계수가
|
||||
없는 채로 보고서가 온다 — 그걸 0 으로 읽으면 디스크 오류에 NO_UNIQUE_CONTENT 라는
|
||||
엉뚱한 사유가 붙는다. 판정하지 않고 통과시키고, 진짜 사유는 report.error 가 말한다."""
|
||||
if unique_content_count is None:
|
||||
return GateResult(True)
|
||||
if unique_content_count <= 0:
|
||||
return GateResult(False, PublishRejectReason.NO_UNIQUE_CONTENT, {"unique_content_count": unique_content_count})
|
||||
return GateResult(True)
|
||||
@@ -83,11 +92,17 @@ def check_jsonld_matches(mismatches: list) -> GateResult:
|
||||
return GateResult(True)
|
||||
|
||||
|
||||
def evaluate(category: PlaceCategory, facts: list, unique_content_count: int, mismatches: list) -> GateResult:
|
||||
def evaluate(
|
||||
category: PlaceCategory, facts: list, unique_content_count: int | None, mismatches: list
|
||||
) -> GateResult:
|
||||
"""게이트 전체. **처음 걸린 것에서 멈춘다** — 운영자가 하나씩 고치게 사유를 하나만 준다.
|
||||
|
||||
순서는 심각도 순: 미검증(클레임) → JSON-LD 불일치(거짓).
|
||||
|
||||
★ unique_content_count 는 받되 여기서 막지 않는다 — 얇은 콘텐츠는 '틀린 것' 이 아니다
|
||||
(test_evaluate_does_not_block_thin_content). 실제로 페이지 쓰기를 거부하는 쪽은
|
||||
렌더러이고, 그 사유는 build_service 가 check_unique_content 로 되짚어 라벨을 붙인다.
|
||||
|
||||
★ 업종 필수 항목 누락은 **막지 않는다**(2026-08-27 결정).
|
||||
막아야 할 것은 "틀린 정보가 나가는 것"이지 "정보가 덜 찬 것"이 아니다.
|
||||
영업시간이 비어 있어도 주소·전화가 확인된 페이지는 그 자체로 쓸모가 있고,
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""랜딩(비로그인)이 읽는 발행 사이트 목록.
|
||||
|
||||
★ 이 파일이 따로 있는 이유는 **경계를 눈에 보이게 두기 위해서**다. 나머지 site 서비스는
|
||||
전부 로그인 + 회사 스코프 안에서 돈다. 여기만 아무나 부른다 — 그래서 무엇을 내보낼지
|
||||
고르는 자리를 한 곳으로 모았다. 사이트 한 곳을 여는 것과 발행 업소 명단을 통째로
|
||||
긁는 것은 다른 일이라, 페이지에 이미 적혀 있는 것만 나간다.
|
||||
|
||||
나가지 않는 것: place_id · company_id · site_id · 전화번호 · 상세 주소 · 좌표.
|
||||
"""
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import sites
|
||||
from common.enums import DBWRType, ErrorType
|
||||
from crud.site_crud import SiteCRUD
|
||||
from router.v1.site.protocol import Res_Showcase, ShowcaseItem
|
||||
from services import site_payload
|
||||
|
||||
|
||||
class ShowcaseService:
|
||||
def __init__(self):
|
||||
self.crud = SiteCRUD()
|
||||
|
||||
async def list(self, limit: int) -> Res_Showcase:
|
||||
res = Res_Showcase()
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
sites.DBType(), DBWRType.DB_READ.value, lambda s: self.crud.list_published(s, limit)
|
||||
)
|
||||
res.result.SetResult(err)
|
||||
if err != ErrorType.SUCCESS:
|
||||
return res
|
||||
|
||||
res.items = [
|
||||
ShowcaseItem(
|
||||
name=place.name,
|
||||
category=place.category,
|
||||
region=site_payload.region_label(place.road_address, place.address),
|
||||
# ★ 주소 규칙은 site_payload 한 곳뿐이다 — 여기서 다시 만들면
|
||||
# 카드가 가리키는 곳과 실제 발행 주소가 갈린다(CLAUDE.md '슬러그 규칙은 두 곳').
|
||||
url=f"/s/{site_payload.publish_slug(place, site)}",
|
||||
thumbnail_url=site.thumbnail_url,
|
||||
)
|
||||
for site, place in rows
|
||||
]
|
||||
return res
|
||||
@@ -108,16 +108,16 @@ _DEFAULT_THEME = {
|
||||
("local", "주변 안내", False), ("faq", "자주 묻는 질문", False),
|
||||
],
|
||||
},
|
||||
PlaceCategory.TOUR_ACTIVITY.value: {
|
||||
"templateId": "tour-visual-tour",
|
||||
PlaceCategory.CLINIC.value: {
|
||||
"templateId": "clinic-visual-clinic",
|
||||
"fontStyle": "Visual Journey",
|
||||
"colors": {"primary": "#0f172a", "secondary": "#475569", "bg": "#ffffff",
|
||||
"card": "#f8fafc", "text": "#020617", "accent": "#0284c7"},
|
||||
"card": "#f8fafc", "text": "#020617", "accent": "#4A9DC4"},
|
||||
"sections": [
|
||||
("hero", "히어로", True), ("intro", "소개", False), ("programs", "체험 프로그램", False),
|
||||
("info", "기본 정보", True), ("exhibition", "관람 및 갤러리 안내", False), ("photos", "사진 갤러리", False),
|
||||
("inquiry", "단체 및 출강 문의", False), ("map", "오시는 길", True), ("weather", "날씨", False),
|
||||
("local", "주변 관광 코스", False), ("faq", "자주 묻는 질문", False),
|
||||
("hero", "히어로", True), ("intro", "병원 소개", False), ("programs", "시술 안내", False),
|
||||
("info", "기본 정보", True), ("exhibition", "진료 안내", False), ("photos", "사진 갤러리", False),
|
||||
("inquiry", "상담 문의", False), ("map", "오시는 길", True), ("weather", "날씨", False),
|
||||
("local", "주변 정보", False), ("faq", "자주 묻는 질문", False),
|
||||
],
|
||||
},
|
||||
}
|
||||
@@ -363,6 +363,15 @@ def _sections(saved_sections, default_spec) -> list:
|
||||
variant_id = _text(item.get("variantId"))
|
||||
if variant_id:
|
||||
entry["variantId"] = variant_id
|
||||
# ★ 사장님이 에디터에 직접 쓴 섹션 본문. variantId 와 같은 이유로 그대로 싣는다 —
|
||||
# 이 필드가 없던 동안 캔버스에 쓴 소개문은 payload 경계에서 통째로 버려졌다.
|
||||
# 저장(sites.theme)은 되는데 발행본에는 안 나오고, 고유 콘텐츠로도 세지 않아
|
||||
# "소개를 썼는데 발행이 고유 콘텐츠 0건으로 막힌다" 가 됐다.
|
||||
# ★ fact 가 아니라 검증 대상이 아니다. 사장님이 자기 가게에 대해 쓴 자기 문장이고,
|
||||
# 섹션 제목(name)이 이미 같은 경로로 나간다.
|
||||
body = _text(item.get("body"))
|
||||
if body:
|
||||
entry["body"] = body
|
||||
out.append(entry)
|
||||
|
||||
for sid, label, locked in default_spec:
|
||||
@@ -540,6 +549,33 @@ def publish_slug(place, site) -> str:
|
||||
return _publish_target(site, str(_get(place, "place_id") or ""), _text(_get(place, "name")))["slug"]
|
||||
|
||||
|
||||
def publish_origin() -> str:
|
||||
"""발행본이 사는 오리진. 썸네일 URL 도 여기서 나온다 —
|
||||
호스트를 새 env 로 또 두면 canonical 과 갈릴 수 있다(CLAUDE.md '발행 호스트는 두 곳')."""
|
||||
return f"https://{DEFAULT_HOST}"
|
||||
|
||||
|
||||
def primary_media(snapshot: dict) -> dict | None:
|
||||
"""대표 사진(og:image) — 객실·메뉴 전용이 아닌 첫 장. 없으면 None.
|
||||
|
||||
★ 썸네일도 이 함수를 쓴다. 규칙을 복제하면 검색 결과에 뜨는 그림과
|
||||
쇼케이스 카드가 다른 사진이 되고, 그건 아무도 눈치채지 못한다."""
|
||||
for row in (snapshot or {}).get("media") or []:
|
||||
if not row.get("unit_id"):
|
||||
return row
|
||||
return None
|
||||
|
||||
|
||||
def region_label(*addresses: str | None) -> str | None:
|
||||
""""강원특별자치도 양양군" — 시·도 + 시·군·구까지만.
|
||||
|
||||
★ 상세 주소는 붙이지 않는다. 로그인 없이 읽히는 목록(쇼케이스)에 쓰이므로
|
||||
'어느 동네인지' 를 넘어서면 안 된다."""
|
||||
parts = _parse_address_parts(*addresses)
|
||||
label = " ".join(p for p in (parts.get("addressRegion"), parts.get("addressLocality")) if p)
|
||||
return label or None
|
||||
|
||||
|
||||
# ── payload 조립 ──────────────────────────────────────────────────────────
|
||||
def to_site_payload(place, snapshot: dict, site, version, links) -> dict:
|
||||
"""스냅샷 + 사이트/버전 행 + 채널 링크 → SitePayload(dict).
|
||||
@@ -568,12 +604,10 @@ def to_site_payload(place, snapshot: dict, site, version, links) -> dict:
|
||||
# ★ sourceType/originUrl 을 반드시 싣는다 — 크롤링 이미지 재게시 권리가 미결이라(DECISIONS 1-2)
|
||||
# 결론이 나면 출처로 걸러낼 수 있어야 한다. 출처를 버리면 그때 다시 수집해야 한다.
|
||||
media = []
|
||||
primary_done = False
|
||||
primary_row = primary_media(snapshot)
|
||||
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
|
||||
is_primary = row is primary_row
|
||||
media.append({
|
||||
"mediaId": str(row.get("media_id") or f"m-{index}"),
|
||||
"url": row.get("url"),
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
"""발행한 사이트의 썸네일을 Azure Blob 에 남긴다 — 랜딩 쇼케이스 카드가 쓰는 그림.
|
||||
|
||||
★ **스크린샷이 아니다.** 헤드리스 브라우저는 이 레포에서 영구 금지고(docs/DECISIONS.md 1-1),
|
||||
워커(python:3.12-slim)에도 프리렌더(node:24-alpine)에도 Chromium 이 없다. 그걸 넣으면
|
||||
이미지가 수백 MB 늘고, 금지해 둔 도구가 다른 목적으로 상비되는 셈이 된다.
|
||||
대신 **그 사이트의 대표 사진(og:image)** 을 그대로 옮긴다 — 검색 결과에 뜨는 그림과
|
||||
쇼케이스 카드가 같은 사진이 된다. 대표 사진 선정은 site_payload.primary_media 한 곳뿐이다.
|
||||
|
||||
★ 블롭 경로는 사이트 디렉터리(`s/<slug>/`) **밖**이다.
|
||||
azure_static._remove_stale_site_files 가 매 발행마다 `s/<slug>/` 를 프리렌더 산출물로
|
||||
통째로 교체하므로, 그 안에 두면 다음 발행에서 조용히 사라진다.
|
||||
|
||||
★ 실패해도 발행을 되돌리지 않는다(emit_payload·indexnow 와 같은 원칙). 그림이 없으면
|
||||
쇼케이스가 글자 카드로 떨어질 뿐이고, 발행 자체는 이미 정확하다.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
import httpx
|
||||
from azure.storage.blob import BlobServiceClient, ContentSettings
|
||||
|
||||
from common.logger import LOG
|
||||
from services import azure_static, site_payload
|
||||
|
||||
# 사이트 경로 밖의 전용 디렉터리. 여기는 발행이 지우지 않는다.
|
||||
THUMB_DIR = "thumbs"
|
||||
|
||||
# 허용 content-type → 저장 확장자. 목록 밖이면 받지 않는다 —
|
||||
# 이미지가 아닌 응답(HTML 오류 페이지 등)을 그대로 올리면 카드가 깨진 그림이 된다.
|
||||
_EXT_BY_TYPE = {
|
||||
"image/jpeg": "jpg",
|
||||
"image/png": "png",
|
||||
"image/gif": "gif",
|
||||
"image/webp": "webp",
|
||||
}
|
||||
|
||||
# 남의 CDN 을 부르는 길이다. 상한이 없으면 발행 잡이 여기서 굳는다.
|
||||
TIMEOUT_SEC = 10.0
|
||||
# 리다이렉트는 따라가되 무한정은 안 된다(CDN 은 보통 1~2회).
|
||||
MAX_REDIRECTS = 3
|
||||
# 5MB. 사진 한 장이 이보다 크면 카드에 쓸 그림이 아니라 다른 것이 왔다고 본다.
|
||||
MAX_BYTES = 5 * 1024 * 1024
|
||||
|
||||
# 썸네일은 재발행마다 바뀔 수 있고 주소는 그대로다 — 길게 캐시하면 옛 그림이 계속 뜬다.
|
||||
CACHE_CONTROL = "public, max-age=60, must-revalidate"
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
return azure_static.is_configured()
|
||||
|
||||
|
||||
def blob_name(slug: str, ext: str) -> str:
|
||||
prefix = os.environ.get("AZURE_STORAGE_PREFIX", azure_static.DEFAULT_PREFIX).strip().strip("/")
|
||||
return "/".join(part for part in (prefix, THUMB_DIR, f"{slug}.{ext}") if part)
|
||||
|
||||
|
||||
def public_url(slug: str, ext: str) -> str:
|
||||
"""공개 주소. 발행 사이트와 같은 오리진이다 — 접두사는 오리진 경로로 흡수된다
|
||||
(CLAUDE.md 'AZURE_STORAGE_PREFIX 와 루트 절대경로는 충돌한다')."""
|
||||
return f"{site_payload.publish_origin()}/{THUMB_DIR}/{slug}.{ext}"
|
||||
|
||||
|
||||
async def _fetch(url: str) -> tuple[bytes, str, str] | None:
|
||||
"""대표 사진을 받아온다. (바이트, content-type, 확장자) 또는 None."""
|
||||
if not url.lower().startswith(("http://", "https://")):
|
||||
LOG.w(f"[thumbnail] 받아올 수 없는 주소다: {url[:120]}")
|
||||
return None
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient(
|
||||
timeout=TIMEOUT_SEC, follow_redirects=True, max_redirects=MAX_REDIRECTS
|
||||
) as client:
|
||||
async with client.stream("GET", url) as res:
|
||||
if res.status_code != 200:
|
||||
LOG.w(f"[thumbnail] 사진을 받지 못했다 HTTP {res.status_code}: {url[:120]}")
|
||||
return None
|
||||
|
||||
content_type = (res.headers.get("content-type") or "").split(";")[0].strip().lower()
|
||||
ext = _EXT_BY_TYPE.get(content_type)
|
||||
if not ext:
|
||||
LOG.w(f"[thumbnail] 이미지가 아니다(content-type={content_type or '없음'}): {url[:120]}")
|
||||
return None
|
||||
|
||||
# Content-Length 가 있으면 한 바이트도 받기 전에 자른다.
|
||||
declared = res.headers.get("content-length")
|
||||
if declared and declared.isdigit() and int(declared) > MAX_BYTES:
|
||||
LOG.w(f"[thumbnail] 사진이 너무 크다({declared} bytes): {url[:120]}")
|
||||
return None
|
||||
|
||||
chunks: list[bytes] = []
|
||||
size = 0
|
||||
async for chunk in res.aiter_bytes():
|
||||
size += len(chunk)
|
||||
# Content-Length 를 안 주는 서버가 있다 — 받으면서도 상한을 본다.
|
||||
if size > MAX_BYTES:
|
||||
LOG.w(f"[thumbnail] 사진이 너무 크다(>{MAX_BYTES} bytes): {url[:120]}")
|
||||
return None
|
||||
chunks.append(chunk)
|
||||
except httpx.HTTPError as ex:
|
||||
LOG.w(f"[thumbnail] 사진을 받지 못했다 {type(ex).__name__}: {ex}")
|
||||
return None
|
||||
|
||||
data = b"".join(chunks)
|
||||
if not data:
|
||||
LOG.w(f"[thumbnail] 빈 응답이다: {url[:120]}")
|
||||
return None
|
||||
return data, content_type, ext
|
||||
|
||||
|
||||
def _upload_sync(slug: str, data: bytes, content_type: str, ext: str) -> str:
|
||||
connection_string = os.environ["AZURE_STORAGE_CONNECTION_STRING"].strip()
|
||||
container_name = (
|
||||
os.environ.get("AZURE_STORAGE_CONTAINER", azure_static.DEFAULT_CONTAINER).strip()
|
||||
or azure_static.DEFAULT_CONTAINER
|
||||
)
|
||||
service = BlobServiceClient.from_connection_string(connection_string)
|
||||
container = service.get_container_client(container_name)
|
||||
name = blob_name(slug, ext)
|
||||
container.upload_blob(
|
||||
name=name,
|
||||
data=data,
|
||||
overwrite=True,
|
||||
# cache_control 은 ContentSettings 에 담아야 블롭 속성으로 실제로 박힌다.
|
||||
content_settings=ContentSettings(content_type=content_type, cache_control=CACHE_CONTROL),
|
||||
)
|
||||
return name
|
||||
|
||||
|
||||
async def store(slug: str, snapshot: dict) -> str | None:
|
||||
"""대표 사진을 썸네일로 올리고 공개 URL 을 돌려준다. 못 하면 None(발행은 그대로 간다).
|
||||
|
||||
SDK 의 동기 I/O 는 별도 스레드에서 돈다 — azure_static.publish 와 같은 이유로,
|
||||
이벤트 루프를 붙잡으면 같은 워커의 다른 잡이 통째로 멈춘다."""
|
||||
if not is_configured():
|
||||
return None
|
||||
|
||||
row = site_payload.primary_media(snapshot)
|
||||
url = str((row or {}).get("url") or "").strip()
|
||||
if not url:
|
||||
LOG.w(f"[thumbnail] 대표 사진이 없다 — 썸네일 없이 발행한다: {slug}")
|
||||
return None
|
||||
|
||||
fetched = await _fetch(url)
|
||||
if fetched is None:
|
||||
return None
|
||||
data, content_type, ext = fetched
|
||||
|
||||
try:
|
||||
name = await asyncio.to_thread(_upload_sync, slug, data, content_type, ext)
|
||||
except Exception as ex: # noqa: BLE001 — 어떤 이유로도 발행을 되돌리지 않는다
|
||||
LOG.w(f"[thumbnail] 업로드 실패(발행은 그대로 진행): {type(ex).__name__}: {ex}")
|
||||
return None
|
||||
|
||||
LOG.i(f"[thumbnail] {slug} → {name} ({len(data)} bytes · {content_type})")
|
||||
return public_url(slug, ext)
|
||||
@@ -41,3 +41,119 @@ async def test_me_without_token_is_rejected(client):
|
||||
기대결과: 인증 단계에서 거부 — HTTP 401 또는 403."""
|
||||
r = await client.get("/v1/auth/me")
|
||||
assert r.status_code in (401, 403)
|
||||
|
||||
|
||||
# ── 가입(id/pw) ──────────────────────────────────────────────────────────────
|
||||
_SIGNUP = {"id": "sajang1", "password": "pw12345678", "name": "김사장", "email": "boss@example.com"}
|
||||
|
||||
|
||||
async def test_signup_creates_account_and_logs_in(client, db_engine):
|
||||
"""검증: 가입 → 받은 토큰으로 곧바로 /me.
|
||||
기대결과: 토큰이 실려 오고, /me 가 방금 만든 신원과 **새로 생긴 소속사**를 돌려준다."""
|
||||
r = await client.post("/v1/auth/signup", json=_SIGNUP)
|
||||
body = r.json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["access_token"] and body["refresh_token"]
|
||||
|
||||
me = (await client.get("/v1/auth/me", headers={"Authorization": f"Bearer {body['access_token']}"})).json()
|
||||
assert me["id"] == "sajang1"
|
||||
assert me["email"] == "boss@example.com"
|
||||
assert me["provider"] == 1 # AuthProvider.LOCAL
|
||||
assert me["company"]["name"] == "김사장" # 회사명 미입력 → 이름으로 채운다
|
||||
|
||||
|
||||
async def test_signup_rejects_duplicate_id(client, db_engine):
|
||||
"""검증: 같은 아이디로 두 번 가입.
|
||||
기대결과: 두 번째는 1101(ACCOUNT_ALREADY_EXIST) — 이메일만 달라도 막힌다."""
|
||||
await client.post("/v1/auth/signup", json=_SIGNUP)
|
||||
r = await client.post("/v1/auth/signup", json={**_SIGNUP, "email": "other@example.com"})
|
||||
assert r.json()["result"]["code"] == 1101
|
||||
|
||||
|
||||
async def test_signup_rejects_duplicate_email(client, db_engine):
|
||||
"""검증: 아이디는 다른데 이메일이 같은 가입.
|
||||
기대결과: 1101 — 한 사람에게 계정이 둘 생기는 걸 이메일에서 끊는다."""
|
||||
await client.post("/v1/auth/signup", json=_SIGNUP)
|
||||
r = await client.post("/v1/auth/signup", json={**_SIGNUP, "id": "sajang2"})
|
||||
assert r.json()["result"]["code"] == 1101
|
||||
|
||||
|
||||
async def test_signup_rejects_weak_input(client, db_engine):
|
||||
"""검증: 짧은 비밀번호 / 규칙에 안 맞는 아이디 / 형식이 아닌 이메일.
|
||||
기대결과: 전부 101(INVALID_REQUEST_DATA) — 서버가 마지막 방어선이다(화면 검사만 믿지 않는다)."""
|
||||
for bad in (
|
||||
{**_SIGNUP, "password": "short"},
|
||||
{**_SIGNUP, "id": "1abc"}, # 영문으로 시작해야 한다
|
||||
{**_SIGNUP, "id": "ab"}, # 4자 미만
|
||||
{**_SIGNUP, "id": "google_12345"}, # 구글 계정 아이디 접두어는 선점 금지
|
||||
{**_SIGNUP, "email": "not-an-email"},
|
||||
):
|
||||
r = await client.post("/v1/auth/signup", json=bad)
|
||||
assert r.json()["result"]["code"] == 101, bad
|
||||
|
||||
|
||||
# ── 구글 로그인 ──────────────────────────────────────────────────────────────
|
||||
def _stub_google(monkeypatch, *, sub="1234567890", email="g@example.com", name="구글유저"):
|
||||
"""ID 토큰 검증을 대역으로 바꾼다. 서명 검증 자체는 test_google_identity.py 가 본다."""
|
||||
from services.external.google_identity import GoogleAccount
|
||||
|
||||
async def _verify(_credential):
|
||||
return GoogleAccount(sub=sub, email=email, name=name)
|
||||
|
||||
monkeypatch.setattr("services.auth_service.verify_id_token", _verify)
|
||||
|
||||
|
||||
async def test_google_login_creates_then_reuses_account(client, db_engine, monkeypatch):
|
||||
"""검증: 같은 구글 계정으로 두 번 로그인.
|
||||
기대결과: 첫 번째에 계정이 생기고, 두 번째는 **같은 user_id** 로 붙는다(계정이 늘지 않는다)."""
|
||||
_stub_google(monkeypatch)
|
||||
|
||||
first = (await client.post("/v1/auth/google", json={"credential": "x"})).json()
|
||||
assert first["result"]["success"] is True
|
||||
me1 = (await client.get("/v1/auth/me", headers={"Authorization": f"Bearer {first['access_token']}"})).json()
|
||||
assert me1["provider"] == 2 # AuthProvider.GOOGLE
|
||||
assert me1["id"] == "google_1234567890"
|
||||
|
||||
second = (await client.post("/v1/auth/google", json={"credential": "x"})).json()
|
||||
me2 = (await client.get("/v1/auth/me", headers={"Authorization": f"Bearer {second['access_token']}"})).json()
|
||||
assert me2["user_id"] == me1["user_id"]
|
||||
|
||||
|
||||
async def test_google_login_follows_sub_not_email(client, db_engine, monkeypatch):
|
||||
"""검증: 같은 sub 인데 구글 쪽 이메일이 바뀐 경우.
|
||||
기대결과: 같은 계정으로 들어온다 — 매칭 키가 이메일이 아니라 sub 라서."""
|
||||
_stub_google(monkeypatch, email="before@example.com")
|
||||
first = (await client.post("/v1/auth/google", json={"credential": "x"})).json()
|
||||
me1 = (await client.get("/v1/auth/me", headers={"Authorization": f"Bearer {first['access_token']}"})).json()
|
||||
|
||||
_stub_google(monkeypatch, email="after@example.com")
|
||||
second = (await client.post("/v1/auth/google", json={"credential": "x"})).json()
|
||||
me2 = (await client.get("/v1/auth/me", headers={"Authorization": f"Bearer {second['access_token']}"})).json()
|
||||
assert me2["user_id"] == me1["user_id"]
|
||||
|
||||
|
||||
async def test_google_login_refuses_to_link_existing_local_account(client, db_engine, monkeypatch):
|
||||
"""검증: id/pw 로 이미 가입된 이메일로 구글 로그인.
|
||||
기대결과: 1105(ACCOUNT_PROVIDER_CONFLICT) — 소유 증명 없이 잇지 않는다(계정 선점 방지)."""
|
||||
await client.post("/v1/auth/signup", json=_SIGNUP)
|
||||
|
||||
_stub_google(monkeypatch, email=_SIGNUP["email"])
|
||||
r = await client.post("/v1/auth/google", json={"credential": "x"})
|
||||
assert r.json()["result"]["code"] == 1105
|
||||
|
||||
|
||||
async def test_password_login_against_google_account_is_refused(client, db_engine, monkeypatch):
|
||||
"""검증: 구글로 만들어진 계정에 id/pw 로그인 시도.
|
||||
기대결과: 1105 — 500 이 아니다(대조할 비밀번호가 없는 계정이라 해시 검증에 들어가면 터진다)."""
|
||||
_stub_google(monkeypatch)
|
||||
await client.post("/v1/auth/google", json={"credential": "x"})
|
||||
|
||||
r = await client.post("/v1/auth/login", json={"id": "google_1234567890", "password": "whatever"})
|
||||
assert r.json()["result"]["code"] == 1105
|
||||
|
||||
|
||||
async def test_google_login_is_off_when_client_id_is_empty(client, db_engine):
|
||||
"""검증: GOOGLE_CLIENT_ID 가 비어 있을 때(테스트 기본값) 구글 로그인 호출.
|
||||
기대결과: 1106(OAUTH_NOT_CONFIGURED) — 네트워크를 타지 않고 즉시 끊긴다."""
|
||||
r = await client.post("/v1/auth/google", json={"credential": "anything"})
|
||||
assert r.json()["result"]["code"] == 1106
|
||||
@@ -136,6 +136,29 @@ async def test_no_unique_content_blocks_publish(auth_headers, client):
|
||||
assert r["gate"]["reason"] == PublishRejectReason.NO_UNIQUE_CONTENT.name
|
||||
|
||||
|
||||
async def test_owner_written_intro_counts_as_unique_content(auth_headers, client):
|
||||
"""검증: fact·FAQ·사진 설명은 없지만 사장님이 소개 섹션 본문을 직접 썼다.
|
||||
기대결과: 실제 발행본에 표시되는 소개문 1건으로 계수되어 발행된다."""
|
||||
h = await auth_headers("owner-intro")
|
||||
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/theme", headers=h, json={"theme": {"sections": [{
|
||||
"id": "intro", "name": "소개", "enabled": True, "locked": False,
|
||||
"body": "하조대의 아침 바다를 조용히 바라볼 수 있는 작은 숙소입니다.",
|
||||
}]}})
|
||||
|
||||
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["unique_content_count"] == 1
|
||||
assert r["published"] is True
|
||||
|
||||
|
||||
async def test_missing_required_field_warns_but_publishes(auth_headers, client, db_engine):
|
||||
"""검증: 취소 규정 없이 빌드한다.
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ from common.enums import PlaceCategory
|
||||
|
||||
def test_all_categories_have_schema():
|
||||
"""검증: PlaceCategory 의 모든 업종에 스키마 파일이 있는지.
|
||||
기대결과: 4개 업종(숙박·카페·음식점·관광체험)이 모두 로드되고 code 가 1:1로 맞는다."""
|
||||
기대결과: 4개 업종(숙박·카페·음식점·피부과·성형외과)이 모두 로드되고 code 가 1:1로 맞는다."""
|
||||
schemas = all_schemas()
|
||||
assert set(schemas) == {c.value for c in PlaceCategory}
|
||||
for code, schema in schemas.items():
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
.env 에 APP_ENV=local 이 들어 있어도 테스트는 반드시 test DB 를 봐야 한다 —
|
||||
그 규칙이 깨지면 db_engine 픽스처의 TRUNCATE 가 dev DB 를 지운다.
|
||||
"""
|
||||
from config.server_configs import APP_ENV, external_api_config, main_db_config
|
||||
from config.server_configs import APP_ENV, external_api_config, google_oauth_config, main_db_config
|
||||
|
||||
|
||||
def test_tests_run_against_test_db():
|
||||
@@ -20,3 +20,5 @@ def test_external_api_keys_are_absent_in_tests():
|
||||
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 가 새어 들어왔다"
|
||||
# 구글 client_id 도 같은 규칙이다. 이게 새어 들어오면 구글 로그인 테스트가 진짜 JWKS 를 받으러 나간다.
|
||||
assert not google_oauth_config.client_id, "GOOGLE_CLIENT_ID 가 테스트 환경에 설정돼 있다 — .env 가 새어 들어왔다"
|
||||
@@ -0,0 +1,144 @@
|
||||
"""구글 ID 토큰 검증 — 서명·수신자(aud)·발급자(iss)·이메일 인증.
|
||||
|
||||
★ 왜 대역이 아니라 진짜 서명을 쓰나
|
||||
이 파일이 지키는 건 "우리가 받아들이면 안 되는 토큰을 거부하는가" 하나다. 검증 함수를
|
||||
대역으로 바꾸면 그 질문 자체가 사라진다. 그래서 여기서는 테스트용 RSA 키를 만들어 **진짜로
|
||||
서명하고**, 구글 공개키 조회(_fetch_jwks)만 그 키로 바꿔 끼운다. 네트워크는 타지 않는다.
|
||||
|
||||
특히 aud 검사: 남의 서비스에 발급된 **진짜 구글 토큰**을 그대로 우리 서버에 보내면
|
||||
서명도 발급자도 전부 맞다. 그걸 거르는 검사는 aud 하나뿐이다.
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from jose import jwk
|
||||
from jose import jwt as jose_jwt
|
||||
|
||||
from services.external import google_identity
|
||||
from services.external.google_identity import GoogleNotConfigured, GoogleTokenInvalid, verify_id_token
|
||||
|
||||
_KID = "test-key-1"
|
||||
_CLIENT_ID = "our-app.apps.googleusercontent.com"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def keypair():
|
||||
"""테스트 전용 RSA 키 → (서명용 PEM, 구글 JWKS 를 흉내 낸 공개키 묶음)."""
|
||||
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
private_pem = key.private_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PrivateFormat.PKCS8,
|
||||
encryption_algorithm=serialization.NoEncryption(),
|
||||
).decode()
|
||||
public_pem = key.public_key().public_bytes(
|
||||
encoding=serialization.Encoding.PEM,
|
||||
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
||||
).decode()
|
||||
|
||||
entry = {k: (v.decode() if isinstance(v, bytes) else v) for k, v in jwk.construct(public_pem, "RS256").to_dict().items()}
|
||||
entry["kid"] = _KID
|
||||
return private_pem, {"keys": [entry]}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def google_configured(monkeypatch, keypair):
|
||||
"""client_id 를 채우고 JWKS 조회를 테스트 키로 바꾼다. 캐시는 테스트마다 비운다."""
|
||||
_, jwks = keypair
|
||||
monkeypatch.setattr(google_identity.google_oauth_config, "client_id", _CLIENT_ID)
|
||||
|
||||
async def _fetch():
|
||||
return jwks
|
||||
|
||||
monkeypatch.setattr(google_identity, "_fetch_jwks", _fetch)
|
||||
monkeypatch.setattr(google_identity, "_jwks", None)
|
||||
monkeypatch.setattr(google_identity, "_jwks_at", 0.0)
|
||||
|
||||
|
||||
def _token(keypair, **overrides) -> str:
|
||||
private_pem, _ = keypair
|
||||
claims = {
|
||||
"iss": "https://accounts.google.com",
|
||||
"aud": _CLIENT_ID,
|
||||
"sub": "1234567890",
|
||||
"email": "boss@example.com",
|
||||
"email_verified": True,
|
||||
"name": "김사장",
|
||||
"exp": int(time.time()) + 600,
|
||||
"iat": int(time.time()),
|
||||
}
|
||||
claims.update(overrides)
|
||||
return jose_jwt.encode(claims, private_pem, algorithm="RS256", headers={"kid": _KID})
|
||||
|
||||
|
||||
async def test_valid_token_yields_identity(keypair):
|
||||
"""검증: 우리 client_id 로 발급된 정상 토큰.
|
||||
기대결과: sub·email·name 이 그대로 나온다."""
|
||||
account = await verify_id_token(_token(keypair))
|
||||
assert account.sub == "1234567890"
|
||||
assert account.email == "boss@example.com"
|
||||
assert account.name == "김사장"
|
||||
|
||||
|
||||
async def test_token_for_another_app_is_refused(keypair):
|
||||
"""검증: 서명·발급자는 진짜인데 aud 가 **다른 서비스**인 토큰.
|
||||
기대결과: 거부 — 이 검사가 없으면 남의 앱 토큰으로 우리 계정에 들어온다."""
|
||||
with pytest.raises(GoogleTokenInvalid):
|
||||
await verify_id_token(_token(keypair, aud="someone-else.apps.googleusercontent.com"))
|
||||
|
||||
|
||||
async def test_token_from_another_issuer_is_refused(keypair):
|
||||
"""검증: 우리 aud 를 달고 있지만 iss 가 구글이 아닌 토큰.
|
||||
기대결과: 거부."""
|
||||
with pytest.raises(GoogleTokenInvalid):
|
||||
await verify_id_token(_token(keypair, iss="https://evil.example.com"))
|
||||
|
||||
|
||||
async def test_expired_token_is_refused(keypair):
|
||||
"""검증: 만료된 토큰.
|
||||
기대결과: 거부 — 한 번 새어 나간 토큰이 영원히 열쇠가 되지 않게."""
|
||||
with pytest.raises(GoogleTokenInvalid):
|
||||
await verify_id_token(_token(keypair, exp=int(time.time()) - 10))
|
||||
|
||||
|
||||
async def test_unverified_email_is_refused(keypair):
|
||||
"""검증: email_verified=false.
|
||||
기대결과: 거부 — 미인증 이메일을 신원으로 쓰면 이메일 기반 중복 판정이 전부 흔들린다."""
|
||||
with pytest.raises(GoogleTokenInvalid):
|
||||
await verify_id_token(_token(keypair, email_verified=False))
|
||||
|
||||
|
||||
async def test_tampered_signature_is_refused(keypair):
|
||||
"""검증: 본문을 바꾼 토큰(서명 불일치).
|
||||
기대결과: 거부."""
|
||||
head, payload, sig = _token(keypair).split(".")
|
||||
other = _token(keypair, sub="9999999999").split(".")[1]
|
||||
with pytest.raises(GoogleTokenInvalid):
|
||||
await verify_id_token(f"{head}.{other}.{sig}")
|
||||
|
||||
|
||||
async def test_unknown_kid_refetches_keys_once(keypair, monkeypatch):
|
||||
"""검증: 캐시에 없는 kid(키 회전 직후).
|
||||
기대결과: JWKS 를 한 번 더 받아 검증에 성공한다 — TTL 만 믿으면 회전 직후 전원 로그인 실패다."""
|
||||
private_pem, jwks = keypair
|
||||
calls = {"n": 0}
|
||||
|
||||
async def _fetch():
|
||||
calls["n"] += 1
|
||||
# 첫 호출은 우리 kid 가 없는(=낡은) 묶음을 준다.
|
||||
return {"keys": []} if calls["n"] == 1 else jwks
|
||||
|
||||
monkeypatch.setattr(google_identity, "_fetch_jwks", _fetch)
|
||||
account = await verify_id_token(_token(keypair))
|
||||
assert account.sub == "1234567890"
|
||||
assert calls["n"] == 2
|
||||
|
||||
|
||||
async def test_missing_client_id_disables_google_login(monkeypatch, keypair):
|
||||
"""검증: GOOGLE_CLIENT_ID 가 비어 있을 때.
|
||||
기대결과: GoogleNotConfigured — 검증을 시도조차 하지 않는다(aud 대조 대상이 없다)."""
|
||||
monkeypatch.setattr(google_identity.google_oauth_config, "client_id", "")
|
||||
with pytest.raises(GoogleNotConfigured):
|
||||
await verify_id_token(_token(keypair))
|
||||
@@ -64,7 +64,8 @@ def _client(handler, api_key: str = "test-kakao-key") -> KakaoLocalClient:
|
||||
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,
|
||||
phone=phone, latitude=38.0, longitude=128.6, category_name=None,
|
||||
category_group_code=None, place_url=None,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""상호명 공개 검색 — 로그인 없이 열려 있고, 업종을 LLM 없이 외부 분류로 추정한다.
|
||||
|
||||
★ 인증이 없는 유일한 place 경로다. 우리 DB 값이 하나도 나가지 않는지 여기서 고정한다.
|
||||
"""
|
||||
from common.enums import ErrorType, PlaceCategory
|
||||
from common.utils import rate_limit
|
||||
from services.external import kakao as kakao_client
|
||||
from services.external import naver as naver_client
|
||||
from services.place_category import guess_category
|
||||
|
||||
|
||||
def _kp(name, category_name, group_code, kakao_id="1"):
|
||||
return kakao_client.KakaoPlace(
|
||||
kakao_place_id=kakao_id, name=name, road_address="강원 양양군 A로 1", address="양양읍 1-1",
|
||||
phone="033-000-0000", latitude=38.0, longitude=128.6,
|
||||
category_name=category_name, category_group_code=group_code, place_url="http://x",
|
||||
)
|
||||
|
||||
|
||||
def _patch_kakao(monkeypatch, rows):
|
||||
monkeypatch.setattr(kakao_client.KakaoLocalClient, "enabled", property(lambda self: True))
|
||||
|
||||
async def _search(self, name, x=None, y=None, size=15):
|
||||
return rows
|
||||
|
||||
async def _close(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(kakao_client.KakaoLocalClient, "search_keyword", _search)
|
||||
monkeypatch.setattr(kakao_client.KakaoLocalClient, "aclose", _close)
|
||||
|
||||
|
||||
# ── 업종 추정 ────────────────────────────────────────────────────────────
|
||||
def test_group_code_maps_to_category():
|
||||
assert guess_category("가정,생활 > 숙박 > 펜션", "AD5") is PlaceCategory.LODGING
|
||||
assert guess_category("음식점 > 카페", "CE7") is PlaceCategory.CAFE
|
||||
assert guess_category("음식점 > 한식 > 육류,고기", "FD6") is PlaceCategory.RESTAURANT
|
||||
|
||||
|
||||
def test_hospital_needs_the_right_department():
|
||||
"""HP8 은 병원이라는 것까지만 말한다 — 우리가 여는 건 피부과·성형외과뿐이다."""
|
||||
assert guess_category("의료,건강 > 병원 > 피부과", "HP8") is PlaceCategory.CLINIC
|
||||
assert guess_category("의료,건강 > 병원 > 치과", "HP8") is None
|
||||
|
||||
|
||||
def test_skin_care_shop_is_not_a_clinic():
|
||||
"""'피부' 로 보면 피부관리실이 병원으로 걸린다 — 의료 광고 규제가 붙는 업종이라 제일 비싸다."""
|
||||
assert guess_category("생활,서비스 > 미용 > 피부관리") is None
|
||||
|
||||
|
||||
def test_naver_has_no_group_code():
|
||||
assert guess_category("숙박>게스트하우스") is PlaceCategory.LODGING
|
||||
assert guess_category("음식점>카페,디저트") is PlaceCategory.CAFE
|
||||
|
||||
|
||||
def test_unknown_category_is_none():
|
||||
"""모르면 None. 억지로 고르지 않는다 — 화면이 사장님에게 직접 묻는다."""
|
||||
assert guess_category(None) is None
|
||||
assert guess_category("스포츠,레저 > 골프장") is None
|
||||
|
||||
|
||||
# ── 엔드포인트 ───────────────────────────────────────────────────────────
|
||||
async def test_search_needs_no_token(client, monkeypatch):
|
||||
rate_limit.reset()
|
||||
_patch_kakao(monkeypatch, [_kp("하조대펜션", "가정,생활 > 숙박 > 펜션", "AD5")])
|
||||
|
||||
res = await client.get("/v1/place/search", params={"q": "하조대펜션"})
|
||||
|
||||
assert res.status_code == 200
|
||||
body = res.json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["items"][0]["name"] == "하조대펜션"
|
||||
assert body["items"][0]["category"] == PlaceCategory.LODGING.value
|
||||
|
||||
|
||||
async def test_search_leaks_nothing_of_ours(client, monkeypatch):
|
||||
"""공개 응답이라 우리 DB 값이 새면 그대로 밖이다. 좌표·전화도 뺐다."""
|
||||
rate_limit.reset()
|
||||
_patch_kakao(monkeypatch, [_kp("하조대펜션", "가정,생활 > 숙박 > 펜션", "AD5")])
|
||||
|
||||
item = (await client.get("/v1/place/search", params={"q": "하조대펜션"})).json()["items"][0]
|
||||
|
||||
for leaked in ("place_id", "company_id", "owner_user_id", "phone", "latitude", "longitude",
|
||||
"external_place_id", "address"):
|
||||
assert leaked not in item, f"{leaked} 가 공개 응답에 나갔다"
|
||||
|
||||
|
||||
async def test_search_does_not_create_a_place(client, monkeypatch, auth_headers):
|
||||
"""검색만으로 사업장이 생기면 안 된다 — 랜딩 트래픽이 그대로 DB 가 된다."""
|
||||
rate_limit.reset()
|
||||
_patch_kakao(monkeypatch, [_kp("하조대펜션", "가정,생활 > 숙박 > 펜션", "AD5")])
|
||||
h = await auth_headers("u1")
|
||||
|
||||
before = (await client.get("/v1/place/list", headers=h)).json()["total"]
|
||||
await client.get("/v1/place/search", params={"q": "하조대펜션"})
|
||||
after = (await client.get("/v1/place/list", headers=h)).json()["total"]
|
||||
|
||||
assert before == after
|
||||
|
||||
|
||||
async def test_search_rejects_short_query(client):
|
||||
rate_limit.reset()
|
||||
res = await client.get("/v1/place/search", params={"q": "가"})
|
||||
assert res.status_code == 422 # min_length=2
|
||||
|
||||
|
||||
async def test_rate_limit_closes_the_tap(client, monkeypatch):
|
||||
"""인증이 없는데 유료 외부 API 를 부른다 — 새로고침만으로 요금이 나가면 안 된다."""
|
||||
rate_limit.reset()
|
||||
_patch_kakao(monkeypatch, [_kp("하조대펜션", "가정,생활 > 숙박 > 펜션", "AD5")])
|
||||
|
||||
from services import place_service
|
||||
|
||||
monkeypatch.setattr(place_service, "_PUBLIC_SEARCH_PER_MIN", 2)
|
||||
for _ in range(2):
|
||||
assert (await client.get("/v1/place/search", params={"q": "하조대펜션"})).json()["result"]["success"] is True
|
||||
|
||||
blocked = (await client.get("/v1/place/search", params={"q": "하조대펜션"})).json()
|
||||
assert blocked["result"]["success"] is False
|
||||
assert blocked["result"]["code"] == ErrorType.HTTP_TO_MANY_REQUEST.value
|
||||
@@ -79,6 +79,12 @@ def test_zero_unique_content_blocks_publish():
|
||||
assert check_unique_content(1).passed is True
|
||||
|
||||
|
||||
def test_unmeasured_unique_content_is_not_zero():
|
||||
"""검증: 렌더러가 계수를 못 재고(None) 실패했다.
|
||||
기대결과: 통과 — 디스크·번들 오류에 NO_UNIQUE_CONTENT 라는 엉뚱한 사유가 붙으면 안 된다."""
|
||||
assert check_unique_content(None).passed is True
|
||||
|
||||
|
||||
def test_jsonld_mismatch_blocks_publish():
|
||||
"""검증: 구조화 데이터 값이 화면 값과 다르다.
|
||||
기대결과: ★ 규칙 3 — JSONLD_MISMATCH 로 거부. 검색엔진에만 다른 말을 하면 안 된다."""
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""공개 쇼케이스 목록 — 랜딩이 로그인 없이 부르는 유일한 사이트 조회.
|
||||
|
||||
이 경로가 절대 하면 안 되는 것:
|
||||
- 발행되지 않은 사이트를 보여주는 것 — 열면 404 다.
|
||||
- 사업장 식별자·전화번호·상세 주소를 흘리는 것. 사이트 한 곳을 여는 것과
|
||||
발행 업소 명단을 통째로 긁는 것은 다른 일이다.
|
||||
"""
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.enums import PlaceCategory, PlaceStatus, SiteStatus
|
||||
|
||||
|
||||
async def _publish(db_engine, company_id, name, *, status, domain, thumb=None, minutes_ago=0):
|
||||
"""places + sites 를 직접 넣는다 — 여기서 보는 건 목록 조회지 빌드 파이프라인이 아니다."""
|
||||
pid, sid = uuid.uuid4(), 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, address, phone) "
|
||||
"VALUES (:p,:c,:n,:cat,:st,:road,:addr,:phone)"),
|
||||
{"p": pid, "c": uuid.UUID(company_id), "n": name, "cat": PlaceCategory.LODGING.value,
|
||||
"st": PlaceStatus.PUBLISHED.value,
|
||||
"road": "강원특별자치도 양양군 현북면 하조대3길 12-3", "addr": "강원특별자치도 양양군 현북면 하광정리 1-2",
|
||||
"phone": "033-672-0000"},
|
||||
)
|
||||
await c.execute(
|
||||
text("INSERT INTO sites (site_id, place_id, domain, status, thumbnail_url, published_at) "
|
||||
"VALUES (:s,:p,:d,:st,:t,:at)"),
|
||||
{"s": sid, "p": pid, "d": domain, "st": status, "t": thumb,
|
||||
"at": datetime.now(timezone.utc) - timedelta(minutes=minutes_ago)},
|
||||
)
|
||||
return str(pid)
|
||||
|
||||
|
||||
async def test_발행된_사이트만_로그인_없이_보인다(client, db_engine, company_id):
|
||||
"""검증: 발행본 1개 + 미발행(DRAFT) 1개를 두고 인증 헤더 없이 부른다.
|
||||
기대결과: 발행본만 나온다."""
|
||||
await _publish(db_engine, company_id, "하조대펜션", status=SiteStatus.PUBLISHED.value,
|
||||
domain="hajodae", thumb="https://w4ai.o2o.kr/thumbs/hajodae.jpg")
|
||||
await _publish(db_engine, company_id, "아직펜션", status=SiteStatus.DRAFT.value, domain="notyet")
|
||||
|
||||
res = await client.get("/v1/showcase")
|
||||
|
||||
assert res.status_code == 200
|
||||
items = res.json()["items"]
|
||||
assert [i["name"] for i in items] == ["하조대펜션"]
|
||||
assert items[0]["url"] == "/s/hajodae"
|
||||
assert items[0]["thumbnail_url"] == "https://w4ai.o2o.kr/thumbs/hajodae.jpg"
|
||||
assert items[0]["category"] == PlaceCategory.LODGING.value
|
||||
|
||||
|
||||
async def test_개인정보와_내부값은_나가지_않는다(client, db_engine, company_id):
|
||||
"""검증: 응답 항목의 키를 그대로 본다.
|
||||
기대결과: 상호명·업종·지역·주소·썸네일뿐. 지역은 시·군까지고 상세 주소는 없다."""
|
||||
await _publish(db_engine, company_id, "하조대펜션", status=SiteStatus.PUBLISHED.value, domain="hajodae")
|
||||
|
||||
item = (await client.get("/v1/showcase")).json()["items"][0]
|
||||
|
||||
assert set(item) <= {"name", "category", "region", "url", "thumbnail_url"}
|
||||
assert item["region"] == "강원특별자치도 양양군"
|
||||
# 번지·전화번호가 어디로도 새지 않았는지 통째로 확인한다.
|
||||
body = (await client.get("/v1/showcase")).text
|
||||
assert "033-672-0000" not in body
|
||||
assert "하조대3길" not in body
|
||||
|
||||
|
||||
async def test_썸네일이_없으면_키가_없다(client, db_engine, company_id):
|
||||
"""★ 썸네일은 발행의 부수 효과라 실패할 수 있다(대표 사진이 없거나 CDN 이 죽었거나).
|
||||
그때 카드는 글자로 떨어져야지 목록에서 사라지면 안 된다."""
|
||||
await _publish(db_engine, company_id, "그림없는집", status=SiteStatus.PUBLISHED.value, domain="nopic")
|
||||
|
||||
item = (await client.get("/v1/showcase")).json()["items"][0]
|
||||
|
||||
assert item["name"] == "그림없는집"
|
||||
assert "thumbnail_url" not in item
|
||||
|
||||
|
||||
async def test_최신_발행순이고_limit_로_자른다(client, db_engine, company_id):
|
||||
await _publish(db_engine, company_id, "먼저", status=SiteStatus.PUBLISHED.value, domain="first", minutes_ago=60)
|
||||
await _publish(db_engine, company_id, "나중", status=SiteStatus.PUBLISHED.value, domain="second", minutes_ago=1)
|
||||
|
||||
items = (await client.get("/v1/showcase")).json()["items"]
|
||||
assert [i["name"] for i in items] == ["나중", "먼저"]
|
||||
|
||||
items = (await client.get("/v1/showcase?limit=1")).json()["items"]
|
||||
assert [i["name"] for i in items] == ["나중"]
|
||||
|
||||
# 상한 밖은 거부한다 — 전체 명단을 한 번에 긁어가는 요청을 열어 두지 않는다.
|
||||
assert (await client.get("/v1/showcase?limit=999")).status_code == 422
|
||||
@@ -222,6 +222,18 @@ def test_owner_disabled_section_stays_disabled():
|
||||
assert next(s for s in theme["sections"] if s["id"] == "photos")["enabled"] is False
|
||||
|
||||
|
||||
def test_owner_written_section_body_reaches_publish_payload():
|
||||
"""검증: 에디터에서 직접 쓴 소개 본문.
|
||||
기대결과: 발행 payload 에 그대로 남는다 — 저장만 되고 경계에서 버려지면 발행본과 계수에 못 쓴다."""
|
||||
theme = _payload_theme({"sections": [{
|
||||
"id": "intro", "name": "소개", "enabled": True, "locked": False,
|
||||
"body": "바다를 보며 조용히 쉬어가는 작은 숙소입니다.",
|
||||
}]})
|
||||
assert next(s for s in theme["sections"] if s["id"] == "intro")["body"] == (
|
||||
"바다를 보며 조용히 쉬어가는 작은 숙소입니다."
|
||||
)
|
||||
|
||||
|
||||
def test_partial_colors_are_filled_from_category_default():
|
||||
"""검증: 저장된 색이 일부 키만 담고 있을 때.
|
||||
기대결과: 빠진 자리는 업종 기본이 메운다 — 렌더러 타입이 6개를 모두 요구하므로
|
||||
@@ -255,15 +267,15 @@ def test_saved_theme_does_not_override_chosen_template():
|
||||
# 여기에 없는 섹션은 사장님이 에디터에서 아무리 봐도 사이트에 나오지 않는다.
|
||||
# 실측으로 날씨·실시간 예약·대관 문의·관람 안내가 그렇게 빠져 있었다.
|
||||
_ADMIN_SECTIONS_TS = (
|
||||
pathlib.Path(__file__).resolve().parents[2] / "front/src/data/industryData.ts" # parents[2] = solution/
|
||||
pathlib.Path(__file__).resolve().parents[2] / "frontend/src/data/industryData.ts" # parents[2] = solution/
|
||||
)
|
||||
|
||||
# 에디터 업종 키 → PlaceCategory. 이름이 다른 건 두 층의 어휘가 달라서다(tour vs TOUR_ACTIVITY).
|
||||
# 에디터 업종 키 → PlaceCategory. 이름이 다른 건 두 층의 어휘가 달라서다(clinic vs CLINIC).
|
||||
_INDUSTRY_TO_CATEGORY = {
|
||||
"stay": PlaceCategory.LODGING.value,
|
||||
"cafe": PlaceCategory.CAFE.value,
|
||||
"restaurant": PlaceCategory.RESTAURANT.value,
|
||||
"tour": PlaceCategory.TOUR_ACTIVITY.value,
|
||||
"clinic": PlaceCategory.CLINIC.value,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
"""발행 썸네일 — 사이트의 대표 사진을 Azure Blob 으로 옮긴다.
|
||||
|
||||
★ 스크린샷이 아니다(헤드리스 브라우저는 영구 금지, docs/DECISIONS.md 1-1).
|
||||
그래서 여기서 볼 것은 "무엇을 대표로 고르는가"와 "무엇을 받지 않는가" 두 가지다.
|
||||
|
||||
이 경로가 절대 하면 안 되는 것:
|
||||
- 썸네일 실패로 발행을 되돌리는 것 — 정적 파일은 이미 올라갔다.
|
||||
- 이미지가 아닌 응답을 그대로 올리는 것 — 카드가 깨진 그림이 된다.
|
||||
- 사이트 디렉터리(`s/<slug>/`) 안에 두는 것 — 다음 발행이 통째로 지운다.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from services import azure_static, site_payload, site_thumbnail
|
||||
|
||||
|
||||
def _snapshot(*rows):
|
||||
return {"media": list(rows)}
|
||||
|
||||
|
||||
def _transport(monkeypatch, handler):
|
||||
"""사진을 내려주는 CDN 대역. 테스트가 실제 네트워크를 부르지 않게 한다."""
|
||||
real = httpx.AsyncClient
|
||||
|
||||
def factory(**kwargs):
|
||||
return real(transport=httpx.MockTransport(handler), **kwargs)
|
||||
|
||||
monkeypatch.setattr(site_thumbnail.httpx, "AsyncClient", factory)
|
||||
|
||||
|
||||
class FakeContainer:
|
||||
def __init__(self):
|
||||
self.uploads = {}
|
||||
|
||||
def upload_blob(self, name, data, **options):
|
||||
self.uploads[name] = {"body": data, **options}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def blob(monkeypatch):
|
||||
container = FakeContainer()
|
||||
service = SimpleNamespace(get_container_client=lambda name: container)
|
||||
monkeypatch.setattr(
|
||||
site_thumbnail.BlobServiceClient, "from_connection_string", lambda value: service
|
||||
)
|
||||
monkeypatch.setenv("AZURE_STORAGE_CONNECTION_STRING", "UseDevelopmentStorage=true")
|
||||
monkeypatch.delenv("AZURE_STORAGE_PREFIX", raising=False)
|
||||
return container
|
||||
|
||||
|
||||
def test_대표사진은_객실전용이_아닌_첫장이다():
|
||||
# og:image 선정(site_payload)과 같은 함수를 쓴다 — 두 벌이면 검색 결과와 카드가 갈린다.
|
||||
snapshot = _snapshot(
|
||||
{"media_id": "m1", "url": "https://cdn.test/room.jpg", "unit_id": "u1"},
|
||||
{"media_id": "m2", "url": "https://cdn.test/front.jpg", "unit_id": None},
|
||||
{"media_id": "m3", "url": "https://cdn.test/back.jpg", "unit_id": None},
|
||||
)
|
||||
assert site_payload.primary_media(snapshot)["media_id"] == "m2"
|
||||
|
||||
|
||||
def test_설정이_없으면_아무것도_하지_않는다(monkeypatch):
|
||||
monkeypatch.delenv("AZURE_STORAGE_CONNECTION_STRING", raising=False)
|
||||
assert site_thumbnail.is_configured() is False
|
||||
|
||||
|
||||
async def test_대표사진이_없으면_None_이고_발행은_그대로(blob):
|
||||
"""검증: 승인 사진이 객실 전용뿐이라 대표가 없다.
|
||||
기대결과: None 을 돌려주고 업로드하지 않는다(예외를 올리지 않는다)."""
|
||||
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/room.jpg", "unit_id": "u1"})
|
||||
assert await site_thumbnail.store("butter", snapshot) is None
|
||||
assert blob.uploads == {}
|
||||
|
||||
|
||||
async def test_이미지가_아니면_받지_않는다(blob, monkeypatch):
|
||||
"""검증: 사진 URL 이 HTML(오류 페이지)을 돌려준다.
|
||||
기대결과: 거부하고 None. 깨진 그림을 쇼케이스에 올리지 않는다."""
|
||||
_transport(monkeypatch, lambda req: httpx.Response(200, headers={"content-type": "text/html"}, content=b"<html>"))
|
||||
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/front.jpg", "unit_id": None})
|
||||
|
||||
assert await site_thumbnail.store("butter", snapshot) is None
|
||||
assert blob.uploads == {}
|
||||
|
||||
|
||||
async def test_상한을_넘는_사진은_받지_않는다(blob, monkeypatch):
|
||||
body = b"x" * (site_thumbnail.MAX_BYTES + 1)
|
||||
_transport(monkeypatch, lambda req: httpx.Response(200, headers={"content-type": "image/jpeg"}, content=body))
|
||||
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/huge.jpg", "unit_id": None})
|
||||
|
||||
assert await site_thumbnail.store("butter", snapshot) is None
|
||||
assert blob.uploads == {}
|
||||
|
||||
|
||||
async def test_네트워크_실패는_삼킨다(blob, monkeypatch):
|
||||
def _boom(request):
|
||||
raise httpx.ConnectTimeout("timed out", request=request)
|
||||
|
||||
_transport(monkeypatch, _boom)
|
||||
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/front.jpg", "unit_id": None})
|
||||
|
||||
assert await site_thumbnail.store("butter", snapshot) is None
|
||||
|
||||
|
||||
async def test_사이트_디렉터리_밖의_thumbs_에_올린다(blob, monkeypatch):
|
||||
"""검증: 대표 사진을 받아 업로드한다.
|
||||
기대결과: `<prefix>/thumbs/<slug>.<ext>` — `s/<slug>/` 안이 아니다.
|
||||
★ 사이트 경로는 매 발행마다 프리렌더 산출물로 통째로 교체된다
|
||||
(azure_static._remove_stale_site_files) — 그 안에 두면 다음 발행에서 조용히 사라진다."""
|
||||
_transport(monkeypatch, lambda req: httpx.Response(200, headers={"content-type": "image/jpeg"}, content=b"jpegbytes"))
|
||||
snapshot = _snapshot({"media_id": "m1", "url": "https://cdn.test/front.jpg", "unit_id": None})
|
||||
|
||||
url = await site_thumbnail.store("butter", snapshot)
|
||||
|
||||
assert url == "https://w4ai.o2o.kr/thumbs/butter.jpg"
|
||||
name = f"{azure_static.DEFAULT_PREFIX}/thumbs/butter.jpg"
|
||||
assert set(blob.uploads) == {name}
|
||||
assert not name.startswith(f"{azure_static.DEFAULT_PREFIX}/{azure_static.SITE_ROOT_DIR}/")
|
||||
|
||||
uploaded = blob.uploads[name]
|
||||
assert uploaded["body"] == b"jpegbytes"
|
||||
settings = uploaded["content_settings"]
|
||||
assert settings.content_type == "image/jpeg"
|
||||
# 썸네일은 재발행마다 바뀌는데 주소는 그대로다 — 길게 캐시하면 옛 그림이 계속 뜬다.
|
||||
assert settings.cache_control == site_thumbnail.CACHE_CONTROL
|
||||
|
||||
|
||||
# ── 발행 경로와의 배선 ────────────────────────────────────────────────────
|
||||
# 아래 두 건은 "발행이 썸네일에 매달리지 않는가" 를 본다. 썸네일 만들기 자체는 위에서 봤다.
|
||||
async def test_발행하면_사이트에_썸네일_주소가_남는다(auth_headers, client, db_engine, monkeypatch):
|
||||
from services import build_service
|
||||
from tests.test_build_publish import _approved_media, _place, _run, _verified_facts
|
||||
|
||||
async def _store(slug, snapshot):
|
||||
return f"https://w4ai.o2o.kr/thumbs/{slug}.jpg"
|
||||
|
||||
monkeypatch.setattr(build_service.site_thumbnail, "store", _store)
|
||||
|
||||
h = await auth_headers("u1")
|
||||
pid = await _place(client, h, "썸네일펜션")
|
||||
await _verified_facts(client, h, pid, {"intro": "하조대 해변 도보 3분 거리의 펜션입니다."})
|
||||
await _approved_media(db_engine, pid)
|
||||
|
||||
await client.post(f"/v1/place/{pid}/site/build", headers=h, json={"publish": True})
|
||||
await _run()
|
||||
|
||||
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()["site"]
|
||||
assert site["thumbnail_url"].startswith("https://w4ai.o2o.kr/thumbs/")
|
||||
|
||||
|
||||
async def test_썸네일을_못_만들어도_발행은_성공한다(auth_headers, client, db_engine, monkeypatch):
|
||||
"""★ 썸네일은 발행의 부수 효과다 — 정적 파일은 이미 올라갔다. 여기서 되돌리면
|
||||
사장님 사이트가 그림 하나 때문에 안 나간다."""
|
||||
from services import build_service
|
||||
from tests.test_build_publish import _approved_media, _place, _run, _verified_facts
|
||||
|
||||
async def _store(slug, snapshot):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(build_service.site_thumbnail, "store", _store)
|
||||
|
||||
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()
|
||||
|
||||
assert (await client.get(f"/v1/job/{job_id}", headers=h)).json()["job"]["result"]["published"] is True
|
||||
site = (await client.get(f"/v1/place/{pid}/site", headers=h)).json()["site"]
|
||||
assert "thumbnail_url" not in site
|
||||
@@ -203,13 +203,31 @@ async def test_local_content_is_scoped_to_the_places_region(db_engine, company_i
|
||||
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 가 비어 있는 사업장(수집이 지역을 특정하지 못한 경우).
|
||||
async def test_region_code_is_derived_from_the_address_when_missing(db_engine, company_id):
|
||||
"""검증: region_code 가 비어 있지만 도로명주소는 있는 사업장.
|
||||
기대결과: 주소에서 지역 키를 유도해 그 지역 콘텐츠를 담는다 — places.region_code 를 채우는
|
||||
코드가 생기기 전에 만들어진 사업장(실측 28곳 중 25곳)이 영영 지역 정보 없이 발행되지 않게 한다."""
|
||||
from common.enums import LocalContentStatus, LocalContentType
|
||||
from services.external.naver import region_key
|
||||
|
||||
derived = region_key(_Place("x").road_address)
|
||||
pid = await _seed(db_engine, company_id)
|
||||
await _local(db_engine, derived, LocalContentType.FESTIVAL, LocalContentStatus.PUBLISHED, "양양축제")
|
||||
|
||||
snap = await build_snapshot(_RegionPlace(pid, ""))
|
||||
assert snap["local"]["region_code"] == derived
|
||||
assert [c["title"] for c in snap["local"]["contents"]] == ["양양축제"]
|
||||
|
||||
|
||||
async def test_place_without_any_region_key_gets_no_local_content(db_engine, company_id):
|
||||
"""검증: 지역 코드도 읽을 만한 주소도 없는 사업장.
|
||||
기대결과: 빈 목록 — 조회할 캐시 키가 없다. 지어내지 않는다."""
|
||||
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, ""))
|
||||
place = _RegionPlace(pid, "")
|
||||
place.road_address = None
|
||||
snap = await build_snapshot(place)
|
||||
assert snap["local"] == {"region_code": None, "contents": []}
|
||||
@@ -10,8 +10,7 @@ VITE_PUBLISH_HOST=w4ai.o2o.kr
|
||||
# 발행 사이트 렌더러 개발 서버. 에디터 상단 "발행본 사이트 열기" 가 이 주소를 연다.
|
||||
VITE_SITE_PREVIEW_URL=http://localhost:3000
|
||||
|
||||
# ── 개발 전용 자동 로그인(선택) ────────────────────────────
|
||||
# 값이 있으면 개발 서버에서 빌더를 열 때 이 계정으로 자동 로그인한다.
|
||||
# 운영 번들에는 들어가지 않는다. 실제 값은 .env 에만 둔다(커밋 금지).
|
||||
VITE_DEV_LOGIN_ID=
|
||||
VITE_DEV_LOGIN_PW=
|
||||
# 구글 로그인 클라이언트 ID. 비우면 구글 버튼이 아예 안 뜬다(누르면 실패하는 버튼을 두지 않는다).
|
||||
# ★ 로컬에서 compose 없이 띄울 때만 쓴다. compose 로 띄우면 루트 .env 의 GOOGLE_CLIENT_ID 가
|
||||
# 주입돼 이 값을 덮는다 — 백엔드의 aud 대조와 같은 값이어야 하므로 단일 출처는 루트 .env 다.
|
||||
VITE_GOOGLE_CLIENT_ID=
|
||||
@@ -9,7 +9,12 @@
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300..900&display=swap"
|
||||
href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300..900&family=Noto+Serif+KR:wght@400;600;700&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<!-- 7080 아이템(가요 다방·일력·승차권) 전용. 이 셋이 없으면 간판/명조가 고딕으로 떨어져 감성이 사라진다 -->
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Gugi&family=Gowun+Batang:wght@400;700&family=Nanum+Pen+Script&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<link rel="icon" type="image/svg+xml" href="/brand/favicon-w4a.svg?v=14" />
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0"?>
|
||||
<users>
|
||||
<user>B2F7F84EB3B85C839F5B1F17DDDA6C2E</user>
|
||||
</users>
|
||||
@@ -25,7 +25,9 @@ import type {
|
||||
|
||||
import type {
|
||||
HTTPValidationError,
|
||||
ReqGoogleLogin,
|
||||
ReqLogin,
|
||||
ReqSignup,
|
||||
ReqUpdateMe,
|
||||
ResLogin,
|
||||
ResMe,
|
||||
@@ -105,6 +107,136 @@ export const useLogin = <TError = void | HTTPValidationError,
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
}
|
||||
/**
|
||||
* id/pw 로 가입한다. 회사(테넌트) 1개가 함께 생기고, 성공하면 곧바로 로그인 토큰을 발급한다.
|
||||
* @summary 회원가입
|
||||
*/
|
||||
export const signup = (
|
||||
reqSignup: ReqSignup,
|
||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
||||
) => {
|
||||
|
||||
|
||||
return customFetch<ResLogin>(
|
||||
{url: `/v1/auth/signup`, method: 'POST',
|
||||
headers: {'Content-Type': 'application/json', },
|
||||
data: reqSignup, signal
|
||||
},
|
||||
options);
|
||||
}
|
||||
|
||||
|
||||
|
||||
export const getSignupMutationOptions = <TError = void | HTTPValidationError,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof signup>>, TError,{data: ReqSignup}, TContext>, request?: SecondParameter<typeof customFetch>}
|
||||
): UseMutationOptions<Awaited<ReturnType<typeof signup>>, TError,{data: ReqSignup}, TContext> => {
|
||||
|
||||
const mutationKey = ['signup'];
|
||||
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<Awaited<ReturnType<typeof signup>>, {data: ReqSignup}> = (props) => {
|
||||
const {data} = props ?? {};
|
||||
|
||||
return signup(data,requestOptions)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
return { mutationFn, ...mutationOptions }}
|
||||
|
||||
export type SignupMutationResult = NonNullable<Awaited<ReturnType<typeof signup>>>
|
||||
export type SignupMutationBody = ReqSignup
|
||||
export type SignupMutationError = void | HTTPValidationError
|
||||
|
||||
/**
|
||||
* @summary 회원가입
|
||||
*/
|
||||
export const useSignup = <TError = void | HTTPValidationError,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof signup>>, TError,{data: ReqSignup}, TContext>, request?: SecondParameter<typeof customFetch>}
|
||||
, queryClient?: QueryClient): UseMutationResult<
|
||||
Awaited<ReturnType<typeof signup>>,
|
||||
TError,
|
||||
{data: ReqSignup},
|
||||
TContext
|
||||
> => {
|
||||
|
||||
const mutationOptions = getSignupMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
}
|
||||
/**
|
||||
* 구글 ID 토큰(GIS credential)을 검증하고 JWT 토큰을 발급한다. 처음 온 계정은 그 자리에서 만든다.
|
||||
* @summary 구글 로그인
|
||||
*/
|
||||
export const googleLogin = (
|
||||
reqGoogleLogin: ReqGoogleLogin,
|
||||
options?: SecondParameter<typeof customFetch>,signal?: AbortSignal
|
||||
) => {
|
||||
|
||||
|
||||
return customFetch<ResLogin>(
|
||||
{url: `/v1/auth/google`, method: 'POST',
|
||||
headers: {'Content-Type': 'application/json', },
|
||||
data: reqGoogleLogin, signal
|
||||
},
|
||||
options);
|
||||
}
|
||||
|
||||
|
||||
|
||||
export const getGoogleLoginMutationOptions = <TError = void | HTTPValidationError,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof googleLogin>>, TError,{data: ReqGoogleLogin}, TContext>, request?: SecondParameter<typeof customFetch>}
|
||||
): UseMutationOptions<Awaited<ReturnType<typeof googleLogin>>, TError,{data: ReqGoogleLogin}, TContext> => {
|
||||
|
||||
const mutationKey = ['googleLogin'];
|
||||
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<Awaited<ReturnType<typeof googleLogin>>, {data: ReqGoogleLogin}> = (props) => {
|
||||
const {data} = props ?? {};
|
||||
|
||||
return googleLogin(data,requestOptions)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
return { mutationFn, ...mutationOptions }}
|
||||
|
||||
export type GoogleLoginMutationResult = NonNullable<Awaited<ReturnType<typeof googleLogin>>>
|
||||
export type GoogleLoginMutationBody = ReqGoogleLogin
|
||||
export type GoogleLoginMutationError = void | HTTPValidationError
|
||||
|
||||
/**
|
||||
* @summary 구글 로그인
|
||||
*/
|
||||
export const useGoogleLogin = <TError = void | HTTPValidationError,
|
||||
TContext = unknown>(options?: { mutation?:UseMutationOptions<Awaited<ReturnType<typeof googleLogin>>, TError,{data: ReqGoogleLogin}, TContext>, request?: SecondParameter<typeof customFetch>}
|
||||
, queryClient?: QueryClient): UseMutationResult<
|
||||
Awaited<ReturnType<typeof googleLogin>>,
|
||||
TError,
|
||||
{data: ReqGoogleLogin},
|
||||
TContext
|
||||
> => {
|
||||
|
||||
const mutationOptions = getGoogleLoginMutationOptions(options);
|
||||
|
||||
return useMutation(mutationOptions, queryClient);
|
||||
}
|
||||
/**
|
||||
* refresh 토큰으로 access 토큰을 재발급한다.
|
||||
* @summary 액세스 토큰 갱신
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* users.provider 코드값. 이 계정이 무엇으로 신원을 증명하는가.
|
||||
|
||||
한 계정은 수단 하나다 — 같은 이메일이라도 id/pw 계정과 구글 계정을 자동으로 잇지 않는다.
|
||||
이으려면 "먼저 가입한 쪽의 소유"를 증명받아야 하는데, 그 증명 없이 이메일만 보고 이으면
|
||||
남이 먼저 만들어 둔 계정에 내 구글 로그인이 들어간다(계정 선점). 보류 사유는 DECISIONS.md 1절.
|
||||
*/
|
||||
export type AuthProvider = typeof AuthProvider[keyof typeof AuthProvider];
|
||||
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-redeclare
|
||||
export const AuthProvider = {
|
||||
LOCAL: 1,
|
||||
GOOGLE: 2,
|
||||
} as const;
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
export * from './auditCheckData';
|
||||
export * from './auditCheckDataRecommendation';
|
||||
export * from './authProvider';
|
||||
export * from './buildStatus';
|
||||
export * from './checkSlugParams';
|
||||
export * from './companyData';
|
||||
@@ -120,8 +121,12 @@ export * from './reqCreatePlace';
|
||||
export * from './reqCreatePlaceOwnerUserId';
|
||||
export * from './reqCreateUnit';
|
||||
export * from './reqExtractFacts';
|
||||
export * from './reqGoogleLogin';
|
||||
export * from './reqLogin';
|
||||
export * from './reqPublishLocalContent';
|
||||
export * from './reqSignup';
|
||||
export * from './reqSignupCompanyName';
|
||||
export * from './reqSignupName';
|
||||
export * from './reqSiteSlug';
|
||||
export * from './reqSiteStatus';
|
||||
export * from './reqSiteTemplate';
|
||||
|
||||
@@ -17,5 +17,5 @@ export const PlaceCategory = {
|
||||
LODGING: 1,
|
||||
CAFE: 2,
|
||||
RESTAURANT: 3,
|
||||
TOUR_ACTIVITY: 4,
|
||||
CLINIC: 4,
|
||||
} as const;
|
||||
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* 구글 로그인. 프론트(GIS)가 받은 ID 토큰을 그대로 넘긴다.
|
||||
|
||||
필드 이름이 `credential` 인 이유는 GIS 콜백이 주는 이름 그대로이기 때문이다 —
|
||||
`access_token`/`id_token` 으로 바꿔 부르면 우리 토큰과 헷갈린다.
|
||||
*/
|
||||
export interface ReqGoogleLogin {
|
||||
credential?: string;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
import type { ReqSignupName } from './reqSignupName';
|
||||
import type { ReqSignupCompanyName } from './reqSignupCompanyName';
|
||||
|
||||
/**
|
||||
* id/pw 가입. 가입 = 새 테넌트(회사) 1개 + 그 회사의 첫 계정 1개다.
|
||||
|
||||
★ 이메일을 필수로 받는 이유: 같은 이메일이 이미 구글로 가입돼 있는지 판단할 근거가 없으면
|
||||
한 사람에게 계정이 둘 생긴다. 지금 이메일 인증 절차는 없다 — 소유 증명이 아니라
|
||||
**중복 판정용** 이다.
|
||||
*/
|
||||
export interface ReqSignup {
|
||||
id?: string;
|
||||
password?: string;
|
||||
name?: ReqSignupName;
|
||||
email?: string;
|
||||
company_name?: ReqSignupCompanyName;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type ReqSignupCompanyName = string | null;
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Generated by orval v7.21.0 🍺
|
||||
* Do not edit manually.
|
||||
* Web4Ai API
|
||||
* OpenAPI spec version: 0.1.0
|
||||
*/
|
||||
|
||||
export type ReqSignupName = string | null;
|
||||
@@ -10,6 +10,7 @@ import type { ResMeName } from './resMeName';
|
||||
import type { ResMeEmail } from './resMeEmail';
|
||||
import type { ResMeContactNumber } from './resMeContactNumber';
|
||||
import type { UserRole } from './userRole';
|
||||
import type { AuthProvider } from './authProvider';
|
||||
import type { ResMeCompany } from './resMeCompany';
|
||||
|
||||
export interface ResMe {
|
||||
@@ -21,5 +22,6 @@ export interface ResMe {
|
||||
email?: ResMeEmail;
|
||||
contact_number?: ResMeContactNumber;
|
||||
role?: UserRole;
|
||||
provider?: AuthProvider;
|
||||
company?: ResMeCompany;
|
||||
}
|
||||
@@ -17,9 +17,8 @@ export const router = createBrowserRouter([
|
||||
* 빌더는 로그인 화면을 앞에 세우지 않는다 — 위저드를 열자마자 로그인부터 만나면
|
||||
* 만들어 보기도 전에 막힌다.
|
||||
*
|
||||
* 대신 세션은 조용히 확보한다:
|
||||
* 개발 → useDevAutoLogin() 이 .env 의 개발 계정으로 자동 로그인한다
|
||||
* 운영 → 이미 로그인돼 있으면 그대로 쓰고, 아니면 서버가 필요한 순간(2단계 검색)에만 알린다
|
||||
* 대신 세션은 조용히 확보한다 — VITE_AUTO_LOGIN_ID·PW 가 주입돼 있으면 useAutoLogin() 이
|
||||
* 그 계정으로 붙고, 없으면 서버가 필요한 순간(2단계 검색)에만 알린다.
|
||||
*
|
||||
* 에디터(6단계)는 전체 화면이 필요해 AppShell 을 스스로 끄고 켠다 — BuilderPage 참조.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import {useEffect, useRef, useState} from 'react';
|
||||
import {GOOGLE_CLIENT_ID, isGoogleLoginEnabled, loadGoogleIdentity} from '@/lib/googleIdentity';
|
||||
|
||||
/**
|
||||
* 구글이 그려 주는 버튼을 그대로 쓴다.
|
||||
*
|
||||
* ★ 우리가 직접 만든 버튼을 쓰지 않는 이유: 구글 브랜드 가이드가 로고·문구·비율을 정해 두고,
|
||||
* 그걸 어긋나게 그리면 심사에서 걸린다. renderButton 이 그 규격을 지켜 준다.
|
||||
* ★ 스크립트가 안 오면(광고 차단기·사내망) 빈 칸이 남는다 — 안내 문구로 바꿔 준다.
|
||||
* "눌러도 아무 일이 없는 자리"가 화면에 남는 게 제일 나쁘다.
|
||||
*/
|
||||
export function GoogleSignInButton({
|
||||
onCredential,
|
||||
text = 'continue_with',
|
||||
}: {
|
||||
onCredential: (credential: string) => void;
|
||||
text?: 'continue_with' | 'signin_with' | 'signup_with';
|
||||
}) {
|
||||
const holder = useRef<HTMLDivElement>(null);
|
||||
const [failed, setFailed] = useState(false);
|
||||
|
||||
// 콜백은 ref 로 들고 간다 — GIS 는 initialize 시점의 함수를 붙잡고 있어서,
|
||||
// 의존성에 넣으면 렌더마다 버튼을 다시 그리게 된다.
|
||||
const handler = useRef(onCredential);
|
||||
handler.current = onCredential;
|
||||
|
||||
useEffect(() => {
|
||||
if (!isGoogleLoginEnabled()) return;
|
||||
let alive = true;
|
||||
|
||||
loadGoogleIdentity()
|
||||
.then((api) => {
|
||||
if (!alive || !holder.current) return;
|
||||
api.initialize({
|
||||
client_id: GOOGLE_CLIENT_ID,
|
||||
callback: (res) => {
|
||||
if (res.credential) handler.current(res.credential);
|
||||
},
|
||||
// 화면을 열자마자 마지막 계정으로 자동 로그인되는 동작은 끈다 —
|
||||
// 계정이 여러 개인 사람이 원하지 않은 계정으로 들어간다.
|
||||
auto_select: false,
|
||||
});
|
||||
api.renderButton(holder.current, {
|
||||
type: 'standard',
|
||||
theme: 'outline',
|
||||
size: 'large',
|
||||
shape: 'rectangular',
|
||||
text,
|
||||
locale: 'ko',
|
||||
logo_alignment: 'center',
|
||||
// GIS 는 숫자 px 만 받는다(최대 400). 컨테이너 폭이 잡히기 전이면 최소값으로 그린다.
|
||||
width: holder.current.offsetWidth || 320,
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
if (alive) setFailed(true);
|
||||
});
|
||||
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [text]);
|
||||
|
||||
if (!isGoogleLoginEnabled()) return null;
|
||||
|
||||
if (failed) {
|
||||
return (
|
||||
<p className="text-center text-[11px] leading-relaxed text-muted-foreground">
|
||||
구글 로그인을 불러오지 못했습니다. 아이디/비밀번호로 로그인해 주세요.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
// 높이를 미리 잡아 둔다 — 버튼이 뒤늦게 그려지면서 아래 내용이 밀리지 않게.
|
||||
return <div ref={holder} className="flex h-10 w-full items-center justify-center" />;
|
||||
}
|
||||
@@ -1,4 +1,113 @@
|
||||
import type {IndustryData, IndustryType} from '@o2o/shared';
|
||||
import type {IndustryData, IndustryType, TemplateItem} from '@o2o/shared';
|
||||
/**
|
||||
* 템플릿 세 벌.
|
||||
*
|
||||
* ★ 예전엔 업종마다 다섯 벌이었는데 넷이 "흰 바탕 + 고딕 + 둥근 모서리"에 색조만 달랐다 —
|
||||
* 골라도 뭐가 달라지는지 알 수 없었다. 지금은 서체·모서리·테두리·그림자·여백까지 갈린다.
|
||||
* 같은 얼굴을 색만 바꿔 늘리지 않는다.
|
||||
* ★ 업종이 바꾸는 건 accent 하나다. 생김새는 업종이 아니라 취향의 문제다.
|
||||
*/
|
||||
const LOOK = {
|
||||
simple: {
|
||||
fontHeading: "'Pretendard Variable', 'Noto Sans KR', system-ui, sans-serif",
|
||||
fontBody: "'Pretendard Variable', 'Noto Sans KR', system-ui, sans-serif",
|
||||
radius: '0.75rem',
|
||||
borderWidth: '1px',
|
||||
shadow: '0 1px 2px rgb(0 0 0 / 0.06)',
|
||||
headingTracking: '-0.02em',
|
||||
headingWeight: '700',
|
||||
sectionSpace: '3.5rem',
|
||||
},
|
||||
magazine: {
|
||||
fontHeading: "'Noto Serif KR', 'Batang', 'Times New Roman', serif",
|
||||
fontBody: "'Pretendard Variable', 'Noto Sans KR', system-ui, sans-serif",
|
||||
radius: '0px',
|
||||
borderWidth: '1px',
|
||||
shadow: 'none',
|
||||
headingTracking: '-0.03em',
|
||||
headingWeight: '700',
|
||||
sectionSpace: '5rem',
|
||||
},
|
||||
retro: {
|
||||
fontHeading: "'Gugi', 'Noto Sans KR', sans-serif",
|
||||
fontBody: "'Gowun Batang', 'Noto Serif KR', serif",
|
||||
radius: '0px',
|
||||
borderWidth: '2px',
|
||||
shadow: '4px 4px 0 rgb(27 26 21 / 0.16)',
|
||||
// 간판체는 자간을 벌리면 글자가 흩어진다. 굵기도 한 벌뿐이라 700 을 주면 가짜 볼드가 씌워진다.
|
||||
headingTracking: '0em',
|
||||
headingWeight: '400',
|
||||
sectionSpace: '4rem',
|
||||
},
|
||||
} as const;
|
||||
|
||||
/** 업종 하나의 템플릿 세 벌. accent 만 업종이 정한다. */
|
||||
function templatesFor(
|
||||
industryId: IndustryType,
|
||||
accent: string,
|
||||
retro: {name: string; description: string},
|
||||
): TemplateItem[] {
|
||||
return [
|
||||
{
|
||||
id: `${industryId}-simple`,
|
||||
industryId,
|
||||
name: '심플',
|
||||
tone: 'info',
|
||||
toneLabel: '깔끔한 기본',
|
||||
description: '흰 바탕에 고딕. 읽기 쉽고 어디에도 어울립니다. 무엇을 고를지 모르겠으면 이것.',
|
||||
colors: {
|
||||
primary: '#18181b',
|
||||
secondary: '#52525b',
|
||||
bg: '#ffffff',
|
||||
card: '#fafafa',
|
||||
text: '#09090b',
|
||||
accent,
|
||||
},
|
||||
fontStyle: '고딕',
|
||||
look: LOOK.simple,
|
||||
},
|
||||
{
|
||||
id: `${industryId}-magazine`,
|
||||
industryId,
|
||||
name: '매거진',
|
||||
tone: 'photo',
|
||||
toneLabel: '잡지 편집',
|
||||
description: '명조 제목에 각진 모서리, 그림자 없이 선으로만. 사진과 글이 많을 때 품이 납니다.',
|
||||
colors: {
|
||||
primary: '#111111',
|
||||
secondary: '#57534e',
|
||||
bg: '#ffffff',
|
||||
card: '#f7f6f4',
|
||||
text: '#111111',
|
||||
accent,
|
||||
},
|
||||
fontStyle: '명조 제목',
|
||||
look: LOOK.magazine,
|
||||
},
|
||||
{
|
||||
id: `${industryId}-retro`,
|
||||
industryId,
|
||||
name: retro.name,
|
||||
tone: 'photo',
|
||||
toneLabel: '레트로 감성',
|
||||
description: retro.description,
|
||||
colors: {
|
||||
primary: '#1b1a15',
|
||||
secondary: '#4c4739',
|
||||
bg: '#e4dac0',
|
||||
card: '#f2ebd9',
|
||||
text: '#1b1a15',
|
||||
// 레트로의 정체성이 이 주(朱) 잉크다 — 업종 accent 로 갈아끼우지 않는다.
|
||||
accent: '#bf2f1b',
|
||||
},
|
||||
fontStyle: '옛 간판체',
|
||||
look: LOOK.retro,
|
||||
// 이 템플릿이 팔려는 게 바로 이 아이템들이다.
|
||||
defaultSectionTypes: ['songs', 'daily', 'course', 'schedule'],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
export const INDUSTRY_CONFIGS: Record<IndustryType, IndustryData> = {
|
||||
stay: {
|
||||
@@ -24,93 +133,10 @@ export const INDUSTRY_CONFIGS: Record<IndustryType, IndustryData> = {
|
||||
{ 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',
|
||||
},
|
||||
],
|
||||
templates: templatesFor('stay', '#2563eb', {
|
||||
name: '옛 항구',
|
||||
description: '갱지 바탕에 간판체. 도넛판·일력·승차권이 함께 들어옵니다. 오래된 항구 도시의 인상으로 묵는 곳을 소개합니다.',
|
||||
}),
|
||||
},
|
||||
|
||||
cafe: {
|
||||
@@ -136,76 +162,10 @@ export const INDUSTRY_CONFIGS: Record<IndustryType, IndustryData> = {
|
||||
{ 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',
|
||||
},
|
||||
],
|
||||
templates: templatesFor('cafe', '#b45309', {
|
||||
name: '옛 다방',
|
||||
description: '갱지 바탕에 간판체. LP 와 손글씨로, 다방 시절의 인상으로 지금의 커피를 이야기합니다.',
|
||||
}),
|
||||
},
|
||||
|
||||
restaurant: {
|
||||
@@ -231,171 +191,39 @@ export const INDUSTRY_CONFIGS: Record<IndustryType, IndustryData> = {
|
||||
{ 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',
|
||||
},
|
||||
],
|
||||
templates: templatesFor('restaurant', '#16a34a', {
|
||||
name: '노포',
|
||||
description: '갱지 바탕에 간판체. 오래 해온 집이라는 사실 자체가 메뉴판이 됩니다.',
|
||||
}),
|
||||
},
|
||||
|
||||
tour: {
|
||||
id: 'tour',
|
||||
name: '관광 · 체험',
|
||||
subName: '체험공간 · 전시',
|
||||
description: '원데이 클래스, 도자기·목공 공방, 사설 갤러리, 팜스테이',
|
||||
clinic: {
|
||||
id: 'clinic',
|
||||
name: '피부과 · 성형외과',
|
||||
subName: '의원 · 클리닉',
|
||||
description: '피부과, 성형외과, 미용 클리닉',
|
||||
channels: [
|
||||
{ id: 'naver_place', name: '네이버 플레이스', checked: true },
|
||||
{ id: 'frip', name: '프립 (체험 플랫폼)', checked: true },
|
||||
{ id: 'kakao_channel', 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',
|
||||
},
|
||||
{ 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: false, description: '현재 기온과 주변 날씨' },
|
||||
{ id: 'local', type: 'local', name: '주변 정보', isLocked: false, isEnabled: false, description: '주변 편의시설' },
|
||||
{ id: 'faq', type: 'faq', name: '자주 묻는 질문', isLocked: false, isEnabled: true, description: '예약 변경, 회복 기간, 주의사항' },
|
||||
],
|
||||
templates: templatesFor('clinic', '#4A9DC4', {
|
||||
name: '클린',
|
||||
description: '여백과 낮은 채도. 과장 없이 정보를 먼저 보여줍니다.',
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* 에디터 앞의 로그인 관문.
|
||||
*
|
||||
* ★ 위저드(1~5단계)는 로그인을 요구하지 않는다 — 만들어 보기도 전에 막으면 아무도 안 만든다.
|
||||
* 에디터부터는 편집한 것을 저장하고 발행해야 하는데 그게 전부 토큰을 쓴다. 토큰 없이 들여보내면
|
||||
* 저장이 조용히 실패하고 사장님은 발행하고 나서야 안다.
|
||||
* ★ /login 으로 튕기지 않는다. 위저드에서 쌓은 상태를 들고 돌아올 방법을 사장님이 알 수 없다.
|
||||
*/
|
||||
import {SignInForm} from './SignInForm';
|
||||
|
||||
export function EditorSignInGate({onBack}: {onBack: () => void}) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-muted/30 px-4">
|
||||
<SignInForm
|
||||
submitLabel="로그인하고 편집 시작"
|
||||
header={
|
||||
<div className="space-y-1 text-center">
|
||||
<img src="/brand/web4ai-wordmark.svg" alt="Web4Ai" className="mx-auto mb-3 h-9 w-auto" />
|
||||
<h1 className="text-sm font-bold">편집을 시작하려면 로그인해 주세요</h1>
|
||||
<p className="text-xs leading-relaxed text-muted-foreground">
|
||||
여기까지 만든 내용은 그대로 있습니다. 편집한 것을 저장하고 발행하는 데 계정이 필요합니다.
|
||||
</p>
|
||||
</div>
|
||||
}
|
||||
footer={
|
||||
<button
|
||||
type="button"
|
||||
onClick={onBack}
|
||||
className="w-full text-center text-[11px] text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
|
||||
>
|
||||
디자인 고르기로 돌아가기
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* 로그인 폼 한 벌.
|
||||
*
|
||||
* ★ 로그인 화면과 에디터 진입 관문이 같은 폼을 쓴다. 두 벌로 두면 토큰을 심는 순서
|
||||
* (signIn → me)가 한쪽에서만 지켜지고, 그 실수는 "로그인은 됐는데 계속 401" 로 나타난다.
|
||||
*/
|
||||
import {useState, type FormEvent, type ReactNode} from 'react';
|
||||
import {LogIn} from 'lucide-react';
|
||||
import {login, me, UserRole} from '@/api';
|
||||
import {Button} from '@/components/ui/button';
|
||||
import {Input} from '@/components/ui/input';
|
||||
import {notifyApiError} from '@/lib/notify';
|
||||
import {toAuthUser, useAuthStore} from '@/stores/auth';
|
||||
|
||||
interface SignInFormProps {
|
||||
/** 폼 위에 붙는 제목·설명. 화면마다 하는 말이 다르다. */
|
||||
header: ReactNode;
|
||||
/** 폼 아래 각주(빌더로 돌아가기 등). */
|
||||
footer?: ReactNode;
|
||||
submitLabel?: string;
|
||||
onSignedIn?: () => void;
|
||||
}
|
||||
|
||||
export function SignInForm({header, footer, submitLabel = '로그인', onSignedIn}: SignInFormProps) {
|
||||
const signIn = useAuthStore((s) => s.signIn);
|
||||
const [id, setId] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const handleSubmit = async (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const res = await login({id, password});
|
||||
if (res.result?.success === false) {
|
||||
notifyApiError({data: res}, '아이디 또는 비밀번호를 확인해 주세요.');
|
||||
return;
|
||||
}
|
||||
// ★ RemoveNoneResponse 라 성공 응답에서도 토큰 필드가 빠져 올 수 있다.
|
||||
// 빈 토큰으로 로그인 상태를 만들면 이후 모든 요청이 401 로 흐른다 — 여기서 끊는다.
|
||||
if (!res.access_token || !res.refresh_token) {
|
||||
notifyApiError({data: res}, '로그인 응답에 토큰이 없습니다.');
|
||||
return;
|
||||
}
|
||||
const tokens = {accessToken: res.access_token, refreshToken: res.refresh_token};
|
||||
|
||||
// 토큰을 먼저 심어야 뒤이은 me() 가 Authorization 을 달고 나간다.
|
||||
signIn(tokens, {userId: '', id, role: UserRole.USER});
|
||||
|
||||
const meRes = await me();
|
||||
// 신원이 안 왔으면 방금 심은 임시 사용자를 그대로 둔다 — 토큰은 유효하므로 화면은 진행시킨다.
|
||||
if (meRes.user_id && meRes.id) signIn(tokens, toAuthUser(meRes));
|
||||
onSignedIn?.();
|
||||
} catch (error) {
|
||||
notifyApiError(error, '로그인에 실패했습니다.');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className="w-full max-w-sm space-y-4 rounded-2xl border border-border bg-card p-7"
|
||||
>
|
||||
{header}
|
||||
|
||||
<div className="space-y-3">
|
||||
<div>
|
||||
<label htmlFor="login-id" className="mb-1.5 block text-xs font-semibold">
|
||||
아이디
|
||||
</label>
|
||||
<Input
|
||||
id="login-id"
|
||||
value={id}
|
||||
onChange={(e) => setId(e.target.value)}
|
||||
autoComplete="username"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="login-pw" className="mb-1.5 block text-xs font-semibold">
|
||||
비밀번호
|
||||
</label>
|
||||
<Input
|
||||
id="login-pw"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete="current-password"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button type="submit" variant="primary" className="w-full" isLoading={isSubmitting}>
|
||||
<LogIn />
|
||||
<span>{submitLabel}</span>
|
||||
</Button>
|
||||
|
||||
{footer}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -60,6 +60,8 @@ export function CanvasView() {
|
||||
// 템플릿을 바꿔도 화면 면적의 대부분이 그대로다 — 쇼케이스와 같은 식(lib/color.ts)을 쓴다.
|
||||
const surfaces = deriveSurfaces(template.colors);
|
||||
|
||||
const look = template.look;
|
||||
|
||||
const themeVars = {
|
||||
'--tpl-surface': surfaces.surface,
|
||||
'--tpl-surface-alt': surfaces.surfaceAlt,
|
||||
@@ -71,6 +73,28 @@ export function CanvasView() {
|
||||
'--tpl-card': template.colors.card,
|
||||
'--tpl-text': template.colors.text,
|
||||
'--tpl-accent': template.colors.accent,
|
||||
|
||||
// 색만 바꾸면 템플릿이 다 같아 보인다 — 생김새를 가르는 건 아래쪽이다.
|
||||
'--tpl-font-heading': look.fontHeading,
|
||||
'--tpl-font-body': look.fontBody,
|
||||
'--tpl-heading-tracking': look.headingTracking,
|
||||
'--tpl-heading-weight': look.headingWeight,
|
||||
'--tpl-section-space': look.sectionSpace,
|
||||
'--tpl-border-width': look.borderWidth,
|
||||
|
||||
// ★ Tailwind v4 의 테마 변수를 캔버스 안에서만 덮는다. 이러면 변이 파일 40여 개에 흩어진
|
||||
// rounded-* · shadow-* 를 하나도 안 고치고 전부 템플릿을 따르게 된다.
|
||||
// 배수는 Tailwind 기본 비율(0.25/0.375/0.5/0.75/1/1.5rem)을 그대로 옮긴 것이라,
|
||||
// 기준값이 0.75rem 이면 지금까지와 픽셀 단위로 같고 0 이면 전부 각진다.
|
||||
'--radius-sm': `calc(${look.radius} * 0.34)`,
|
||||
'--radius-md': `calc(${look.radius} * 0.5)`,
|
||||
'--radius-lg': `calc(${look.radius} * 0.67)`,
|
||||
'--radius-xl': look.radius,
|
||||
'--radius-2xl': `calc(${look.radius} * 1.34)`,
|
||||
'--radius-3xl': `calc(${look.radius} * 2)`,
|
||||
'--shadow-xs': look.shadow,
|
||||
'--shadow-sm': look.shadow,
|
||||
'--shadow-md': look.shadow,
|
||||
} as CSSProperties;
|
||||
|
||||
/**
|
||||
|
||||
@@ -2,6 +2,7 @@ import {useState} from 'react';
|
||||
import {
|
||||
AlertTriangle,
|
||||
Check,
|
||||
ClipboardCopy,
|
||||
Image as ImageIcon,
|
||||
Info,
|
||||
FileText,
|
||||
@@ -10,7 +11,9 @@ import {
|
||||
Pencil,
|
||||
Plus,
|
||||
Shapes,
|
||||
Sparkles,
|
||||
Trash2,
|
||||
Wand2,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import type {InfoField} from '@o2o/shared';
|
||||
@@ -20,9 +23,16 @@ import {Input} from '@/components/ui/input';
|
||||
import {PasteFactsPanel, RecollectPanel} from '@/features/onboarding';
|
||||
import {cn} from '@/lib/utils';
|
||||
import {useBuilderStore, useUnverifiedFields, type RightTab} from '@/stores/builder';
|
||||
import {INDUSTRY_CONFIGS} from '@/data/industryData';
|
||||
import {FaqPanel} from './FaqPanel';
|
||||
import {SectionDesignPanel} from './SectionDesignPanel';
|
||||
import {resolveVariant} from './canvas/registry';
|
||||
import {
|
||||
buildPrompt,
|
||||
dataSpecFor,
|
||||
parseSectionData,
|
||||
SECTION_DATA_MAX_CHARS,
|
||||
} from './canvas/dataSpec';
|
||||
|
||||
const TABS: {id: RightTab; label: string; icon: typeof Info}[] = [
|
||||
{id: 'content', label: '콘텐츠', icon: FileText},
|
||||
@@ -148,7 +158,8 @@ function ContentTab() {
|
||||
className="w-full resize-y rounded-md border border-input bg-background px-3 py-2 text-xs leading-relaxed outline-none focus:border-ring focus:ring-2 focus:ring-ring/30"
|
||||
/>
|
||||
</label>}
|
||||
{!supportsTitle && !supportsDescription && !supportsBody && (
|
||||
{dataSpecFor(section.type) && <SectionDataPanel sectionId={section.id} sectionType={section.type} />}
|
||||
{!supportsTitle && !supportsDescription && !supportsBody && !dataSpecFor(section.type) && (
|
||||
<p className="rounded-md border border-dashed border-border p-3 text-center text-[11px] text-muted-foreground">
|
||||
이 레이아웃에는 직접 입력하는 문구가 없습니다. 수집된 데이터만 표시합니다.
|
||||
</p>
|
||||
@@ -160,6 +171,159 @@ function ContentTab() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 붙여넣기 아이템의 JSON 입력.
|
||||
*
|
||||
* ★ 원문을 그대로 저장한다. 깨진 JSON 도 담아 두고, 왜 깨졌는지만 아래에 말한다 —
|
||||
* 저장을 막으면 사장님은 고칠 기회 없이 쓰던 걸 잃는다.
|
||||
*/
|
||||
function SectionDataPanel({sectionId, sectionType}: {sectionId: string; sectionType: string}) {
|
||||
const spec = dataSpecFor(sectionType);
|
||||
const sections = useBuilderStore((s) => s.sections);
|
||||
const updateSectionData = useBuilderStore((s) => s.updateSectionData);
|
||||
const storeName = useBuilderStore((s) => s.storeName);
|
||||
const location = useBuilderStore((s) => s.location);
|
||||
const industry = useBuilderStore((s) => s.industry);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [showPrompt, setShowPrompt] = useState(false);
|
||||
|
||||
const section = sections.find((item) => item.id === sectionId);
|
||||
if (!spec || !section) return null;
|
||||
|
||||
const raw = section.data ?? '';
|
||||
const parsed = parseSectionData(sectionType, raw);
|
||||
const tooLong = raw.length > SECTION_DATA_MAX_CHARS;
|
||||
|
||||
// 상호·주소가 이미 박혀 있는 프롬프트. 사장님이 빈칸을 채울 일이 없어야 한다.
|
||||
const promptText = buildPrompt(spec, {
|
||||
storeName,
|
||||
location,
|
||||
industryLabel: INDUSTRY_CONFIGS[industry].name,
|
||||
});
|
||||
|
||||
const copyPrompt = async () => {
|
||||
const text = promptText;
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1600);
|
||||
} catch {
|
||||
// 클립보드가 막힌 브라우저 — 프롬프트를 화면에 띄워 직접 긁을 수 있게 한다.
|
||||
window.prompt('아래 프롬프트를 복사해 ChatGPT 에 붙여넣으세요', text);
|
||||
}
|
||||
};
|
||||
|
||||
/** 유효한 JSON 만 2칸 들여쓰기로 다시 쓴다. 깨져 있으면 손대지 않는다. */
|
||||
const tidy = () => {
|
||||
try {
|
||||
updateSectionData(sectionId, JSON.stringify(JSON.parse(raw), null, 2));
|
||||
} catch {
|
||||
// 그대로 둔다 — 아래 오류 줄이 이미 어디가 깨졌는지 말하고 있다.
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2 rounded-md border border-border bg-muted/30 p-2.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Sparkles className="size-3.5 text-primary" />
|
||||
<span className="text-xs font-bold">{spec.label} 내용 (JSON)</span>
|
||||
</div>
|
||||
<p className="text-[10px] leading-relaxed text-muted-foreground">
|
||||
프롬프트를 복사해 ChatGPT·Claude 에 그대로 붙여넣으면 JSON 을 줍니다. 받은 JSON 을 아래에 붙여넣으세요.
|
||||
</p>
|
||||
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
<Button type="button" size="sm" variant="primary" className="h-7 gap-1 text-[11px]" onClick={copyPrompt}>
|
||||
<ClipboardCopy className="size-3" />
|
||||
{copied ? '복사됨' : '프롬프트 복사'}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 gap-1 text-[11px]"
|
||||
onClick={() => updateSectionData(sectionId, spec.sample)}
|
||||
>
|
||||
<Wand2 className="size-3" />
|
||||
예시 넣기
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-7 text-[11px]"
|
||||
onClick={() => setShowPrompt((v) => !v)}
|
||||
>
|
||||
{showPrompt ? '프롬프트 접기' : '프롬프트 보기'}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-7 text-[11px]"
|
||||
onClick={tidy}
|
||||
disabled={!raw.trim() || Boolean(parsed.error)}
|
||||
>
|
||||
줄맞춤
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{showPrompt && (
|
||||
<div className="space-y-1">
|
||||
<p className="text-[10px] text-muted-foreground">
|
||||
아래 내용이 그대로 복사됩니다. 상호와 지역은 이미 채워져 있습니다.
|
||||
</p>
|
||||
<textarea
|
||||
readOnly
|
||||
value={promptText}
|
||||
rows={12}
|
||||
spellCheck={false}
|
||||
onFocus={(event) => event.currentTarget.select()}
|
||||
className="w-full resize-y rounded-md border border-border bg-background/60 px-2.5 py-2 font-mono text-[10px] leading-relaxed text-muted-foreground outline-none"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<textarea
|
||||
value={raw}
|
||||
onChange={(event) => updateSectionData(sectionId, event.target.value)}
|
||||
placeholder={`{ "kind": "${spec.kind}", "items": [ ... ] }`}
|
||||
rows={10}
|
||||
spellCheck={false}
|
||||
className="w-full resize-y rounded-md border border-input bg-background px-2.5 py-2 font-mono text-[11px] leading-relaxed outline-none focus:border-ring focus:ring-2 focus:ring-ring/30"
|
||||
/>
|
||||
|
||||
{parsed.error ? (
|
||||
<p className="flex items-start gap-1.5 text-[10px] leading-relaxed text-destructive">
|
||||
<AlertTriangle className="mt-px size-3 shrink-0" />
|
||||
{parsed.error}
|
||||
</p>
|
||||
) : raw.trim() ? (
|
||||
<p className="text-[10px] text-muted-foreground">
|
||||
{spec.label} {parsed.items.length}개 · 출처 {parsed.sourced}개
|
||||
{parsed.unverified > 0 && ` · 확인필요 ${parsed.unverified}개`}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{parsed.kindMismatch && (
|
||||
<p className="flex items-start gap-1.5 text-[10px] leading-relaxed text-warning">
|
||||
<AlertTriangle className="mt-px size-3 shrink-0" />
|
||||
이 JSON 은 "{parsed.kindMismatch}" 아이템 것입니다. {spec.label} 섹션에는 kind 가 "{spec.kind}" 인
|
||||
JSON 을 넣어 주세요.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{tooLong && (
|
||||
<p className="flex items-start gap-1.5 text-[10px] leading-relaxed text-destructive">
|
||||
<AlertTriangle className="mt-px size-3 shrink-0" />
|
||||
너무 깁니다({raw.length.toLocaleString()}자). {SECTION_DATA_MAX_CHARS.toLocaleString()}자 아래로 줄여
|
||||
주세요 — 이 상태로는 디자인 설정이 서버에 저장되지 않습니다.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PhotosTab() {
|
||||
const photos = useBuilderStore((s) => s.photos);
|
||||
const setPrimaryPhoto = useBuilderStore((s) => s.setPrimaryPhoto);
|
||||
|
||||
@@ -6,12 +6,15 @@ import {
|
||||
SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy,
|
||||
} from '@dnd-kit/sortable';
|
||||
import {CSS} from '@dnd-kit/utilities';
|
||||
import {useState} from 'react';
|
||||
import type {SectionItem} from '@o2o/shared';
|
||||
import {GripVertical, Layers, Lock, Shapes} from 'lucide-react';
|
||||
import {Check, GripVertical, Layers, Lock, Plus, Shapes, Trash2, X} from 'lucide-react';
|
||||
import {Switch} from '@/components/ui/switch';
|
||||
import {cn} from '@/lib/utils';
|
||||
import {useBuilderStore} from '@/stores/builder';
|
||||
import {ADDABLE_SECTIONS, addableSection} from './canvas/addable';
|
||||
import {resolveVariant} from './canvas/registry';
|
||||
import {VariantThumb} from './canvas/thumbs';
|
||||
|
||||
interface SectionListPanelProps {
|
||||
onAfterSelect?: () => void;
|
||||
@@ -28,7 +31,10 @@ function SortableSection({section, index, onAfterSelect}: SortableSectionProps)
|
||||
const isSelected = useBuilderStore((s) => s.selectedSectionId === section.id);
|
||||
const selectSection = useBuilderStore((s) => s.selectSection);
|
||||
const toggleSection = useBuilderStore((s) => s.toggleSection);
|
||||
const removeSection = useBuilderStore((s) => s.removeSection);
|
||||
const variant = resolveVariant(section, industry);
|
||||
// 업종 기본 섹션은 스위치로 끄는 것이지 빼는 게 아니다 — 뺄 수 있는 건 나중에 넣은 것뿐이다.
|
||||
const canRemove = Boolean(addableSection(section.type));
|
||||
const {attributes, listeners, setNodeRef, transform, transition, isDragging} = useSortable({
|
||||
id: section.id,
|
||||
});
|
||||
@@ -131,6 +137,20 @@ function SortableSection({section, index, onAfterSelect}: SortableSectionProps)
|
||||
</div>
|
||||
|
||||
<div className="flex shrink-0 items-center gap-1" onClick={(event) => event.stopPropagation()} role="presentation">
|
||||
{canRemove && (
|
||||
<button
|
||||
type="button"
|
||||
title={`${section.name} 섹션 빼기`}
|
||||
aria-label={`${section.name} 섹션 빼기`}
|
||||
onClick={() => {
|
||||
if (section.data?.trim() && !window.confirm(`${section.name} 에 넣은 내용도 함께 지워집니다. 뺄까요?`)) return;
|
||||
removeSection(section.id);
|
||||
}}
|
||||
className="rounded p-1 text-muted-foreground opacity-0 transition-opacity hover:bg-destructive/10 hover:text-destructive group-hover:opacity-100 focus-visible:opacity-100"
|
||||
>
|
||||
<Trash2 className="size-3.5" />
|
||||
</button>
|
||||
)}
|
||||
{section.isLocked ? (
|
||||
<span title="SEO·필수 마크업이 달린 섹션이라 끌 수 없습니다." className="p-1 text-muted-foreground">
|
||||
<Lock className="size-4" />
|
||||
@@ -144,9 +164,70 @@ function SortableSection({section, index, onAfterSelect}: SortableSectionProps)
|
||||
);
|
||||
}
|
||||
|
||||
/** [+ 섹션 추가] 가 여는 목록. 이미 들어 있는 것은 '넣음' 으로 표시만 하고 다시 넣지 않는다. */
|
||||
function AddSectionPicker({onClose, onAfterSelect}: {onClose: () => void; onAfterSelect?: () => void}) {
|
||||
const sections = useBuilderStore((s) => s.sections);
|
||||
const addSection = useBuilderStore((s) => s.addSection);
|
||||
|
||||
return (
|
||||
<div className="border-t border-border bg-muted/40 p-2">
|
||||
<div className="flex items-center justify-between px-1 pb-1.5">
|
||||
<span className="text-[11px] font-bold">추가할 섹션</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label="섹션 추가 닫기"
|
||||
className="rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<p className="px-1 pb-2 text-[10px] leading-relaxed text-muted-foreground">
|
||||
내용은 [콘텐츠] 탭에서 프롬프트를 복사해 받은 JSON 을 붙여넣어 채웁니다.
|
||||
</p>
|
||||
<ul className="space-y-1.5">
|
||||
{ADDABLE_SECTIONS.map((item) => {
|
||||
const already = sections.some((section) => section.type === item.type);
|
||||
return (
|
||||
<li key={item.type}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={already}
|
||||
onClick={() => {
|
||||
addSection(item.type);
|
||||
onClose();
|
||||
onAfterSelect?.();
|
||||
}}
|
||||
className={cn(
|
||||
'flex w-full items-start gap-2 rounded-md border p-2 text-left transition-colors',
|
||||
already
|
||||
? 'cursor-default border-border bg-muted/50 text-muted-foreground'
|
||||
: 'border-border bg-card hover:border-primary hover:bg-primary/5',
|
||||
)}
|
||||
>
|
||||
<VariantThumb thumb={item.thumb} className="mt-0.5 w-9 shrink-0" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex items-center gap-1 text-[11px] font-semibold text-foreground">
|
||||
{item.name}
|
||||
{already && <Check className="size-3 text-muted-foreground" />}
|
||||
</span>
|
||||
<span className="mt-0.5 block text-[10px] leading-relaxed text-muted-foreground">
|
||||
{already ? '이미 목록에 있습니다' : item.description}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SectionListPanel({onAfterSelect}: SectionListPanelProps) {
|
||||
const sections = useBuilderStore((s) => s.sections);
|
||||
const reorderSection = useBuilderStore((s) => s.reorderSection);
|
||||
const [isPickerOpen, setPickerOpen] = useState(false);
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, {activationConstraint: {distance: 6}}),
|
||||
useSensor(KeyboardSensor, {coordinateGetter: sortableKeyboardCoordinates}),
|
||||
@@ -191,6 +272,19 @@ export function SectionListPanel({onAfterSelect}: SectionListPanelProps) {
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
|
||||
{isPickerOpen ? (
|
||||
<AddSectionPicker onClose={() => setPickerOpen(false)} onAfterSelect={onAfterSelect} />
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPickerOpen(true)}
|
||||
className="flex items-center justify-center gap-1.5 border-t border-border bg-card p-2.5 text-[11px] font-semibold text-muted-foreground transition-colors hover:bg-primary/5 hover:text-primary"
|
||||
>
|
||||
<Plus className="size-3.5" />
|
||||
섹션 추가
|
||||
</button>
|
||||
)}
|
||||
|
||||
<p className="border-t border-border bg-muted/30 p-2.5 text-center text-[10px] text-muted-foreground">
|
||||
* 자물쇠 항목은 검색·AI 노출에 필요한 마크업이 달려 있어 고정입니다.
|
||||
</p>
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* 나중에 넣을 수 있는 섹션 — [+ 섹션 추가] 가 고르는 목록.
|
||||
*
|
||||
* 업종 시드(industryData)는 "처음부터 있는 것"이고 여기는 "필요하면 넣는 것"이다.
|
||||
* 붙여넣기 아이템은 내용이 없으면 빈 섹션이라, 시드에 박아 두면 아무도 안 쓰는 칸이 늘 붙어 있다.
|
||||
*/
|
||||
import type {SectionItem} from '@o2o/shared';
|
||||
import {SECTION_DATA_SPEC} from './dataSpec';
|
||||
import {defaultVariant} from './registry';
|
||||
import type {ThumbKey} from './types';
|
||||
|
||||
export interface AddableSection {
|
||||
type: string;
|
||||
name: string;
|
||||
description: string;
|
||||
thumb: ThumbKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* 추가할 수 있는 섹션 목록.
|
||||
*
|
||||
* ★ dataSpec 이 단일 출처다 — 아이템을 하나 더 만들면 여기에도 자동으로 나타난다.
|
||||
* 목록을 따로 들면 아이템을 추가하고 이 표를 잊어 "만들었는데 고를 수가 없는" 상태가 된다.
|
||||
*/
|
||||
export const ADDABLE_SECTIONS: AddableSection[] = Object.values(SECTION_DATA_SPEC).map((spec) => {
|
||||
const variant = defaultVariant(spec.kind);
|
||||
return {
|
||||
type: spec.kind,
|
||||
name: spec.label,
|
||||
description: variant?.description ?? '',
|
||||
thumb: variant?.thumb ?? 'cards',
|
||||
};
|
||||
});
|
||||
|
||||
export function addableSection(type: string): AddableSection | undefined {
|
||||
return ADDABLE_SECTIONS.find((item) => item.type === type);
|
||||
}
|
||||
|
||||
/** 목록에 새로 넣을 섹션 한 줄. id 는 타입과 같다 — 같은 아이템을 두 번 넣지 않는다. */
|
||||
export function newSectionOf(type: string): SectionItem | undefined {
|
||||
const addable = addableSection(type);
|
||||
if (!addable) return undefined;
|
||||
return {
|
||||
id: type,
|
||||
type,
|
||||
name: addable.name,
|
||||
description: addable.description,
|
||||
isLocked: false,
|
||||
isEnabled: true,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
/**
|
||||
* 붙여넣기 아이템 계약 — "이 섹션 타입은 어떤 JSON 을 먹나"의 단일 출처.
|
||||
*
|
||||
* 배리에이션 레지스트리와 같은 결이다: 여기 한 줄을 더하면 캔버스·[콘텐츠] 탭·프롬프트가 동시에 는다.
|
||||
* 데이터는 섹션 **타입**에 붙고 모양은 배리에이션이 갈아끼운다 — 같은 곡 JSON 으로 도넛판도 카세트도 된다.
|
||||
*/
|
||||
|
||||
/** 사장님이 스스로 매긴 확신. 미검증 값이 화면·JSON-LD 로 새지 않게 하는 첫 관문이다. */
|
||||
export type DataVerified = '확인' | '확인필요';
|
||||
|
||||
export interface DataSource {
|
||||
name: string;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
export interface SongItem {
|
||||
title: string;
|
||||
artist?: string;
|
||||
lyricist?: string;
|
||||
composer?: string;
|
||||
year?: number;
|
||||
label?: string;
|
||||
labelColor?: string;
|
||||
story?: string;
|
||||
connection?: string;
|
||||
verified?: DataVerified;
|
||||
source?: DataSource;
|
||||
}
|
||||
|
||||
export interface DailyItem {
|
||||
monthDay: string;
|
||||
category?: string;
|
||||
title: string;
|
||||
body?: string;
|
||||
season?: string;
|
||||
tags?: string[];
|
||||
verified?: DataVerified;
|
||||
source?: DataSource;
|
||||
}
|
||||
|
||||
export interface CourseStop {
|
||||
order?: number;
|
||||
name: string;
|
||||
minutes?: number;
|
||||
note?: string;
|
||||
searchQuery?: string;
|
||||
}
|
||||
|
||||
export interface CourseItem {
|
||||
name: string;
|
||||
duration?: string;
|
||||
startsFrom?: string;
|
||||
stops?: CourseStop[];
|
||||
verified?: DataVerified;
|
||||
source?: DataSource;
|
||||
}
|
||||
|
||||
export interface ScheduleSlot {
|
||||
/** 24시간 표기 "09:30". 정렬·플립 시각 표시가 이 값을 그대로 쓴다. */
|
||||
time: string;
|
||||
title: string;
|
||||
place?: string;
|
||||
minutes?: number;
|
||||
note?: string;
|
||||
searchQuery?: string;
|
||||
}
|
||||
|
||||
export interface ScheduleItem {
|
||||
name: string;
|
||||
/** 누구를 위한 하루인가("혼자 온 손님" · "아이와 함께"). 고르는 기준이 된다. */
|
||||
audience?: string;
|
||||
season?: string;
|
||||
slots?: ScheduleSlot[];
|
||||
verified?: DataVerified;
|
||||
source?: DataSource;
|
||||
}
|
||||
|
||||
export interface SectionDataSpec {
|
||||
/** JSON 봉투의 `kind`. 섹션 타입과 같은 값이라 다른 아이템 JSON 을 붙여넣으면 바로 잡힌다. */
|
||||
kind: string;
|
||||
label: string;
|
||||
/** 없으면 그 줄을 통째로 버리는 키. 빈 껍데기가 화면에 줄만 남기는 걸 막는다. */
|
||||
requiredKey: string;
|
||||
/** [예시 넣기] 가 그대로 넣는 값. */
|
||||
sample: string;
|
||||
/** 프롬프트의 '무엇을 시키나' 부분. 머리·공통규칙은 buildPrompt 가 붙인다. */
|
||||
task: string;
|
||||
/** 그 아이템에만 걸리는 금지·형식 규칙. */
|
||||
rules: string;
|
||||
}
|
||||
|
||||
// ★ 테마 전체 상한이 64KB 다(site_service._THEME_MAX_BYTES). 세 아이템이 각자 다 채우면 거절당하고,
|
||||
// 거절은 발행 직전에야 드러난다. 그래서 한 섹션당 여기서 먼저 끊는다.
|
||||
export const SECTION_DATA_MAX_CHARS = 12000;
|
||||
|
||||
export interface PromptContext {
|
||||
storeName: string;
|
||||
/** 사업장 주소 원문. 여기서 시·군·구를 뽑아 '지역'으로 쓴다. */
|
||||
location: string;
|
||||
/** 업종 이름('숙박' · '카페' …). 어떤 손님에게 쓰는 글인지 알려 준다. */
|
||||
industryLabel: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 주소 원문에서 시·군·구 한 조각.
|
||||
*
|
||||
* ★ 주소를 통째로 넣으면 모델이 그 동네 안쪽만 뒤진다. 이야깃거리는 시 단위에 있다.
|
||||
*/
|
||||
export function regionOf(location: string): string {
|
||||
const token = location
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.find((word) => /[시군구]$/.test(word) && word.length >= 2);
|
||||
return token ?? location.trim();
|
||||
}
|
||||
|
||||
const PROMPT_RULES = `
|
||||
[공통 규칙]
|
||||
1. JSON 하나만 출력한다. 인사말·설명·코드펜스를 붙이지 않는다.
|
||||
2. 확인되지 않은 값은 필드를 통째로 뺀다. 빈 문자열로 채우거나 지어내지 않는다.
|
||||
3. source.url 은 실제로 열리는 공식·기관·언론 페이지여야 한다. 검색 결과 주소는 쓰지 않는다.
|
||||
4. 근거가 확실하면 verified 를 "확인", 애매하면 "확인필요" 로 적는다. 애매한 걸 "확인" 으로 올리지 않는다.
|
||||
5. 가사·시·소설의 원문을 한 줄도 옮기지 않는다. 제목과 배경만 쓴다.
|
||||
6. 설명 문장은 항목당 두 문장을 넘기지 않는다.
|
||||
7. 이미지 주소는 만들지 않는다. 필요하면 imageQuery 에 검색어만 적는다.
|
||||
`;
|
||||
|
||||
/**
|
||||
* 붙여넣으면 바로 답이 나오는 프롬프트.
|
||||
*
|
||||
* ★ `[지역]` 같은 빈칸을 남기지 않는다. 빈칸이 있으면 사장님이 못 채우고 그대로 보내고,
|
||||
* 모델은 빈칸을 지명으로 착각해 엉뚱한 곳 이야기를 지어낸다.
|
||||
*/
|
||||
export function buildPrompt(spec: SectionDataSpec, ctx: PromptContext): string {
|
||||
const store = ctx.storeName.trim() || '(가게 이름을 먼저 입력해 주세요)';
|
||||
const region = regionOf(ctx.location) || '(주소를 먼저 입력해 주세요)';
|
||||
const address = ctx.location.trim();
|
||||
|
||||
const head = `너는 지역 콘텐츠 리서처다. 아래 조건에 맞는 JSON 하나만 출력한다.
|
||||
|
||||
[업소] ${store} (${ctx.industryLabel})
|
||||
[지역] ${region}${address && address !== region ? `\n[주소] ${address}` : ''}
|
||||
|
||||
아래 '해야 할 일'에서 [지역] = ${region}, [업소] = ${store}.
|
||||
`;
|
||||
|
||||
return `${head}
|
||||
${spec.task}
|
||||
${PROMPT_RULES}${spec.rules}`;
|
||||
}
|
||||
|
||||
export const SECTION_DATA_SPEC: Record<string, SectionDataSpec> = {
|
||||
songs: {
|
||||
kind: 'songs',
|
||||
label: '가요 다방',
|
||||
requiredKey: 'title',
|
||||
sample: JSON.stringify(
|
||||
{
|
||||
kind: 'songs',
|
||||
version: 1,
|
||||
title: '가요 다방',
|
||||
subtitle: '이 도시를 노래한 곡들',
|
||||
items: [
|
||||
{
|
||||
title: '금강 나그네',
|
||||
artist: '이미자',
|
||||
lyricist: '이병훈',
|
||||
composer: '박춘석',
|
||||
year: 1966,
|
||||
label: '지구레코드',
|
||||
labelColor: '#d4551f',
|
||||
story: '군산항을 모티브로 한 곡. 금강 하구와 항구의 이별 정서를 담았습니다.',
|
||||
connection: '우리 스테이에서 걸어 12분, 내항 부잔교가 이 노래의 배경입니다.',
|
||||
verified: '확인',
|
||||
source: {name: '세계일보', url: 'https://www.segye.com/newsView/20160329000709'},
|
||||
},
|
||||
{
|
||||
title: '님 떠난 군산항',
|
||||
artist: '이미자',
|
||||
labelColor: '#1d3c74',
|
||||
story: '군산항의 이별 정서를 담은 곡. 발표 연도와 작사·작곡은 아직 확인 중입니다.',
|
||||
verified: '확인필요',
|
||||
source: {name: '세계일보', url: 'https://www.segye.com/newsView/20160329000709'},
|
||||
},
|
||||
{
|
||||
title: '헤어진 군산항',
|
||||
artist: '박제연',
|
||||
labelColor: '#2a6053',
|
||||
story: '1960년대 군산을 노래한 곡으로 전해집니다. 항구도시의 정서를 담았습니다.',
|
||||
verified: '확인필요',
|
||||
source: {name: '세계일보', url: 'https://www.segye.com/newsView/20160329000709'},
|
||||
},
|
||||
],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
task: `[해야 할 일]
|
||||
[지역]을 노래한 대중가요를 8곡까지 찾아 아래 JSON 으로 정리한다.
|
||||
1960~80년대 곡을 우선하고, 지명·항구·강·다리가 제목이나 배경에 나오는 곡을 고른다.
|
||||
|
||||
[스키마]
|
||||
{ "kind":"songs", "version":1, "title":"가요 다방", "subtitle":"...", "items":[
|
||||
{ "title":"곡명", "artist":"가수", "lyricist":"작사", "composer":"작곡",
|
||||
"year":1966, "label":"음반사", "labelColor":"#d4551f",
|
||||
"story":"곡의 배경 (두 문장 이내, 가사 없이)",
|
||||
"connection":"[업소]와 이 곡을 잇는 한 문장",
|
||||
"verified":"확인|확인필요",
|
||||
"source":{"name":"출처명","url":"https://..."} } ] }`,
|
||||
rules: `
|
||||
[이 아이템만의 규칙]
|
||||
· lyrics 필드는 스키마에 없다. 어떤 이유로도 만들지 마라. 가사 한 소절도 안 된다.
|
||||
· labelColor 는 레코드 라벨 색이다. 곡의 분위기에 맞춰 진한 색 하나를 hex 로 고른다.
|
||||
· 작사·작곡·발표연도를 모르면 그 필드를 뺀다. "미상" 이라고 쓰지 않는다.`,
|
||||
},
|
||||
|
||||
daily: {
|
||||
kind: 'daily',
|
||||
label: '오늘의 한 장',
|
||||
requiredKey: 'title',
|
||||
sample: JSON.stringify(
|
||||
{
|
||||
kind: 'daily',
|
||||
version: 1,
|
||||
title: '오늘의 한 장',
|
||||
items: [
|
||||
{
|
||||
monthDay: '09-01',
|
||||
category: '장소',
|
||||
title: '군산 내항 부잔교',
|
||||
body: '조수 차가 큰 항구에서 배를 대기 위해 물 위에 띄운 다리입니다. 미곡 반출의 통로이기도 했습니다.',
|
||||
season: '가을',
|
||||
tags: ['#군산내항', '#부잔교'],
|
||||
verified: '확인',
|
||||
source: {name: '군산시 문화관광', url: 'https://www.gunsan.go.kr/tour/'},
|
||||
},
|
||||
{
|
||||
monthDay: '09-02',
|
||||
category: '축제',
|
||||
title: '군산시간여행축제',
|
||||
body: '근대문화도시의 정체성을 축제로 풀어냅니다. 밤에 걷는 골목이 낮과 다릅니다.',
|
||||
season: '가을',
|
||||
tags: ['#시간여행축제', '#근대문화'],
|
||||
verified: '확인필요',
|
||||
source: {name: '군산시 문화관광', url: 'https://www.gunsan.go.kr/tour/'},
|
||||
},
|
||||
{
|
||||
monthDay: '09-03',
|
||||
category: '음식',
|
||||
title: '이성당',
|
||||
body: '오래된 빵집 하나가 도시의 이력이 된 자리입니다. 단팥빵 앞의 줄이 그 증거입니다.',
|
||||
season: '가을',
|
||||
tags: ['#이성당', '#오래된가게'],
|
||||
verified: '확인',
|
||||
source: {name: '대한민국 구석구석', url: 'https://korean.visitkorea.or.kr/'},
|
||||
},
|
||||
],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
task: `[해야 할 일]
|
||||
[지역]의 이야깃거리를 30개 찾아, 하루에 하나씩 뜯어 보는 일력용 JSON 으로 만든다.
|
||||
같은 주제를 두 번 쓰지 않는다. 계절이 맞는 날짜에 배치한다(축제는 실제 개최 시기에).
|
||||
|
||||
[스키마]
|
||||
{ "kind":"daily", "version":1, "title":"오늘의 한 장", "items":[
|
||||
{ "monthDay":"09-02", "category":"역사|인물|장소|음식|축제|바다|문학",
|
||||
"title":"제목", "body":"두 문장 이내", "season":"봄|여름|가을|겨울",
|
||||
"tags":["#태그"], "verified":"확인|확인필요",
|
||||
"source":{"name":"출처명","url":"https://..."} } ] }`,
|
||||
rules: `
|
||||
[이 아이템만의 규칙]
|
||||
· monthDay 는 MM-DD 다. 연도를 넣지 않는다 — 해마다 다시 쓰는 일력이다.
|
||||
· 30개를 억지로 채우지 마라. 확실한 것이 12개면 12개만 낸다.
|
||||
· 같은 장소를 계절만 바꿔 반복하지 않는다.`,
|
||||
},
|
||||
|
||||
course: {
|
||||
kind: 'course',
|
||||
label: '반나절 산책',
|
||||
requiredKey: 'name',
|
||||
sample: JSON.stringify(
|
||||
{
|
||||
kind: 'course',
|
||||
version: 1,
|
||||
title: '반나절 산책',
|
||||
items: [
|
||||
{
|
||||
name: '탁류길 코스',
|
||||
duration: '3시간',
|
||||
startsFrom: '스테이 머뭄',
|
||||
stops: [
|
||||
{order: 1, name: '채만식문학관', minutes: 12, note: '금강 하구 옆. 소설의 배경을 먼저 눈에 담습니다.', searchQuery: '군산 채만식문학관'},
|
||||
{order: 2, name: '군산 내항 부잔교', minutes: 9, note: '조수에 오르내리던 뜬다리. 이 코스의 중심입니다.', searchQuery: '군산 내항 부잔교'},
|
||||
{order: 3, name: '째보선창', minutes: 7, note: '항구 노동의 기억이 남은 선창입니다.', searchQuery: '군산 째보선창'},
|
||||
{order: 4, name: '초원사진관', minutes: 11, note: '영화가 남기고 간 자리입니다.', searchQuery: '군산 초원사진관'},
|
||||
{order: 5, name: '이성당', minutes: 6, note: '코스의 끝. 단팥빵 하나로 반나절을 닫습니다.', searchQuery: '군산 이성당'},
|
||||
],
|
||||
verified: '확인',
|
||||
source: {name: '군산 스탬프투어', url: 'https://www.gunsanstamp.kr/'},
|
||||
},
|
||||
],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
task: `[해야 할 일]
|
||||
[업소]에서 출발하는 반나절 산책 코스를 2~3개 만든다. 코스마다 정거장 4~6곳.
|
||||
걸어서 이동할 수 있는 순서로 배열하고, 앞 정거장에서 다음까지 걸리는 분을 minutes 에 적는다.
|
||||
|
||||
[스키마]
|
||||
{ "kind":"course", "version":1, "title":"반나절 산책", "items":[
|
||||
{ "name":"코스 이름", "duration":"3시간", "startsFrom":"[업소]",
|
||||
"stops":[ {"order":1,"name":"장소","minutes":12,
|
||||
"note":"한 문장","searchQuery":"검색어"} ],
|
||||
"verified":"확인|확인필요",
|
||||
"source":{"name":"출처명","url":"https://..."} } ] }`,
|
||||
rules: `
|
||||
[이 아이템만의 규칙]
|
||||
· 정거장에 url 을 넣지 않는다. searchQuery(지도 검색어)만 넣는다.
|
||||
· minutes 는 도보 기준이다. 차로만 갈 수 있으면 note 에 "차로 이동" 이라고 적는다.
|
||||
· 영업시간·요금은 넣지 않는다. 바뀌면 손님이 헛걸음한다.`,
|
||||
},
|
||||
|
||||
schedule: {
|
||||
kind: 'schedule',
|
||||
label: '여행 스케줄',
|
||||
requiredKey: 'name',
|
||||
sample: JSON.stringify(
|
||||
{
|
||||
kind: 'schedule',
|
||||
version: 1,
|
||||
title: '여행 스케줄',
|
||||
items: [
|
||||
{
|
||||
name: '비 오는 날의 하루',
|
||||
audience: '혼자 온 손님',
|
||||
season: '장마',
|
||||
slots: [
|
||||
{time: '09:00', title: '늦은 아침', place: '스테이 머뭄', minutes: 60, note: '창가 자리에서 비 소리를 먼저 듣습니다.'},
|
||||
{time: '10:30', title: '실내로 피신', place: '군산근대역사박물관', minutes: 90, note: '항구 도시가 어떻게 만들어졌는지 한 바퀴.', searchQuery: '군산근대역사박물관'},
|
||||
{time: '12:30', title: '점심', place: '한일옥', minutes: 60, note: '무국 한 그릇으로 몸을 데웁니다.', searchQuery: '군산 한일옥'},
|
||||
{time: '14:00', title: '책과 커피', place: '마리서사', minutes: 120, note: '비 그칠 때까지 앉아 있기 좋은 곳입니다.', searchQuery: '군산 마리서사'},
|
||||
{time: '17:00', title: '해 질 무렵 산책', place: '경암동 철길마을', minutes: 60, note: '비 온 뒤 철길에 물이 고여 하늘이 두 번 보입니다.', searchQuery: '군산 경암동 철길마을'},
|
||||
],
|
||||
verified: '확인필요',
|
||||
source: {name: '군산시 문화관광', url: 'https://www.gunsan.go.kr/tour'},
|
||||
},
|
||||
],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
task: `[해야 할 일]
|
||||
[업소]에 묵거나 들른 손님이 [지역]에서 하루를 어떻게 보내면 좋을지 여행 스케줄을 2~3개 만든다.
|
||||
스케줄마다 시간대 5~7개. 아침부터 저녁까지 시각 순서로 배열한다.
|
||||
스케줄은 서로 성격이 달라야 한다 — 날씨(비 오는 날)·동행(아이와 함께)·계절 중 하나로 가른다.
|
||||
|
||||
[스키마]
|
||||
{ "kind":"schedule", "version":1, "title":"여행 스케줄", "items":[
|
||||
{ "name":"스케줄 이름", "audience":"누구를 위한 하루", "season":"계절·날씨",
|
||||
"slots":[ {"time":"09:00","title":"무엇을 하나","place":"장소",
|
||||
"minutes":60,"note":"한 문장","searchQuery":"지도 검색어"} ],
|
||||
"verified":"확인|확인필요",
|
||||
"source":{"name":"출처명","url":"https://..."} } ] }`,
|
||||
rules: `
|
||||
[이 아이템만의 규칙]
|
||||
· time 은 24시간 "HH:MM" 로만 적는다. "오전 9시" 처럼 쓰지 않는다.
|
||||
· 그 장소의 영업시간·휴무일을 안다고 가정하지 않는다. 바뀌면 손님이 헛걸음한다.
|
||||
· 첫 칸은 [업소]에서 시작하고, 이동은 걸어서 또는 대중교통으로 갈 수 있는 범위로 짠다.
|
||||
· 장소에 url 을 넣지 않는다. searchQuery 만 넣는다.
|
||||
· 예약이 필요한 곳은 note 에 "예약 필요" 라고만 적고 연락처는 쓰지 않는다.`,
|
||||
},
|
||||
};
|
||||
|
||||
export function dataSpecFor(sectionType: string): SectionDataSpec | undefined {
|
||||
return SECTION_DATA_SPEC[sectionType];
|
||||
}
|
||||
|
||||
export interface ParsedSectionData<T> {
|
||||
items: T[];
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
/** 사람에게 보여줄 실패 사유. 있으면 items 는 비어 있다. */
|
||||
error?: string;
|
||||
/** 붙여넣은 JSON 의 kind 가 이 섹션과 다르다 — 다른 아이템 것을 넣었다는 뜻. */
|
||||
kindMismatch?: string;
|
||||
/** verified 가 '확인' 이 아닌 항목 수. 화면에 각주로 뜬다. */
|
||||
unverified: number;
|
||||
/** source 가 붙은 항목 수. */
|
||||
sourced: number;
|
||||
}
|
||||
|
||||
const EMPTY: ParsedSectionData<never> = {items: [], unverified: 0, sourced: 0};
|
||||
|
||||
/**
|
||||
* JSON.parse 실패를 "몇 번째 줄"로 바꾼다.
|
||||
*
|
||||
* ★ V8 은 두 가지 모양으로 던진다 — `position N (line L column C)` 형과,
|
||||
* 위치 없이 깨진 조각만 인용하는 `Unexpected token 'X', ..."조각" is not valid JSON` 형이다.
|
||||
* 앞의 것만 보면 후자에서 위치를 통째로 잃는다(실제로 그랬다). 뒤의 것은 조각을 원문에서 되찾아 센다.
|
||||
*/
|
||||
function locate(raw: string, message: string): string {
|
||||
const where = (pos: number) => {
|
||||
const before = raw.slice(0, Math.max(0, pos));
|
||||
const line = before.split('\n').length;
|
||||
const col = pos - before.lastIndexOf('\n');
|
||||
return `${line}번째 줄 ${col}번째 글자`;
|
||||
};
|
||||
|
||||
const token = /Unexpected token '(.)'/.exec(message)?.[1];
|
||||
// 쉼표를 하나 더 찍은 경우가 압도적으로 많다 — 그 말을 먼저 해 준다.
|
||||
const hint =
|
||||
token === '}' || token === ']'
|
||||
? '닫는 괄호 바로 앞에 쉼표가 하나 더 있는지 보세요.'
|
||||
: '그 앞의 쉼표·따옴표·괄호를 확인해 주세요.';
|
||||
|
||||
const lineCol = /line (\d+) column (\d+)/.exec(message);
|
||||
if (lineCol) return `${lineCol[1]}번째 줄 ${lineCol[2]}번째 글자에서 JSON 이 끊깁니다. ${hint}`;
|
||||
|
||||
const at = /position (\d+)/.exec(message);
|
||||
if (at) return `${where(Number(at[1]))}에서 JSON 이 끊깁니다. ${hint}`;
|
||||
|
||||
// 위치 없이 조각만 인용하는 형 — 그 조각을 원문에서 되찾는다.
|
||||
const quoted = /\.\.\."([\s\S]*?)" is not valid JSON/.exec(message)?.[1];
|
||||
const found = quoted ? raw.indexOf(quoted) : -1;
|
||||
if (found >= 0) return `${where(found + quoted!.length)} 부근에서 JSON 이 끊깁니다. ${hint}`;
|
||||
|
||||
return 'JSON 이 아닙니다. ChatGPT 가 준 답에서 { 로 시작해 } 로 끝나는 부분만 붙여넣어 주세요.';
|
||||
}
|
||||
|
||||
/**
|
||||
* 붙여넣은 문자열 → 렌더 가능한 항목.
|
||||
*
|
||||
* ★ 절대 throw 하지 않는다. 편집 중인 JSON 은 늘 깨져 있고, 깨진 순간 캔버스가 죽으면 못 고친다.
|
||||
*/
|
||||
export function parseSectionData<T extends object>(
|
||||
sectionType: string,
|
||||
raw: string | undefined,
|
||||
): ParsedSectionData<T> {
|
||||
const spec = SECTION_DATA_SPEC[sectionType];
|
||||
const text = (raw ?? '').trim();
|
||||
if (!spec || !text) return EMPTY as ParsedSectionData<T>;
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch (error) {
|
||||
return {...EMPTY, error: locate(text, error instanceof Error ? error.message : '')};
|
||||
}
|
||||
|
||||
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
||||
return {...EMPTY, error: '바깥이 { } 로 감싸인 JSON 이어야 합니다.'};
|
||||
}
|
||||
|
||||
const envelope = parsed as Record<string, unknown>;
|
||||
const kind = typeof envelope.kind === 'string' ? envelope.kind : undefined;
|
||||
const rawItems = envelope.items;
|
||||
if (!Array.isArray(rawItems)) {
|
||||
return {...EMPTY, error: 'items 배열이 없습니다. 프롬프트로 다시 만들어 주세요.'};
|
||||
}
|
||||
|
||||
const items = rawItems.filter(
|
||||
(item): item is T =>
|
||||
typeof item === 'object' &&
|
||||
item !== null &&
|
||||
!Array.isArray(item) &&
|
||||
typeof (item as Record<string, unknown>)[spec.requiredKey] === 'string' &&
|
||||
((item as Record<string, unknown>)[spec.requiredKey] as string).trim().length > 0,
|
||||
);
|
||||
|
||||
let unverified = 0;
|
||||
let sourced = 0;
|
||||
for (const item of items) {
|
||||
const row = item as Record<string, unknown>;
|
||||
if (row.verified !== '확인') unverified += 1;
|
||||
if (row.source && typeof row.source === 'object') sourced += 1;
|
||||
}
|
||||
|
||||
return {
|
||||
items,
|
||||
title: typeof envelope.title === 'string' ? envelope.title : undefined,
|
||||
subtitle: typeof envelope.subtitle === 'string' ? envelope.subtitle : undefined,
|
||||
kindMismatch: kind && kind !== spec.kind ? kind : undefined,
|
||||
unverified,
|
||||
sourced,
|
||||
};
|
||||
}
|
||||
@@ -54,13 +54,18 @@ export function SectionFrame({
|
||||
onClick={onSelect}
|
||||
className={cn(
|
||||
'relative cursor-pointer transition-all',
|
||||
padded && 'px-4 py-12 sm:px-6 sm:py-16 md:px-8',
|
||||
padded && 'px-4 sm:px-6 md:px-8',
|
||||
isSelected
|
||||
? 'ring-2 ring-stone-900 ring-offset-2'
|
||||
: 'hover:outline-1 hover:outline-dashed hover:outline-stone-300',
|
||||
className,
|
||||
)}
|
||||
style={{backgroundColor: TONE_BG[tone]}}
|
||||
style={{
|
||||
backgroundColor: TONE_BG[tone],
|
||||
// 세로 여백은 템플릿이 정한다 — 이 값 하나로 페이지의 호흡이 바뀐다.
|
||||
// 폴백은 걷어낸 py-12/py-16 과 같은 값이라, 토큰이 없는 곳에서는 지금까지와 동일하다.
|
||||
...(padded ? {paddingBlock: 'var(--tpl-section-space, 3.5rem)'} : {}),
|
||||
}}
|
||||
>
|
||||
{isSelected && (
|
||||
<span
|
||||
|
||||
@@ -52,7 +52,7 @@ export function SectionHeading({
|
||||
</span>
|
||||
)}
|
||||
<h2
|
||||
className="serif-title text-xl font-bold tracking-tight text-stone-900 sm:text-2xl"
|
||||
className="tpl-title serif-title text-xl font-bold tracking-tight text-stone-900 sm:text-2xl"
|
||||
style={titleStyle}
|
||||
>
|
||||
{title}
|
||||
@@ -76,7 +76,7 @@ export function SectionHeading({
|
||||
</span>
|
||||
)}
|
||||
<h2
|
||||
className="serif-title text-xl font-bold tracking-tight text-stone-900 sm:text-2xl"
|
||||
className="tpl-title serif-title text-xl font-bold tracking-tight text-stone-900 sm:text-2xl"
|
||||
style={titleStyle}
|
||||
>
|
||||
{title}
|
||||
@@ -93,7 +93,7 @@ export function SectionHeading({
|
||||
return (
|
||||
<div className={cn('flex items-baseline justify-between gap-3', className)}>
|
||||
<h2
|
||||
className="text-sm font-bold uppercase tracking-[0.18em] text-stone-500"
|
||||
className="tpl-title text-sm font-bold uppercase tracking-[0.18em] text-stone-500"
|
||||
style={colors ? {color: colors.secondary} : undefined}
|
||||
>
|
||||
{title}
|
||||
@@ -113,7 +113,7 @@ export function SectionHeading({
|
||||
>
|
||||
<div>
|
||||
<h2
|
||||
className="serif-title text-xl font-bold tracking-tight text-stone-900 sm:text-2xl"
|
||||
className="tpl-title serif-title text-xl font-bold tracking-tight text-stone-900 sm:text-2xl"
|
||||
style={titleStyle}
|
||||
>
|
||||
{title}
|
||||
|
||||
@@ -63,6 +63,12 @@ import {ProgramsTable} from './variants/programs/ProgramsTable';
|
||||
import {ExhibitionGallery} from './variants/exhibition/ExhibitionGallery';
|
||||
import {ExhibitionNotice} from './variants/exhibition/ExhibitionNotice';
|
||||
|
||||
// 붙여넣기 아이템 — 데이터가 fact 가 아니라 사장님이 넣은 JSON 에서 온다(dataSpec.ts).
|
||||
import {SongsTurntable} from './variants/songs/SongsTurntable';
|
||||
import {DailyCalendar} from './variants/daily/DailyCalendar';
|
||||
import {CourseTickets} from './variants/course/CourseTickets';
|
||||
import {ScheduleTimetable} from './variants/schedule/ScheduleTimetable';
|
||||
|
||||
export const SECTION_VARIANTS: Record<string, SectionVariant[]> = {
|
||||
hero: [
|
||||
{
|
||||
@@ -397,6 +403,50 @@ export const SECTION_VARIANTS: Record<string, SectionVariant[]> = {
|
||||
},
|
||||
],
|
||||
|
||||
songs: [
|
||||
{
|
||||
id: 'songs.turntable',
|
||||
name: '턴테이블',
|
||||
description: '도넛판을 눌러 얹으면 판이 돈다. 곡 3~8개일 때 가장 좋다.',
|
||||
thumb: 'carousel',
|
||||
Component: SongsTurntable,
|
||||
isDefault: true,
|
||||
},
|
||||
],
|
||||
|
||||
daily: [
|
||||
{
|
||||
id: 'daily.calendar',
|
||||
name: '일력',
|
||||
description: '오늘 날짜에 맞는 한 장이 자동으로 펼쳐진다. 매일 바뀌니 다시 올 이유가 된다.',
|
||||
thumb: 'compact',
|
||||
Component: DailyCalendar,
|
||||
isDefault: true,
|
||||
},
|
||||
],
|
||||
|
||||
course: [
|
||||
{
|
||||
id: 'course.tickets',
|
||||
name: '승차권',
|
||||
description: '정거장 하나가 표 한 장. 마지막 표에 완주 도장이 찍힌다.',
|
||||
thumb: 'carousel',
|
||||
Component: CourseTickets,
|
||||
isDefault: true,
|
||||
},
|
||||
],
|
||||
|
||||
schedule: [
|
||||
{
|
||||
id: 'schedule.timetable',
|
||||
name: '대합실 시간표',
|
||||
description: '칸 하나가 시간대 하나. 검은 플립보드에 시각이 먼저 뜬다.',
|
||||
thumb: 'carousel',
|
||||
Component: ScheduleTimetable,
|
||||
isDefault: true,
|
||||
},
|
||||
],
|
||||
|
||||
exhibition: [
|
||||
{
|
||||
id: 'exhibition.gallery',
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* 반나절 산책 — 승차권 캐러셀.
|
||||
*
|
||||
* 표 한 장이 정거장 하나다. 절취선·펀치 구멍·완주 도장은 스탬프투어라는 실제 형식을 그대로 옮긴 것.
|
||||
* ★ 링크는 만들지 않는다. searchQuery 만 보여준다 — 지어낸 주소를 링크하지 않는 이 레포의 규약.
|
||||
*/
|
||||
import {SectionBody, SectionFrame} from '../../primitives';
|
||||
import type {SectionRenderProps} from '../../types';
|
||||
import {parseSectionData, type CourseItem, type CourseStop} from '../../dataSpec';
|
||||
import {
|
||||
CarouselNav,
|
||||
ParseError,
|
||||
PasteHint,
|
||||
RETRO_BODY,
|
||||
RETRO_LINE,
|
||||
RETRO_PAPER,
|
||||
RETRO_PAPER_LIGHT,
|
||||
RETRO_RED,
|
||||
RETRO_SIGN,
|
||||
SourceLine,
|
||||
useCarousel,
|
||||
} from '../retro/common';
|
||||
import '../retro/retro.css';
|
||||
|
||||
function Ticket({
|
||||
stop,
|
||||
courseName,
|
||||
index,
|
||||
isLast,
|
||||
}: {
|
||||
stop: CourseStop;
|
||||
courseName: string;
|
||||
index: number;
|
||||
isLast: boolean;
|
||||
}) {
|
||||
const no = String(stop.order ?? index + 1).padStart(2, '0');
|
||||
|
||||
return (
|
||||
<div
|
||||
className="relative w-[236px] shrink-0 snap-center border shadow-[4px_4px_0_rgba(27,26,21,.13)]"
|
||||
style={{backgroundColor: RETRO_PAPER_LIGHT, borderColor: '#1b1a15'}}
|
||||
>
|
||||
<div
|
||||
className="flex justify-between border-b border-dashed px-4 py-2.5 text-[10px] tracking-[0.12em] text-stone-600"
|
||||
style={{borderColor: '#1b1a15'}}
|
||||
>
|
||||
<span className="truncate">{courseName}</span>
|
||||
<span className="shrink-0">NO.{no}</span>
|
||||
</div>
|
||||
|
||||
<p className="px-4 pt-4 leading-none" style={{fontFamily: RETRO_SIGN, fontSize: 32, color: RETRO_RED}}>
|
||||
{no}
|
||||
</p>
|
||||
<h4 className="px-4 pt-1.5 text-base font-bold text-stone-900" style={{fontFamily: RETRO_BODY}}>
|
||||
{stop.name}
|
||||
</h4>
|
||||
{stop.note && (
|
||||
<p className="px-4 pt-2 text-[13px] leading-relaxed text-stone-600" style={{fontFamily: RETRO_BODY}}>
|
||||
{stop.note}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div
|
||||
className="mt-3 flex justify-between gap-2 border-t border-dashed px-4 py-2.5 text-[10px] text-stone-500"
|
||||
style={{borderColor: RETRO_LINE}}
|
||||
>
|
||||
<span>{stop.minutes ? `도보 ${stop.minutes}분` : '이동 시간 미정'}</span>
|
||||
{stop.searchQuery && <span className="truncate">지도 검색 · {stop.searchQuery}</span>}
|
||||
</div>
|
||||
|
||||
{/* 펀치 구멍 — 표를 표로 만드는 자리 */}
|
||||
<i
|
||||
className="absolute -left-[7px] top-1/2 size-3 rounded-full border"
|
||||
style={{backgroundColor: RETRO_PAPER, borderColor: '#1b1a15'}}
|
||||
/>
|
||||
<i
|
||||
className="absolute -right-[7px] top-1/2 size-3 rounded-full border"
|
||||
style={{backgroundColor: RETRO_PAPER, borderColor: '#1b1a15'}}
|
||||
/>
|
||||
|
||||
{isLast && (
|
||||
<span
|
||||
className="absolute bottom-3 right-3 grid size-14 -rotate-12 place-items-center rounded-full border-2 text-center text-[11px] leading-tight opacity-75"
|
||||
style={{fontFamily: RETRO_SIGN, borderColor: RETRO_RED, color: RETRO_RED}}
|
||||
>
|
||||
완주
|
||||
<br />
|
||||
도장
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CourseRow({course}: {course: CourseItem}) {
|
||||
const {ref, scrollBy} = useCarousel<HTMLDivElement>();
|
||||
const stops = course.stops ?? [];
|
||||
|
||||
return (
|
||||
<div className="space-y-2.5">
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
||||
<div className="flex flex-wrap items-baseline gap-2.5">
|
||||
<h3 className="text-lg text-stone-900" style={{fontFamily: RETRO_SIGN}}>
|
||||
{course.name}
|
||||
</h3>
|
||||
<span className="text-[11px] text-stone-500">
|
||||
{[course.duration, course.startsFrom ? `${course.startsFrom} 출발` : undefined, `${stops.length}곳`]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
</span>
|
||||
</div>
|
||||
{stops.length > 2 && (
|
||||
<CarouselNav onPrev={() => scrollBy(-1)} onNext={() => scrollBy(1)} label={course.name} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{stops.length === 0 ? (
|
||||
<p className="border border-dashed px-4 py-5 text-center text-[11px] text-stone-500" style={{borderColor: RETRO_LINE}}>
|
||||
정거장이 아직 없습니다. JSON 의 stops 배열을 채워 주세요.
|
||||
</p>
|
||||
) : (
|
||||
<div ref={ref} className="w4-scroll flex snap-x snap-mandatory gap-4 overflow-x-auto pb-3">
|
||||
{stops.map((stop, index) => (
|
||||
<Ticket
|
||||
key={`${stop.name}-${index}`}
|
||||
stop={stop}
|
||||
courseName={course.name}
|
||||
index={index}
|
||||
isLast={index === stops.length - 1}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<SourceLine source={course.source} verified={course.verified} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CourseTickets(props: SectionRenderProps) {
|
||||
const {section, isSelected, onSelect} = props;
|
||||
const parsed = parseSectionData<CourseItem>(section.type, section.data);
|
||||
|
||||
return (
|
||||
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="tint">
|
||||
<SectionBody width="wide">
|
||||
<div className="space-y-1.5">
|
||||
<h2 className="text-2xl text-stone-900 sm:text-3xl" style={{fontFamily: RETRO_SIGN}}>
|
||||
{parsed.title || section.name}
|
||||
</h2>
|
||||
{(parsed.subtitle || section.description) && (
|
||||
<p className="text-sm text-stone-600" style={{fontFamily: RETRO_BODY}}>
|
||||
{parsed.subtitle || section.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{parsed.error ? (
|
||||
<ParseError message={parsed.error} />
|
||||
) : parsed.items.length === 0 ? (
|
||||
<PasteHint label="반나절 산책" />
|
||||
) : (
|
||||
<div className="space-y-8">
|
||||
{parsed.items.map((course, index) => (
|
||||
<CourseRow key={`${course.name}-${index}`} course={course} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</SectionBody>
|
||||
</SectionFrame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
/**
|
||||
* 오늘의 한 장 — 뜯어 넘기는 일력.
|
||||
*
|
||||
* 이 팩에서 유일하게 캐러셀이 아니다. '오늘'은 하나여야 하니까. 다만 어제·내일이 양옆에
|
||||
* 반쯤 걸쳐 있어 넘길 수 있다는 걸 눈으로 알려 준다.
|
||||
*/
|
||||
import {useMemo, useState} from 'react';
|
||||
import {SectionBody, SectionFrame} from '../../primitives';
|
||||
import type {SectionRenderProps} from '../../types';
|
||||
import {parseSectionData, type DailyItem} from '../../dataSpec';
|
||||
import {
|
||||
CarouselNav,
|
||||
ParseError,
|
||||
PasteHint,
|
||||
RETRO_BODY,
|
||||
RETRO_LINE,
|
||||
RETRO_PAPER,
|
||||
RETRO_PAPER_LIGHT,
|
||||
RETRO_RED,
|
||||
RETRO_SIGN,
|
||||
SourceLine,
|
||||
} from '../retro/common';
|
||||
import '../retro/retro.css';
|
||||
|
||||
const DOW = ['일', '월', '화', '수', '목', '금', '토'];
|
||||
|
||||
function todayMonthDay(): string {
|
||||
const now = new Date();
|
||||
return `${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** MM-DD 를 올해 날짜로 읽어 요일을 낸다. 형식이 아니면 undefined — 지어내지 않는다. */
|
||||
function dowOf(monthDay: string): string | undefined {
|
||||
const m = /^(\d{2})-(\d{2})$/.exec(monthDay.trim());
|
||||
if (!m) return undefined;
|
||||
const date = new Date(new Date().getFullYear(), Number(m[1]) - 1, Number(m[2]));
|
||||
if (Number.isNaN(date.getTime())) return undefined;
|
||||
return DOW[date.getDay()];
|
||||
}
|
||||
|
||||
function CalendarPage({item, muted}: {item: DailyItem; muted?: boolean}) {
|
||||
const [month, day] = item.monthDay.split('-');
|
||||
const dow = dowOf(item.monthDay);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`w4-paper relative w-[254px] shrink-0 border shadow-[5px_6px_0_rgba(27,26,21,.13)] transition-all ${
|
||||
muted ? 'scale-[.93] opacity-45' : ''
|
||||
}`}
|
||||
style={{backgroundColor: RETRO_PAPER_LIGHT, borderColor: RETRO_LINE}}
|
||||
>
|
||||
{/* 뜯어낸 자국 */}
|
||||
<div
|
||||
className="w4-perf h-3.5 border-b border-dashed"
|
||||
style={{['--tear' as string]: RETRO_PAPER, borderColor: RETRO_LINE}}
|
||||
/>
|
||||
<div className="absolute inset-x-0 top-0 flex justify-around px-10">
|
||||
{[0, 1, 2].map((i) => (
|
||||
<i
|
||||
key={i}
|
||||
className="-mt-1 size-2 rounded-full border"
|
||||
style={{backgroundColor: RETRO_PAPER, borderColor: RETRO_LINE}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="border-b px-5 pb-3 pt-6 text-center" style={{borderColor: RETRO_LINE}}>
|
||||
<p className="text-[11px] tracking-[0.2em] text-stone-500">{month}月</p>
|
||||
<p className="mt-1 leading-none" style={{fontFamily: RETRO_SIGN, fontSize: 72, color: RETRO_RED}}>
|
||||
{String(Number(day) || day)}
|
||||
</p>
|
||||
{dow && <p className="mt-1.5 text-[11px] tracking-[0.3em] text-stone-600">{dow}曜</p>}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 px-5 pb-5 pt-4">
|
||||
{item.category && (
|
||||
<p className="text-[10px] tracking-[0.16em] text-emerald-800">{item.category}</p>
|
||||
)}
|
||||
<h3 className="text-base font-bold leading-snug text-stone-900" style={{fontFamily: RETRO_BODY}}>
|
||||
{item.title}
|
||||
</h3>
|
||||
{item.body && (
|
||||
<p className="text-[13px] leading-relaxed text-stone-600" style={{fontFamily: RETRO_BODY}}>
|
||||
{item.body}
|
||||
</p>
|
||||
)}
|
||||
{item.tags && item.tags.length > 0 && (
|
||||
<p className="text-[10px] text-stone-500">{item.tags.join(' ')}</p>
|
||||
)}
|
||||
<div className="border-t border-dashed pt-2.5" style={{borderColor: RETRO_LINE}}>
|
||||
<SourceLine source={item.source} verified={item.verified} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DailyCalendar(props: SectionRenderProps) {
|
||||
const {section, isSelected, onSelect} = props;
|
||||
const parsed = parseSectionData<DailyItem>(section.type, section.data);
|
||||
|
||||
const items = useMemo(
|
||||
() => [...parsed.items].sort((a, b) => a.monthDay.localeCompare(b.monthDay)),
|
||||
[parsed.items],
|
||||
);
|
||||
|
||||
// 오늘 날짜가 목록에 없으면 오늘 **이후 첫 장**을 편다 — 지난 날짜를 오늘로 내걸지 않는다.
|
||||
const startIndex = useMemo(() => {
|
||||
if (items.length === 0) return 0;
|
||||
const today = todayMonthDay();
|
||||
const exact = items.findIndex((item) => item.monthDay === today);
|
||||
if (exact >= 0) return exact;
|
||||
const upcoming = items.findIndex((item) => item.monthDay >= today);
|
||||
return upcoming >= 0 ? upcoming : 0;
|
||||
}, [items]);
|
||||
|
||||
const [offset, setOffset] = useState(0);
|
||||
const index = items.length > 0 ? (startIndex + offset + items.length * 100) % items.length : 0;
|
||||
const at = (delta: number) => items[(index + delta + items.length) % items.length];
|
||||
|
||||
return (
|
||||
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="paper">
|
||||
<SectionBody width="wide">
|
||||
<div className="space-y-1.5">
|
||||
<h2 className="text-2xl text-stone-900 sm:text-3xl" style={{fontFamily: RETRO_SIGN}}>
|
||||
{parsed.title || section.name}
|
||||
</h2>
|
||||
{(parsed.subtitle || section.description) && (
|
||||
<p className="text-sm text-stone-600" style={{fontFamily: RETRO_BODY}}>
|
||||
{parsed.subtitle || section.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{parsed.error ? (
|
||||
<ParseError message={parsed.error} />
|
||||
) : items.length === 0 ? (
|
||||
<PasteHint label="오늘의 한 장" />
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<div className="w4-scroll flex items-start justify-center gap-5 overflow-x-auto pb-3">
|
||||
{items.length > 1 && <CalendarPage item={at(-1)} muted />}
|
||||
<CalendarPage item={items[index]} />
|
||||
{items.length > 1 && <CalendarPage item={at(1)} muted />}
|
||||
</div>
|
||||
{items.length > 1 && (
|
||||
<CarouselNav
|
||||
onPrev={() => setOffset((v) => v - 1)}
|
||||
onNext={() => setOffset((v) => v + 1)}
|
||||
label="날짜"
|
||||
/>
|
||||
)}
|
||||
<p className="text-center text-[11px] text-stone-500">
|
||||
오늘 날짜에 맞는 장이 자동으로 펼쳐집니다 · 총 {items.length}장
|
||||
{parsed.unverified > 0 && ` · 확인 필요 ${parsed.unverified}장`}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</SectionBody>
|
||||
</SectionFrame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* 7080 아이템이 공유하는 조각 — 서체 스택, 출처 각주, 캐러셀 화살표.
|
||||
*
|
||||
* 세 아이템이 각자 만들면 같은 각주가 세 모양이 된다. 출처 표기는 이 레포의 규약이라 특히 갈리면 안 된다.
|
||||
*/
|
||||
import {useCallback, useRef} from 'react';
|
||||
import {ChevronLeft, ChevronRight, MousePointerClick} from 'lucide-react';
|
||||
import {cn} from '@/lib/utils';
|
||||
import type {DataSource, DataVerified} from '../../dataSpec';
|
||||
|
||||
/** 옛 간판체. 큰 글자에만 쓴다 — 본문에 쓰면 읽히지 않는다. */
|
||||
export const RETRO_SIGN = "'Gugi', 'Noto Sans KR', sans-serif";
|
||||
/** 본문 명조. */
|
||||
export const RETRO_BODY = "'Gowun Batang', 'Noto Serif KR', serif";
|
||||
/** 손글씨. 엽서·주석 한 줄에만. */
|
||||
export const RETRO_HAND = "'Nanum Pen Script', 'Gowun Batang', cursive";
|
||||
|
||||
export const RETRO_PAPER = '#e4dac0';
|
||||
export const RETRO_PAPER_LIGHT = '#f2ebd9';
|
||||
export const RETRO_INK = '#1b1a15';
|
||||
export const RETRO_INK_SOFT = '#4c4739';
|
||||
export const RETRO_LINE = '#c0b493';
|
||||
export const RETRO_RED = '#bf2f1b';
|
||||
|
||||
/**
|
||||
* 출처 한 줄 + 확신 배지.
|
||||
*
|
||||
* ★ 확인되지 않은 값을 숨기지 않고 **드러낸다.** 숨기면 사장님이 그게 미검증인 줄 모르고 발행한다.
|
||||
*/
|
||||
export function SourceLine({
|
||||
source,
|
||||
verified,
|
||||
tone = 'light',
|
||||
}: {
|
||||
source?: DataSource;
|
||||
verified?: DataVerified;
|
||||
tone?: 'light' | 'dark';
|
||||
}) {
|
||||
const dark = tone === 'dark';
|
||||
if (!source && !verified) return null;
|
||||
|
||||
return (
|
||||
<p
|
||||
className={cn(
|
||||
'flex flex-wrap items-center gap-x-2 gap-y-1 text-[10px]',
|
||||
dark ? 'text-stone-400' : 'text-stone-500',
|
||||
)}
|
||||
>
|
||||
{verified && (
|
||||
<span
|
||||
className="border px-1.5 py-px"
|
||||
style={{
|
||||
color: verified === '확인' ? '#2a6053' : '#b07d10',
|
||||
borderColor: 'currentColor',
|
||||
}}
|
||||
>
|
||||
{verified}
|
||||
</span>
|
||||
)}
|
||||
{source?.name && (
|
||||
<span>
|
||||
출처 ·{' '}
|
||||
{source.url ? (
|
||||
<a
|
||||
href={source.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
className="underline underline-offset-2"
|
||||
>
|
||||
{source.name}
|
||||
</a>
|
||||
) : (
|
||||
source.name
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
/** 가로 스크롤 + 화살표. 스크롤 컨테이너를 ref 로 잡아 한 화면의 80%씩 민다. */
|
||||
export function useCarousel<T extends HTMLElement>() {
|
||||
const ref = useRef<T>(null);
|
||||
const scrollBy = useCallback((dir: -1 | 1) => {
|
||||
const box = ref.current;
|
||||
if (!box) return;
|
||||
box.scrollBy({left: box.clientWidth * 0.8 * dir, behavior: 'smooth'});
|
||||
}, []);
|
||||
return {ref, scrollBy};
|
||||
}
|
||||
|
||||
export function CarouselNav({
|
||||
onPrev,
|
||||
onNext,
|
||||
tone = 'light',
|
||||
label,
|
||||
}: {
|
||||
onPrev: () => void;
|
||||
onNext: () => void;
|
||||
tone?: 'light' | 'dark';
|
||||
label: string;
|
||||
}) {
|
||||
const dark = tone === 'dark';
|
||||
const base = cn(
|
||||
'flex size-8 items-center justify-center border transition-colors',
|
||||
dark
|
||||
? 'border-stone-600 bg-stone-800/60 text-stone-300 hover:bg-stone-700'
|
||||
: 'border-stone-400 bg-white/70 text-stone-700 hover:bg-stone-900 hover:text-white',
|
||||
);
|
||||
const stop = (fn: () => void) => (event: React.MouseEvent) => {
|
||||
event.stopPropagation();
|
||||
fn();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex justify-end gap-1.5">
|
||||
<button type="button" className={base} onClick={stop(onPrev)} aria-label={`${label} 이전`}>
|
||||
<ChevronLeft className="size-4" />
|
||||
</button>
|
||||
<button type="button" className={base} onClick={stop(onNext)} aria-label={`${label} 다음`}>
|
||||
<ChevronRight className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 붙여넣을 JSON 이 아직 없을 때 — 어디로 가야 하는지 말해 준다.
|
||||
*
|
||||
* ★ 그냥 "준비 중"이라고 두면 사장님은 이 섹션이 자동으로 채워지는 줄 알고 기다린다.
|
||||
*/
|
||||
export function PasteHint({label}: {label: string}) {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-2 border border-dashed border-stone-400/70 bg-white/50 px-4 py-8 text-center">
|
||||
<MousePointerClick className="size-4 text-stone-400" />
|
||||
<p className="text-xs font-semibold text-stone-600">{label} 내용이 아직 없습니다</p>
|
||||
<p className="max-w-[34ch] text-[11px] leading-relaxed text-stone-500">
|
||||
오른쪽 [콘텐츠] 탭에서 프롬프트를 복사해 ChatGPT 에 넣고, 받은 JSON 을 붙여넣으면 바로 여기에 그려집니다.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 파싱이 깨졌을 때. 캔버스를 비우지 않고 왜 안 그려지는지 그 자리에 말한다. */
|
||||
export function ParseError({message}: {message: string}) {
|
||||
return (
|
||||
<div className="border border-dashed border-red-400/70 bg-red-50/70 px-4 py-5 text-center">
|
||||
<p className="text-xs font-semibold text-red-700">붙여넣은 JSON 을 읽지 못했습니다</p>
|
||||
<p className="mt-1.5 text-[11px] leading-relaxed text-red-600">{message}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* 7080 아이템 전용 질감 — Tailwind 로는 못 그리는 것만 여기 둔다.
|
||||
* 도넛판 홈, 갱지 결, 절취선, 펀치 구멍. 색은 전부 인라인 변수로 받아 템플릿 팔레트를 따른다.
|
||||
*/
|
||||
|
||||
/* 갱지 — 두 방향 결이 겹쳐야 종이로 읽힌다. */
|
||||
.w4-paper {
|
||||
background-image:
|
||||
repeating-linear-gradient(0deg, rgb(27 26 21 / 3%) 0 1px, transparent 1px 3px),
|
||||
repeating-linear-gradient(90deg, rgb(27 26 21 / 2%) 0 1px, transparent 1px 4px);
|
||||
}
|
||||
|
||||
/* 도넛판. --lbl 이 라벨 색이다. */
|
||||
.w4-disc {
|
||||
background:
|
||||
radial-gradient(circle at 50% 50%, transparent 0 15.5%, var(--lbl, #d4551f) 15.5% 33%, transparent 33%),
|
||||
repeating-radial-gradient(circle at 50% 50%, #1a1812 0 1.4px, #15140f 1.4px 3px),
|
||||
#15140f;
|
||||
box-shadow: 0 0 0 1px #000, inset 0 0 40px rgb(0 0 0 / 80%);
|
||||
}
|
||||
.w4-disc-sheen {
|
||||
background: conic-gradient(
|
||||
from 210deg,
|
||||
rgb(255 255 255 / 12%),
|
||||
transparent 22%,
|
||||
transparent 70%,
|
||||
rgb(255 255 255 / 7%)
|
||||
);
|
||||
}
|
||||
.w4-spin {
|
||||
animation: w4-rev 2.2s linear infinite;
|
||||
}
|
||||
@keyframes w4-rev {
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
/* 미니 판 — 캐러셀에 늘어서는 작은 것. */
|
||||
.w4-disc-mini {
|
||||
background:
|
||||
radial-gradient(circle at 50% 50%, transparent 0 14%, var(--lbl, #d4551f) 14% 34%, transparent 34%),
|
||||
repeating-radial-gradient(circle at 50% 50%, #1a1812 0 1.2px, #15140f 1.2px 2.6px),
|
||||
#15140f;
|
||||
box-shadow: 0 3px 10px rgb(0 0 0 / 45%);
|
||||
}
|
||||
|
||||
/* 일력 톱니 — 뜯어낸 자국. */
|
||||
.w4-perf {
|
||||
background: repeating-linear-gradient(90deg, transparent 0 8px, var(--tear, #e4dac0) 8px 9px);
|
||||
}
|
||||
|
||||
/* 승차권 절취선 */
|
||||
.w4-dash {
|
||||
border-top: 1px dashed currentcolor;
|
||||
}
|
||||
|
||||
.w4-scroll {
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.w4-scroll::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.w4-spin {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
/**
|
||||
* 여행 스케줄 — 대합실 시간표 캐러셀.
|
||||
*
|
||||
* 칸 하나가 시간대 하나다. 위쪽 검은 판은 역 대합실의 플립보드(가운데 접힘선)를 그대로 옮긴 것 —
|
||||
* 시각이 먼저 읽히고 무엇을 하는지가 뒤따라야 시간표로 읽힌다.
|
||||
* ★ 승차권(course)과 일부러 다르게 짰다. 저쪽은 '어디를 도는가'(순번), 여기는 '언제 무엇을'(시각)이다.
|
||||
* ★ 링크는 만들지 않는다. searchQuery 만 보여준다 — 지어낸 주소를 링크하지 않는 이 레포의 규약.
|
||||
*/
|
||||
import {SectionBody, SectionFrame} from '../../primitives';
|
||||
import type {SectionRenderProps} from '../../types';
|
||||
import {parseSectionData, type ScheduleItem, type ScheduleSlot} from '../../dataSpec';
|
||||
import {
|
||||
CarouselNav,
|
||||
ParseError,
|
||||
PasteHint,
|
||||
RETRO_BODY,
|
||||
RETRO_INK,
|
||||
RETRO_LINE,
|
||||
RETRO_PAPER_LIGHT,
|
||||
RETRO_RED,
|
||||
RETRO_SIGN,
|
||||
SourceLine,
|
||||
useCarousel,
|
||||
} from '../retro/common';
|
||||
import '../retro/retro.css';
|
||||
|
||||
/** "09:30" → 9시 30분. 형식이 어긋나면 원문을 그대로 보여준다(지어내지 않는다). */
|
||||
function splitTime(time: string): {head: string; tail?: string} {
|
||||
const match = /^(\d{1,2}):(\d{2})$/.exec(time.trim());
|
||||
if (!match) return {head: time.trim()};
|
||||
return {head: match[1].padStart(2, '0'), tail: match[2]};
|
||||
}
|
||||
|
||||
function Slot({slot, isLast}: {slot: ScheduleSlot; isLast: boolean}) {
|
||||
const {head, tail} = splitTime(slot.time ?? '');
|
||||
|
||||
return (
|
||||
<div className="flex shrink-0 snap-center items-stretch">
|
||||
<div
|
||||
className="w-[228px] border shadow-[4px_4px_0_rgba(27,26,21,.13)]"
|
||||
style={{backgroundColor: RETRO_PAPER_LIGHT, borderColor: RETRO_INK}}
|
||||
>
|
||||
{/* 플립보드 — 가운데 접힘선이 이 판을 시계로 만든다 */}
|
||||
<div className="relative px-4 py-3 text-center" style={{backgroundColor: RETRO_INK}}>
|
||||
<span
|
||||
className="inline-flex items-baseline gap-1 leading-none text-[#f2ebd9]"
|
||||
style={{fontFamily: RETRO_SIGN, fontSize: 30}}
|
||||
>
|
||||
{head}
|
||||
{tail && <span className="text-[#c0b493]">:{tail}</span>}
|
||||
</span>
|
||||
<i
|
||||
aria-hidden
|
||||
className="pointer-events-none absolute inset-x-0 top-1/2 border-t"
|
||||
style={{borderColor: 'rgba(242,235,217,.22)'}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 px-4 pb-3 pt-3.5">
|
||||
<h4 className="text-base font-bold text-stone-900" style={{fontFamily: RETRO_BODY}}>
|
||||
{slot.title}
|
||||
</h4>
|
||||
{slot.place && (
|
||||
<p className="text-[12px] font-semibold" style={{fontFamily: RETRO_BODY, color: RETRO_RED}}>
|
||||
{slot.place}
|
||||
</p>
|
||||
)}
|
||||
{slot.note && (
|
||||
<p className="text-[13px] leading-relaxed text-stone-600" style={{fontFamily: RETRO_BODY}}>
|
||||
{slot.note}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="flex justify-between gap-2 border-t border-dashed px-4 py-2 text-[10px] text-stone-500"
|
||||
style={{borderColor: RETRO_LINE}}
|
||||
>
|
||||
<span>{slot.minutes ? `${slot.minutes}분 머묾` : '머무는 시간 미정'}</span>
|
||||
{slot.searchQuery && <span className="truncate">지도 검색 · {slot.searchQuery}</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 칸과 칸 사이의 시간 — 점선이 이어져야 '흐른다'로 읽힌다 */}
|
||||
{!isLast && (
|
||||
<div aria-hidden className="flex w-8 items-center justify-center">
|
||||
<i className="block h-px w-full border-t border-dashed" style={{borderColor: RETRO_LINE}} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ScheduleRow({schedule}: {schedule: ScheduleItem}) {
|
||||
const {ref, scrollBy} = useCarousel<HTMLDivElement>();
|
||||
const slots = schedule.slots ?? [];
|
||||
const span =
|
||||
slots.length > 1 ? `${slots[0]?.time ?? ''}–${slots[slots.length - 1]?.time ?? ''}` : undefined;
|
||||
|
||||
return (
|
||||
<div className="space-y-2.5">
|
||||
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
||||
<div className="flex flex-wrap items-baseline gap-2.5">
|
||||
<h3 className="text-lg text-stone-900" style={{fontFamily: RETRO_SIGN}}>
|
||||
{schedule.name}
|
||||
</h3>
|
||||
<span className="text-[11px] text-stone-500">
|
||||
{[schedule.audience, schedule.season, span, `${slots.length}칸`]
|
||||
.filter(Boolean)
|
||||
.join(' · ')}
|
||||
</span>
|
||||
</div>
|
||||
{slots.length > 2 && (
|
||||
<CarouselNav onPrev={() => scrollBy(-1)} onNext={() => scrollBy(1)} label={schedule.name} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{slots.length === 0 ? (
|
||||
<p
|
||||
className="border border-dashed px-4 py-5 text-center text-[11px] text-stone-500"
|
||||
style={{borderColor: RETRO_LINE}}
|
||||
>
|
||||
시간대가 아직 없습니다. JSON 의 slots 배열을 채워 주세요.
|
||||
</p>
|
||||
) : (
|
||||
<div ref={ref} className="w4-scroll flex snap-x snap-mandatory overflow-x-auto pb-3">
|
||||
{slots.map((slot, index) => (
|
||||
<Slot
|
||||
key={`${slot.time}-${slot.title}-${index}`}
|
||||
slot={slot}
|
||||
isLast={index === slots.length - 1}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<SourceLine source={schedule.source} verified={schedule.verified} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ScheduleTimetable(props: SectionRenderProps) {
|
||||
const {section, isSelected, onSelect} = props;
|
||||
const parsed = parseSectionData<ScheduleItem>(section.type, section.data);
|
||||
|
||||
return (
|
||||
<SectionFrame section={section} isSelected={isSelected} onSelect={onSelect} tone="tint">
|
||||
<SectionBody width="wide">
|
||||
<div className="space-y-1.5">
|
||||
<h2 className="text-2xl text-stone-900 sm:text-3xl" style={{fontFamily: RETRO_SIGN}}>
|
||||
{parsed.title || section.name}
|
||||
</h2>
|
||||
{(parsed.subtitle || section.description) && (
|
||||
<p className="text-sm text-stone-600" style={{fontFamily: RETRO_BODY}}>
|
||||
{parsed.subtitle || section.description}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{parsed.error ? (
|
||||
<ParseError message={parsed.error} />
|
||||
) : parsed.items.length === 0 ? (
|
||||
<PasteHint label="여행 스케줄" />
|
||||
) : (
|
||||
<div className="space-y-8">
|
||||
{parsed.items.map((schedule, index) => (
|
||||
<ScheduleRow key={`${schedule.name}-${index}`} schedule={schedule} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</SectionBody>
|
||||
</SectionFrame>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user