[feat] 협상 멘트 스타일 파이프라인(마커) + agent 카드 DB 소스 + supplier_items 연동
표현 아키텍처: agent 스크립트는 의미(텍스트)만 소유, 표현(굵기·색)은 프론트 소유.
Slate 는 negodata 에디터 내부에만 두고, 전송/저장은 마커 문자열 한 벌(구버전의 리치텍스트 이중관리 폐기).
- 트랙 A (negodata): serializeToMarker 추가 — Slate 마크(bold/underline/color)를 **/__/{{토큰}} 로
인코딩해 nego_cards.script 저장. edit_script(Slate 원본)는 재편집 전용. 고정 3색 → 시맨틱 토큰(강조/안내).
- 트랙 B (agent): 카드 멘트 DB 소스 — ICardScriptRepository/CardScriptDbRepository(port+adapter),
ScriptRepository.resolve_card_script 가 cards.source_type=backoffice_db 면 card.nego_cards.script 우선,
없으면 파일 폴백. action_id→card_id→nego_cards.number 매칭.
- 트랙 C (양 프론트): renderEmphasis 재귀 파서 — **굵게**·__밑줄__·{{강조|빨강}}·{{안내|파랑}} 중첩 렌더.
색은 시맨틱 토큰→디자인 토큰 클래스(다크모드 안전). negodata tokens.css 에 --info 신설. CardTable 미리보기 적용.
- supplier_items 연동: 유통코드=supplier_items.supply_type(→quotations.supplier_type 폴백),
파트너유형=상품별 매핑 협력사 수(→세션 이력 폴백).
- 가격 수용률: 기존 공급가(item_price) 기준 양보율로 정정 — 첫 라운드부터 실값(첫 제시가 기준 0 아님).
테스트: agent 86/86, 공급사 frontend·negodata front tsc 통과.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dc0e78ec73
commit
1c8c4254a6
24 files changed
+509
-45
No files matched your search
@@ -29,6 +29,12 @@ _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",
|
||||
column("supplier_id"), column("item_id"), column("supply_type"), column("deleted"),
|
||||
schema="partner",
|
||||
)
|
||||
|
||||
|
||||
class INegoContextCRUD(ABC):
|
||||
@@ -47,14 +53,25 @@ class INegoContextCRUD(ABC):
|
||||
"""협력사 총매출액(suppliers.total_revenue — KTC 미러). 없으면 0.0."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_supply_type(self, cdb: AsyncSession, supplier_id, item_id) -> Tuple[ErrorType, Optional[int]]:
|
||||
"""이 협력사가 이 상품을 공급하는 방식(supplier_items.supply_type: 0=none/1=유통/2=제조/3=총판).
|
||||
매핑이 없으면 None."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_quotation_supplier_type(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[int]]:
|
||||
"""견적의 협력사 유형(quotations.supplier_type: 0=none/1=유통/2=제조/3=총판). 미지정 시 None."""
|
||||
"""견적의 협력사 유형(quotations.supplier_type — supplier_items 매핑 부재 시 폴백). 미지정 시 None."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def count_item_suppliers(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
"""상품에 연결된 협력사 수(협상 세션 이력 기준 distinct supplier)."""
|
||||
"""상품에 연결된 협력사 수 — supplier_items 매핑 기준 distinct supplier."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def count_item_session_suppliers(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
"""상품에 연결된 협력사 수 — 협상 세션 이력 기준(supplier_items 매핑 부재 시 폴백)."""
|
||||
pass
|
||||
|
||||
|
||||
@@ -105,6 +122,23 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0.0
|
||||
|
||||
async def get_supply_type(self, cdb: AsyncSession, supplier_id, item_id) -> Tuple[ErrorType, Optional[int]]:
|
||||
try:
|
||||
query = (
|
||||
select(_SUPPLIER_ITEMS.c.supply_type)
|
||||
.where(_SUPPLIER_ITEMS.c.supplier_id == supplier_id,
|
||||
_SUPPLIER_ITEMS.c.item_id == item_id,
|
||||
_SUPPLIER_ITEMS.c.deleted == False) # noqa: E712
|
||||
.limit(1)
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "get_supply_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 get_quotation_supplier_type(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, Optional[int]]:
|
||||
try:
|
||||
query = (
|
||||
@@ -123,8 +157,8 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
async def count_item_suppliers(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
try:
|
||||
query = (
|
||||
select(func.count(distinct(_SESSIONS.c.supplier_id)))
|
||||
.where(_SESSIONS.c.item_id == item_id, _SESSIONS.c.deleted == False) # noqa: E712
|
||||
select(func.count(distinct(_SUPPLIER_ITEMS.c.supplier_id)))
|
||||
.where(_SUPPLIER_ITEMS.c.item_id == item_id, _SUPPLIER_ITEMS.c.deleted == False) # noqa: E712
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "count_item_suppliers failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS or not rows:
|
||||
@@ -133,3 +167,17 @@ class NegoContextCRUD(INegoContextCRUD):
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
|
||||
async def count_item_session_suppliers(self, cdb: AsyncSession, item_id) -> Tuple[ErrorType, int]:
|
||||
try:
|
||||
query = (
|
||||
select(func.count(distinct(_SESSIONS.c.supplier_id)))
|
||||
.where(_SESSIONS.c.item_id == item_id, _SESSIONS.c.deleted == False) # noqa: E712
|
||||
)
|
||||
err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "count_item_session_suppliers failed.", raise_error=False)
|
||||
if err_type != ErrorType.SUCCESS or not rows:
|
||||
return err_type, 0
|
||||
return ErrorType.SUCCESS, int(rows[0] or 0)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, 0
|
||||
@@ -25,8 +25,10 @@ from negotiation.qtable.domain.model.snapshot import PartnerType
|
||||
# 1:1 견적유형 → 재협상 스크립트. QuotationType: 1=renego, 3=new_nego (2=requote, 4=new_quote 는 1:N 재견적).
|
||||
_ONE_TO_ONE_QT_TYPES = (1, 3)
|
||||
|
||||
# 유통 코드: quotations.supplier_type(1=distribution 유통, 2=manufacture 제조, 3=sole_agency 총판)
|
||||
# 유통 코드: 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 견적 기록 — 매핑 부재 시 폴백).
|
||||
_SUPPLIER_TYPE_TO_CODE = {2: "A", 3: "B", 1: "C"}
|
||||
|
||||
|
||||
@@ -38,9 +40,9 @@ class NegotiationDbContext:
|
||||
target_price: int # 목표 매입가(원) — sessions.target_price
|
||||
anchor_price: int # 앵커링가 — sessions.anchoring_price(생성 시 박제). 없으면 target(무할인 폴백)
|
||||
item_price: int # 기존 공급가(품목 기준가, items.price) — 인하율 멘트용. 없으면 0
|
||||
partner_type: PartnerType # 상품에 연결된 협력사 수(distinct supplier) → NONE/SINGLE/MULTIPLE
|
||||
partner_type: PartnerType # 상품에 연결된 협력사 수(supplier_items 매핑, 없으면 세션 이력) → NONE/SINGLE/MULTIPLE
|
||||
revenue_amount: float # 매출액(원) — suppliers.total_revenue(KTC 미러). 없으면 0
|
||||
distribution_code: Optional[str] # 유통 코드(A/B/C) — quotations.supplier_type 매핑. 미지정 시 None
|
||||
distribution_code: Optional[str] # 유통 코드(A/B/C) — supplier_items.supply_type → quotations.supplier_type. 미지정 시 None
|
||||
|
||||
|
||||
class NegotiationContextLoader:
|
||||
@@ -74,14 +76,20 @@ class NegotiationContextLoader:
|
||||
# 매출액: 협력사 총매출(KTC total_revenue 미러). 미기재 시 0 → 호출부 기본값.
|
||||
_, revenue_amount = await self.crud.get_supplier_total_revenue(s, supplier_id)
|
||||
|
||||
# 유통 코드: 견적의 협력사 유형(supplier_type) 매핑. 미지정 시 None → 호출부 기본값.
|
||||
_, supplier_type = await self.crud.get_quotation_supplier_type(s, quotation_id)
|
||||
# 유통 코드: 이 협력사×이 상품의 공급 방식(supplier_items.supply_type) 우선.
|
||||
# 매핑이 없으면 견적 기록(quotations.supplier_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)
|
||||
|
||||
# 파트너사 유형: 상품에 연결된 협력사 수(협상 세션 이력 기준 distinct supplier). 실패 시 SINGLE.
|
||||
# 파트너사 유형: 상품에 연결된 협력사 수 — supplier_items 매핑(등록 기준) 우선.
|
||||
# 매핑이 아직 없으면 협상 세션 이력 기준 폴백(더미보다 항상 낫다). 실패 시 SINGLE.
|
||||
err, supplier_count = await self.crud.count_item_suppliers(s, item_id)
|
||||
if err == ErrorType.SUCCESS and supplier_count == 0:
|
||||
err, supplier_count = await self.crud.count_item_session_suppliers(s, item_id)
|
||||
if err != ErrorType.SUCCESS:
|
||||
supplier_count = 1
|
||||
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
- 탐색 순서: tenants/<id>/resources/ → 없으면 tenants/_base/resources/ 폴백.
|
||||
- 브랜드({company_name}/{service_name})는 TenantConfig.resources 에서 주입(클린룸: 특정사 브랜드 비포함).
|
||||
- 협상 변수({input_price}, {target}, {offer_1pct} 등)는 format_script 에서 치환.
|
||||
- 표현 규칙: 스크립트는 의미(텍스트)만 소유한다. 문장 내 강조는 `**굵게**` 경량 마커만 허용
|
||||
— 렌더(굵기·색)는 프론트 소유(frontend emphasis.tsx). 선행 Chat_server 의 리치텍스트 JSON
|
||||
이중 관리(response_scripts.json)는 채택하지 않는다.
|
||||
|
||||
Chat_server 구조 참고, 동적 import 해킹/특정사 표현은 제거(CLEANROOM.md).
|
||||
"""
|
||||
@@ -12,17 +15,25 @@ import json
|
||||
import os
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import DBType, DBWRType, ErrorType
|
||||
from common.logger import LOG
|
||||
from negotiation.cards.adapters.card_script_db import CardScriptDbRepository
|
||||
from negotiation.cards.ports.card_script_port import ICardScriptRepository
|
||||
from tenancy.config import TenantConfig
|
||||
|
||||
_RQ_FILES = {"재협상": "scripts_renegotiation.json", "재견적": "scripts_requote.json"}
|
||||
_CARD_SOURCE_DB = "backoffice_db"
|
||||
|
||||
|
||||
class ScriptRepository:
|
||||
def __init__(self, config: TenantConfig, tenants_dir: str):
|
||||
def __init__(self, config: TenantConfig, tenants_dir: str,
|
||||
card_repo: Optional[ICardScriptRepository] = None):
|
||||
self._config = config
|
||||
self._tenants_dir = tenants_dir
|
||||
self._cache: Dict[str, Any] = {}
|
||||
# 카드 멘트 DB 소스(backoffice_db). file 모드면 미사용.
|
||||
self._card_repo: ICardScriptRepository = card_repo or CardScriptDbRepository()
|
||||
|
||||
# ---- 경로 해석 (_base 폴백) ---------------------------------------
|
||||
def _resource_path(self, filename: str) -> Optional[str]:
|
||||
@@ -69,12 +80,37 @@ class ScriptRepository:
|
||||
return self._load_json("scripts_cards.json")
|
||||
|
||||
def card_script(self, action_id: int, variables: Optional[Dict[str, Any]] = None) -> Optional[str]:
|
||||
"""선택된 카드(action_id)의 스크립트를 변수 치환해서 반환. 없으면 None(호출부가 기본 문구 유지)."""
|
||||
"""선택된 카드(action_id)의 파일 스크립트를 변수 치환해서 반환. 없으면 None(호출부가 기본 문구 유지)."""
|
||||
text = self.card_scripts().get(str(action_id))
|
||||
if not text:
|
||||
return None
|
||||
return self.format_script(text, variables)
|
||||
|
||||
async def resolve_card_script(self, action_id: int, card_id: Optional[str],
|
||||
variables: Optional[Dict[str, Any]] = None) -> Optional[str]:
|
||||
"""카드 멘트 해석. cards.source_type == 'backoffice_db' 면 card.nego_cards.script(DB)를
|
||||
우선 조회하고, 없거나 file 모드면 scripts_cards.json(파일) 폴백. 변수 치환 후 반환.
|
||||
|
||||
DB 멘트는 백오피스(negodata)가 편집한 정본이라 파일보다 우선한다. 마커(**굵게** 등)가
|
||||
섞여 있어도 agent 는 불투명 텍스트로 취급 — 표현 렌더는 프론트 소유.
|
||||
"""
|
||||
if self._config.cards.source_type == _CARD_SOURCE_DB and card_id:
|
||||
db_text = await self._fetch_card_script_db(card_id)
|
||||
if db_text:
|
||||
return self.format_script(db_text, variables)
|
||||
return self.card_script(action_id, variables) # 파일 폴백
|
||||
|
||||
async def _fetch_card_script_db(self, card_id: str) -> Optional[str]:
|
||||
async def _q(s):
|
||||
_, text = await self._card_repo.get_script_by_number(s, card_id)
|
||||
return text
|
||||
|
||||
try:
|
||||
return await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
|
||||
except Exception as ex: # DB 불가 등 — 파일 폴백으로 협상은 계속되어야 함
|
||||
LOG.e_no_callstack(f"[ScriptRepository] 카드 멘트 DB 조회 실패 card_id={card_id}: {ex}")
|
||||
return None
|
||||
|
||||
def client_step_mapping(self) -> dict:
|
||||
return self._load_json("client_step_mapping.json")
|
||||
|
||||
|
||||
Reference in new issue
Block a user