[feat] agent: Req_Chat 슬림화 — 협상 컨텍스트를 DB 조회로 전환 + CRUD 계층 도입

- Req_Chat 을 session_id/user_input/client_step 3필드로 축소 — rq_type·목표가·앵커·품목가·
  매출액·유통코드·파트너 유형·수용률 필드 전부 제거
- NegotiationContextLoader 신설: 세션 시작 시 공유 DB 1회 조회로 컨텍스트 확정
  · rq_type = sessions.qt_type ({1,3}→재협상 / {2,4}→재견적)
  · anchor = sessions.anchoring_price(박제) — NULL 이면 무할인 폴백 anchor=target (v1.2 정책 승계)
  · 매출액 = suppliers.total_revenue(KTC 미러), 유통코드 = quotations.supplier_type 매핑
  · 파트너 유형 = 상품별 distinct supplier 수 → PartnerType enum(0=NONE/1=SINGLE/2=MULTIPLE)
- 가격 수용률은 세션 내 동적 계산: max(0, (첫 제시가−현재가)/첫 제시가)
- DB 쿼리를 backend crud 패턴으로 분리: INegoContextCRUD(ABC)+NegoContextCRUD,
  IChatSessionRepository 인터페이스 추가 (테스트 더블 주입 가능)
- 와일드카드 1% 수락 시 합의가=offer_1pct 반영 + Res_Chat.settled_price 신설 —
  backend 요약/입찰가가 이를 최우선 사용 (19,800원 수락이 20,000원으로 기록되던 버그 수정)
- backend: agent 전송 바디 3필드로 축소, 앵커/파트너 조회 메서드 제거,
  test_anchoring_chat 을 새 구조로 재작업(박제 소비/폴백 검증은 agent 테스트로 이관)
- 데모 페이지(/demo·negotiation_demo.html) 제거 — 컨텍스트 주입 경로 폐지로 무의미
- 테스트: agent 83/83, backend 57/57 (컨텍스트 로더 실데이터 왕복 4종 + CRUD 더블 검증 포함)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
HyeongBaeYangandClaude Fable 5 committed 2026-07-07 09:44:21 +09:00
1 parent 1ac42ddc9c
commit ed175c5b65
18 files changed
+641 -267

No files matched your search

+44 -2
View File
@@ -31,7 +31,7 @@ async def _run(svc, eng, turns):
"""turns: user_input 리스트(첫 None=시작). 반환: 응답 리스트."""
sid, out = None, []
for ui in turns:
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input=ui, rq_type="재협상"))
r = await svc.chat(eng, Req_Chat(session_id=sid, user_input=ui))
sid = r.session_id
out.append(r)
if r.chat_end:
@@ -76,6 +76,48 @@ async def test_full_conversation_reaches_completion(db_engine):
assert cnt >= 1
@pytest.mark.asyncio
async def test_wildcard_1pct_accept_settles_at_offer_price(db_engine):
"""와일드카드 1% 인하 제안을 '예'로 수락하면 합의가는 인하 제안가(offer_1pct)여야 한다.
회귀: 수락해도 input_price 가 직전 제시가로 남아 요약/입찰가가 원래 가격(예: 20000)으로
잡히던 버그 — settled_price 가 인하가(예: 19800)로 내려와야 한다.
"""
reset_sessions()
eng = await _reg().get_engine("ktcommerce")
svc = ChatService()
# anchor=9900(기본). 10000 은 anchor*1.02(10098) 이내 → wild_card_1pct 발동, offer_1pct=9900.
out = await _run(svc, eng, [None, "확인", "예", "확인", "10000", "예", "예",
"협상 내용을 확인했으며, 이의가 없음에 동의합니다."])
steps = [r.step for r in out]
assert "wild_card_1pct" in steps
# 수락 후 협상완료(요약 턴)·협상종료(종료 턴) 모두 합의가 = 인하 제안가 9900
done = [r for r in out if r.step in ("협상완료", "협상종료")]
assert done and all(r.settled_price == 9900 for r in done)
def test_partner_type_enum_mapping():
"""PartnerType 계약값(0=NONE/1=SINGLE/2=MULTIPLE)과 수→유형 매핑."""
from negotiation.qtable.domain.model.snapshot import PartnerType
assert PartnerType.NONE == 0 and PartnerType.SINGLE == 1 and PartnerType.MULTIPLE == 2
assert PartnerType.from_count(0) is PartnerType.NONE
assert PartnerType.from_count(1) is PartnerType.SINGLE
assert PartnerType.from_count(2) is PartnerType.MULTIPLE
assert PartnerType.from_count(7) is PartnerType.MULTIPLE
def test_acceptance_ratio_dynamic_calc():
"""가격 수용률 동적 계산 — 첫 제시가 대비 양보율. 첫 제시/미기록=0, 인상 시 0 클립."""
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 # 과거 세션 호환(첫 제시가 미기록)
@pytest.mark.asyncio
async def test_priority_completes_without_wildcard(db_engine):
reset_sessions()
@@ -95,7 +137,7 @@ async def test_tenant_brand_isolation(db_engine):
reset_sessions()
svc = ChatService()
reg = _reg()
ik = await svc.chat(await reg.get_engine("imarketkorea"), Req_Chat(session_id=None, rq_type="재협상"))
ik = await svc.chat(await reg.get_engine("imarketkorea"), Req_Chat(session_id=None))
assert "데모상사 B" in ik.script