[feat] negodata/backend: 견적 자동마감 스케줄러 + 다음 라운드 재생성(자동/수동)

- APScheduler 크론(KST 5분): 마감일 지난 견적 / 모든 세션 종결 견적 → close_and_decide
- 마감 판정: 단독 최저가 낙찰 확정 / 동가·전원미참여 다음 라운드 재생성 / 거부·한도 마감
- 재생성: 같은 견적번호 체인(round+1, 이름 '(N차)'), 공급사 수로 재협상·재견적, 사유별 한도(미참여1+동가1)
- 수동 재생성 POST /regenerate/{qt_id} (마지막 차수만 허용)
- CloseOutcome enum + 잡 결과별 로그

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
minaChoiandClaude Opus 4.8 committed 2026-06-23 16:36:22 +09:00
1 parent d47476dc04
commit 7f948075e5
10 files changed
+641 -189

No files matched your search

+81 -9
View File
@@ -10,7 +10,7 @@ from common.database.model.models import (
quotations, sessions, chats, nego_cards, wild_cards, items, suppliers, quotation_settings,
version_nego_cards, version_wild_cards,
)
from common.enums import ErrorType, QuotationStatus, QuotationType, SessionStatus
from common.enums import ErrorType, QuotationStatus, SessionStatus
from common.logger import LOG
from common.utils.gtime import GTime
@@ -93,13 +93,25 @@ class IQuotationCRUD(ABC):
pass
@abstractmethod
async def list_requote_done(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
async def list_all_sessions_ended(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
pass
@abstractmethod
async def list_chain_equal_flags(self, cdb: AsyncSession, number, current_round) -> Tuple[ErrorType, list]:
pass
@abstractmethod
async def chain_max_round(self, cdb: AsyncSession, number) -> Tuple[ErrorType, int]:
pass
@abstractmethod
async def list_done_sessions(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, list]:
pass
@abstractmethod
async def list_sessions_status(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, list]:
pass
@abstractmethod
async def bulk_update_quotation_status(self, cdb: AsyncSession, qt_ids, status: int) -> ErrorType:
pass
@@ -379,24 +391,32 @@ class QuotationCRUD(IQuotationCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, []
async def list_requote_done(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
"""[잡②] 재견적(REQUOTE) 중 협상완료(DONE) 세션이 1건 이상이고 아직 안 닫힌 견적 qt_id 목록.
재견적은 세션이 독립적이라 하나라도 완료되면 나머지를 기다리지 않고 마감 대상."""
async def list_all_sessions_ended(self, cdb: AsyncSession) -> Tuple[ErrorType, list]:
"""[잡②] 아직 안 닫혔는데 모든 세션이 종결된 견적 qt_id 목록(견적 타입 무관 — KTC 와 동일).
종결 = 협상완료/협상거부/미참여 → 즉 진행중(IN_PROGRESS)·미시작(CREATED) 세션이 하나도 없음.
세션이 1개 이상 있어야 하며, 마감일과 무관하게 협상이 다 끝났으면 즉시 마감 대상."""
try:
done_exists = (
# 아직 안 끝난(진행중·미시작) 세션이 하나라도 있으면 제외
pending_exists = (
select(sessions.session_id)
.where(
sessions.quotation_id == quotations.qt_id,
sessions.status == SessionStatus.DONE.value,
sessions.status.in_([SessionStatus.CREATED.value, SessionStatus.IN_PROGRESS.value]),
sessions.deleted == False, # noqa: E712
)
.exists()
)
# 세션이 최소 1개는 있어야(세션 없는 견적은 대상 아님)
any_session = (
select(sessions.session_id)
.where(sessions.quotation_id == quotations.qt_id, sessions.deleted == False) # noqa: E712
.exists()
)
query = select(quotations.qt_id).where(
quotations.type == QuotationType.REQUOTE.value,
quotations.status != QuotationStatus.CLOSED.value,
quotations.deleted == False, # noqa: E712
done_exists,
any_session,
~pending_exists,
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
if err_type != ErrorType.SUCCESS:
@@ -427,6 +447,58 @@ class QuotationCRUD(IQuotationCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, []
async def list_chain_equal_flags(self, cdb: AsyncSession, number, current_round) -> Tuple[ErrorType, list]:
"""[재생성 한도] 같은 견적번호(체인)의 이전 라운드(round < current_round)들의 equal_bid_yn 목록. 삭제 제외.
True=동가로 닫힌 라운드 / 그 외(False·NULL)=미참여로 닫힌 라운드."""
try:
query = select(quotations.equal_bid_yn).where(
quotations.number == number,
quotations.round < current_round,
quotations.deleted == False, # noqa: E712
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
if err_type != ErrorType.SUCCESS:
return err_type, []
return ErrorType.SUCCESS, list(rows)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, []
async def chain_max_round(self, cdb: AsyncSession, number) -> Tuple[ErrorType, int]:
"""같은 견적번호(체인)의 최대 round. 다음 라운드 = 이 값 + 1.
uq_quotations_number(number, round) 충돌 방지 — 원본 round+1이 아니라 체인 최신 기준으로 매긴다."""
try:
query = select(func.max(quotations.round)).where(
quotations.number == number,
quotations.deleted == False, # noqa: E712
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
if err_type != ErrorType.SUCCESS:
return err_type, 0
# 단일 컬럼 select → rows[0] 이 스칼라(max) 값. 행 없거나 전부 NULL이면 None.
mx = rows[0] if rows else None
return ErrorType.SUCCESS, int(mx or 0)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def list_sessions_status(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, list]:
"""[마감 판정] 견적의 모든 세션 → (status, supplier_id, bid_price, supplier_name). 삭제 제외.
공급사가 지워졌어도 세션 집계엔 포함되도록 outerjoin(이때 name 은 None)."""
try:
query = (
select(sessions.status, sessions.supplier_id, sessions.bid_price, suppliers.name)
.outerjoin(suppliers, suppliers.supplier_id == sessions.supplier_id)
.where(sessions.quotation_id == qt_id, sessions.deleted == False) # noqa: E712
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
if err_type != ErrorType.SUCCESS:
return err_type, []
return ErrorType.SUCCESS, list(rows)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, []
async def bulk_update_quotation_status(self, cdb: AsyncSession, qt_ids, status: int) -> ErrorType:
"""[잡①] 여러 견적의 status 를 한 번에 전이."""
try: