Merge branch 'main' of https://gitea.o2o.kr/Negosium/o2o-negosium
# Conflicts: # postgres-init/03-seed-negodata.sql
This commit is contained in:
commit
088c57f415
26 files changed
+675
-315
No files matched your search
@@ -138,6 +138,31 @@ class wild_cards(MainTableMixin, MAIN_BASE):
|
||||
memo = Column(String(255), nullable=True) # 자유 메모
|
||||
|
||||
|
||||
class versions(MainTableMixin, MAIN_BASE):
|
||||
__tablename__ = "versions"
|
||||
|
||||
version_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
user_id = Column(UUID(as_uuid=True), nullable=False, index=True) # 버전 생성 유저
|
||||
code = Column(Integer, nullable=False, default=0) # 빠른 조회용
|
||||
name = Column(String(10), nullable=False) # 버전명
|
||||
|
||||
|
||||
class version_nego_cards(MainTableMixin, MAIN_BASE):
|
||||
__tablename__ = "version_nego_cards"
|
||||
|
||||
vnc_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
version_id = Column(UUID(as_uuid=True), nullable=False, index=True) # versions.version_id
|
||||
nego_card_id = Column(UUID(as_uuid=True), nullable=False, index=True) # nego_cards.nego_card_id
|
||||
|
||||
|
||||
class version_wild_cards(MainTableMixin, MAIN_BASE):
|
||||
__tablename__ = "version_wild_cards"
|
||||
|
||||
vwc_id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
version_id = Column(UUID(as_uuid=True), nullable=False, index=True) # versions.version_id
|
||||
wild_card_id = Column(UUID(as_uuid=True), nullable=False, index=True) # wild_cards.wild_card_id
|
||||
|
||||
|
||||
class quotation_settings(MainTableMixin, MAIN_BASE):
|
||||
__tablename__ = "quotation_settings"
|
||||
__table_args__ = {"schema": "quotation"}
|
||||
|
||||
@@ -8,6 +8,7 @@ process_count = 1
|
||||
is_ssl = false
|
||||
is_test = true
|
||||
client_url = "http://localhost:3000" # CORS 허용
|
||||
nego_chat_url = "http://localhost:3300" # 공급사 협상 프론트 base(세션 chat 실행 URL). 미설정 시 기본값 동일.
|
||||
|
||||
[LogConfig]
|
||||
print_console = true
|
||||
|
||||
@@ -8,6 +8,7 @@ class WebServerConfig(ConfigModel):
|
||||
is_ssl: bool = False
|
||||
is_test: bool = False
|
||||
client_url: str = ""
|
||||
nego_chat_url: str = "http://localhost:3300"
|
||||
|
||||
|
||||
class LogConfig(ConfigModel):
|
||||
|
||||
@@ -6,7 +6,10 @@ 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.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
|
||||
@@ -28,6 +31,30 @@ class IQuotationCRUD(ABC):
|
||||
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
|
||||
@@ -52,6 +79,10 @@ class IQuotationCRUD(ABC):
|
||||
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(
|
||||
@@ -110,6 +141,32 @@ class QuotationCRUD(IQuotationCRUD):
|
||||
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
|
||||
@@ -130,6 +187,117 @@ class QuotationCRUD(IQuotationCRUD):
|
||||
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:
|
||||
|
||||
@@ -13,18 +13,21 @@ class QuotationProtocol(WebPacketProtocol):
|
||||
|
||||
class Req_CreateQuotation(QuotationProtocol):
|
||||
qt_setting_id: uuid.UUID
|
||||
version_id: uuid.UUID
|
||||
version_id: Optional[uuid.UUID] = None # 미지정 시 기본 전략 버전(card.versions 시드)으로 채움
|
||||
name: str = ""
|
||||
number: str = ""
|
||||
type: int = 0
|
||||
status: int = 0
|
||||
start_time: datetime
|
||||
start_time: Optional[datetime] = None # 미지정 시 생성 시각(UTC)
|
||||
end_time: datetime
|
||||
round: int = 1
|
||||
manager_name: Optional[str] = None
|
||||
manager_email: Optional[str] = None
|
||||
manager_contact_number: Optional[str] = None
|
||||
memo: Optional[str] = None
|
||||
item_ids: list[uuid.UUID] = [] # 협상 대상 상품. item×supplier 조합마다 세션 1개 생성
|
||||
supplier_ids: list[uuid.UUID] = [] # 협상 초청 공급사
|
||||
card_ids: list[uuid.UUID] = [] # 선택 협상카드. 버전을 만들어 묶고 quotation.version_id 로 연결
|
||||
|
||||
|
||||
class QuotationData(WebPacketProtocol):
|
||||
@@ -52,6 +55,8 @@ class QuotationData(WebPacketProtocol):
|
||||
equal_bid_yn: Optional[bool] = None
|
||||
equal_bid_data: Optional[Any] = None
|
||||
participation_count: int = 0 # 견적별 참여 협력사 수(세션 distinct supplier). 목록 집계로 채움.
|
||||
item_id: Optional[uuid.UUID] = None # 대표 상품 id(세션의 첫 item). 목록 조인으로 채움.
|
||||
item_name: Optional[str] = None # 대표 상품명. 목록 조인으로 채움.
|
||||
created_at: Optional[datetime] = None
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
@@ -68,22 +73,6 @@ class Res_DeleteQuotation(Res_WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
class AsyncJob(WebPacketProtocol):
|
||||
status: str = ""
|
||||
message: str = ""
|
||||
|
||||
|
||||
class Res_CreateQuotation(Res_WebPacketProtocol):
|
||||
quotation: Optional[QuotationData] = None
|
||||
async_job: Optional[AsyncJob] = None
|
||||
|
||||
|
||||
class Res_QuotationStatus(Res_WebPacketProtocol):
|
||||
qt_id: Optional[uuid.UUID] = None
|
||||
job_status: int = 0
|
||||
message: str = ""
|
||||
|
||||
|
||||
class SessionData(WebPacketProtocol):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
@@ -102,6 +91,24 @@ class SessionData(WebPacketProtocol):
|
||||
reject_reason: Optional[str] = None
|
||||
reject_price: Optional[int] = None
|
||||
reject_delivery_type: Optional[int] = None
|
||||
url: str = "" # 세션 chat 실행 URL(공급사 협상 프론트). DB 미저장 — session_id 로 구성
|
||||
|
||||
|
||||
class AsyncJob(WebPacketProtocol):
|
||||
status: str = ""
|
||||
message: str = ""
|
||||
|
||||
|
||||
class Res_CreateQuotation(Res_WebPacketProtocol):
|
||||
quotation: Optional[QuotationData] = None
|
||||
sessions: list[SessionData] = [] # 견적 생성과 함께 만들어진 협상 세션(각 url 포함)
|
||||
async_job: Optional[AsyncJob] = None
|
||||
|
||||
|
||||
class Res_QuotationStatus(Res_WebPacketProtocol):
|
||||
qt_id: Optional[uuid.UUID] = None
|
||||
job_status: int = 0
|
||||
message: str = ""
|
||||
|
||||
|
||||
class Res_QuotationSessions(Res_WebPacketProtocol):
|
||||
|
||||
@@ -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