[feat] negodata: 견적목록 상품조인 + 견적/카드 페이지네이션 + 견적중단 서버연동 + 발의→등록
- 견적 목록에 대표 상품(세션 item) 조인 노출 → '대상 상품 확인 불가' 해소 (backend protocol/crud/service + orval 재생성 + front mapQuotation 매핑) - 견적·협상카드 목록 클라이언트 페이지네이션 추가 (useClientPagination) - 견적중단을 서버 stop_quotation 호출로 영속 처리(상태=견적마감) - 신규 협상견적 라벨 발의→등록 통일 - 발의 위저드 카드선택에 협상/와일드 구분 뱃지 추가 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
53b8a78de7
commit
4f0e4c29ce
25 files changed
+668
-165
No files matched your search
@@ -1,11 +1,14 @@
|
||||
import uuid
|
||||
from datetime import timezone
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import quotations, sessions, chats
|
||||
from common.enums import DBWRType, ErrorType
|
||||
from common.database.model.models import quotations, sessions, chats, versions, version_nego_cards, version_wild_cards
|
||||
from common.enums import DBWRType, ErrorType, QuotationStatus, SessionStatus
|
||||
from common.models.gmodel import PageParams
|
||||
from common.utils.gtime import GTime
|
||||
from config.server_configs import web_server_config
|
||||
from crud.quotation_crud import IQuotationCRUD, QuotationCRUD
|
||||
from router.v1.quotation.protocol import (
|
||||
AsyncJob,
|
||||
@@ -32,9 +35,42 @@ class QuotationService:
|
||||
user_id 는 생성 시 소유자로만 기록한다(조회/변경 시 소유권 필터 없음).
|
||||
"""
|
||||
|
||||
# 기본 전략 버전(card.versions 시드). 견적 생성 시 version_id 미지정이면 이 값으로 채운다.
|
||||
DEFAULT_VERSION_ID = uuid.UUID("00000000-0000-0000-0000-000000000030")
|
||||
|
||||
def __init__(self, quotation_crud: IQuotationCRUD = Depends(QuotationCRUD)):
|
||||
self.quotation_crud = quotation_crud
|
||||
|
||||
@staticmethod
|
||||
def _session_chat_url(session_id) -> str:
|
||||
"""세션 chat 실행 URL(공급사 협상 프론트). ChatPage 가 session_id 쿼리로 진입한다."""
|
||||
base = (web_server_config.nego_chat_url or "").rstrip("/")
|
||||
return f"{base}/chat?session_id={session_id}"
|
||||
|
||||
@staticmethod
|
||||
def _calc_target_price(price, margin) -> int:
|
||||
"""세션 목표가(원). 단가 있으면 목표 마진율 적용가, 없으면 0."""
|
||||
if not price:
|
||||
return 0
|
||||
if margin and margin > 0:
|
||||
return int(int(price) / (1 + margin))
|
||||
return int(price)
|
||||
|
||||
@staticmethod
|
||||
def _naive_utc(dt):
|
||||
"""DB 컬럼이 naive(TIMESTAMP WITHOUT TIME ZONE)라, tz-aware 입력(프론트 toISOString 등)은 UTC naive 로 변환."""
|
||||
if dt is None:
|
||||
return dt
|
||||
if getattr(dt, "tzinfo", None) is not None:
|
||||
return dt.astimezone(timezone.utc).replace(tzinfo=None)
|
||||
return dt
|
||||
|
||||
@staticmethod
|
||||
def _gen_number() -> str:
|
||||
"""견적번호 자동 생성(미지정 시). EST-YYYYMM-XXXX."""
|
||||
now = GTime.UTC()
|
||||
return f"EST-{now:%Y%m}-{uuid.uuid4().hex[:4].upper()}"
|
||||
|
||||
async def _fetch(self, qt_id: uuid.UUID):
|
||||
"""견적 단건 조회. (ErrorType, quotation|None) 반환. (회사 스코프 없음)"""
|
||||
err_type, quotation = await DB_SESSION_MNG.execute_lambda(
|
||||
@@ -58,9 +94,11 @@ class QuotationService:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 참여 협력사 수(세션 distinct supplier)를 이 페이지 견적들에 대해 한 방으로 세서 합친다(메인 쿼리 비건드림).
|
||||
# 참여 협력사 수(세션 distinct supplier)와 대표 상품(세션 item)을 이 페이지 견적들에 대해
|
||||
# 각각 한 방으로 모아 합친다(메인 쿼리 비건드림).
|
||||
qt_ids = [r.qt_id for r in rows]
|
||||
counts = {}
|
||||
item_map = {}
|
||||
if qt_ids:
|
||||
cnt_err, got = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
@@ -69,8 +107,18 @@ class QuotationService:
|
||||
)
|
||||
if cnt_err == ErrorType.SUCCESS:
|
||||
counts = got
|
||||
im_err, got_im = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.item_map(s, qt_ids),
|
||||
)
|
||||
if im_err == ErrorType.SUCCESS:
|
||||
item_map = got_im
|
||||
for r in rows:
|
||||
r.participation_count = counts.get(r.qt_id, 0)
|
||||
item = item_map.get(r.qt_id)
|
||||
if item:
|
||||
r.item_id, r.item_name = item
|
||||
|
||||
res.quotations = [QuotationData.model_validate(r) for r in rows]
|
||||
res.total = total
|
||||
@@ -87,23 +135,133 @@ class QuotationService:
|
||||
|
||||
async def create_quotation(self, user_id: str, data: dict) -> Res_CreateQuotation:
|
||||
res = Res_CreateQuotation()
|
||||
quotation = quotations(**data, user_id=uuid.UUID(user_id))
|
||||
|
||||
# 세션 생성용 입력은 quotations 컬럼이 아니므로 분리한다(상품 × 공급사 조합마다 세션 1개).
|
||||
item_ids = data.pop("item_ids", []) or []
|
||||
supplier_ids = data.pop("supplier_ids", []) or []
|
||||
card_ids = data.pop("card_ids", []) or []
|
||||
|
||||
# NOT NULL 컬럼 보정(프론트 미전송 시 서버 디폴트).
|
||||
if not data.get("version_id"):
|
||||
data["version_id"] = self.DEFAULT_VERSION_ID
|
||||
if not data.get("start_time"):
|
||||
data["start_time"] = GTime.UTC()
|
||||
if not data.get("number"):
|
||||
data["number"] = self._gen_number()
|
||||
if not data.get("status"):
|
||||
data["status"] = QuotationStatus.CREATED.value
|
||||
if not data.get("round"):
|
||||
data["round"] = 1 # ORM 기본값은 flush 시점이라, 세션 스냅샷용으로 미리 확정한다
|
||||
# DB 컬럼이 naive 라, tz-aware 로 들어온 시각(프론트 toISOString)을 UTC naive 로 맞춘다.
|
||||
data["start_time"] = self._naive_utc(data.get("start_time"))
|
||||
data["end_time"] = self._naive_utc(data.get("end_time"))
|
||||
|
||||
# 세션 목표가 입력(상품 단가 + 견적 세팅 목표 마진율). 읽기 트랜잭션에서 먼저 조회.
|
||||
prices = {}
|
||||
if item_ids:
|
||||
_err, prices = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.get_item_prices(s, item_ids),
|
||||
)
|
||||
prices = prices if _err == ErrorType.SUCCESS else {}
|
||||
_err, margin = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.get_target_margin(s, data["qt_setting_id"]),
|
||||
)
|
||||
margin = margin if _err == ErrorType.SUCCESS else None
|
||||
|
||||
# 선택 협상카드가 있으면 새 버전을 만들어 카드들을 묶고, quotation.version_id 로 연결한다.
|
||||
# (quotation↔card 는 chats 가 아니라 version → version_nego_cards/version_wild_cards 로 연결.)
|
||||
version_obj = None
|
||||
link_rows = []
|
||||
if card_ids:
|
||||
_err, card_types = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.classify_card_ids(s, card_ids),
|
||||
)
|
||||
card_types = card_types if _err == ErrorType.SUCCESS else {}
|
||||
new_version_id = uuid.uuid4()
|
||||
version_obj = versions(
|
||||
version_id=new_version_id,
|
||||
user_id=uuid.UUID(user_id),
|
||||
code=0,
|
||||
name=(data.get("number") or "견적버전")[:10],
|
||||
)
|
||||
for cid in card_ids:
|
||||
t = card_types.get(cid)
|
||||
if t == 1:
|
||||
link_rows.append(version_nego_cards(version_id=new_version_id, nego_card_id=cid))
|
||||
elif t == 2:
|
||||
link_rows.append(version_wild_cards(version_id=new_version_id, wild_card_id=cid))
|
||||
data["version_id"] = new_version_id
|
||||
|
||||
# qt_id 를 미리 발급해 세션 FK(quotation_id)와 묶고, 한 트랜잭션에 함께 insert 한다.
|
||||
qt_id = uuid.uuid4()
|
||||
quotation = quotations(**data, qt_id=qt_id, user_id=uuid.UUID(user_id))
|
||||
|
||||
session_objs = []
|
||||
for iid in item_ids:
|
||||
tp = self._calc_target_price(prices.get(iid), margin)
|
||||
for sid in supplier_ids:
|
||||
session_objs.append(
|
||||
sessions(
|
||||
session_id=uuid.uuid4(),
|
||||
quotation_id=qt_id,
|
||||
item_id=iid,
|
||||
supplier_id=sid,
|
||||
qt_number=quotation.number,
|
||||
qt_round=quotation.round,
|
||||
qt_type=quotation.type,
|
||||
target_price=tp,
|
||||
status=SessionStatus.CREATED.value,
|
||||
end_time=quotation.end_time,
|
||||
)
|
||||
)
|
||||
|
||||
# 버전 → (버전-카드 매핑) → 견적 → 세션 순으로 한 트랜잭션에 insert(FK 순서 보장).
|
||||
ops = []
|
||||
if version_obj is not None:
|
||||
ops.append(lambda s: self.quotation_crud.add_rows(s, [version_obj]))
|
||||
ops.append(lambda s: self.quotation_crud.add_rows(s, link_rows))
|
||||
ops.append(lambda s: self.quotation_crud.add_quotation(s, quotation))
|
||||
ops.append(lambda s: self.quotation_crud.add_sessions(s, session_objs))
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[quotations.DBType()],
|
||||
[lambda s: self.quotation_crud.add_quotation(s, quotation)],
|
||||
ops,
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 서버 기본값(created_at/updated_at) 로드 위해 재조회 (응답 shape 은 Res_CreateQuotation 유지).
|
||||
|
||||
# 서버 기본값(created_at/updated_at) 로드 위해 재조회.
|
||||
f_err, fresh = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.get_by_id(s, quotation.qt_id),
|
||||
lambda s: self.quotation_crud.get_by_id(s, qt_id),
|
||||
)
|
||||
res.quotation = QuotationData.model_validate(fresh if f_err == ErrorType.SUCCESS and fresh is not None else quotation)
|
||||
# 네고시움 백엔드 비동기 요청은 스텁이므로 row 만 생성한다.
|
||||
res.async_job = AsyncJob(status="submitted", message="견적 생성 작업 요청됨(스텁)")
|
||||
|
||||
# 생성된 세션 + 각 세션 chat 실행 URL 을 함께 반환(협상리스트에서 바로 진입 가능).
|
||||
res.sessions = [
|
||||
SessionData(
|
||||
session_id=so.session_id,
|
||||
qt_id=so.quotation_id,
|
||||
supplier_id=so.supplier_id,
|
||||
item_id=so.item_id,
|
||||
qt_number=so.qt_number,
|
||||
qt_round=so.qt_round,
|
||||
qt_type=so.qt_type,
|
||||
target_price=so.target_price,
|
||||
status=so.status,
|
||||
end_time=so.end_time,
|
||||
url=self._session_chat_url(so.session_id),
|
||||
)
|
||||
for so in session_objs
|
||||
]
|
||||
res.async_job = AsyncJob(status="created", message=f"협상 세션 {len(session_objs)}건 생성")
|
||||
return res
|
||||
|
||||
async def stop_quotation(self, qt_id: str) -> Res_Quotation:
|
||||
@@ -119,7 +277,7 @@ class QuotationService:
|
||||
# 상태를 '견적마감'으로 변경(실제 DB 업데이트)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[quotations.DBType()],
|
||||
[lambda s: self.quotation_crud.update_quotation(s, qt_uuid, {"status": "견적마감"})],
|
||||
[lambda s: self.quotation_crud.update_quotation(s, qt_uuid, {"status": QuotationStatus.CLOSED.value})],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
@@ -207,6 +365,7 @@ class QuotationService:
|
||||
reject_reason=r.reject_reason,
|
||||
reject_price=r.reject_price,
|
||||
reject_delivery_type=r.reject_delivery_type,
|
||||
url=self._session_chat_url(r.session_id),
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
@@ -252,34 +411,34 @@ class QuotationService:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 견적의 버전(quotation.version_id)에 묶인 카드를 조회한다(version_nego_cards/version_wild_cards).
|
||||
err_type, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
chats.DBType(),
|
||||
quotations.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.quotation_crud.list_used_cards(s, qt_uuid),
|
||||
lambda s: self.quotation_crud.get_version_cards(s, quotation.version_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
res.qt_id = quotation.qt_id
|
||||
# rows = [(chat_row, card_id, number, name, script, edit_script, condition, memo), ...].
|
||||
# nego/wild 구분은 chats.card_type. condition/memo 는 와일드카드에만 존재.
|
||||
# rows = [(card_type, card_pk, number, name, script, edit_script, condition, memo), ...].
|
||||
cards = []
|
||||
for chat_row, nc_id, nc_number, nc_name, nc_script, nc_edit, wc_condition, wc_memo in rows:
|
||||
is_wild = chat_row.card_type == 2
|
||||
for card_type, card_pk, number, name, script, edit, condition, memo in rows:
|
||||
is_wild = card_type == 2
|
||||
cards.append(
|
||||
QuotationCardData(
|
||||
session_card_id=chat_row.chat_id,
|
||||
session_card_id=card_pk,
|
||||
qt_id=quotation.qt_id,
|
||||
nego_card_id=None if is_wild else nc_id,
|
||||
wild_card_id=nc_id if is_wild else None,
|
||||
type=chat_row.card_type if chat_row.card_type is not None else 1,
|
||||
number=nc_number,
|
||||
name=nc_name,
|
||||
script=nc_script,
|
||||
edit_script=nc_edit,
|
||||
condition=wc_condition if is_wild else None,
|
||||
memo=wc_memo if is_wild else None,
|
||||
nego_card_id=None if is_wild else card_pk,
|
||||
wild_card_id=card_pk if is_wild else None,
|
||||
type=card_type,
|
||||
number=number,
|
||||
name=name,
|
||||
script=script,
|
||||
edit_script=edit,
|
||||
condition=condition,
|
||||
memo=memo,
|
||||
)
|
||||
)
|
||||
res.cards = cards
|
||||
|
||||
Reference in new issue
Block a user