git 저장소가 없어 히스토리·협업 기반이 아예 없던 상태를 연다.
함께 문서를 재편했다. 그동안 문서가 있어도 "이 제품이 뭘 푸는가"와
"어떻게 도는가"를 담은 문서가 없어서, 목표 문장이 backend/frontend
README 두 곳에 복붙돼 있었다 — 상위 문서가 없어 아래로 샌 것이다.
신설
README.md 레포 진입점 + 문서 지도 + 문서 규칙 4가지
AGENTS.md 에이전트·신규 합류자용 함정 목록과 규약
(CLAUDE.md 는 여기로 걸린 심볼릭 링크)
docs/PRODUCT.md 제품 정의 — 문제·사용자·원칙·**non-goals**·성공 기준
docs/ARCHITECTURE.md payload 경계·발행 파이프라인·서빙 결정·앱 분리 설계
이동
backend/docs/DECISIONS.md → docs/DECISIONS.md
백엔드만의 결정이 아니다. 게다가 코드 주석 ~25곳이 이미
`docs/DECISIONS.md` 로 적고 있어 레포 루트 기준으로는 그게 맞다.
갱신
docs/DEPLOY.md 서빙 결정 반영 — nginx 정적 서빙이 지금 경로(3절),
Azure 는 나중에 켤 때(4절)로 분리
docs/ARCHITECTURE.md 사이트 = 한 장(2026-08-31) 구조 반영
docs/COLLECTION_SEO_AEO_FLOW.md
robots.txt·sitemap.xml 은 오리진 루트에만 굽는다는 점 명시
frontend/site/scripts/prerender.ts
헤더 주석의 렌더 보고서 경로가 실제(422줄)와 달라 수정
.gitignore
★ CLAUDE.md 를 더 이상 무시하지 않는다. 에이전트 지침은 팀과 모든
에이전트가 공유하는 규약이라 커밋해야 한다 — 무시하면 클론한 사람이
"배포 후 republish_all.py 필수" 같은 함정을 전달받지 못한다.
개인용 오버라이드는 ~/.claude/CLAUDE.md 에 둔다.
257 lines
12 KiB
Python
257 lines
12 KiB
Python
from abc import ABC, abstractmethod
|
|
from typing import Optional, Tuple
|
|
|
|
from sqlalchemy import and_, select, update
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.database.model.models import facts
|
|
from common.enums import ErrorType, FactStatus
|
|
from common.logger import LOG
|
|
from common.utils.gtime import GTime
|
|
|
|
# ★ 사이트에 나가는 상태. PUBLISHABLE_FACT_STATUSES 와 같은 집합이어야 한다.
|
|
# 유니크 인덱스(uq_facts_published_*)의 조건과도 같아야 한다.
|
|
_PUBLISHED = (FactStatus.VERIFIED.value, FactStatus.CORRECTED.value)
|
|
# 후보 — 재수집이 올려놓은 확인 대기 항목. 여러 건 공존한다.
|
|
_CANDIDATE = (FactStatus.UNVERIFIED.value, FactStatus.PENDING_OWNER.value)
|
|
# 화면에 보이는 것 전체(이력 제외).
|
|
_ACTIVE = _PUBLISHED + _CANDIDATE
|
|
|
|
|
|
def _unit_cond(unit_id):
|
|
"""unit_id 는 NULL 비교라 == 로 걸면 안 된다(사업장 단위 fact 를 못 찾는다)."""
|
|
return facts.unit_id.is_(None) if unit_id is None else facts.unit_id == unit_id
|
|
|
|
|
|
# fact CRUD. 항상 place_id 로 스코프한다.
|
|
class IFactCRUD(ABC):
|
|
@abstractmethod
|
|
async def add_fact(self, cdb: AsyncSession, fact: facts) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_fact(self, cdb: AsyncSession, place_id, fact_id) -> Tuple[ErrorType, facts]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def list_facts(self, cdb: AsyncSession, place_id, unit_id, status, publishable_only, active_only) -> Tuple[ErrorType, list]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_published_fact(self, cdb: AsyncSession, place_id, unit_id, key) -> Tuple[ErrorType, facts]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_candidate(self, cdb: AsyncSession, place_id, unit_id, key, source_type) -> Tuple[ErrorType, facts]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def refresh_collected(self, cdb: AsyncSession, fact_id, source_type, source_url, ts) -> Tuple[ErrorType, int]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def update_candidate(self, cdb: AsyncSession, fact_id, value, source_url, status, ts) -> Tuple[ErrorType, int]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def transition(self, cdb: AsyncSession, fact_id, from_statuses, to_status, data: dict) -> Tuple[ErrorType, int]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def expire_published(self, cdb: AsyncSession, place_id, unit_id, key, ts, except_fact_id=None) -> Tuple[ErrorType, int]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def reject_candidates(self, cdb: AsyncSession, place_id, unit_id, key, ts, except_fact_id=None) -> Tuple[ErrorType, int]:
|
|
pass
|
|
|
|
|
|
class FactCRUD(IFactCRUD):
|
|
async def add_fact(self, cdb: AsyncSession, fact: facts) -> ErrorType:
|
|
try:
|
|
return await DB_SESSION_MNG.insert(cdb, fact)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def get_fact(self, cdb: AsyncSession, place_id, fact_id) -> Tuple[ErrorType, facts]:
|
|
try:
|
|
query = (
|
|
select(facts)
|
|
.where(facts.fact_id == fact_id, facts.place_id == place_id, facts.deleted == False) # noqa: E712
|
|
.limit(1)
|
|
)
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, None
|
|
if len(row_list) != 1:
|
|
return ErrorType.DB_INVALID_KEY, None
|
|
return ErrorType.SUCCESS, row_list[0]
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, None
|
|
|
|
async def list_facts(
|
|
self, cdb: AsyncSession, place_id, unit_id=None, status: Optional[int] = None,
|
|
publishable_only: bool = False, active_only: bool = True,
|
|
) -> Tuple[ErrorType, list]:
|
|
"""fact 목록.
|
|
publishable_only=True → ★ VERIFIED·CORRECTED 만 (사이트 렌더·발행 게이트가 쓰는 경로)
|
|
active_only=True → REJECTED·EXPIRED 이력 제외 (관리 화면 기본: 노출값 + 후보)
|
|
"""
|
|
try:
|
|
conditions = [facts.place_id == place_id, facts.deleted == False] # noqa: E712
|
|
if unit_id is not None:
|
|
conditions.append(facts.unit_id == unit_id)
|
|
if publishable_only:
|
|
conditions.append(facts.status.in_(_PUBLISHED))
|
|
elif status is not None:
|
|
conditions.append(facts.status == status)
|
|
elif active_only:
|
|
conditions.append(facts.status.in_(_ACTIVE))
|
|
|
|
# 노출값이 먼저, 그 아래 후보. 같은 key 끼리 붙어 보이게 정렬한다.
|
|
query = select(facts).where(and_(*conditions)).order_by(
|
|
facts.key.asc(), facts.status.desc(), facts.collected_at.desc()
|
|
)
|
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
|
return (err_type, list(rows) if err_type == ErrorType.SUCCESS else [])
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, []
|
|
|
|
async def get_published_fact(self, cdb: AsyncSession, place_id, unit_id, key) -> Tuple[ErrorType, facts]:
|
|
"""★ 지금 사이트에 나가고 있는 값. 없으면 (SUCCESS, None).
|
|
유니크 인덱스가 1건만 허용하므로 결과는 0 또는 1건이다."""
|
|
try:
|
|
query = (
|
|
select(facts)
|
|
.where(and_(
|
|
facts.place_id == place_id,
|
|
facts.key == key,
|
|
facts.deleted == False, # noqa: E712
|
|
facts.status.in_(_PUBLISHED),
|
|
_unit_cond(unit_id),
|
|
))
|
|
.limit(1)
|
|
)
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, None
|
|
return ErrorType.SUCCESS, (row_list[0] if row_list else None)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, None
|
|
|
|
async def get_candidate(self, cdb: AsyncSession, place_id, unit_id, key, source_type) -> Tuple[ErrorType, facts]:
|
|
"""같은 출처가 이미 올려둔 후보. 재수집이 같은 후보를 계속 쌓지 않도록 갱신 대상을 찾는다."""
|
|
try:
|
|
query = (
|
|
select(facts)
|
|
.where(and_(
|
|
facts.place_id == place_id,
|
|
facts.key == key,
|
|
facts.source_type == source_type,
|
|
facts.deleted == False, # noqa: E712
|
|
facts.status.in_(_CANDIDATE),
|
|
_unit_cond(unit_id),
|
|
))
|
|
.order_by(facts.collected_at.desc())
|
|
.limit(1)
|
|
)
|
|
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, None
|
|
return ErrorType.SUCCESS, (row_list[0] if row_list else None)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, None
|
|
|
|
async def refresh_collected(self, cdb: AsyncSession, fact_id, source_type, source_url, ts) -> Tuple[ErrorType, int]:
|
|
"""★ 재수집했는데 값이 그대로일 때 — 검증 상태를 건드리지 않고 '언제 다시 확인했는지'만 갱신한다.
|
|
|
|
이게 없으면 값이 안 바뀌었는데도 재수집마다 검증이 초기화돼 사이트에서 사실이 사라진다."""
|
|
try:
|
|
values = {"collected_at": ts, "updated_at": ts}
|
|
if source_url:
|
|
values["source_url"] = source_url
|
|
query = update(facts).where(facts.fact_id == fact_id, facts.deleted == False).values(**values) # noqa: E712
|
|
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, 0
|
|
|
|
async def update_candidate(self, cdb: AsyncSession, fact_id, value, source_url, status: int, ts) -> Tuple[ErrorType, int]:
|
|
"""기존 후보를 새 수집값으로 갱신. 같은 출처의 후보가 계속 쌓이는 것을 막는다."""
|
|
try:
|
|
query = (
|
|
update(facts)
|
|
.where(facts.fact_id == fact_id, facts.status.in_(_CANDIDATE), facts.deleted == False) # noqa: E712
|
|
.values(value=value, source_url=source_url, status=status, collected_at=ts, updated_at=ts)
|
|
)
|
|
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, 0
|
|
|
|
async def transition(self, cdb: AsyncSession, fact_id, from_statuses, to_status: int, data: dict) -> Tuple[ErrorType, int]:
|
|
"""검증 상태 전이 — **출발 상태를 WHERE 에 걸어** 조건부로만 바꾼다.
|
|
|
|
적용행수 0 = 그 사이 다른 사람이 이미 상태를 바꿨다는 뜻(동시 처리 가드).
|
|
허용 전이 판정 자체는 service 가 FACT_STATUS_TRANSITIONS 로 먼저 한다."""
|
|
try:
|
|
query = (
|
|
update(facts)
|
|
.where(
|
|
facts.fact_id == fact_id,
|
|
facts.status.in_(tuple(from_statuses)),
|
|
facts.deleted == False, # noqa: E712
|
|
)
|
|
.values(status=to_status, updated_at=GTime.UTC(), **data)
|
|
)
|
|
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, 0
|
|
|
|
async def expire_published(self, cdb: AsyncSession, place_id, unit_id, key, ts, except_fact_id=None) -> Tuple[ErrorType, int]:
|
|
"""현재 노출값을 EXPIRED 로 내려 자리를 비운다(후보 승격·직접 교체 직전에 호출).
|
|
|
|
지우지 않고 이력으로 남긴다 — 예전에 뭐가 나갔는지 추적할 수 있어야 한다."""
|
|
try:
|
|
conditions = [
|
|
facts.place_id == place_id,
|
|
facts.key == key,
|
|
facts.deleted == False, # noqa: E712
|
|
facts.status.in_(_PUBLISHED),
|
|
_unit_cond(unit_id),
|
|
]
|
|
if except_fact_id is not None:
|
|
conditions.append(facts.fact_id != except_fact_id)
|
|
query = update(facts).where(and_(*conditions)).values(status=FactStatus.EXPIRED.value, updated_at=ts)
|
|
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, 0
|
|
|
|
async def reject_candidates(self, cdb: AsyncSession, place_id, unit_id, key, ts, except_fact_id=None) -> Tuple[ErrorType, int]:
|
|
"""남은 후보를 REJECTED 로 정리한다(하나를 승격시켰으니 나머지는 판정된 셈).
|
|
|
|
후보를 그대로 두면 사람 확인 큐에 이미 처리된 항목이 계속 남는다."""
|
|
try:
|
|
conditions = [
|
|
facts.place_id == place_id,
|
|
facts.key == key,
|
|
facts.deleted == False, # noqa: E712
|
|
facts.status.in_(_CANDIDATE),
|
|
_unit_cond(unit_id),
|
|
]
|
|
if except_fact_id is not None:
|
|
conditions.append(facts.fact_id != except_fact_id)
|
|
query = update(facts).where(and_(*conditions)).values(status=FactStatus.REJECTED.value, updated_at=ts)
|
|
return await DB_SESSION_MNG.add_with_rowcount(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, 0
|