구조: 사장님(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

+9
View File
@@ -0,0 +1,9 @@
from common.enums import UserRole
def is_owner_or_admin(resource_user_id, user_id, role) -> bool:
"""변경 액션 공용 소유권 판정 — 리소스 소유자(user_id 일치) 또는 최고관리자 이상(OWNER/DEVELOPER)이면 True.
프론트의 버튼 게이팅과 같은 규칙을 백엔드에서 강제하는 단일 출처.
소유자 없는 공용 리소스(예: user_id NULL 공용카드)는 이 판정 대상이 아니다(도메인별 별도 처리)."""
return str(resource_user_id) == str(user_id) or (role or 0) >= UserRole.OWNER.value
@@ -0,0 +1,26 @@
"""업종별 fact 스키마 패키지.
업종마다 필드가 완전히 다르므로(숙박=체크인시간, 카페=브레이크타임) facts 는 key-value 로 두고,
'어떤 key 가 존재하는가'는 업종별 JSON 스키마가 정의한다.
**업종 추가 = resources/ 에 JSON 파일 1개 추가 + PlaceCategory 에 코드 1줄.** 로직 수정 없음.
"""
from common.category_schema.loader import (
CategorySchema,
CategorySchemaError,
FieldSpec,
all_schemas,
get_schema,
is_valid_key,
load_schemas,
)
__all__ = [
"CategorySchema",
"CategorySchemaError",
"FieldSpec",
"all_schemas",
"get_schema",
"is_valid_key",
"load_schemas",
]
@@ -0,0 +1,171 @@
"""업종별 fact 스키마 — 업종마다 어떤 key 가 존재하는지의 유일한 소스.
resources/*.json 을 최초 사용 시 메모리에 로드한다. DB 에 저장하지 않으며 런타임에 수정하지 않는다.
**업종 추가 = resources/ 에 JSON 파일 1개 추가 + PlaceCategory 에 코드 1줄 추가.** 코드 수정은 없다.
검증 실패 시 예외를 던진다(요청 실패가 아니라 잘못된 리소스 배포를 조기에 드러내기 위함 —
파일은 코드와 함께 배포되므로 정상 배포에선 실패하지 않는다).
필드 속성
key : facts.key 에 저장되는 식별자. 업종 안에서 유일해야 한다
label : 화면·프롬프트에 쓰는 한글 이름
type : text | number | bool | time
scope : place(사업장 단위) | unit(객실·메뉴·프로그램 단위)
required : 발행 검수 게이트의 필수 항목. 빠지면 PUBLISH_REQUIRED_FACT_MISSING
critical : ★ 틀리면 손님이 헛걸음하거나 예약 클레임이 나는 항목.
미검증 상태로는 절대 노출하지 않는다(절대규칙 1)
allow_llm : LLM 이 값을 만들어도 되는 필드인가. **False 가 기본** — LLM 은 사실을 만들지 않는다.
True 인 것은 소개문처럼 '문장' 자체가 산출물인 필드뿐이다(절대규칙 7)
unit : 값의 단위(원·명·분…). 없으면 null
"""
import json
from pathlib import Path
from common.enums import PlaceCategory
_RESOURCE_DIR = Path(__file__).parent / "resources"
_ALLOWED_TYPES = ("text", "number", "bool", "time")
_ALLOWED_SCOPES = ("place", "unit")
_schemas: dict | None = None # category code -> CategorySchema
class CategorySchemaError(RuntimeError):
"""업종 스키마 로드/검증 실패."""
class FieldSpec:
"""업종 스키마의 필드 1개. JSON 한 행에 대응한다."""
__slots__ = ("key", "label", "type", "scope", "required", "critical", "allow_llm", "unit")
def __init__(self, row: dict, source: str):
for name in ("key", "label", "type", "scope"):
if not isinstance(row.get(name), str) or not row[name]:
raise CategorySchemaError(f"{source}: 필드 '{name}' 이 비었거나 문자열이 아님 — {row}")
if row["type"] not in _ALLOWED_TYPES:
raise CategorySchemaError(f"{source}: type 값 오류 key={row['key']} type={row['type']} (허용 {_ALLOWED_TYPES})")
if row["scope"] not in _ALLOWED_SCOPES:
raise CategorySchemaError(f"{source}: scope 값 오류 key={row['key']} scope={row['scope']} (허용 {_ALLOWED_SCOPES})")
for name in ("required", "critical", "allow_llm"):
if not isinstance(row.get(name), bool):
raise CategorySchemaError(f"{source}: '{name}' 은 bool 이어야 함 key={row['key']} value={row.get(name)}")
self.key = row["key"]
self.label = row["label"]
self.type = row["type"]
self.scope = row["scope"]
self.required = row["required"]
self.critical = row["critical"]
self.allow_llm = row["allow_llm"]
self.unit = row.get("unit")
def to_dict(self) -> dict:
return {name: getattr(self, name) for name in self.__slots__}
class CategorySchema:
"""업종 1개의 fact 스키마."""
def __init__(self, doc: dict, source: str):
code = doc.get("code")
try:
self.category = PlaceCategory(code)
except ValueError as ex:
raise CategorySchemaError(f"{source}: PlaceCategory 에 없는 code={code}") from ex
self.name = doc.get("category")
self.label = doc.get("label")
if not isinstance(self.name, str) or not isinstance(self.label, str):
raise CategorySchemaError(f"{source}: category/label 이 문자열이 아님")
rows = doc.get("fields")
if not isinstance(rows, list) or not rows:
raise CategorySchemaError(f"{source}: fields 가 비었음")
self.fields: dict[str, FieldSpec] = {}
for row in rows:
spec = FieldSpec(row, source)
if spec.key in self.fields:
raise CategorySchemaError(f"{source}: key 중복 — {spec.key}")
self.fields[spec.key] = spec
@property
def code(self) -> int:
return self.category.value
def get(self, key: str) -> FieldSpec | None:
return self.fields.get(key)
def has(self, key: str) -> bool:
return key in self.fields
def keys_by_scope(self, scope: str) -> list[str]:
return [k for k, f in self.fields.items() if f.scope == scope]
def required_keys(self, scope: str | None = None) -> list[str]:
"""발행 검수 게이트가 존재를 확인하는 필수 key 목록."""
return [k for k, f in self.fields.items() if f.required and (scope is None or f.scope == scope)]
def critical_keys(self) -> list[str]:
"""★ 미검증 상태로 노출하면 안 되는 key 목록(체크인·취사·반려동물·취소 규정 등)."""
return [k for k, f in self.fields.items() if f.critical]
def llm_writable_keys(self) -> list[str]:
"""LLM 이 값을 만들어도 되는 key 목록. 나머지는 LLM 이 값을 채울 수 없다."""
return [k for k, f in self.fields.items() if f.allow_llm]
def load_schemas() -> None:
"""리소스 디렉터리 전체 로드 + 검증. 최초 1회 호출(멱등).
파일을 하나 추가하면 그대로 새 업종이 된다 — 로더 코드는 건드리지 않는다."""
global _schemas
if _schemas is not None:
return
paths = sorted(_RESOURCE_DIR.glob("*.json"))
if not paths:
raise CategorySchemaError(f"업종 스키마 파일이 없습니다: {_RESOURCE_DIR}")
loaded: dict[int, CategorySchema] = {}
for path in paths:
try:
doc = json.loads(path.read_text(encoding="utf-8"))
except Exception as ex:
raise CategorySchemaError(f"업종 스키마 파일 로드 실패: {path}: {ex}") from ex
schema = CategorySchema(doc, path.name)
if schema.code in loaded:
raise CategorySchemaError(f"업종 code 중복: {schema.code} ({path.name})")
loaded[schema.code] = schema
missing = [c.name for c in PlaceCategory if c.value not in loaded]
if missing:
raise CategorySchemaError(f"PlaceCategory 에 있으나 스키마 파일이 없는 업종: {missing}")
_schemas = loaded
def get_schema(category) -> CategorySchema:
"""업종 코드(int 또는 PlaceCategory) → 스키마. 없는 업종이면 CategorySchemaError."""
if _schemas is None:
load_schemas()
code = category.value if isinstance(category, PlaceCategory) else category
schema = _schemas.get(code)
if schema is None:
raise CategorySchemaError(f"지원하지 않는 업종 코드: {code}")
return schema
def all_schemas() -> dict:
"""전 업종 스키마. {code: CategorySchema}"""
if _schemas is None:
load_schemas()
return dict(_schemas)
def is_valid_key(category, key: str) -> bool:
"""해당 업종에 존재하는 fact key 인지. facts 쓰기 전 검증에 쓴다(FACT_INVALID_KEY)."""
try:
return get_schema(category).has(key)
except CategorySchemaError:
return False
@@ -0,0 +1,31 @@
{
"category": "cafe",
"code": 2,
"label": "카페",
"fields": [
{ "key": "business_hours", "label": "영업시간", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "closed_days", "label": "휴무일", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "break_time", "label": "브레이크타임", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "last_order", "label": "라스트오더", "type": "time", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "pet_allowed", "label": "반려동물 동반", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "kids_allowed", "label": "아동 입장", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "parking", "label": "주차 가능", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "parking_free_hours", "label": "무료 주차 시간", "type": "number", "scope": "place", "required": false, "critical": true, "allow_llm": false, "unit": "시간" },
{ "key": "seat_count", "label": "좌석 수", "type": "number", "scope": "place", "required": false, "critical": false, "allow_llm": false, "unit": "석" },
{ "key": "wifi", "label": "와이파이", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "power_outlet", "label": "콘센트", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "study_allowed", "label": "장시간 이용", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "terrace", "label": "테라스·야외석", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "takeout", "label": "테이크아웃", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "delivery", "label": "배달", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "signature_menu", "label": "대표 메뉴", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "price_range", "label": "가격대", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "payment_methods", "label": "결제 수단", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "wheelchair_accessible", "label": "휠체어 접근", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "intro", "label": "카페 소개", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": true },
{ "key": "menu_name", "label": "메뉴명", "type": "text", "scope": "unit", "required": true, "critical": false, "allow_llm": false },
{ "key": "menu_price", "label": "메뉴 가격", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
{ "key": "menu_intro", "label": "메뉴 소개", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": true }
]
}
@@ -0,0 +1,38 @@
{
"category": "lodging",
"code": 1,
"label": "숙박",
"fields": [
{ "key": "check_in_time", "label": "체크인 시간", "type": "time", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "check_out_time", "label": "체크아웃 시간", "type": "time", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "cancel_policy", "label": "취소·환불 규정", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "cooking_allowed", "label": "취사 가능", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "pet_allowed", "label": "반려동물 동반", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "smoking", "label": "흡연 가능", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "extra_person_fee", "label": "인원 추가 요금", "type": "number", "scope": "place", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
{ "key": "reception_hours", "label": "프런트 운영시간", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "parking", "label": "주차 가능", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "parking_capacity", "label": "주차 대수", "type": "number", "scope": "place", "required": false, "critical": false, "allow_llm": false, "unit": "대" },
{ "key": "wifi", "label": "와이파이", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "bbq_available", "label": "바비큐 이용", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "bbq_fee", "label": "바비큐 이용료", "type": "number", "scope": "place", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
{ "key": "breakfast", "label": "조식 제공", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "baby_amenities", "label": "유아용품 비치", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "pickup_service", "label": "픽업 서비스", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "intro", "label": "숙소 소개", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": true },
{ "key": "room_type", "label": "객실 타입", "type": "text", "scope": "unit", "required": true, "critical": false, "allow_llm": false },
{ "key": "standard_capacity", "label": "기준 인원", "type": "number", "scope": "unit", "required": true, "critical": true, "allow_llm": false, "unit": "명" },
{ "key": "max_capacity", "label": "최대 인원", "type": "number", "scope": "unit", "required": true, "critical": true, "allow_llm": false, "unit": "명" },
{ "key": "bed_type", "label": "침대 구성", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "room_size", "label": "객실 면적", "type": "number", "scope": "unit", "required": false, "critical": false, "allow_llm": false, "unit": "㎡" },
{ "key": "bathroom_count", "label": "욕실 수", "type": "number", "scope": "unit", "required": false, "critical": false, "allow_llm": false, "unit": "개" },
{ "key": "has_kitchen", "label": "주방 여부", "type": "bool", "scope": "unit", "required": false, "critical": true, "allow_llm": false },
{ "key": "has_aircon", "label": "에어컨", "type": "bool", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "view", "label": "전망", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "weekday_price", "label": "주중 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
{ "key": "weekend_price", "label": "주말 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
{ "key": "peak_price", "label": "성수기 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
{ "key": "room_intro", "label": "객실 소개", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": true }
]
}
@@ -0,0 +1,32 @@
{
"category": "restaurant",
"code": 3,
"label": "음식점",
"fields": [
{ "key": "business_hours", "label": "영업시간", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "closed_days", "label": "휴무일", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "break_time", "label": "브레이크타임", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "last_order", "label": "라스트오더", "type": "time", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "reservation_required", "label": "예약 필수", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "reservation_channel", "label": "예약 방법", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "pet_allowed", "label": "반려동물 동반", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "kids_allowed", "label": "아동 입장", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "corkage", "label": "콜키지", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "room_available", "label": "룸·별실", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "group_seat_max", "label": "단체석 최대 인원", "type": "number", "scope": "place", "required": false, "critical": true, "allow_llm": false, "unit": "명" },
{ "key": "parking", "label": "주차 가능", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "parking_capacity", "label": "주차 대수", "type": "number", "scope": "place", "required": false, "critical": false, "allow_llm": false, "unit": "대" },
{ "key": "takeout", "label": "포장", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "delivery", "label": "배달", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "payment_methods", "label": "결제 수단", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "signature_menu", "label": "대표 메뉴", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "price_range", "label": "가격대", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "wheelchair_accessible", "label": "휠체어 접근", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "intro", "label": "가게 소개", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": true },
{ "key": "menu_name", "label": "메뉴명", "type": "text", "scope": "unit", "required": true, "critical": false, "allow_llm": false },
{ "key": "menu_price", "label": "메뉴 가격", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
{ "key": "menu_min_order", "label": "최소 주문 인분", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "인분" },
{ "key": "menu_intro", "label": "메뉴 소개", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": true }
]
}
@@ -0,0 +1,32 @@
{
"category": "tour_activity",
"code": 4,
"label": "관광체험",
"fields": [
{ "key": "operating_hours", "label": "운영시간", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "closed_days", "label": "휴무일", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "reservation_required", "label": "예약 필수", "type": "bool", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "reservation_channel", "label": "예약 방법", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "cancel_policy", "label": "취소·환불 규정", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "age_limit", "label": "연령 제한", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "safety_notice", "label": "안전 유의사항", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "weather_dependent", "label": "우천 시 운영", "type": "text", "scope": "place", "required": true, "critical": true, "allow_llm": false },
{ "key": "what_to_bring", "label": "준비물", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "session_times", "label": "회차 시간", "type": "text", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "guide_language", "label": "안내 언어", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "parking", "label": "주차 가능", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "wheelchair_accessible", "label": "휠체어 접근", "type": "bool", "scope": "place", "required": false, "critical": true, "allow_llm": false },
{ "key": "locker_available", "label": "물품보관함", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "shower_available", "label": "샤워시설", "type": "bool", "scope": "place", "required": false, "critical": false, "allow_llm": false },
{ "key": "intro", "label": "체험 소개", "type": "text", "scope": "place", "required": false, "critical": false, "allow_llm": true },
{ "key": "program_name", "label": "프로그램명", "type": "text", "scope": "unit", "required": true, "critical": false, "allow_llm": false },
{ "key": "program_duration", "label": "소요 시간", "type": "number", "scope": "unit", "required": true, "critical": true, "allow_llm": false, "unit": "분" },
{ "key": "program_capacity", "label": "회차당 정원", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "명" },
{ "key": "program_min_people", "label": "최소 출발 인원", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "명" },
{ "key": "price_adult", "label": "성인 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
{ "key": "price_child", "label": "소인 요금", "type": "number", "scope": "unit", "required": false, "critical": true, "allow_llm": false, "unit": "원" },
{ "key": "program_level", "label": "난이도", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": false },
{ "key": "program_intro", "label": "프로그램 소개", "type": "text", "scope": "unit", "required": false, "critical": false, "allow_llm": true }
]
}
+198
View File
@@ -0,0 +1,198 @@
"""사이트 1건 생성 원가 미터 — **$1 예산을 코드로 강제한다.**
★ 제품 제약: **업소 1곳의 사이트를 만드는 데 드는 외부 API 비용은 $1(1,400원)을 넘으면 안 된다.**
이 모듈은 그 예산을 "문서에 적힌 목표" 가 아니라 **호출을 막는 가드**로 만든다.
쓰는 법 — 사이트 1건 = 미터 1개:
meter = CostMeter(place_id=42)
meter.guard(Provider.PERPLEXITY, calls=1, tokens=3000) # 호출 "전" 에 물어본다
...실제 호출...
meter.charge(Provider.PERPLEXITY, calls=1, tokens=3100) # 호출 "후" 에 실측을 적는다
`guard()` 가 BudgetExceeded 를 던지면 **그 호출은 하지 않는다.** 이미 쓴 돈은 못 돌려받지만
다음 호출을 막아 손실이 선형으로 늘어나는 것을 끊는다.
비용 리스크 순서(큰 것부터): Gemini(사진 장수에 비례) > Perplexity(토큰+요청 요금) > Kakao(건당 2원).
"""
from dataclasses import dataclass, field
from enum import Enum
from common.logger import LOG
# ── 예산 ────────────────────────────────────────────────────────
USD_KRW = 1400.0 # 환산 환율. 실제 청구 환율과 다를 수 있다.
SITE_BUDGET_KRW = 1400.0 # ★ 사이트 1건당 상한 = $1
# 예산의 몇 %까지 차면 경고를 남길지. 넘겨도 막지는 않는다 — 막는 건 100% 지점이다.
WARN_RATIO = 0.7
class Provider(Enum):
PERPLEXITY = "perplexity"
KAKAO = "kakao"
GEMINI = "gemini"
TOUR_API = "tour_api"
OPEN_METEO = "open_meteo"
@dataclass(frozen=True)
class Rate:
"""공급자별 단가(원 기준).
confirmed=False 는 **아직 공식 단가표로 확인하지 않은 추정치**라는 뜻이다.
추정치로 예산을 계산하면 "예산 안" 이라는 결론 자체가 추정이 된다 —
실제 배치를 돌리기 전에 `assert_rates_confirmed()` 로 막는다.
"""
per_call_krw: float = 0.0 # 호출 1건당 고정비
per_search_krw: float = 0.0 # 검색 1회당 (Perplexity 는 토큰과 별도 과금)
per_1k_token_krw: float = 0.0 # 토큰 1,000개당
per_image_krw: float = 0.0 # 이미지 1장당
confirmed: bool = False
source: str = ""
# ── 단가표 ──────────────────────────────────────────────────────
# ★ 확정된 것만 confirmed=True 다. 나머지는 자리만 잡아둔 추정치이므로
# 공식 단가표를 확인해서 교체하기 전에는 실배치를 돌리면 안 된다.
RATES: dict[Provider, Rate] = {
# 레포에 확정값이 있다(.env.example): 키워드/카테고리 검색 2원, 좌표 변환 0.5원.
# 좌표 변환은 per_call 로 따로 세지 않고 호출측이 kakao_coord 로 구분해 넘긴다.
Provider.KAKAO: Rate(
per_call_krw=2.0,
confirmed=True,
source=".env.example — 키워드/카테고리 검색 2원 (무료 쿼터 초과분)",
),
# Sonar 기본 search_context_size=low: 요청 $5/1K + 입력/출력 각각 $1/1M.
# 2026-08-28 환산(USD_KRW=1,400)이다. 내부 검색 횟수에는 별도 요금이 없다.
Provider.PERPLEXITY: Rate(
per_call_krw=7.0,
per_1k_token_krw=1.4,
confirmed=True,
source="https://docs.perplexity.ai/docs/getting-started/pricing — Sonar low context",
),
# ★ 미확인 — Google AI Studio 단가표 확인 후 교체할 것.
Provider.GEMINI: Rate(
per_image_krw=1.0,
per_1k_token_krw=0.5,
confirmed=False,
source="추정치",
),
# 공공데이터·무료.
Provider.TOUR_API: Rate(confirmed=True, source="공공데이터포털 무료(일 트래픽 제한)"),
Provider.OPEN_METEO: Rate(confirmed=True, source="무료, 키 불필요"),
}
# 카카오 좌표 변환은 키워드 검색보다 4배 싸다 — 같은 공급자지만 단가가 다르다.
KAKAO_COORD_KRW = 0.5
class BudgetExceeded(Exception):
"""사이트 1건 예산을 넘겼다. 호출측은 **더 호출하지 말고** 작업을 중단한다."""
def __init__(self, place_id: int | None, spent_krw: float, would_add_krw: float):
self.place_id = place_id
self.spent_krw = spent_krw
self.would_add_krw = would_add_krw
super().__init__(
f"사이트 원가 예산 초과 (place_id={place_id}): "
f"이미 {spent_krw:.1f}원 + 이번 {would_add_krw:.1f}원 > 상한 {SITE_BUDGET_KRW:.0f}원"
)
class UnconfirmedRate(Exception):
"""추정 단가로 실배치를 돌리려 했다."""
def assert_rates_confirmed(*providers: Provider) -> None:
"""실배치 직전에 호출한다. 추정 단가가 섞여 있으면 막는다.
★ 이걸 건너뛰면 "예산 안에 들어온다" 는 결론이 추정 위에 서게 된다.
"""
bad = [p for p in (providers or tuple(RATES)) if not RATES[p].confirmed]
if bad:
names = ", ".join(p.value for p in bad)
raise UnconfirmedRate(
f"단가 미확인: {names} — 공식 단가표로 RATES 를 교체한 뒤에 배치를 돌려라"
)
def estimate_krw(
provider: Provider,
*,
calls: int = 0,
searches: int = 0,
tokens: int = 0,
images: int = 0,
kakao_coord_calls: int = 0,
) -> float:
"""이번 호출의 원가(원)를 계산한다. 실측이든 예상이든 같은 식을 쓴다."""
rate = RATES[provider]
krw = (
rate.per_call_krw * calls
+ rate.per_search_krw * searches
+ rate.per_1k_token_krw * (tokens / 1000.0)
+ rate.per_image_krw * images
)
if provider is Provider.KAKAO:
krw += KAKAO_COORD_KRW * kakao_coord_calls
return krw
@dataclass
class CostMeter:
"""사이트 1건(업소 1곳)의 원가 누적기. **미터 1개 = 사이트 1건**이다."""
place_id: int | None = None
budget_krw: float = SITE_BUDGET_KRW
spent_krw: float = 0.0
by_provider: dict[str, float] = field(default_factory=dict)
calls: int = 0
_warned: bool = False
@property
def remaining_krw(self) -> float:
return max(0.0, self.budget_krw - self.spent_krw)
@property
def spent_usd(self) -> float:
return self.spent_krw / USD_KRW
def guard(self, provider: Provider, **units) -> float:
"""호출 **전** 에 예산을 확인한다. 넘으면 BudgetExceeded — 호출하지 마라.
돌려주는 값은 이번 호출의 예상 원가(원)다.
"""
krw = estimate_krw(provider, **units)
if self.spent_krw + krw > self.budget_krw:
raise BudgetExceeded(self.place_id, self.spent_krw, krw)
return krw
def charge(self, provider: Provider, **units) -> float:
"""호출 **후** 에 실측 사용량을 적는다. 적고 나서 예산을 넘었으면 예외를 던진다.
★ 이미 나간 호출은 되돌릴 수 없다 — 예외의 목적은 **다음 호출을 막는 것**이다.
"""
krw = estimate_krw(provider, **units)
self.spent_krw += krw
self.calls += 1
self.by_provider[provider.value] = self.by_provider.get(provider.value, 0.0) + krw
if not self._warned and self.spent_krw >= self.budget_krw * WARN_RATIO:
self._warned = True
LOG.w(
f"[cost] place_id={self.place_id} 예산 {WARN_RATIO:.0%} 소진 — "
f"{self.spent_krw:.1f}/{self.budget_krw:.0f}원"
)
if self.spent_krw > self.budget_krw:
LOG.w(f"[cost] place_id={self.place_id} 예산 초과 — {self.summary()}")
raise BudgetExceeded(self.place_id, self.spent_krw - krw, krw)
return krw
def summary(self) -> str:
parts = " ".join(f"{k}={v:.1f}원" for k, v in sorted(self.by_provider.items()))
return (
f"place_id={self.place_id} 합계={self.spent_krw:.1f}원(${self.spent_usd:.3f}) "
f"호출={self.calls}건 상한={self.budget_krw:.0f}원 [{parts}]"
)
@@ -0,0 +1,263 @@
from asyncio import current_task
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_scoped_session
from sqlalchemy.util._collections import immutabledict
from common.database.model.models import MAIN_BASE
from common.enums import DBType, DBWRType, ErrorType
from common.logger import LOG
from common.singleton import Singleton
from config.server_configs import main_db_config
class DBSessionManager(Singleton):
"""DB 세션/엔진 관리자 (싱글톤).
핵심 패턴
- DBType(논리 DB) x DBWRType(Read/Write) 조합마다 별도 async 엔진을 둔다.
=> 조회는 Read 복제본, 변경은 Write 주 DB 로 자연스럽게 분리된다.
- 비즈니스 로직(service)은 직접 세션을 열지 않고 "람다"를 넘긴다.
execute_lambda : 단일 쿼리 (주로 조회)
execute_lambda_run : 동일 DB 의 여러 변경 쿼리를 한 트랜잭션으로 commit
세션 open/close 와 commit/rollback 은 매니저가 책임진다.
"""
def __init__(self):
if DBSessionManager.is_init():
LOG.e_no_callstack("already init DBSessionManager")
return
DBSessionManager.set_init()
self.__DB_URL_MAP = {"postgresql": "postgresql+asyncpg"}
# 종료 시 dispose 하기 위해 생성한 엔진을 모아둔다.
self.__engines = []
# 논리 DB -> config. DB 가 늘어나면 여기에 추가만 하면 된다.
self.__db_type_map = {
DBType.MAIN.value: main_db_config,
}
# Write 엔진 맵
self.__write_session = {
DBType.MAIN.value: self.create_engine(DBType.MAIN.value, DBWRType.DB_WRITE.value),
}
# Read 엔진 맵
self.__read_session = {
DBType.MAIN.value: self.create_engine(DBType.MAIN.value, DBWRType.DB_READ.value),
}
def create_engine(self, db_type: int, db_wr_type: int):
db_config = self.__db_type_map.get(db_type)
if not db_config:
raise ValueError("Invalid database type")
if db_wr_type == DBWRType.DB_READ.value:
pw = (":" + db_config.read_pw) if len(db_config.read_pw) > 0 else ""
db_url = f"{self.__DB_URL_MAP[db_config.db_type]}://{db_config.read_id}{pw}@{db_config.read_host}:{db_config.read_port}/{db_config.name}"
LOG.i(f"Read DB create engine url : {db_url}")
else:
pw = (":" + db_config.write_pw) if len(db_config.write_pw) > 0 else ""
db_url = f"{self.__DB_URL_MAP[db_config.db_type]}://{db_config.write_id}{pw}@{db_config.write_host}:{db_config.write_port}/{db_config.name}"
LOG.i(f"Write DB create engine url : {db_url}")
# SSL/TLS: 관리형 DB(RDS/Aurora/Azure)는 보통 TLS 필수. sslmode 가 설정되면 asyncpg 에 전달.
connect_args = {}
sslmode = (getattr(db_config, "sslmode", "") or "").lower()
if sslmode and sslmode != "disable":
connect_args["ssl"] = sslmode
engine = create_async_engine(
db_url,
echo=db_config.show_log,
pool_size=db_config.pool_size,
max_overflow=db_config.max_overflow,
pool_pre_ping=True,
pool_recycle=600,
connect_args=connect_args,
)
self.__engines.append(engine)
scoped_session = async_scoped_session(
sessionmaker(engine, class_=AsyncSession, expire_on_commit=False, autocommit=False, autoflush=False),
scopefunc=current_task,
)
return scoped_session
def is_registered(self, db_type: int) -> bool:
"""해당 논리 DB 가 등록돼 있는지 — 선택 연동(부속 DB)의 배치가 실행 전 확인하는 용도."""
return db_type in self.__db_type_map
async def dispose_all(self):
"""모든 엔진의 커넥션 풀을 정리한다. 앱 종료/테스트 종료 시 호출한다.
호출하지 않으면 풀 커넥션이 이벤트 루프 종료 후 GC 되며 경고를 남긴다.
"""
for engine in self.__engines:
await engine.dispose()
# ---- 세션 lifecycle -------------------------------------------------
async def start_session(self, db_type: int, db_wr_type: int) -> AsyncSession:
if db_wr_type == DBWRType.DB_WRITE.value:
return self.__write_session[db_type]()
return self.__read_session[db_type]()
async def end_session(self, db_type: int, db_wr_type: int):
if db_wr_type == DBWRType.DB_WRITE.value:
await self.__write_session[db_type].remove()
else:
await self.__read_session[db_type].remove()
# ---- 저수준 DB 연산 (crud 에서 호출) --------------------------------
async def run(self, db: AsyncSession, err_msg="DB Run Failed", raise_error=True) -> ErrorType:
try:
await db.commit()
return ErrorType.SUCCESS
except IntegrityError as ex:
await db.rollback()
LOG.e_no_callstack(f"duplicated. {ex}")
return ErrorType.DB_ALREADY_SAME_KEY
except Exception as ex:
await db.rollback()
err_type = ErrorType.DB_RUN_FAILED
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
if raise_error:
raise RuntimeError(err_type.name, err_msg)
return err_type
async def insert(self, db: AsyncSession, obj, err_msg="DB Failed", raise_error=True) -> ErrorType:
try:
if isinstance(obj, MAIN_BASE):
db.add(obj)
elif isinstance(obj, list):
db.add_all(obj)
else:
raise RuntimeError("DO NOT USE QUERY IN DBJOB")
return ErrorType.SUCCESS
except Exception as ex:
await db.rollback()
err_type = ErrorType.DB_RUN_FAILED
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
if raise_error:
raise RuntimeError(err_type.name, err_msg)
return err_type
async def add(self, db: AsyncSession, query, err_msg="DB Operation Failed", raise_error=True) -> ErrorType:
"""update/delete 등 비-select 쿼리 실행."""
try:
if hasattr(query, "column_descriptions"):
raise RuntimeError("DO NOT USE SELECT QUERY IN DBJOB")
await db.execute(query, execution_options=immutabledict({"synchronize_session": "fetch"}))
return ErrorType.SUCCESS
except IntegrityError as ex:
await db.rollback()
err_type = ErrorType.DB_ALREADY_SAME_KEY
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
return err_type
except Exception as ex:
await db.rollback()
err_type = ErrorType.DB_RUN_FAILED
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
if raise_error:
raise RuntimeError(err_type.name, err_msg)
return err_type
async def add_with_rowcount(self, db: AsyncSession, query, err_msg="DB Operation Failed") -> tuple[ErrorType, int]:
"""update/delete 등 비-select 쿼리 실행 후 (ErrorType, 영향행수) 반환.
조건부 갱신(WHERE 로 상태를 거른 UPDATE)이 실제로 적용됐는지 판별하는 동시처리 가드용."""
try:
if hasattr(query, "column_descriptions"):
raise RuntimeError("DO NOT USE SELECT QUERY IN DBJOB")
res = await db.execute(query, execution_options=immutabledict({"synchronize_session": "fetch"}))
return ErrorType.SUCCESS, res.rowcount
except IntegrityError as ex:
await db.rollback()
err_type = ErrorType.DB_ALREADY_SAME_KEY
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
return err_type, 0
except Exception as ex:
await db.rollback()
err_type = ErrorType.DB_RUN_FAILED
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
return err_type, 0
async def execute(self, db: AsyncSession, query, err_msg="DB Query Execution Failed", raise_error=True) -> tuple[ErrorType, list]:
"""select 쿼리 실행 후 결과 리스트 반환."""
try:
if not hasattr(query, "column_descriptions"):
raise RuntimeError("DO NOT USE NON-SELECT QUERY IN DBJOB")
res = await db.execute(query, execution_options=immutabledict({"synchronize_session": "fetch"}))
return ErrorType.SUCCESS, res.scalars().fetchall() if 1 == len(query.column_descriptions) else res.all()
except Exception as ex:
err_type = ErrorType.DB_RUN_FAILED
LOG.e_no_callstack(f"[{err_type.name}] {err_msg=}, {ex=}")
if raise_error:
raise RuntimeError(err_type.name, err_msg)
return err_type, []
# ---- 람다 실행 진입점 (service 에서 호출) ---------------------------
async def execute_lambda(self, db_type: int, db_wr_type: int, func):
"""단일 쿼리 호출. func(session) 한 개를 실행하고 결과를 그대로 반환."""
s = await self.start_session(db_type, db_wr_type)
try:
return await func(s)
finally:
await self.end_session(db_type, db_wr_type)
async def execute_lambda_run(self, db_type_list: list[int], func_list: list):
"""동일 DB 의 변경 쿼리 여러 개를 한 트랜잭션으로 실행 후 commit.
하나라도 SUCCESS 가 아니면 즉시 중단(rollback)된다.
"""
temp_list = list(set(db_type_list))
if len(temp_list) != 1:
return ErrorType.DB_INVALID_TYPE
db_type = temp_list[0]
s = await self.start_session(db_type, DBWRType.DB_WRITE.value)
try:
for func in func_list:
err_type = await func(s)
if err_type != ErrorType.SUCCESS:
return err_type
return await self.run(s)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
finally:
await self.end_session(db_type, DBWRType.DB_WRITE.value)
async def execute_lambda_write(self, db_type: int, func):
"""Write 세션에서 func(session) 을 실행하고 commit 한 뒤 **func 의 반환값을 그대로** 돌려준다.
execute_lambda_run 은 ErrorType 만, execute_lambda_claim 은 (ErrorType, 적용행수) 만 돌려준다.
작업 큐처럼 "변경하면서 값을 받아와야" 하는 경우(RETURNING 절)를 위한 진입점이다 —
원자적 claim(FOR UPDATE SKIP LOCKED + UPDATE + RETURNING)은 조회/변경을 나눌 수 없다.
예외는 rollback 후 그대로 전파한다(호출측이 잡 실패로 처리)."""
s = await self.start_session(db_type, DBWRType.DB_WRITE.value)
try:
result = await func(s)
await s.commit()
return result
except Exception:
await s.rollback()
raise
finally:
await self.end_session(db_type, DBWRType.DB_WRITE.value)
async def execute_lambda_claim(self, db_type: int, func) -> tuple[ErrorType, int]:
"""조건부 변경 쿼리 1건을 한 트랜잭션으로 실행/commit 하고 (ErrorType, 적용행수) 반환.
동시처리 가드용 — func(session) -> (ErrorType, rowcount). 적용행수 0 이면 다른 호출자가 이미 처리한 것.
(Postgres READ COMMITTED 에서 같은 행 UPDATE 는 행 잠금으로 직렬화되어, 진 호출자는 0 을 받는다.)"""
s = await self.start_session(db_type, DBWRType.DB_WRITE.value)
try:
err_type, rowcount = await func(s)
if err_type != ErrorType.SUCCESS:
return err_type, 0
commit_err = await self.run(s)
return commit_err, rowcount
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
finally:
await self.end_session(db_type, DBWRType.DB_WRITE.value)
DB_SESSION_MNG = DBSessionManager()
@@ -0,0 +1,507 @@
import uuid
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, Index, Integer, SmallInteger, Numeric, String, Text, Boolean, DateTime
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.sql import text
from common.enums import (
DBType,
UserStatus,
UserRole,
CompanyStatus,
PlaceStatus,
FactStatus,
MediaStatus,
SiteStatus,
BuildStatus,
JobStatus,
)
# 모든 ORM 모델의 베이스. insert 시 isinstance 체크에도 사용된다.
MAIN_BASE = declarative_base()
# 공통 mixin
# DB 계약(_DBTypeMixin)과 ERD 공통 컬럼(MainTableMixin)을 분리해 둔다.
def _utc_now_sql():
return text("(now() AT TIME ZONE 'utc')")
class _DBTypeMixin:
"""모델이 자신이 속한 논리 DB 를 알려준다 (람다 실행 시 DBType 으로 세션 선택)."""
@staticmethod
def DBType():
return DBType.MAIN.value
# ERD 공통 컬럼
class MainTableMixin(_DBTypeMixin):
created_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql())
updated_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql(), onupdate=_utc_now_sql())
deleted = Column(Boolean, nullable=False, server_default=text("false"), default=False)
# ERD 도메인 모델
class companies(MainTableMixin, MAIN_BASE):
__tablename__ = "companies"
__table_args__ = {"schema": "company"}
company_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name = Column(String(100), nullable=False)
business_number = Column(String(30), nullable=True)
code = Column(Integer, nullable=True) # 내부 인덱스용
representative_name = Column(String(50), nullable=True)
email = Column(String(255), nullable=True)
contact_number = Column(String(20), nullable=True)
website_url = Column(String(255), nullable=True)
industry = Column(SmallInteger, nullable=True) # 업종 코드 (스키마 SMALLINT)
status = Column(SmallInteger, nullable=False, default=CompanyStatus.ACTIVE.value) # CompanyStatus
# 회사별 커스터마이징 설정. branding(CI)/labels(용어)/features(동작)
settings = Column(JSONB, nullable=True)
class users(MainTableMixin, MAIN_BASE):
__tablename__ = "users"
__table_args__ = {"schema": "company"}
user_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
company_id = Column(UUID(as_uuid=True), nullable=False, index=True)
id = Column(String(20), nullable=False, unique=True, index=True) # 로그인 아이디
password = Column(String(255), nullable=False) # bcrypt 해시 (ERD VARCHAR(30)→255 확장)
name = Column(String(50), nullable=True)
email = Column(String(255), nullable=True)
contact_number = Column(String(20), nullable=True)
last_accessed_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql())
status = Column(SmallInteger, nullable=False, default=UserStatus.ACTIVE.value)
role = Column(SmallInteger, nullable=False, default=UserRole.USER.value)
# ============================================================
# place : 사업장 / 별칭 / 채널 링크 / 객실·메뉴·프로그램 / 사진
# ============================================================
class places(MainTableMixin, MAIN_BASE):
"""사업장. 상호명 하나로 시작해서, 카카오 로컬 검증을 통과해야 수집이 열린다.
★ verified_at 이 NULL 이면 collector 진입 금지 — 검증 없이 수집하면 남의 가게가 섞인다."""
__tablename__ = "places"
__table_args__ = (
Index("idx_places_region_code", "region_code", postgresql_where=text("deleted = false")),
{"schema": "place"},
)
place_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
company_id = Column(UUID(as_uuid=True), nullable=False, index=True) # 테넌트 스코프(company.companies)
owner_user_id = Column(UUID(as_uuid=True), nullable=True, index=True) # 사장님 계정(company.users)
name = Column(String(200), nullable=False) # 상호명(입력값)
category = Column(SmallInteger, nullable=False) # PlaceCategory — 업종 스키마 선택 키
status = Column(SmallInteger, nullable=False, server_default=text("1"), default=PlaceStatus.DRAFT.value)
# ---- 카카오 로컬 검증 산출물 (동일 업소 판정) ----
# 동일 업소 판정 키. 소스에 따라 있을 수도 없을 수도 있다 —
# 카카오는 고유 id 를 주지만 네이버는 안 준다(그 경우 상호명+도로명주소가 대체 키).
external_source = Column(SmallInteger, nullable=True) # ExternalPlaceSource
external_place_id = Column(String(64), nullable=True)
road_address = Column(String(255), nullable=True)
address = Column(String(255), nullable=True) # 지번
phone = Column(String(30), nullable=True)
latitude = Column(Numeric(10, 7), nullable=True)
longitude = Column(Numeric(10, 7), nullable=True)
region_code = Column(String(10), nullable=True) # 행정구역 코드 — ★ 지역정보 캐시 키(사이트 50개여도 조회 1회)
verified_at = Column(DateTime(timezone=True), nullable=True) # ★ NULL = 미검증 → 수집·발행 금지
verified_by = Column(UUID(as_uuid=True), nullable=True)
# ★ 노출값(VERIFIED/CORRECTED fact)이 마지막으로 바뀐 시각. 개별 재빌드 대상 판별용 —
# site_versions.built_at < content_updated_at 인 사이트만 다시 빌드한다.
content_updated_at = Column(DateTime(timezone=True), nullable=True)
class place_aliases(MainTableMixin, MAIN_BASE):
"""상호 별칭. 동명 업소 구분과 재검색에 쓴다(옛 상호, '본관/별관' 표기 등)."""
__tablename__ = "place_aliases"
__table_args__ = {"schema": "place"}
alias_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
place_id = Column(UUID(as_uuid=True), nullable=False, index=True)
alias = Column(String(200), nullable=False)
source_type = Column(SmallInteger, nullable=False) # SourceType
class place_links(MainTableMixin, MAIN_BASE):
"""Perplexity 가 발견한 채널 URL.
★ confirmed_at 이 NULL 이면 크롤링 대상이 아니다 — 카카오 로컬로 동일 업소임을 확인한 URL만 넘긴다.
raw 에 Perplexity 응답(본문 + search_results)을 통째로 남긴다. 환각 추적용이며 사실 근거로 쓰지 않는다."""
__tablename__ = "place_links"
__table_args__ = (
Index(
"uq_place_links_place_url",
"place_id",
"url",
unique=True,
postgresql_where=text("deleted = false"),
),
{"schema": "place"},
)
link_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
place_id = Column(UUID(as_uuid=True), nullable=False, index=True)
channel = Column(SmallInteger, nullable=False) # LinkChannel
url = Column(String(1000), nullable=False)
title = Column(String(300), nullable=True) # 발견 시 제목/스니펫
discovered_by = Column(SmallInteger, nullable=False) # SourceType (API=Perplexity, OWNER=직접 입력)
discovered_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql())
confirmed_at = Column(DateTime(timezone=True), nullable=True) # ★ NULL = 미확정, 크롤링 금지
confirmed_by = Column(UUID(as_uuid=True), nullable=True)
raw = Column(JSONB, nullable=True) # Perplexity 응답 원문(본문 + search_results)
class units(MainTableMixin, MAIN_BASE):
"""업종별 하위 단위 — 숙박=객실, 카페·음식점=메뉴, 관광체험=프로그램.
가변 필드는 facts(scope=unit)로 들어가고, 여기에는 목록 렌더에 필요한 뼈대만 둔다."""
__tablename__ = "units"
__table_args__ = {"schema": "place"}
unit_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
place_id = Column(UUID(as_uuid=True), nullable=False, index=True)
name = Column(String(200), nullable=False)
sort_order = Column(Integer, nullable=False, server_default=text("0"), default=0)
class media(MainTableMixin, MAIN_BASE):
"""사진. Gemini Vision 이 분류 라벨과 alt 를 만든다.
★ source_type 을 반드시 남긴다 — 크롤링 이미지의 재게시 권리가 미결이라(docs/DECISIONS.md 1-2),
결론에 따라 발행 시 source_type 으로 걸러낼 수 있어야 한다.
★ vision_confidence 가 낮으면 자동 반영하지 않고 PENDING_REVIEW 로 사람 확인 큐에 둔다."""
__tablename__ = "media"
__table_args__ = {"schema": "place"}
media_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
place_id = Column(UUID(as_uuid=True), nullable=False, index=True)
unit_id = Column(UUID(as_uuid=True), nullable=True, index=True) # 객실·메뉴 사진이면 연결
url = Column(String(1000), nullable=False) # 우리가 보관하는 접근 URL
origin_url = Column(String(1000), nullable=True) # 수집 원본 이미지 URL
source_type = Column(SmallInteger, nullable=False) # SourceType — OWNER 업로드 / CRAWL 수집
source_url = Column(String(1000), nullable=True) # 수집한 페이지 URL
label = Column(String(200), nullable=True) # Vision 분류 라벨 (예: "A동 침실")
alt_text = Column(String(500), nullable=True) # Vision 생성 alt
vision_confidence = Column(Numeric(4, 3), nullable=True) # 0.000~1.000
status = Column(SmallInteger, nullable=False, server_default=text("1"), default=MediaStatus.PENDING_REVIEW.value)
width = Column(Integer, nullable=True)
height = Column(Integer, nullable=True)
sort_order = Column(Integer, nullable=False, server_default=text("0"), default=0)
# ============================================================
# fact : 사실 / FAQ
# ============================================================
class facts(MainTableMixin, MAIN_BASE):
"""★ 가장 중요한 테이블. 모든 사실은 값과 함께 출처·수집시각·검증상태를 갖는다.
- key 는 업종 스키마(common/category_schema)에 정의된 것만 허용한다.
- unit_id 가 NULL 이면 사업장 단위 fact, 있으면 객실·메뉴·프로그램 단위 fact.
- ★ VERIFIED / CORRECTED 만 사이트에 노출한다(PUBLISHABLE_FACT_STATUSES).
- ★ CORRECTED(사장님 수정본)는 잠긴다 — 자동 갱신이 덮어쓰지 않는다.
활성 유니크: 같은 (place, unit, key) 로 살아있는 fact 는 1건. REJECTED/EXPIRED 는 이력으로 남기므로 제외한다."""
__tablename__ = "facts"
__table_args__ = (
# unit_id 가 NULL 인 행끼리는 유니크가 안 걸리므로 place 단위 / unit 단위를 나눠 건다.
# 노출값은 (사업장, 단위, key) 당 1건. 후보(1,2)·이력(5,6)은 제외 — 재수집이 쌓일 수 있게.
Index(
"uq_facts_published_place_key",
"place_id",
"key",
unique=True,
postgresql_where=text("deleted = false AND unit_id IS NULL AND status IN (3, 4)"),
),
Index(
"uq_facts_published_unit_key",
"place_id",
"unit_id",
"key",
unique=True,
postgresql_where=text("deleted = false AND unit_id IS NOT NULL AND status IN (3, 4)"),
),
# 후보 조회 경로(사람 확인 큐) — 재수집이 올려놓은 대기 항목.
Index(
"idx_facts_candidate",
"place_id",
"key",
"source_type",
postgresql_where=text("deleted = false AND status IN (1, 2)"),
),
# 발행 게이트가 "노출 가능한 fact" 만 훑는 경로.
Index(
"idx_facts_publishable",
"place_id",
"status",
postgresql_where=text("deleted = false AND status IN (3, 4)"),
),
{"schema": "fact"},
)
fact_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
place_id = Column(UUID(as_uuid=True), nullable=False, index=True)
unit_id = Column(UUID(as_uuid=True), nullable=True, index=True)
key = Column(String(100), nullable=False) # 업종 스키마의 필드 key
value = Column(Text, nullable=True)
unit = Column(String(30), nullable=True) # 값의 단위(원·명·분…)
source_type = Column(SmallInteger, nullable=False) # SourceType — owner | api | crawl | llm
source_url = Column(String(1000), nullable=True)
collected_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql())
verified_by = Column(UUID(as_uuid=True), nullable=True) # company.users.user_id
verified_at = Column(DateTime(timezone=True), nullable=True)
status = Column(SmallInteger, nullable=False, server_default=text("1"), default=FactStatus.UNVERIFIED.value)
expires_at = Column(DateTime(timezone=True), nullable=True) # 지나면 EXPIRED 전이 대상
class faqs(MainTableMixin, MAIN_BASE):
"""FAQ. ★ 확보된 fact 만 근거로 쓴다 — source_fact_ids 가 비면 발행 게이트가 반려한다."""
__tablename__ = "faqs"
__table_args__ = {"schema": "fact"}
faq_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
place_id = Column(UUID(as_uuid=True), nullable=False, index=True)
question = Column(String(500), nullable=False)
answer = Column(Text, nullable=False)
source_fact_ids = Column(JSONB, nullable=True) # ★ 근거 fact_id 배열. 비면 반려
generated_by = Column(SmallInteger, nullable=False) # SourceType — LLM | OWNER
status = Column(SmallInteger, nullable=False, server_default=text("1"), default=FactStatus.UNVERIFIED.value)
sort_order = Column(Integer, nullable=False, server_default=text("0"), default=0)
# ============================================================
# local : 지역 정보(행정구역 코드 단위 캐시) / 가는 길 / 주변
# ============================================================
class local_contents(MainTableMixin, MAIN_BASE):
"""지역 정보 캐시. ★ 키는 place_id 가 아니라 region_code 다 —
같은 지역에 사이트 50개가 생겨도 외부 조회는 1회여야 한다.
★ 외부 API 실패 시 이 행을 지우거나 비우지 않는다 — 직전 값을 그대로 유지하고 내부 알림만 낸다."""
__tablename__ = "local_contents"
__table_args__ = (
# external_id 가 있는 항목(축제·관광지·맛집)은 출처 고유 ID 로 중복을 막는다.
Index(
"uq_local_contents_keyed",
"region_code",
"content_type",
"external_id",
unique=True,
postgresql_where=text("deleted = false AND external_id IS NOT NULL"),
),
# external_id 가 없는 항목(날씨)은 지역 × 종류당 1행.
Index(
"uq_local_contents_single",
"region_code",
"content_type",
unique=True,
postgresql_where=text("deleted = false AND external_id IS NULL"),
),
{"schema": "local"},
)
local_content_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
region_code = Column(String(10), nullable=False, index=True) # 카카오 행정구역 코드 = 캐시 키
content_type = Column(SmallInteger, nullable=False) # LocalContentType
source = Column(SmallInteger, nullable=False) # LocalSource
external_id = Column(String(100), nullable=True) # TourAPI contentid 등 출처 고유 ID
title = Column(String(300), nullable=True)
body = Column(JSONB, nullable=False) # 원문 페이로드
status = Column(SmallInteger, nullable=False, server_default=text("1")) # LocalContentStatus
published_at = Column(DateTime(timezone=True), nullable=True)
published_by = Column(UUID(as_uuid=True), nullable=True)
display_start_at = Column(DateTime(timezone=True), nullable=True)
display_end_at = Column(DateTime(timezone=True), nullable=True)
collected_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql())
expires_at = Column(DateTime(timezone=True), nullable=True) # TTL — 지나면 갱신 대상(값은 유지)
class routes(MainTableMixin, MAIN_BASE):
"""가는 길. 검증 상태(FactStatus)를 그대로 쓴다 — 틀린 경로 안내도 헛걸음을 만든다."""
__tablename__ = "routes"
__table_args__ = {"schema": "local"}
route_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
place_id = Column(UUID(as_uuid=True), nullable=False, index=True)
origin_name = Column(String(200), nullable=False) # 출발지 (예: "서울역")
transport = Column(SmallInteger, nullable=False) # TransportType
duration_min = Column(Integer, nullable=True)
distance_m = Column(Integer, nullable=True)
description = Column(Text, nullable=True)
source_type = Column(SmallInteger, nullable=False) # SourceType
status = Column(SmallInteger, nullable=False, server_default=text("1"), default=FactStatus.UNVERIFIED.value)
sort_order = Column(Integer, nullable=False, server_default=text("0"), default=0)
class nearby_links(MainTableMixin, MAIN_BASE):
"""주변 맛집·시설. 카카오 카테고리 검색 결과를 사업장에 붙인 것.
카테고리 검색은 좌표 변환보다 4배 비싸므로 region_code 단위 캐시(local_contents)에서 파생시킨다."""
__tablename__ = "nearby_links"
__table_args__ = {"schema": "local"}
nearby_link_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
place_id = Column(UUID(as_uuid=True), nullable=False, index=True)
region_code = Column(String(10), nullable=True) # 어느 지역 캐시에서 왔는지
name = Column(String(200), nullable=False)
category_name = Column(String(100), nullable=True) # 카카오 category_name
kakao_place_id = Column(String(32), nullable=True)
distance_m = Column(Integer, nullable=True)
url = Column(String(1000), nullable=True)
latitude = Column(Numeric(10, 7), nullable=True)
longitude = Column(Numeric(10, 7), nullable=True)
sort_order = Column(Integer, nullable=False, server_default=text("0"), default=0)
# ============================================================
# site : 사이트 / 버전 / 발행 로그 / AI 노출 점검
# ============================================================
class sites(MainTableMixin, MAIN_BASE):
"""발행 대상 사이트. 사업장당 1개.
★ 해지는 물리 삭제가 아니라 status 전이로만 처리한다 — 색인된 페이지를 갑자기 404 로 만들지 않는다."""
__tablename__ = "sites"
__table_args__ = (
Index("uq_sites_place", "place_id", unique=True, postgresql_where=text("deleted = false")),
Index("uq_sites_domain", "domain", unique=True, postgresql_where=text("deleted = false AND domain IS NOT NULL")),
{"schema": "site"},
)
site_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
place_id = Column(UUID(as_uuid=True), nullable=False)
domain = Column(String(255), nullable=True)
path_prefix = Column(String(100), nullable=True)
# 사장님이 고른 템플릿 키(프론트 배리에이션 레지스트리의 id). 서버는 해석하지 않고 보관·반환만 한다 —
# 템플릿 목록은 프론트가 소유하므로, 서버가 값을 검증하면 템플릿을 늘릴 때마다 백엔드를 고쳐야 한다.
# NULL 이면 발행 잡이 업종 기본 템플릿으로 굽는다(services/site_payload).
template_id = Column(String(100), nullable=True)
# 에디터가 정한 색·서체·섹션(순서·on/off·배리에이션). template_id 와 같은 이유로 서버에 저장한다 —
# 브라우저에만 두면 발행 잡이 읽을 곳이 없어 업종 기본 모양으로 굽고, 고른 디자인과 발행본이 갈린다.
# ★ 컬럼으로 펼치지 않고 jsonb 로 통째로 담는 이유: 섹션 목록·배리에이션 키·색 토큰 이름은
# 프론트가 소유한다. 펼치면 프론트가 항목 하나 늘릴 때마다 마이그레이션이 따라와야 한다.
# ★ templateId 는 여기 넣지 않는다 — 위 template_id 컬럼이 소유한다. 두 곳에 두면 어느 쪽이 진짜인지 갈린다.
# NULL 이면 발행 잡이 업종 기본 색·서체·섹션으로 굽는다(services/site_payload).
theme = Column(JSONB, nullable=True)
status = Column(SmallInteger, nullable=False, server_default=text("1"), default=SiteStatus.DRAFT.value)
current_version_id = Column(UUID(as_uuid=True), nullable=True) # site.site_versions.site_version_id
published_at = Column(DateTime(timezone=True), nullable=True)
class site_versions(MainTableMixin, MAIN_BASE):
"""빌드 버전. ★ 정적 빌드 — snapshot 에 빌드 시점 데이터를 박제하고, 방문자는 DB 와 만나지 않는다.
★ 개별 재빌드 단위다. 사이트 1,000개에서 전체 재빌드는 못 쓴다.
★ jsonld 값은 화면에 보이는 값과 같아야 한다 — 불일치면 빌드 실패(PUBLISH_JSONLD_MISMATCH).
★ unique_content_count 가 0 이면 발행 API 가 거부한다(스팸 판정 대상)."""
__tablename__ = "site_versions"
__table_args__ = (
Index("uq_site_versions_no", "site_id", "version", unique=True, postgresql_where=text("deleted = false")),
{"schema": "site"},
)
site_version_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
site_id = Column(UUID(as_uuid=True), nullable=False, index=True)
version = Column(Integer, nullable=False) # 1부터
build_status = Column(SmallInteger, nullable=False, server_default=text("1"), default=BuildStatus.PENDING.value)
snapshot = Column(JSONB, nullable=True) # 빌드 시점 데이터 박제
jsonld = Column(JSONB, nullable=True) # 구조화 데이터
unique_content_count = Column(Integer, nullable=False, server_default=text("0"), default=0) # ★ 0 이면 발행 거부
build_error = Column(Text, nullable=True)
built_at = Column(DateTime(timezone=True), nullable=True)
class publish_logs(MainTableMixin, MAIN_BASE):
"""발행 시도 기록. 검수 게이트가 막았으면 result=REJECTED + reject_reason 을 남긴다."""
__tablename__ = "publish_logs"
__table_args__ = {"schema": "site"}
publish_log_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
site_id = Column(UUID(as_uuid=True), nullable=False, index=True)
site_version_id = Column(UUID(as_uuid=True), nullable=True)
action = Column(SmallInteger, nullable=False) # PublishAction
result = Column(SmallInteger, nullable=False) # PublishResult
reject_reason = Column(SmallInteger, nullable=True) # PublishRejectReason
detail = Column(JSONB, nullable=True) # 막힌 항목 목록(미검증 fact key 등)
actor_user_id = Column(UUID(as_uuid=True), nullable=True)
class ai_check_results(MainTableMixin, MAIN_BASE):
"""AI 검색 노출 점검. 이 서비스의 목표 지표 —
AI 가 이 가게를 **우리 사이트를 근거로** 설명하는가, 아니면 여전히 OTA 를 인용하는가."""
__tablename__ = "ai_check_results"
__table_args__ = {"schema": "site"}
ai_check_result_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
place_id = Column(UUID(as_uuid=True), nullable=False, index=True)
engine = Column(SmallInteger, nullable=False) # AiEngine
query = Column(String(500), nullable=False) # 던진 질의
answer = Column(Text, nullable=True)
cited_urls = Column(JSONB, nullable=True) # 인용된 URL 목록
is_own_site_cited = Column(Boolean, nullable=False, server_default=text("false"), default=False) # ★ 핵심 지표
ota_cited = Column(Boolean, nullable=False, server_default=text("false"), default=False) # OTA 가 대신 인용됐는지
checked_at = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql())
# ============================================================
# job : 작업 큐 (PostgreSQL 을 큐로 — LPS 의 job 큐 구조 이식)
# ============================================================
class jobs(MainTableMixin, MAIN_BASE):
"""작업 큐. 수집·비전분석·빌드는 몇 분 걸려 동기 요청으로 처리할 수 없다.
- 할당은 **단일 문장 원자 claim**: FOR UPDATE SKIP LOCKED 서브쿼리 + 같은 UPDATE + RETURNING.
워커 컨테이너가 몇 개든 같은 잡 이중 할당이 불가능하다.
- 복구는 타임아웃 추측이 아니라 **lease 만료 소유권** — 워커가 죽어도 reaper 가 회수한다.
(도커에서 컨테이너를 재시작해도 진행 중이던 잡이 증발하지 않는다.)
- 재시도·백오프·dead-letter 를 큐에 내장한다.
- dedupe_key 로 활성 중복(PENDING/RUNNING)을 막는다 — 같은 사업장 수집이 두 번 돌지 않게.
※ 이 테이블만 MainTableMixin 의 deleted 를 쓰지 않는다(잡은 이력이지 소프트 삭제 대상이 아니다).
그래도 컬럼은 남겨 공통 규약을 깨지 않는다.
"""
__tablename__ = "jobs"
__table_args__ = (
# claim 경로: status=PENDING & run_after<=now() 을 priority·created_at 순으로 훑는다.
Index("ix_jobs_claim", "status", "run_after", "priority", "created_at"),
# reaper 경로: 만료된 lease 회수.
Index("ix_jobs_lease", "status", "lease_until"),
# 활성 중복 방지 — 같은 dedupe_key 는 PENDING(1)/RUNNING(2) 중 하나만.
Index(
"uq_jobs_dedupe_active",
"dedupe_key",
unique=True,
postgresql_where=text("status IN (1, 2) AND dedupe_key IS NOT NULL"),
),
{"schema": "job"},
)
# ★ 이 테이블만 PK 에 server_default 가 필요하다 — 큐 전이는 raw SQL(RETURNING) 이라
# ORM 의 Python 쪽 default(uuid.uuid4)가 적용되지 않는다. init.sql 의 DEFAULT gen_random_uuid() 와 맞춘다.
# (다른 테이블은 ORM 으로만 INSERT 하므로 원본 보일러플레이트대로 Python default 만 둔다.)
job_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), default=uuid.uuid4)
job_type = Column(SmallInteger, nullable=False) # JobType
status = Column(SmallInteger, nullable=False, server_default=text("1"), default=JobStatus.PENDING.value)
priority = Column(SmallInteger, nullable=False, server_default=text("100"), default=100) # 낮을수록 우선
payload = Column(JSONB, nullable=False, server_default=text("'{}'::jsonb")) # 잡 입력
result = Column(JSONB, nullable=True) # 잡 출력(완료 시)
dedupe_key = Column(String(200), nullable=True) # 활성 중복 방지 키(부분 유니크)
attempts = Column(SmallInteger, nullable=False, server_default=text("0"), default=0) # claim 시 +1
max_attempts = Column(SmallInteger, nullable=False, server_default=text("3"), default=3)
run_after = Column(DateTime(timezone=True), nullable=False, server_default=_utc_now_sql()) # 백오프
lease_until = Column(DateTime(timezone=True), nullable=True) # 소유권 임대 만료(reaper 회수 기준)
worker_id = Column(String(80), nullable=True) # 현재 점유 워커
run_started_at = Column(DateTime(timezone=True), nullable=True) # RUNNING 진입 시각
last_error = Column(Text, nullable=True)
+392
View File
@@ -0,0 +1,392 @@
from enum import Enum, auto
from fastapi import HTTPException
class CodeEnum(Enum):
"""OpenAPI 스키마에 x-enum-varnames(멤버 이름)을 실어 orval 이 이름 있는 enum 을 생성하게 하는 베이스."""
@classmethod
def __get_pydantic_json_schema__(cls, core_schema, handler):
json_schema = handler(core_schema)
json_schema = handler.resolve_ref_schema(json_schema)
json_schema["x-enum-varnames"] = [m.name for m in cls]
return json_schema
class ErrorType(Enum):
"""서버 전역 결과 코드. Res_WebPacketProtocol.result 에 담겨 클라이언트로 전달된다.
HTTP status 와 겹치지 않도록 구간을 분리해서 관리한다.
도메인 코드는 모듈이 붙을 때 구간을 새로 열어 추가한다
(places 1200 / facts 1300 / collector 1400 / generator 1500 / local 1600 / sites 1700 / reports 1800 예약).
"""
SUCCESS = 0
FAIL = 1
# DB / Redis 에러
DB_RUN_FAILED = 10
DB_ALREADY_SAME_KEY = auto()
DB_INVALID_KEY = auto()
DB_EMPTY_DATA = auto()
DB_INVALID_TYPE = auto()
# 요청/직렬화 에러
JSON_PARSE_ERROR = 100
INVALID_REQUEST_DATA = auto()
INTERNAL_EXCEPTION = auto()
# http 에러 코드와 겹치지 않게 설정 - router 전용 예외 발생 옵션
HTTP_FORBIDDEN = 403
HTTP_INVALID_CLIENT_REQUEST = 419
HTTP_TO_MANY_REQUEST = 429
HTTP_INVALID_CLIENT_ACCESS = 433
HTTP_ACCESS_TOKEN_EXPIRED = 434
HTTP_REFRESH_TOKEN_EXPIRED = 435
HTTP_INVALID_TOKEN_ACCESS = 436
# 계정 관련 에러
ACCOUNT_INVALID_INFO = 1100
ACCOUNT_ALREADY_EXIST = auto()
ACCOUNT_BLOCKED_USER = auto()
ACCOUNT_NOT_FOUND = auto()
ACCOUNT_FORBIDDEN = auto() # 최고관리자 외 접근 / 다른 회사·최고관리자 대상 변경 시도
# 사업장(places) 관련 에러
PLACE_NOT_FOUND = 1200
PLACE_ALREADY_EXIST = auto() # 같은 회사 안에 같은 카카오 장소 ID — 중복 등록
PLACE_NOT_VERIFIED = auto() # ★ 동일 업소 검증 전 — 수집·발행 진입 금지
PLACE_VERIFY_NO_CANDIDATE = auto() # 카카오 로컬에서 후보를 못 찾음
PLACE_VERIFY_AMBIGUOUS = auto() # 동명 업소 다수 — 사람이 골라야 함
PLACE_INVALID_CATEGORY = auto() # 지원하지 않는 업종 코드
UNIT_NOT_FOUND = auto()
LINK_NOT_FOUND = auto()
LINK_NOT_CONFIRMED = auto() # ★ 확정 안 된 URL — 크롤링 대상 아님
MEDIA_NOT_FOUND = auto()
# fact 관련 에러
FACT_NOT_FOUND = 1300
FACT_INVALID_KEY = auto() # 업종 스키마에 없는 key
FACT_INVALID_TRANSITION = auto() # 허용되지 않은 검증 상태 전이
FACT_LOCKED = auto() # ★ CORRECTED(사장님 수정본) — 자동 갱신이 덮어쓸 수 없다
FACT_SOURCE_REQUIRED = auto() # source_type 이 owner 가 아닌데 source_url 이 없음
FAQ_NOT_FOUND = auto()
FAQ_UNGROUNDED = auto() # ★ 확보된 fact 로 뒷받침되지 않는 문장 — 반려
# 수집(collector) 관련 에러
COLLECT_ADAPTER_NOT_FOUND = 1400 # 해당 URL 을 처리할 어댑터 없음
COLLECT_ADAPTER_DISABLED = auto() # 법무 검토 전이라 미등록된 어댑터(HeadlessAdapter 등)
COLLECT_FETCH_FAILED = auto()
COLLECT_ALREADY_RUNNING = auto()
# 생성(generator) 관련 에러
GENERATOR_NOT_CONFIGURED = 1500 # GEMINI_API_KEY 미설정
GENERATOR_CALL_FAILED = auto()
GENERATOR_INVALID_OUTPUT = auto() # 구조화 출력 파싱 실패
GENERATOR_LOW_CONFIDENCE = auto() # 신뢰도 낮음 — 자동 반영 금지, 사람 확인 큐로
# 지역 정보(local) 관련 에러
LOCAL_NOT_CONFIGURED = 1600 # KAKAO_REST_API_KEY / TOUR_API_KEY 미설정
LOCAL_REGION_UNKNOWN = auto() # 좌표 → 행정구역 코드 변환 실패
LOCAL_FETCH_FAILED = auto() # ★ 실패해도 직전 값을 유지한다 — 빈 값을 내보내지 않는다
# 사이트(sites) 관련 에러
SITE_NOT_FOUND = 1700
SITE_VERSION_NOT_FOUND = auto()
SITE_BUILD_FAILED = auto()
PUBLISH_UNVERIFIED_FACT = auto() # ★ 미검증 fact 포함 — 발행 거부
PUBLISH_NO_UNIQUE_CONTENT = auto() # ★ 고유 콘텐츠 0건 — 발행 거부(스팸 판정 대상)
PUBLISH_JSONLD_MISMATCH = auto() # ★ 구조화 데이터 값 != 화면 값 — 빌드 실패
PUBLISH_REQUIRED_FACT_MISSING = auto() # 업종 스키마의 required 필드 누락
SITE_SLUG_LOCKED = auto() # ★ 이미 발행된 사이트의 주소 변경 — 색인된 페이지가 404 가 된다
# 리포트(reports) 관련 에러
REPORT_NOT_FOUND = 1800
# 작업 큐(job) 관련 에러
JOB_NOT_FOUND = 1900
JOB_ALREADY_QUEUED = auto() # 같은 dedupe_key 의 활성 잡이 이미 있다
JOB_NOT_DEAD = auto() # DEAD 가 아닌 잡을 재큐하려 함
# ErrorType 의 HTTP_* 값과 status_code 를 맞춰 router 단에서 raise 한다.
EXCEPTION_FORBIDDEN = HTTPException(status_code=ErrorType.HTTP_FORBIDDEN.value, detail=ErrorType.HTTP_FORBIDDEN.name)
EXCEPTION_INVALID_CLIENT_REQUEST = HTTPException(status_code=ErrorType.HTTP_INVALID_CLIENT_REQUEST.value, detail=ErrorType.HTTP_INVALID_CLIENT_REQUEST.name)
EXCEPTION_TO_MANY_REQUEST = HTTPException(status_code=ErrorType.HTTP_TO_MANY_REQUEST.value, detail=ErrorType.HTTP_TO_MANY_REQUEST.name)
EXCEPTION_INVALID_CLIENT_ACCESS = HTTPException(status_code=ErrorType.HTTP_INVALID_CLIENT_ACCESS.value, detail=ErrorType.HTTP_INVALID_CLIENT_ACCESS.name)
EXCEPTION_ACCESS_TOKEN_EXPIRED = HTTPException(status_code=ErrorType.HTTP_ACCESS_TOKEN_EXPIRED.value, detail=ErrorType.HTTP_ACCESS_TOKEN_EXPIRED.name)
EXCEPTION_REFRESH_TOKEN_EXPIRED = HTTPException(status_code=ErrorType.HTTP_REFRESH_TOKEN_EXPIRED.value, detail=ErrorType.HTTP_REFRESH_TOKEN_EXPIRED.name)
EXCEPTION_HTTP_INVALID_TOKEN_ACCESS = HTTPException(status_code=ErrorType.HTTP_INVALID_TOKEN_ACCESS.value, detail=ErrorType.HTTP_INVALID_TOKEN_ACCESS.name)
class DBType(Enum):
"""논리 DB 구분. 모델마다 DBType() 으로 자신이 속한 DB 를 반환한다.
DB 가 늘어나면 여기에 추가하고 db_session_manager 의 맵에 등록만 하면 된다.
"""
MAIN = 1
class DBWRType(Enum):
"""Read / Write 접속 구분. 조회는 DB_READ, 변경은 DB_WRITE 엔진을 사용한다."""
DB_READ = 1
DB_WRITE = 2
# 도메인 코드값
class UserStatus(CodeEnum):
"""users.status 코드값."""
ACTIVE = 1
INACTIVE = 2
class UserRole(CodeEnum):
"""users.role 코드값.
1=일반, 2=최고관리자(고객사 최상위), 3=개발자(우리 내부 운영 계정).
개발자 계정은 고객사에 존재를 노출하지 않는다 — 회원 목록에서 빼고 총계에도 넣지 않는다."""
USER = 1
OWNER = 2 # 최고관리자: 자기 회사 계정 관리 + 회사 설정
DEVELOPER = 3 # 개발자(내부 운영): 최고관리자 권한 전부 + 고객사에 보이지 않음
class CompanyStatus(CodeEnum):
"""companies.status 코드값."""
ACTIVE = 1
INACTIVE = 2
class PlaceCategory(CodeEnum):
"""places.category 코드값. 업종 — 스키마 파일(common/category_schema/resources/*.json)과 1:1.
업종 추가 = 여기에 코드 추가 + 스키마 파일 1개 추가."""
LODGING = 1 # 숙박
CAFE = 2 # 카페
RESTAURANT = 3 # 음식점
TOUR_ACTIVITY = 4 # 관광체험
class ExternalPlaceSource(CodeEnum):
"""places.external_source 코드값. 동일 업소 검증에 쓴 외부 장소 DB.
카카오는 안정적인 고유 place id 를 준다 → 그걸로 중복 등록을 막는다.
네이버는 고유 id 가 없다(응답의 link 는 업체 홈페이지다) → 상호명+도로명주소로 막는다."""
KAKAO = 1 # dapi.kakao.com — 고유 place id O · 전화번호 O · 행정구역 코드 O
NAVER = 2 # openapi.naver.com 지역검색 — 고유 id X · 전화번호 X · 5건 제한
class PlaceStatus(CodeEnum):
"""places.status 코드값. 사업장 생애주기.
해지는 삭제가 아니라 SUSPENDED 로의 상태 전이다(색인된 페이지를 갑자기 404 로 만들지 않는다)."""
DRAFT = 1 # 등록만 됨 — 동일 업소 검증 전
COLLECTING = 2 # 수집 진행 중
REVIEW = 3 # 검수 대기(사람 확인 큐)
PUBLISHED = 4 # 발행됨
SUSPENDED = 5 # 해지·중지 — 사이트 상태 전이로 처리
class SourceType(CodeEnum):
"""facts.source_type / media.source_type / place_aliases.source_type 공용 코드값.
값이 어디서 왔는지 — 모든 사실은 출처를 갖는다."""
OWNER = 1 # 사장님이 직접 입력·업로드
API = 2 # 공식 API (카카오 로컬 · TourAPI · Open-Meteo · Perplexity)
CRAWL = 3 # 크롤링
LLM = 4 # LLM 생성 — ★ 사실이 아니라 문장에만 쓴다
class FactStatus(CodeEnum):
"""facts.status / faqs.status / routes.status 공용 검증 상태.
★ VERIFIED 와 CORRECTED 만 사이트에 노출한다(PUBLISHABLE_FACT_STATUSES)."""
UNVERIFIED = 1 # 수집됐으나 아무도 확인 안 함
PENDING_OWNER = 2 # 사장님 확인 대기
VERIFIED = 3 # 확인됨 — 노출 가능
CORRECTED = 4 # 사장님이 고침 — 노출 가능 + ★ 잠김(자동 갱신이 덮어쓸 수 없다)
REJECTED = 5 # 틀린 값으로 판정 — 노출 안 함
EXPIRED = 6 # 유효기간 지남 — 노출 안 함, 재수집 대상
# ★ 절대규칙 1: 이 두 상태만 사이트에 노출한다. 발행 게이트가 이 집합으로 필터링한다.
PUBLISHABLE_FACT_STATUSES = {FactStatus.VERIFIED, FactStatus.CORRECTED}
# 후보 — 재수집이 올려놓은 확인 대기 항목. 노출값과 달리 (place, unit, key) 당 여러 건 공존한다.
CANDIDATE_FACT_STATUSES = {FactStatus.UNVERIFIED, FactStatus.PENDING_OWNER}
# ★ 절대규칙 6: 자동 수집(api/crawl/llm)이 덮어쓸 수 없는 상태. 사장님 수정본은 후보로만 도전받는다.
LOCKED_FACT_STATUSES = {FactStatus.CORRECTED}
class FactWriteOutcome(CodeEnum):
"""fact 기록 결과. 재수집(업데이트)이 무엇을 했는지 호출측이 알아야 한다 —
특히 사이트 재빌드가 필요한 경우(PUBLISHED_REPLACED)를 구분해야 한다."""
PUBLISHED_CREATED = 1 # 노출값이 없던 자리에 사람이 직접 넣어 바로 노출됐다
PUBLISHED_REPLACED = 2 # ★ 노출값이 교체됐다 — 사이트 재빌드 대상
REFRESHED = 3 # 재수집했는데 값이 그대로 — 검증 유지, 확인 시각만 갱신
CANDIDATE_CREATED = 4 # 노출값과 다른 값이 들어와 후보로 쌓였다(사람 확인 대기)
CANDIDATE_UPDATED = 5 # 같은 출처의 기존 후보를 새 수집값으로 갱신했다
# 검증 상태 전이 허용표. 여기에 없는 전이는 FACT_INVALID_TRANSITION 으로 거부한다.
FACT_STATUS_TRANSITIONS = {
FactStatus.UNVERIFIED: {FactStatus.PENDING_OWNER, FactStatus.VERIFIED, FactStatus.REJECTED, FactStatus.EXPIRED},
FactStatus.PENDING_OWNER: {FactStatus.VERIFIED, FactStatus.CORRECTED, FactStatus.REJECTED, FactStatus.EXPIRED},
FactStatus.VERIFIED: {FactStatus.CORRECTED, FactStatus.REJECTED, FactStatus.EXPIRED},
FactStatus.CORRECTED: {FactStatus.CORRECTED, FactStatus.REJECTED}, # 사장님만 다시 고칠 수 있다
FactStatus.REJECTED: {FactStatus.UNVERIFIED}, # 재수집으로만 되살아난다
FactStatus.EXPIRED: {FactStatus.UNVERIFIED},
}
class LinkChannel(CodeEnum):
"""place_links.channel 코드값. Perplexity 가 발견하는 채널 종류."""
YANOLJA = 1 # 야놀자
GOODCHOICE = 2 # 여기어때
NAVER_PLACE = 3 # 네이버 플레이스
INSTAGRAM = 4
OFFICIAL_SITE = 5 # 사장님 자체 홈페이지
BLOG = 6
ETC = 99
class MediaStatus(CodeEnum):
"""media.status 코드값. 비전 결과 신뢰도가 낮으면 자동 반영하지 않고 PENDING_REVIEW 로 둔다."""
PENDING_REVIEW = 1 # 사람 확인 큐 — Vision 분석 전이거나 신뢰도가 낮다
APPROVED = 2 # 사람이 확인함(또는 Vision 신뢰도가 충분히 높음)
REJECTED = 3
# ★ Vision 결과를 자동 반영해도 되는 신뢰도 하한. 이 아래는 사람 확인 큐(PENDING_REVIEW)로 남긴다.
# "신뢰도 낮은 항목은 자동 반영하지 말고 사람 확인 큐로 보낸다" 를 한 곳에서만 판단한다.
VISION_AUTO_APPROVE_CONFIDENCE = 0.7
class LocalContentType(CodeEnum):
"""local_contents.content_type 코드값. 행정구역 코드 단위로 캐싱되는 지역 정보 종류."""
WEATHER = 1 # 날씨 (Open-Meteo)
FESTIVAL = 2 # 축제 (TourAPI 행사정보, 주 1회)
ATTRACTION = 3 # 관광지 (TourAPI 지역기반, 월 1회)
RESTAURANT = 4 # 주변 맛집 (카카오 카테고리 검색)
class LocalSource(CodeEnum):
"""local_contents.source 코드값. 어느 외부 API 에서 왔는지."""
OPEN_METEO = 1 # 날씨. API 키 불필요
TOUR_API = 2 # 한국관광공사. ★ 자체 areaCode 체계 — 카카오 행정구역 코드와 다르다
KAKAO_LOCAL = 3
OFFICIAL_WEB = 4 # 지자체·행사 공식 홈페이지에서 운영자가 검수해 등록
class LocalContentStatus(CodeEnum):
"""운영 관리자가 검수하는 지역 콘텐츠 발행 상태."""
REVIEW = 1
PUBLISHED = 2
ENDED = 3
class TransportType(CodeEnum):
"""routes.transport 코드값. 가는 길 수단."""
CAR = 1
PUBLIC = 2
WALK = 3
class SiteStatus(CodeEnum):
"""sites.status 코드값. ★ 해지는 물리 삭제가 아니라 상태 전이로만 처리한다."""
DRAFT = 1
REVIEW = 2 # 검수 게이트 대기
PUBLISHED = 3
SUSPENDED = 4 # 해지 유예 — 페이지는 살아있음
UNPUBLISHED = 5 # 내림
class BuildStatus(CodeEnum):
"""site_versions.build_status 코드값. 정적 빌드는 개별 재빌드 단위로 돈다."""
PENDING = 1
BUILDING = 2
BUILT = 3
FAILED = 4
class PublishAction(CodeEnum):
"""publish_logs.action 코드값."""
PUBLISH = 1
UNPUBLISH = 2
REBUILD = 3
SUSPEND = 4
RESUME = 5
class PublishResult(CodeEnum):
"""publish_logs.result 코드값."""
SUCCESS = 1
REJECTED = 2 # 검수 게이트가 막음 — reject_reason 참고
FAILED = 3 # 빌드/배포 자체가 실패
class PublishRejectReason(CodeEnum):
"""publish_logs.reject_reason 코드값. 검수 게이트가 발행을 막은 이유(절대규칙 1~3)."""
UNVERIFIED_FACT = 1 # 미검증 fact 포함
NO_UNIQUE_CONTENT = 2 # 고유 콘텐츠 0건
JSONLD_MISMATCH = 3 # 구조화 데이터 값 != 화면 값
REQUIRED_FACT_MISSING = 4 # 업종 스키마 required 필드 누락
class AiEngine(CodeEnum):
"""ai_check_results.engine 코드값. AI 검색이 우리 사이트를 근거로 답하는지 측정할 대상."""
CHATGPT = 1
PERPLEXITY = 2
GEMINI = 3
CLAUDE = 4
ETC = 99
# ============================================================
# 작업 큐 (LPS 의 job 큐 구조를 이식 — PostgreSQL 을 큐로 쓴다)
# ============================================================
class JobType(CodeEnum):
"""jobs.job_type 코드값. 수집·비전·빌드는 몇 분씩 걸려 동기 요청으로 처리할 수 없다.
무거운 잡(브라우저 필요)과 가벼운 잡(HTTP API 만)을 코드로 갈라 둔다 —
크롤링 법무 결론이 나면 무거운 잡만 별도 워커 이미지로 분리한다."""
COLLECT = 1 # 수집 파이프라인: Perplexity 채널 발견 → 카카오 검증 → 크롤링
VISION = 2 # 사진 분류 + alt 생성 (Gemini Vision, 20~50장 배치)
COPY = 3 # 소개문·FAQ 작성 (Gemini 텍스트) — 확보된 fact 만 근거로
BUILD = 4 # 사이트 정적 빌드 — ★ 개별 재빌드 단위
LOCAL_SYNC = 5 # 지역 정보 갱신 — 행정구역 코드 단위(같은 지역 사이트 50개여도 1회)
AI_CHECK = 6 # AI 검색 노출 점검
class JobStatus(CodeEnum):
"""jobs.status 코드값. 작업 큐 상태.
전이는 전부 조건부 원자 UPDATE(CAS)로만 한다. 실패는 재시도 가능하면
PENDING(run_after=백오프)으로 되돌리고, 소진되면 DEAD(dead-letter)."""
PENDING = 1 # 대기(claim 가능). run_after <= now() 일 때만 실제 claim 대상
RUNNING = 2 # 워커가 점유 중(lease_until 까지 소유). 만료 시 reaper 가 회수
DONE = 3 # 완료
DEAD = 4 # dead-letter — max_attempts 소진(수동 개입/알림 대상)
# claim 대상이 되는 활성 상태. dedupe 부분 유니크 인덱스의 조건과 같아야 한다.
ACTIVE_JOB_STATUSES = {JobStatus.PENDING, JobStatus.RUNNING}
+43
View File
@@ -0,0 +1,43 @@
import sys
import traceback
from datetime import datetime, timezone
class _Logger:
"""원본 DerbyServer LOG 인터페이스를 간소화한 버전.
LOG.i / LOG.d / LOG.w / LOG.e_no_callstack / LOG.SetPrefix 를 제공한다.
"""
def __init__(self):
self._prefix = ""
def SetPrefix(self, prefix: str):
self._prefix = prefix
def _now(self) -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
def _write(self, level: str, msg):
head = f"{self._now()} [{level}]"
if self._prefix:
head += f"[{self._prefix}]"
print(f"{head} {msg}", file=sys.stderr if level in ("WARN", "ERROR") else sys.stdout)
def d(self, msg):
self._write("DEBUG", msg)
def i(self, msg):
self._write("INFO", msg)
def w(self, msg):
self._write("WARN", msg)
def e(self, msg):
self._write("ERROR", msg)
traceback.print_stack()
def e_no_callstack(self, msg):
self._write("ERROR", msg)
LOG = _Logger()
+86
View File
@@ -0,0 +1,86 @@
import json
from typing import Optional
from fastapi import Query
from pydantic import BaseModel, Field
from common.enums import ErrorType, UserRole
class StructModel:
"""프로토콜/구조체 식별용 마커 클래스."""
pass
class ErrorInfo(BaseModel, StructModel):
"""모든 응답에 공통으로 실리는 결과 정보. result.success / code / desc 로 내려간다."""
success: Optional[bool] = True
code: Optional[int] = ErrorType.SUCCESS.value
desc: Optional[str] = ErrorType.SUCCESS.name
def SetResult(self, enum: ErrorType):
if enum is not None:
self.success = ErrorType.SUCCESS.value == enum.value
self.code = enum.value
self.desc = enum.name
# ---- Protocol 규약 -------------------------------------------------------
# 모든 통신 패킷은 WebPacketProtocol 을 상속한다.
# 요청 : Req_xxx (WebPacketProtocol)
# 응답 : Res_xxx (Res_WebPacketProtocol) - 항상 result 필드를 가진다.
# 각 라우터 폴더의 protocol.py 에 Req_/Res_ 를 정의한다.
class WebPacketProtocol(BaseModel, StructModel):
pass
class Req_WebPacketProtocol(WebPacketProtocol):
pass
class Res_WebPacketProtocol(WebPacketProtocol):
# default_factory 로 인스턴스마다 새 ErrorInfo 를 생성한다 (mutable default 공유 방지).
result: ErrorInfo = Field(default_factory=ErrorInfo)
msg: Optional[str] = None
class Res_PageProtocol(Res_WebPacketProtocol):
# 목록 응답 공용 페이지 메타.
total: int = 0
page: int = 0
size: int = 0
class PageParams:
# 목록 엔드포인트 공용 쿼리 파라미터. 라우터에서 Depends() 로 주입한다.
def __init__(self, page: int = Query(1, ge=1), size: int = Query(20, ge=1, le=100)):
self.page = page
self.size = size
@property
def skip(self) -> int:
return (self.page - 1) * self.size
class UserInfo(StructModel):
"""JWT subject 로 인코딩되는 유저 식별 정보."""
user_id: str # users.user_id (uuid) — 데이터 스코프 키
id: str # users.id (로그인 아이디) — get_me 재조회 키
company_id: str # users.company_id (uuid) — 멀티테넌트 스코프 키
role: int # users.role (UserRole) — 권한 게이트(최고관리자 등) 판단 키
def __init__(self, *args, **kwargs) -> None:
super().__init__()
# 구버전 토큰(role 미포함) 도 디코딩되도록 기본값을 먼저 깔고 kwargs 로 덮어쓴다.
self.role = UserRole.USER.value
for dictionary in args:
for key in dictionary:
setattr(self, key, dictionary[key])
for key in kwargs:
setattr(self, key, kwargs[key])
def to_json(self) -> str:
return json.dumps(self.__dict__)
+16
View File
@@ -0,0 +1,16 @@
class Singleton:
_init = False
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "instance"):
cls.instance = super(Singleton, cls).__new__(cls)
return cls.instance
@classmethod
def is_init(cls):
return cls._init
@classmethod
def set_init(cls):
cls._init = True
+21
View File
@@ -0,0 +1,21 @@
from datetime import datetime, timezone, timedelta
class GTime:
"""서버 전역에서 UTC 기준 시간을 사용하기 위한 유틸. (원본 DerbyServer 패턴 축약)"""
@staticmethod
def UTC() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
@staticmethod
def UTCStr(fmt: str = "%Y-%m-%d %H:%M:%S") -> str:
return GTime.UTC().strftime(fmt)
@staticmethod
def AddMinutes(minutes: int) -> datetime:
return GTime.UTC() + timedelta(minutes=minutes)
@staticmethod
def AddDays(days: int) -> datetime:
return GTime.UTC() + timedelta(days=days)