QuotationCardData 에 number/edit_script/condition/memo 추가, card 카탈로그(nego/wild) 라이브 조인으로 채움. DB 컬럼 변경 없음(기존 카드 테이블 조인만 확장). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
218 lines
9.1 KiB
Python
218 lines
9.1 KiB
Python
from abc import ABC, abstractmethod
|
|
from datetime import datetime
|
|
from typing import Optional, Tuple
|
|
|
|
from sqlalchemy import select, func, and_, update
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.database.model.models import quotations, sessions, chats, nego_cards, wild_cards
|
|
from common.enums import ErrorType
|
|
from common.logger import LOG
|
|
from common.utils.gtime import GTime
|
|
|
|
|
|
# 견적 CRUD.
|
|
class IQuotationCRUD(ABC):
|
|
@abstractmethod
|
|
async def search(
|
|
self, cdb: AsyncSession, status, type_, start_from, start_to, skip, limit
|
|
) -> Tuple[ErrorType, list, int]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_by_id(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, quotations]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def add_quotation(self, cdb: AsyncSession, quotation: quotations) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def update_quotation(self, cdb: AsyncSession, qt_id, data: dict) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def soft_delete(self, cdb: AsyncSession, qt_id) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def list_sessions(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, list]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def list_chats(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, list]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def list_used_cards(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, list]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def session_counts(self, cdb: AsyncSession, qt_ids) -> Tuple[ErrorType, dict]:
|
|
pass
|
|
|
|
|
|
class QuotationCRUD(IQuotationCRUD):
|
|
async def search(
|
|
self,
|
|
cdb: AsyncSession,
|
|
status: Optional[str],
|
|
type_: Optional[str],
|
|
start_from: Optional[datetime],
|
|
start_to: Optional[datetime],
|
|
skip: int,
|
|
limit: int,
|
|
) -> Tuple[ErrorType, list, int]:
|
|
try:
|
|
conditions = [quotations.deleted == False] # noqa: E712
|
|
if status:
|
|
conditions.append(quotations.status == status)
|
|
if type_:
|
|
conditions.append(quotations.type == type_)
|
|
if start_from:
|
|
conditions.append(quotations.start_time >= start_from)
|
|
if start_to:
|
|
conditions.append(quotations.start_time <= start_to)
|
|
where = and_(*conditions)
|
|
|
|
cnt_err, cnt_rows = await DB_SESSION_MNG.execute(cdb, select(func.count()).select_from(quotations).where(where))
|
|
if cnt_err != ErrorType.SUCCESS:
|
|
return cnt_err, [], 0
|
|
total = int(cnt_rows[0] or 0) if cnt_rows else 0
|
|
|
|
list_err, rows = await DB_SESSION_MNG.execute(
|
|
cdb,
|
|
select(quotations).where(where).order_by(quotations.created_at.desc()).offset(skip).limit(limit),
|
|
)
|
|
if list_err != ErrorType.SUCCESS:
|
|
return list_err, [], 0
|
|
return ErrorType.SUCCESS, list(rows), total
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, [], 0
|
|
|
|
async def session_counts(self, cdb: AsyncSession, qt_ids) -> Tuple[ErrorType, dict]:
|
|
"""견적 id 목록에 대해 참여 협력사 수(distinct supplier)를 한 번에 센다. {qt_id: count}."""
|
|
try:
|
|
if not qt_ids:
|
|
return ErrorType.SUCCESS, {}
|
|
query = (
|
|
select(sessions.quotation_id, func.count(func.distinct(sessions.supplier_id)))
|
|
.where(sessions.quotation_id.in_(qt_ids), sessions.deleted == False) # noqa: E712
|
|
.group_by(sessions.quotation_id)
|
|
)
|
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, {}
|
|
return ErrorType.SUCCESS, {r[0]: int(r[1] or 0) for r in rows}
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, {}
|
|
|
|
async def get_by_id(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, quotations]:
|
|
try:
|
|
query = select(quotations).where(quotations.qt_id == qt_id, quotations.deleted == False).limit(1) # noqa: E712
|
|
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 add_quotation(self, cdb: AsyncSession, quotation: quotations) -> ErrorType:
|
|
try:
|
|
return await DB_SESSION_MNG.insert(cdb, quotation)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def update_quotation(self, cdb: AsyncSession, qt_id, data: dict) -> ErrorType:
|
|
try:
|
|
if not data:
|
|
return ErrorType.SUCCESS
|
|
query = update(quotations).where(quotations.qt_id == qt_id).values(**data)
|
|
return await DB_SESSION_MNG.add(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def soft_delete(self, cdb: AsyncSession, qt_id) -> ErrorType:
|
|
try:
|
|
query = update(quotations).where(quotations.qt_id == qt_id).values(deleted=True, updated_at=GTime.UTC())
|
|
return await DB_SESSION_MNG.add(cdb, query)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
# ----- 견적 상세: 세션 / 채팅 / 사용카드 (읽기 전용) -----
|
|
async def list_sessions(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, list]:
|
|
try:
|
|
query = (
|
|
select(sessions)
|
|
.where(sessions.quotation_id == qt_id, sessions.deleted == False) # noqa: E712
|
|
.order_by(sessions.created_at.asc())
|
|
)
|
|
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 list_chats(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, list]:
|
|
try:
|
|
query = (
|
|
select(chats)
|
|
.where(chats.session_id == session_id, chats.deleted == False) # noqa: E712
|
|
.order_by(chats.seq.asc())
|
|
)
|
|
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 list_used_cards(self, cdb: AsyncSession, qt_id) -> Tuple[ErrorType, list]:
|
|
"""견적의 세션들에서 실제 사용된 카드(chats.card_used_yn)를 카드 카탈로그와 조인.
|
|
반환: [(chat_row, card_id, number, name, script, edit_script, condition, memo), ...].
|
|
card_type 1=nego_cards / 2=wild_cards 양쪽을 LEFT JOIN 해서 어느 쪽이든 잡는다.
|
|
condition/memo 는 wild_cards 에만 있는 컬럼이라 nego 카드면 NULL 로 나온다.
|
|
"""
|
|
try:
|
|
query = (
|
|
select(
|
|
chats,
|
|
func.coalesce(nego_cards.nego_card_id, wild_cards.wild_card_id).label("card_pk"),
|
|
func.coalesce(nego_cards.number, wild_cards.number).label("card_number"),
|
|
func.coalesce(nego_cards.name, wild_cards.name).label("card_name"),
|
|
func.coalesce(nego_cards.script, wild_cards.script).label("card_script"),
|
|
func.coalesce(nego_cards.edit_script, wild_cards.edit_script).label("card_edit_script"),
|
|
wild_cards.condition.label("card_condition"),
|
|
wild_cards.memo.label("card_memo"),
|
|
)
|
|
.join(sessions, sessions.session_id == chats.session_id)
|
|
.outerjoin(nego_cards, and_(nego_cards.nego_card_id == chats.card_id, chats.card_type == 1))
|
|
.outerjoin(wild_cards, and_(wild_cards.wild_card_id == chats.card_id, chats.card_type == 2))
|
|
.where(
|
|
sessions.quotation_id == qt_id,
|
|
chats.card_used_yn == True, # noqa: E712
|
|
chats.deleted == False, # noqa: E712
|
|
sessions.deleted == False, # noqa: E712
|
|
)
|
|
.order_by(chats.created_at.asc())
|
|
)
|
|
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, []
|