[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
@@ -47,6 +47,11 @@ _T_SUPPLIERS = table(
|
||||
column("supplier_id"), column("company_id"), column("user_id"), column("name"), column("total_revenue"),
|
||||
schema="partner",
|
||||
)
|
||||
_T_SUPPLIER_ITEMS = table(
|
||||
"supplier_items",
|
||||
column("supplier_id"), column("item_id"), column("supply_type"),
|
||||
schema="partner",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -87,11 +92,19 @@ async def test_context_loaded_from_db(db_engine):
|
||||
status=2, end_time=now + timedelta(days=1),
|
||||
))
|
||||
|
||||
def _ins_mapping(s, supplier_id, supply_type):
|
||||
return DB_SESSION_MNG.add(s, insert(_T_SUPPLIER_ITEMS).values(
|
||||
supplier_id=supplier_id, item_id=iid, supply_type=supply_type,
|
||||
))
|
||||
|
||||
err = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[DBType.MAIN.value],
|
||||
[_ins_item, _ins_supplier, _ins_quote,
|
||||
lambda s: _ins_sess(s, sid, sup1),
|
||||
lambda s: _ins_sess(s, sid2, sup2)], # 같은 상품에 공급사 2곳 → MULTIPLE
|
||||
lambda s: _ins_sess(s, sid2, sup2),
|
||||
# 상품↔협력사 매핑(supplier_items): 협상 상대 sup1 은 총판(3), sup2 는 유통(1) → 취급 2곳
|
||||
lambda s: _ins_mapping(s, sup1, 3),
|
||||
lambda s: _ins_mapping(s, sup2, 1)],
|
||||
)
|
||||
assert err == ErrorType.SUCCESS
|
||||
|
||||
@@ -109,14 +122,26 @@ async def test_context_loaded_from_db(db_engine):
|
||||
assert c["anchor_price"] == 19000 # sessions.anchoring_price(박제)
|
||||
assert c["item_price"] == 5000
|
||||
assert c["revenue_amount"] == 55_000_000.0 # 매출액 = suppliers.total_revenue
|
||||
assert c["distribution_code"] == "A" # supplier_type=2(제조) → A
|
||||
assert c["partner_count"] == 2 # 공급사 2곳 → MULTIPLE
|
||||
assert c["distribution_code"] == "B" # supplier_items.supply_type=3(총판) → B (매핑 우선)
|
||||
assert c["partner_count"] == 2 # 매핑 기준 취급 협력사 2곳 → MULTIPLE
|
||||
|
||||
# 매핑 삭제 후 새 세션(sid2) → 폴백 경로: 유통코드=quotations.supplier_type, 파트너=세션 이력
|
||||
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))],
|
||||
)
|
||||
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["partner_count"] == 2 # 폴백: 세션 이력 distinct supplier 2곳
|
||||
finally:
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[DBType.MAIN.value],
|
||||
[lambda s: DB_SESSION_MNG.add(s, delete(_T_SESSIONS).where(_T_SESSIONS.c.quotation_id == qid)),
|
||||
lambda s: DB_SESSION_MNG.add(s, delete(_T_QUOTATIONS).where(_T_QUOTATIONS.c.qt_id == qid)),
|
||||
lambda s: DB_SESSION_MNG.add(s, delete(_T_ITEMS).where(_T_ITEMS.c.item_id == iid)),
|
||||
lambda s: DB_SESSION_MNG.add(s, delete(_T_SUPPLIER_ITEMS).where(_T_SUPPLIER_ITEMS.c.item_id == iid)),
|
||||
lambda s: DB_SESSION_MNG.add(s, delete(_T_SUPPLIERS).where(_T_SUPPLIERS.c.supplier_id == sup1))],
|
||||
)
|
||||
|
||||
@@ -171,11 +196,17 @@ async def test_loader_with_crud_double(db_engine):
|
||||
async def get_supplier_total_revenue(self, cdb, supplier_id):
|
||||
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):
|
||||
return ErrorType.SUCCESS, 0 # 연결 협력사 없음 → NONE
|
||||
return ErrorType.SUCCESS, 0 # 매핑 없음 → 세션 이력 폴백
|
||||
|
||||
async def count_item_session_suppliers(self, cdb, item_id):
|
||||
return ErrorType.SUCCESS, 0 # 이력도 없음 → NONE
|
||||
|
||||
ctx = await NegotiationContextLoader(crud=_FakeCRUD()).load(str(uuid.uuid4()))
|
||||
assert ctx is not None
|
||||
|
||||
@@ -109,13 +109,17 @@ def test_partner_type_enum_mapping():
|
||||
|
||||
|
||||
def test_acceptance_ratio_dynamic_calc():
|
||||
"""가격 수용률 동적 계산 — 첫 제시가 대비 양보율. 첫 제시/미기록=0, 인상 시 0 클립."""
|
||||
"""가격 수용률 동적 계산 — 기존 공급가(item_price) 기준 양보율. 첫 라운드부터 실값."""
|
||||
calc = ChatService._acceptance_ratio
|
||||
assert calc({}) == 0.0 # 가격 입력 전
|
||||
assert calc({"first_offer_price": 11000, "input_price": 11000}) == 0.0 # 첫 제시(양보 0)
|
||||
assert calc({"first_offer_price": 11000, "input_price": 10200}) == pytest.approx(800 / 11000)
|
||||
assert calc({"first_offer_price": 10000, "input_price": 12000}) == 0.0 # 인상(비정상) → 0
|
||||
assert calc({"input_price": 9800}) == 0.0 # 과거 세션 호환(첫 제시가 미기록)
|
||||
# 기존 공급가 12000 기준: 첫 제시 11000 도 첫 라운드부터 양보율 실값 (스크립트 discount_rate 와 동일 기준)
|
||||
assert calc({"item_price": 12000, "input_price": 11000}) == pytest.approx(1000 / 12000)
|
||||
assert calc({"item_price": 12000, "first_offer_price": 11000, "input_price": 10200}) == pytest.approx(1800 / 12000)
|
||||
assert calc({"item_price": 10000, "input_price": 12000}) == 0.0 # 기존가보다 인상(비정상) → 0
|
||||
# 기존 공급가 없음(신규 협상) → 첫 제시가 기준 폴백: 첫 제시 0, 이후 양보율
|
||||
assert calc({"item_price": 0, "first_offer_price": 11000, "input_price": 11000}) == 0.0
|
||||
assert calc({"item_price": 0, "first_offer_price": 11000, "input_price": 10200}) == pytest.approx(800 / 11000)
|
||||
assert calc({"input_price": 9800}) == 0.0 # 기준가 전무(과거 세션 호환)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -87,3 +87,59 @@ def test_client_step_and_variable_mapping_load():
|
||||
assert csm["가격협상_확인"] == "가격협상"
|
||||
vm = repo.variable_mapping()
|
||||
assert vm["인터넷 최저가"] == "internet_min_price"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_card_script_file_mode_default():
|
||||
"""기본(source_type='file'): resolve_card_script 가 파일 카드 멘트를 반환(하위호환)."""
|
||||
repo = _repo()
|
||||
assert repo._config.cards.source_type == "file"
|
||||
# action 0 파일 멘트가 변수 치환되어 나온다 (DB 무접근)
|
||||
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800})
|
||||
assert out and "9800" in out
|
||||
|
||||
|
||||
class _FakeCardRepo:
|
||||
"""ICardScriptRepository 더블 — DB 없이 카드코드→멘트 매핑만 흉내(세션 인자 무시)."""
|
||||
|
||||
def __init__(self, by_number: dict):
|
||||
self._by = by_number
|
||||
|
||||
async def get_script_by_number(self, cdb, number):
|
||||
from common.enums import ErrorType
|
||||
return ErrorType.SUCCESS, self._by.get(number)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_card_script_db_mode_prefers_db(monkeypatch):
|
||||
"""source_type='backoffice_db': card.nego_cards.script(정본)를 파일보다 우선 사용 + 마커 보존."""
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce")
|
||||
cfg.cards.source_type = "backoffice_db"
|
||||
fake = _FakeCardRepo({"NGC-A001": "DB 편집 멘트 **{input_price}원** 검토 중입니다."})
|
||||
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
|
||||
|
||||
# execute_lambda 를 세션 없이 콜백만 실행하도록 대체(순수 단위검증)
|
||||
async def _fake_lambda(_db, _wr, func):
|
||||
return await func(None)
|
||||
from negotiation.chat.service import script_repository as _sr
|
||||
monkeypatch.setattr(_sr.DB_SESSION_MNG, "execute_lambda", _fake_lambda)
|
||||
|
||||
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800})
|
||||
assert out == "DB 편집 멘트 **9800원** 검토 중입니다." # DB 우선 + 마커(**) 불투명 보존 + 변수 치환
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resolve_card_script_db_mode_falls_back_to_file(monkeypatch):
|
||||
"""DB 에 해당 카드 멘트가 없으면 파일(scripts_cards.json)로 폴백."""
|
||||
cfg = TenantConfigLoader(tenants_dir=_TENANTS_DIR, cache_ttl_seconds=0).load("ktcommerce")
|
||||
cfg.cards.source_type = "backoffice_db"
|
||||
fake = _FakeCardRepo({}) # DB 미보유
|
||||
repo = ScriptRepository(cfg, _TENANTS_DIR, card_repo=fake)
|
||||
|
||||
async def _fake_lambda(_db, _wr, func):
|
||||
return await func(None)
|
||||
from negotiation.chat.service import script_repository as _sr
|
||||
monkeypatch.setattr(_sr.DB_SESSION_MNG, "execute_lambda", _fake_lambda)
|
||||
|
||||
out = await repo.resolve_card_script(0, "NGC-A001", {"input_price": 9800})
|
||||
assert out and "9800" in out # 파일 폴백 멘트
|
||||
Reference in new issue
Block a user