[refactor] 공급유형 기준을 상품-협력사 매핑으로 전환

This commit is contained in:
minaChoi committed 2026-07-07 17:05:07 +09:00
1 parent 9ac8fe6363
commit d21e7c10b0
35 files changed
+157 -333

No files matched your search

@@ -28,7 +28,6 @@ _SESSIONS = table(
)
_ITEMS = table("items", column("item_id"), column("price"), column("deleted"), schema="partner")
_SUPPLIERS = table("suppliers", column("supplier_id"), column("total_revenue"), column("deleted"), schema="partner")
_QUOTATIONS = table("quotations", column("qt_id"), column("supplier_type"), column("deleted"), schema="quotation")
# 상품↔협력사 매핑 (2026-07-07 신설): supply_type = 이 협력사가 이 상품을 공급하는 방식(SupplierType).
_SUPPLIER_ITEMS = table(
"supplier_items",
@@ -59,11 +58,6 @@ class INegoContextCRUD(ABC):
매핑이 없으면 None."""
pass
@abstractmethod
async def get_quotation_supplier_type(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[int]]:
"""견적의 협력사 유형(quotations.supplier_type — supplier_items 매핑 부재 시 폴백). 미지정 시 None."""
pass
@abstractmethod
async def count_item_suppliers(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
"""상품에 연결된 협력사 수 — supplier_items 매핑 기준 distinct supplier."""
@@ -139,21 +133,6 @@ class NegoContextCRUD(INegoContextCRUD):
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None
async def get_quotation_supplier_type(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[int]]:
try:
query = (
select(_QUOTATIONS.c.supplier_type)
.where(_QUOTATIONS.c.qt_id == quotation_id, _QUOTATIONS.c.deleted == False) # noqa: E712
.limit(1)
)
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_quotation_supplier_type failed.", raise_error=False)
if err_type != ErrorType.SUCCESS or not rows or rows[0] is None:
return err_type, None
return ErrorType.SUCCESS, int(rows[0])
except Exception as ex:
LOG.e_no_callstack(ex)
return ErrorType.DB_RUN_FAILED, None
async def count_item_suppliers(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
try:
query = (
@@ -27,8 +27,7 @@ _ONE_TO_ONE_QT_TYPES = (1, 3)
# 유통 코드: SupplierType(1=distribution 유통, 2=manufacture 제조, 3=sole_agency 총판)
# → 테넌트 code_map 키(A/B/C). 제조→A, 총판→B, 유통→C (0=none/NULL 은 미지정 → 호출부 기본값).
# 소스 우선순위: partner.supplier_items.supply_type(이 협력사×이 상품 매핑, 2026-07-07 신설)
# → quotations.supplier_type(재견적 1:1 견적 기록 — 매핑 부재 시 폴백).
# 소스: partner.supplier_items.supply_type(이 협력사×이 상품 매핑).
_SUPPLIER_TYPE_TO_CODE = {2: "A", 3: "B", 1: "C"}
@@ -42,7 +41,7 @@ class NegotiationDbContext:
item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0
partner_type: PartnerType # 상품에 연결된 협력사 수(supplier_items 매핑, 없으면 세션 이력) → NONE/SINGLE/MULTIPLE
revenue_amount: float # 매출액(원) — suppliers.total_revenue(KTC 미러). 없으면 0
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type → quotations.supplier_type. 미지정 시 None
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type. 미지정 시 None
class NegotiationContextLoader:
@@ -62,7 +61,7 @@ class NegotiationContextLoader:
err, row = await self.crud.get_session_row(s, sid)
if err != ErrorType.SUCCESS or row is None:
return None
qt_type, target_price, anchoring_price, item_id, quotation_id, supplier_id = row
qt_type, target_price, anchoring_price, item_id, _quotation_id, supplier_id = row
target = int(target_price or 0)
# 앵커링가: 세션 생성 시 박제된 값(anchoring_price)을 그대로 사용 — 협상 중 불변.
@@ -76,11 +75,9 @@ class NegotiationContextLoader:
# 매출액: 협력사 총매출(KTC total_revenue 미러). 미기재 시 0 → 호출부 기본값.
_, revenue_amount = await self.crud.get_supplier_total_revenue(s, supplier_id)
# 유통 코드: 이 협력사×이 상품의 공급 방식(supplier_items.supply_type) 우선.
# 매핑이 없으면 견적 기록(quotations.supplier_type) 폴백. 미지정 시 None → 호출부 기본값.
# 유통 코드: 이 협력사×이 상품의 공급 방식(supplier_items.supply_type).
# 매핑이 없거나 미지정이면 None → 호출부 기본값.
_, supplier_type = await self.crud.get_supply_type(s, supplier_id, item_id)
if not supplier_type:
_, supplier_type = await self.crud.get_quotation_supplier_type(s, quotation_id)
# 기존 공급가(품목 기준가) — 없으면 0(인하율 멘트 미표시).
_, item_price = await self.crud.get_item_price(s, item_id)
+1 -1
View File
@@ -13,7 +13,7 @@ class Req_Chat(Req_WebPacketProtocol):
협상 컨텍스트(rq_type/목표가/앵커링가/품목가/매출액/유통코드/파트너 유형)는 요청에 싣지
않는다 — 세션 시작 시 agent 가 DB 에서 1회 조회해 확정한다(NegotiationContextLoader):
negotiation.sessions(qt_type·target_price·anchoring_price), partner.items(price),
partner.suppliers(total_revenue), quotation.quotations(supplier_type), 상품별 협력사 수.
partner.suppliers(total_revenue), partner.supplier_items(supply_type), 상품별 협력사 수.
행이 없으면(데모/테스트 직접 호출) 기본값 폴백.
가격 수용률은 세션 내 라운드별 제시가로 매 턴 동적 계산: max(0, (기존 공급가−현재가)/기존 공급가)
— 첫 제시가부터 기존 공급가 대비 인하가 반영되므로 첫 라운드도 실값. 기존 공급가 없으면 첫 제시가 기준.
+2 -2
View File
@@ -31,7 +31,7 @@ _DEFAULT_RQ_TYPE = "재협상"
_DEFAULT_TARGET_PRICE = 10000 # KT 목표 매입가
_DEFAULT_ANCHOR_PRICE = 9900 # 앵커링가(목표가보다 낮음). 제시가 ≤ anchor → 우선협상
_DEFAULT_REVENUE_AMOUNT = 20_000_000 # 매출액(원) — suppliers.total_revenue 미기재 시 폴백
_DEFAULT_DISTRIBUTION_CODE = "A" # 유통 코드 — quotations.supplier_type 미지정 시 폴백
_DEFAULT_DISTRIBUTION_CODE = "A" # 유통 코드 — supplier_items.supply_type 미지정 시 폴백
class ChatService:
@@ -69,7 +69,7 @@ class ChatService:
session_id=req.session_id or str(uuid.uuid4()), tenant_id=engine.tenant_id, company_id=engine.company_id,
rq_type=rq_type, action_space_size=engine.action_space_size,
context={
# 매출액 = suppliers.total_revenue, 유통코드 = quotations.supplier_type 매핑 (loader).
# 매출액 = suppliers.total_revenue, 유통코드 = supplier_items.supply_type 매핑 (loader).
# 미기재/미지정이면 기본값 폴백.
"revenue_amount": db_ctx.revenue_amount if db_ctx and db_ctx.revenue_amount > 0 else _DEFAULT_REVENUE_AMOUNT,
"distribution_code": db_ctx.distribution_code if db_ctx and db_ctx.distribution_code else _DEFAULT_DISTRIBUTION_CODE,
+4 -8
View File
@@ -34,7 +34,7 @@ _T_QUOTATIONS = table(
"quotations",
column("qt_id"), column("user_id"), column("qt_setting_id"), column("version_id"),
column("name"), column("number"), column("type"), column("status"),
column("start_time"), column("end_time"), column("supplier_type"),
column("start_time"), column("end_time"),
schema="quotation",
)
_T_ITEMS = table(
@@ -80,7 +80,6 @@ async def test_context_loaded_from_db(db_engine):
qt_id=qid, user_id=uuid.uuid4(), qt_setting_id=uuid.uuid4(), version_id=uuid.uuid4(),
name="로더 테스트", number="QT-LOADER-TEST", type=3, status=2,
start_time=now, end_time=now + timedelta(days=1),
supplier_type=2, # manufacture(제조) → 유통 코드 "A"
))
def _ins_sess(s, session_id, supplier_id):
@@ -125,7 +124,7 @@ async def test_context_loaded_from_db(db_engine):
assert c["distribution_code"] == "B" # supplier_items.supply_type=3(총판) → B (매핑 우선)
assert c["partner_count"] == 2 # 매핑 기준 취급 협력사 2곳 → MULTIPLE
# 매핑 삭제 후 새 세션(sid2) → 폴백 경로: 유통코드=quotations.supplier_type, 파트너=세션 이력
# 매핑 삭제 후 새 세션(sid2) → 유통코드는 ChatService 기본값, 파트너는 세션 이력 폴백
err = await DB_SESSION_MNG.execute_lambda_run(
[DBType.MAIN.value],
[lambda s: DB_SESSION_MNG.add(s, delete(_T_SUPPLIER_ITEMS).where(_T_SUPPLIER_ITEMS.c.item_id == iid))],
@@ -133,7 +132,7 @@ async def test_context_loaded_from_db(db_engine):
assert err == ErrorType.SUCCESS
await ChatService().chat(eng, Req_Chat(session_id=str(sid2)))
c2 = (await ChatSessionRepository(eng.company_id).get(str(sid2))).context
assert c2["distribution_code"] == "A" # 폴백: quotations.supplier_type=2(제조) → A
assert c2["distribution_code"] == "A" # 매핑 없음 → ChatService 기본값
assert c2["partner_count"] == 2 # 폴백: 세션 이력 distinct supplier 2곳
finally:
await DB_SESSION_MNG.execute_lambda_run(
@@ -197,9 +196,6 @@ async def test_loader_with_crud_double(db_engine):
return ErrorType.SUCCESS, 12_000_000.0
async def get_supply_type(self, cdb, supplier_id, item_id):
return ErrorType.SUCCESS, None # 매핑 없음 → 견적 기록 폴백
async def get_quotation_supplier_type(self, cdb, quotation_id):
return ErrorType.SUCCESS, 3 # sole_agency(총판) → "B"
async def count_item_suppliers(self, cdb, item_id):
@@ -215,7 +211,7 @@ async def test_loader_with_crud_double(db_engine):
assert ctx.anchor_price == 50000 # 미박제 → 무할인 폴백(anchor=target)
assert ctx.item_price == 7000
assert ctx.revenue_amount == 12_000_000.0
assert ctx.distribution_code == "B" # supplier_type=3(총판) → B
assert ctx.distribution_code == "B" # supply_type=3(총판) → B
assert ctx.partner_type is PartnerType.NONE