- 견적 목록에 대표 상품(세션 item) 조인 노출 → '대상 상품 확인 불가' 해소 (backend protocol/crud/service + orval 재생성 + front mapQuotation 매핑) - 견적·협상카드 목록 클라이언트 페이지네이션 추가 (useClientPagination) - 견적중단을 서버 stop_quotation 호출로 영속 처리(상태=견적마감) - 신규 협상견적 라벨 발의→등록 통일 - 발의 위저드 카드선택에 협상/와일드 구분 뱃지 추가 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
386 lines
17 KiB
Python
386 lines
17 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, items, quotation_settings,
|
|
version_nego_cards, version_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 add_sessions(self, cdb: AsyncSession, session_list: list) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_item_prices(self, cdb: AsyncSession, item_ids) -> Tuple[ErrorType, dict]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_target_margin(self, cdb: AsyncSession, qt_setting_id) -> Tuple[ErrorType, Optional[float]]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def add_rows(self, cdb: AsyncSession, obj_list: list) -> ErrorType:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def classify_card_ids(self, cdb: AsyncSession, card_ids) -> Tuple[ErrorType, dict]:
|
|
pass
|
|
|
|
@abstractmethod
|
|
async def get_version_cards(self, cdb: AsyncSession, version_id) -> Tuple[ErrorType, list]:
|
|
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
|
|
|
|
@abstractmethod
|
|
async def item_map(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 item_map(self, cdb: AsyncSession, qt_ids) -> Tuple[ErrorType, dict]:
|
|
"""견적 id 목록에 대해 대표 상품(세션의 첫 item) {qt_id: (item_id, item_name)} 을 한 번에 가져온다."""
|
|
try:
|
|
if not qt_ids:
|
|
return ErrorType.SUCCESS, {}
|
|
query = (
|
|
select(sessions.quotation_id, sessions.item_id, items.name)
|
|
.join(items, items.item_id == sessions.item_id)
|
|
.where(
|
|
sessions.quotation_id.in_(qt_ids),
|
|
sessions.deleted == False, # noqa: E712
|
|
items.deleted == False, # noqa: E712
|
|
)
|
|
)
|
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, {}
|
|
result = {}
|
|
for qid, iid, iname in rows:
|
|
if qid not in result: # 견적당 대표 1개(첫 세션 상품)
|
|
result[qid] = (iid, iname)
|
|
return ErrorType.SUCCESS, result
|
|
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 add_sessions(self, cdb: AsyncSession, session_list: list) -> ErrorType:
|
|
"""견적 생성 시 만들어진 협상 세션들을 한 번에 insert. 빈 목록이면 그냥 통과."""
|
|
try:
|
|
if not session_list:
|
|
return ErrorType.SUCCESS
|
|
return await DB_SESSION_MNG.insert(cdb, session_list)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def add_rows(self, cdb: AsyncSession, obj_list: list) -> ErrorType:
|
|
"""임의 ORM 행 묶음 insert(버전/버전-카드 매핑 등). 빈 목록이면 통과."""
|
|
try:
|
|
if not obj_list:
|
|
return ErrorType.SUCCESS
|
|
return await DB_SESSION_MNG.insert(cdb, obj_list)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED
|
|
|
|
async def classify_card_ids(self, cdb: AsyncSession, card_ids) -> Tuple[ErrorType, dict]:
|
|
"""선택 카드 id 를 협상(1)/와일드(2)로 분류. {card_id: card_type}."""
|
|
try:
|
|
if not card_ids:
|
|
return ErrorType.SUCCESS, {}
|
|
out = {}
|
|
n_err, n_rows = await DB_SESSION_MNG.execute(
|
|
cdb, select(nego_cards.nego_card_id).where(nego_cards.nego_card_id.in_(card_ids), nego_cards.deleted == False) # noqa: E712
|
|
)
|
|
if n_err != ErrorType.SUCCESS:
|
|
return n_err, {}
|
|
for r in n_rows:
|
|
out[r] = 1
|
|
w_err, w_rows = await DB_SESSION_MNG.execute(
|
|
cdb, select(wild_cards.wild_card_id).where(wild_cards.wild_card_id.in_(card_ids), wild_cards.deleted == False) # noqa: E712
|
|
)
|
|
if w_err != ErrorType.SUCCESS:
|
|
return w_err, {}
|
|
for r in w_rows:
|
|
out[r] = 2
|
|
return ErrorType.SUCCESS, out
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, {}
|
|
|
|
async def get_version_cards(self, cdb: AsyncSession, version_id) -> Tuple[ErrorType, list]:
|
|
"""견적 버전에 묶인 카드. version_nego_cards/version_wild_cards 조인.
|
|
반환: [(card_type, card_pk, number, name, script, edit_script, condition, memo), ...]."""
|
|
try:
|
|
out = []
|
|
n_q = (
|
|
select(
|
|
nego_cards.nego_card_id, nego_cards.number, nego_cards.name,
|
|
nego_cards.script, nego_cards.edit_script,
|
|
)
|
|
.join(version_nego_cards, version_nego_cards.nego_card_id == nego_cards.nego_card_id)
|
|
.where(version_nego_cards.version_id == version_id, version_nego_cards.deleted == False, nego_cards.deleted == False) # noqa: E712
|
|
)
|
|
n_err, n_rows = await DB_SESSION_MNG.execute(cdb, n_q)
|
|
if n_err != ErrorType.SUCCESS:
|
|
return n_err, []
|
|
for pk, number, name, script, edit in n_rows:
|
|
out.append((1, pk, number, name, script, edit, None, None))
|
|
w_q = (
|
|
select(
|
|
wild_cards.wild_card_id, wild_cards.number, wild_cards.name,
|
|
wild_cards.script, wild_cards.edit_script, wild_cards.condition, wild_cards.memo,
|
|
)
|
|
.join(version_wild_cards, version_wild_cards.wild_card_id == wild_cards.wild_card_id)
|
|
.where(version_wild_cards.version_id == version_id, version_wild_cards.deleted == False, wild_cards.deleted == False) # noqa: E712
|
|
)
|
|
w_err, w_rows = await DB_SESSION_MNG.execute(cdb, w_q)
|
|
if w_err != ErrorType.SUCCESS:
|
|
return w_err, []
|
|
for pk, number, name, script, edit, condition, memo in w_rows:
|
|
out.append((2, pk, number, name, script, edit, condition, memo))
|
|
return ErrorType.SUCCESS, out
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, []
|
|
|
|
async def get_item_prices(self, cdb: AsyncSession, item_ids) -> Tuple[ErrorType, dict]:
|
|
"""item_id -> price(원, NULL 가능) 매핑. 세션 목표가 계산 입력."""
|
|
try:
|
|
if not item_ids:
|
|
return ErrorType.SUCCESS, {}
|
|
query = select(items.item_id, items.price).where(
|
|
items.item_id.in_(item_ids), items.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, {r[0]: r[1] for r in rows}
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, {}
|
|
|
|
async def get_target_margin(self, cdb: AsyncSession, qt_setting_id) -> Tuple[ErrorType, Optional[float]]:
|
|
"""견적 세팅의 목표 마진율. 세션 목표가 = price / (1 + margin)."""
|
|
try:
|
|
query = select(quotation_settings.target_margin_rate).where(
|
|
quotation_settings.qt_setting_id == qt_setting_id
|
|
).limit(1)
|
|
err_type, rows = await DB_SESSION_MNG.execute(cdb, query)
|
|
if err_type != ErrorType.SUCCESS:
|
|
return err_type, None
|
|
return ErrorType.SUCCESS, (float(rows[0]) if rows and rows[0] is not None else None)
|
|
except Exception as ex:
|
|
LOG.e_no_callstack(ex)
|
|
return ErrorType.DB_RUN_FAILED, None
|
|
|
|
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, []
|