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

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

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

## 왜

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

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

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

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

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

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

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

## 그 밖

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

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

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

No files matched your search

@@ -0,0 +1,52 @@
# 복사해서 사용: cp config.local.toml.example config.local.toml
# 실제 config.local.toml 은 시크릿 포함이라 커밋하지 않는다(.gitignore: *.toml).
# 모든 서버는 APP_ENV=local 로 띄우며 이 파일을 읽는다.
[WebServerConfig]
server_name = "O2oSiteServer"
port = 9800
process_count = 1
is_ssl = false
is_test = true
# 관리자 프론트 오리진 — CORS 허용. 쉼표로 여러 개.
# vite 는 3000 이 쓰이고 있으면 3001, 3002… 로 옮겨 뜨므로 개발 포트 대역을 함께 적어 둔다.
# 운영에서는 실제 도메인 하나만 남긴다.
client_url = "http://localhost:3000,http://localhost:3001,http://localhost:3002,http://localhost:3003,http://localhost:3004,http://localhost:3005"
landing_url = "" # 랜딩(마케팅 사이트). 없으면 빈값
[LogConfig]
print_console = true
log_level = "debug"
# DB Read/Write 분리. 도커 실행 시 host 는 docker-compose 의 DB_HOST 로 override.
# 관리형 DB(RDS/Aurora/Azure)는 host 에 엔드포인트, sslmode="require".
[MainDBConfig]
db_type = "postgresql"
name = "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 = "" # 공공데이터포털 전국문화축제표준데이터 일반 인증키
@@ -0,0 +1,51 @@
# 복사해서 사용: 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 = ""
+37
View File
@@ -0,0 +1,37 @@
import tomllib
from typing import Optional, Type, Dict, TypeVar
from pydantic import BaseModel
class ConfigModel(BaseModel):
pass
# APP_ENV
# local : 로컬 환경(개인 pc)
# dev : 개발환경 (사내 pc)
# prod : 서비스 환경 (클라우드 서버)
#
# 실행시 환경변수 설정
# linux : export APP_ENV=dev
# window : set APP_ENV=dev
class Configs:
ConfigType = TypeVar("ConfigType", bound=ConfigModel)
def __init__(self, file_path: str):
self._settings: Dict[Type["Configs.ConfigType"], "Configs.ConfigType"] = self._load_settings_from_toml(file_path)
def _load_settings_from_toml(self, file_path: str) -> Dict[Type[ConfigType], ConfigType]:
with open(file_path, "rb") as f:
toml_content = tomllib.load(f)
config_subclasses = ConfigModel.__subclasses__()
configs = {
config_class: config_class.model_validate(toml_content[config_class.__name__])
for config_class in config_subclasses
if config_class.__name__ in toml_content
}
return configs
def get(self, config_class: Type[ConfigType]) -> Optional[ConfigType]:
return self._settings.get(config_class)
+66
View File
@@ -0,0 +1,66 @@
from config.config_loader import ConfigModel
class WebServerConfig(ConfigModel):
server_name: str = ""
port: int = 0
process_count: int = 1
is_ssl: bool = False
is_test: bool = False
client_url: str = "" # 관리자 프론트 오리진. CORS 허용 대상
landing_url: str = "" # 랜딩(마케팅 사이트) 오리진. 빈값=미허용
class LogConfig(ConfigModel):
print_console: bool = True
log_level: str = "debug"
# DB Read/Write 분리 설정.
# 하나의 논리 DB 에 대해 write(주) / read(복제) 접속 정보를 각각 가진다.
class MainDBConfig(ConfigModel):
db_type: str = "postgresql"
name: str = ""
write_host: str = ""
write_port: int = 5432
write_id: str = ""
write_pw: str = ""
read_host: str = ""
read_port: int = 5432
read_id: str = ""
read_pw: str = ""
show_log: bool = False
# 커넥션 풀 사이징. 실제 동시 커넥션 상한 = (pool_size + max_overflow) x 엔진수(R/W=2) x 워커수.
# PostgreSQL max_connections 를 넘지 않도록 설정해야 한다. (예: 10+20=30 x 2 x 5워커 = 300)
pool_size: int = 10
max_overflow: int = 20
# SSL/TLS 모드: ""/"disable"=미사용(로컬), "require"/"verify-ca"/"verify-full"=관리형 DB(RDS/Aurora/Azure).
sslmode: str = ""
class JwtToken(ConfigModel):
access_key: str = ""
refresh_key: str = ""
access_expire_min: int = 30
refresh_expire_day: int = 7
# 외부 API 키. 수집 파이프라인(Perplexity → 카카오 로컬 → 크롤링 → Gemini)이 쓴다.
# 키가 비면 해당 어댑터는 비활성 — 서버는 그대로 뜬다(부팅이 외부 계약에 묶이면 안 된다).
class ExternalApiConfig(ConfigModel):
perplexity_api_key: str = "" # 채널 URL 발견 (api.perplexity.ai)
# 동일 업소 검증 — 두 소스 중 설정된 쪽을 쓴다(둘 다 있으면 카카오 우선).
# 카카오: 15건 · 전화번호 O · 고유 place id O · 행정구역 코드 O → 판정 근거가 강하다
# 네이버: 5건 · 전화번호 X · 고유 id 불확실 · 행정구역 코드 X → 그만큼 AMBIGUOUS 가 늘어난다
kakao_rest_api_key: str = "" # dapi.kakao.com (미발급)
naver_client_id: str = "" # openapi.naver.com 지역검색
naver_client_secret: str = ""
gemini_api_key: str = "" # 사진 분류 + 카피 작성 (Google AI Studio)
# 비전 모델. 사진 1장 ≈ 1,200 토큰이라 사업장 1건(50장)에 3.7-flash $0.045 / 2.5-flash $0.018.
# 기본을 3.7 로 두는 이유: 라벨이 틀리면 사람 확인 큐 비용이 모델 값 차이보다 크다.
gemini_vision_model: str = "gemini-3.7-flash"
# 소개문·FAQ 생성 모델. 비전과 따로 둔다 — 텍스트는 토큰이 적어 상위 모델을 써도 싸다.
gemini_text_model: str = "gemini-3.7-flash"
# ★ 이 값 미만이면 자동 반영하지 않고 사람 확인 큐(PENDING_REVIEW)에 남긴다. 운영하며 조정한다.
vision_confidence_threshold: float = 0.7
tour_api_key: str = "" # 공공데이터포털 일반 인증키(전국문화축제표준데이터)
+107
View File
@@ -0,0 +1,107 @@
import os
from dotenv import load_dotenv
from config.config_loader import Configs
from config.config_models import WebServerConfig, LogConfig, MainDBConfig, JwtToken, ExternalApiConfig
# 레포 최상위 .env 를 환경변수로 올린다 (외부 API 키·DB 접속의 배포용 주입 경로).
# override=False: 이미 설정된 실제 환경변수(docker-compose 등)가 항상 이긴다.
# 우선순위 = 실제 환경변수 > .env > config.{APP_ENV}.toml
#
# ★ APP_ENV=test 면 .env 를 읽지 않는다. 실키가 테스트 환경에 새어 들어가면
# 테스트가 실제 외부 API(Perplexity·Gemini·카카오)를 때리고 요금이 나간다.
# 테스트의 외부 연동은 config.test.toml(전 키 빈 값) + MockAdapter 로만 검증한다.
_DOTENV_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), ".env")
if os.environ.get("APP_ENV") != "test":
load_dotenv(_DOTENV_PATH, override=False)
# 실행 환경 결정 (기본 local). 환경변수 APP_ENV 로 변경.
APP_ENV = os.environ.get("APP_ENV", "local")
_config_dir = os.path.dirname(__file__)
_config_file = os.path.join(_config_dir, f"config.{APP_ENV}.toml")
# 운영 전제: 항상 APP_ENV=local 로 띄운다 → config.local.toml 사용 (test/docker 도 local 로 실행).
if not os.path.exists(_config_file):
raise FileNotFoundError(f"설정 파일이 없습니다: {_config_file} (APP_ENV={APP_ENV}). APP_ENV=local 로 실행하세요.")
configs = Configs(_config_file)
web_server_config: WebServerConfig = configs.get(WebServerConfig)
log_config: LogConfig = configs.get(LogConfig)
main_db_config: MainDBConfig = configs.get(MainDBConfig)
jwt_token_config: JwtToken = configs.get(JwtToken)
# [ExternalApiConfig] 섹션이 없는 toml 에서도 죽지 않게 기본값 폴백(전 키 빈 값 → 해당 어댑터 비활성).
external_api_config: ExternalApiConfig = configs.get(ExternalApiConfig) or ExternalApiConfig()
# DB 접속 env override (config.local.toml 유지, 도커에서 host 만 교체). 로컬은 env 미설정 → toml 그대로.
def _apply_db_env_override(cfg: MainDBConfig):
h = os.environ.get("DB_HOST")
if h:
cfg.write_host = cfg.read_host = h
if os.environ.get("DB_PORT"):
cfg.write_port = cfg.read_port = int(os.environ["DB_PORT"])
if os.environ.get("DB_USER"):
cfg.write_id = cfg.read_id = os.environ["DB_USER"]
if os.environ.get("DB_PASSWORD"):
cfg.write_pw = cfg.read_pw = os.environ["DB_PASSWORD"]
if os.environ.get("DB_NAME"):
cfg.name = os.environ["DB_NAME"]
_apply_db_env_override(main_db_config)
# 외부 API 키 env override — 키를 toml 에 안 두고 배포 환경변수로만 주입하는 경우.
def _apply_external_api_env_override(cfg: ExternalApiConfig):
if os.environ.get("PERPLEXITY_API_KEY"):
cfg.perplexity_api_key = os.environ["PERPLEXITY_API_KEY"]
if os.environ.get("KAKAO_REST_API_KEY"):
cfg.kakao_rest_api_key = os.environ["KAKAO_REST_API_KEY"]
if os.environ.get("NAVER_CLIENT_ID"):
cfg.naver_client_id = os.environ["NAVER_CLIENT_ID"]
if os.environ.get("NAVER_CLIENT_SECRET"):
cfg.naver_client_secret = os.environ["NAVER_CLIENT_SECRET"]
if os.environ.get("GEMINI_API_KEY"):
cfg.gemini_api_key = os.environ["GEMINI_API_KEY"]
if os.environ.get("GEMINI_VISION_MODEL"):
cfg.gemini_vision_model = os.environ["GEMINI_VISION_MODEL"]
if os.environ.get("GEMINI_TEXT_MODEL"):
cfg.gemini_text_model = os.environ["GEMINI_TEXT_MODEL"]
if os.environ.get("VISION_CONFIDENCE_THRESHOLD"):
cfg.vision_confidence_threshold = float(os.environ["VISION_CONFIDENCE_THRESHOLD"])
if os.environ.get("TOUR_API_KEY"):
cfg.tour_api_key = os.environ["TOUR_API_KEY"]
_apply_external_api_env_override(external_api_config)
# JWT 시크릿 env override.
# ★ 도커 이미지는 config.local.toml 을 example 사본(플레이스홀더)으로 굽는다 — 시크릿을 안 굽기 위해서다.
# 그래서 env 로 주입하지 않으면 "<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("<"):
from common.logger import LOG
LOG.w(
"[보안] JWT 시크릿이 플레이스홀더입니다 — JWT_ACCESS_SECRET / JWT_REFRESH_SECRET 를 env 로 주입하세요. "
"이 상태로 운영에 띄우면 서명 키가 공개값입니다."
)