여러 줄 주석이 설명보다 경위(예전·실측·지적)를 적고 있어 읽는 사람이 결론을 찾기 어려웠다. - ts·tsx·js·mjs·css·py 478개: 여러 줄 주석은 첫 문장 한 줄로, 과거형·날짜 문장은 삭제 - 주석 위치는 TypeScript 파서·파이썬 tokenize/ast 로 찾는다 — 문자열 안의 # · /* 는 건드리지 않는다 - eslint·ts·noqa·type: ignore 같은 지시 주석은 그대로 둔다 파이썬 275개 정리 전후 AST 동일, TS 298개 주석 뺀 토큰 동일(빈 JSX 주석 10곳만 차이). site·frontend·admin tsc, site vitest 105 passed Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
243 lines
11 KiB
Python
243 lines
11 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 place_facts
|
|
from common.enums import ErrorType, FactStatus
|
|
from common.logger import LOG
|
|
from common.utils.gtime import GTime
|
|
|
|
# 사이트에 나가는 상태.
|
|
_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 place_facts.unit_id.is_(None) if unit_id is None else place_facts.unit_id == unit_id
|
|
|
|
|
|
# fact CRUD.
|
|
class IFactCRUD(ABC):
|
|
@abstractmethod
|
|
async def add_fact(self, cdb: AsyncSession, fact: place_facts) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_fact(self, cdb: AsyncSession, place_id, fact_id) -> Tuple[ErrorType, place_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, place_facts]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_candidate(self, cdb: AsyncSession, place_id, unit_id, key, source_type) -> Tuple[ErrorType, place_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: place_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, place_facts]:
|
|
try:
|
|
query = (
|
|
select(place_facts)
|
|
.where(place_facts.fact_id == fact_id, place_facts.place_id == place_id, place_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 목록."""
|
|
try:
|
|
conditions = [place_facts.place_id == place_id, place_facts.deleted == False] # noqa: E712
|
|
if unit_id is not None:
|
|
conditions.append(place_facts.unit_id == unit_id)
|
|
if publishable_only:
|
|
conditions.append(place_facts.status.in_(_PUBLISHED))
|
|
elif status is not None:
|
|
conditions.append(place_facts.status == status)
|
|
elif active_only:
|
|
conditions.append(place_facts.status.in_(_ACTIVE))
|
|
|
|
# 노출값이 먼저, 그 아래 후보.
|
|
query = select(place_facts).where(and_(*conditions)).order_by(
|
|
place_facts.key.asc(), place_facts.status.desc(), place_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, place_facts]:
|
|
"""지금 사이트에 나가고 있는 값."""
|
|
try:
|
|
query = (
|
|
select(place_facts)
|
|
.where(and_(
|
|
place_facts.place_id == place_id,
|
|
place_facts.key == key,
|
|
place_facts.deleted == False, # noqa: E712
|
|
place_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, place_facts]:
|
|
"""같은 출처가 이미 올려둔 후보."""
|
|
try:
|
|
query = (
|
|
select(place_facts)
|
|
.where(and_(
|
|
place_facts.place_id == place_id,
|
|
place_facts.key == key,
|
|
place_facts.source_type == source_type,
|
|
place_facts.deleted == False, # noqa: E712
|
|
place_facts.status.in_(_CANDIDATE),
|
|
_unit_cond(unit_id),
|
|
))
|
|
.order_by(place_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(place_facts).where(place_facts.fact_id == fact_id, place_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(place_facts)
|
|
.where(place_facts.fact_id == fact_id, place_facts.status.in_(_CANDIDATE), place_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 에 걸어** 조건부로만 바꾼다."""
|
|
try:
|
|
query = (
|
|
update(place_facts)
|
|
.where(
|
|
place_facts.fact_id == fact_id,
|
|
place_facts.status.in_(tuple(from_statuses)),
|
|
place_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 = [
|
|
place_facts.place_id == place_id,
|
|
place_facts.key == key,
|
|
place_facts.deleted == False, # noqa: E712
|
|
place_facts.status.in_(_PUBLISHED),
|
|
_unit_cond(unit_id),
|
|
]
|
|
if except_fact_id is not None:
|
|
conditions.append(place_facts.fact_id != except_fact_id)
|
|
query = update(place_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 = [
|
|
place_facts.place_id == place_id,
|
|
place_facts.key == key,
|
|
place_facts.deleted == False, # noqa: E712
|
|
place_facts.status.in_(_CANDIDATE),
|
|
_unit_cond(unit_id),
|
|
]
|
|
if except_fact_id is not None:
|
|
conditions.append(place_facts.fact_id != except_fact_id)
|
|
query = update(place_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
|