[feat] 공급사 포털: 협상완료 부가정보(select·종료 동의폼)·상태 라벨 통일·예아니오 Enter=예·목록 결과열·재협상 요청/철회 API·테스트

This commit is contained in:
minaChoi committed 2026-07-24 14:18:52 +09:00
1 parent cfee6e89d0
commit d7c4e86f30
46 files changed
+1715 -270

No files matched your search

+80 -9
View File
@@ -1,12 +1,13 @@
from abc import ABC, abstractmethod
from typing import Tuple
from sqlalchemy import case, func, nulls_last, select, update
from sqlalchemy import case, cast, func, nulls_last, or_, select, text, update
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import items, quotations, sessions
from common.enums import ErrorType, SessionStatus
from common.enums import CloseReason, ErrorType, QuotationStatus, RENEGOTIABLE_CLOSE_REASONS, SessionStatus
from common.logger import LOG
@@ -14,11 +15,11 @@ from common.logger import LOG
# 마감일(qt_end_time)은 견적(quotation.end_time)이 진실값이다(session.end_time 은 협상 종료 시점 기록용).
class ISessionCRUD(ABC):
@abstractmethod
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]:
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit, keyword=None, result=None) -> Tuple[ErrorType, list]:
pass
@abstractmethod
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type) -> Tuple[ErrorType, int]:
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, keyword=None, result=None) -> Tuple[ErrorType, int]:
pass
@abstractmethod
@@ -45,20 +46,59 @@ class ISessionCRUD(ABC):
async def update_session_custom(self, cdb: AsyncSession, session_id, supplier_id, custom: dict) -> ErrorType:
pass
@abstractmethod
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
# 같은 견적번호(체인)의 최대 차수. 이미 다음 라운드가 있으면 재협상 요청은 의미가 없다.
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
top = rows[0][0] if rows and rows[0] else None
return ErrorType.SUCCESS, int(top or 0)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def merge_session_custom(self, cdb: AsyncSession, session_id, supplier_id, patch: dict) -> ErrorType:
pass
@abstractmethod
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
pass
class SessionCRUD(ISessionCRUD):
@staticmethod
def __filters(supplier_id, status, qt_type):
def __filters(supplier_id, status, qt_type, keyword=None, result=None):
conds = [sessions.supplier_id == supplier_id, sessions.deleted == False] # noqa: E712
if status is not None:
conds.append(sessions.status == status)
if qt_type is not None:
conds.append(sessions.qt_type == qt_type)
# 검색: 견적번호·상품명·상품코드 부분일치(대소문자 무시). items 는 목록/카운트 둘 다 조인돼 있다.
# ILIKE 와일드카드(%,_)는 escape 해 사용자 입력이 패턴으로 새지 않게 한다.
if keyword and keyword.strip():
kw = keyword.strip().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
like = f"%{kw}%"
conds.append(or_(sessions.qt_number.ilike(like), items.name.ilike(like), items.code.ilike(like)))
# 결과(SessionResult) 필터 — _to_result 파생 규칙을 SQL WHERE 로 그대로 복제(집계·필터 일치용).
# 1=낙찰 2=미낙찰 3=결렬(개찰). 전부 견적 마감(CLOSED) 이 전제.
if result in (1, 2, 3):
conds.append(quotations.status == QuotationStatus.CLOSED.value)
if result == 1:
conds.append(quotations.close_reason == CloseReason.AWARDED.value)
conds.append(quotations.preferred_sp_id == sessions.supplier_id)
elif result == 2:
conds.append(quotations.close_reason == CloseReason.AWARDED.value)
conds.append(or_(quotations.preferred_sp_id.is_(None), quotations.preferred_sp_id != sessions.supplier_id))
else:
conds.append(quotations.close_reason.in_(RENEGOTIABLE_CLOSE_REASONS))
return conds
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]:
async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit, keyword=None, result=None) -> Tuple[ErrorType, list]:
try:
conds = self.__filters(supplier_id, status, qt_type)
conds = self.__filters(supplier_id, status, qt_type, keyword, result)
# 정렬 규칙:
# - order 를 명시(asc/desc)하면 그룹 구분 없이 전체를 마감 기준 한 줄로 정렬(전체 정렬).
@@ -91,6 +131,11 @@ class SessionCRUD(ISessionCRUD):
items.model_name,
items.manufacturer,
sessions.custom,
quotations.status, # 재협상 요청 자격 판정용(마감 여부)
quotations.close_reason, # 개찰(결렬) 사유
quotations.round,
quotations.preferred_sp_id, # 낙찰자(공급사) — 나와 같으면 낙찰, 다르면 미낙찰
sessions.supplier_id, # 이 세션 소유 공급사(=조회자). 낙찰자와 대조
)
.join(items, items.item_id == sessions.item_id)
.join(quotations, quotations.qt_id == sessions.quotation_id)
@@ -107,9 +152,9 @@ class SessionCRUD(ISessionCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, []
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type) -> Tuple[ErrorType, int]:
async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, keyword=None, result=None) -> Tuple[ErrorType, int]:
try:
conds = self.__filters(supplier_id, status, qt_type)
conds = self.__filters(supplier_id, status, qt_type, keyword, result)
query = (
select(func.count())
.select_from(sessions)
@@ -179,6 +224,32 @@ class SessionCRUD(ISessionCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
async def chain_max_round(self, cdb: AsyncSession, number: str) -> Tuple[ErrorType, int]:
# 같은 견적번호(체인)의 최대 차수. 이미 다음 라운드가 있으면 재협상 요청은 의미가 없다.
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
top = rows[0][0] if rows and rows[0] else None
return ErrorType.SUCCESS, int(top or 0)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, 0
async def merge_session_custom(self, cdb: AsyncSession, session_id, supplier_id, patch: dict) -> ErrorType:
# sessions.custom 부분 갱신(기존 키 보존). 부가정보와 재협상 요청이 같은 컬럼을 쓰므로 덮어쓰면 안 된다.
try:
query = (
update(sessions)
.where(sessions.session_id == session_id, sessions.supplier_id == supplier_id)
.values(custom=func.coalesce(sessions.custom, cast(text("'{}'"), JSONB)).op("||")(cast(patch, JSONB)))
)
return await DB_SESSION_MNG.add(cdb, query)
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED
async def update_session_custom(self, cdb: AsyncSession, session_id, supplier_id, custom: dict) -> ErrorType:
# 협상완료 부가정보(sessions.custom) 저장. 본인 공급사 세션만(supplier_id 가드).
try: