o2o-negosium-original/agent/negotiation/chat/service/chat_session_repository.py
hbyang ed175c5b65 [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>
2026-07-07 09:44:21 +09:00

77 lines
3.1 KiB
Python

"""ChatSessionRepository — /chat 세션 상태 DB 영속화 (P8-A).
인메모리 대신 learning.chat_sessions 에 진행 상태를 저장 → 서버 재시작/멀티워커 안전.
company_id 스코프. ChatSession(dataclass) ↔ row 직렬화.
인터페이스(IChatSessionRepository) + 구현 형식 — backend crud 패턴 준용(테스트 더블 주입 가능).
"""
import uuid
from abc import ABC, abstractmethod
from typing import Optional
from sqlalchemy import select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import ChatSessionRow
from common.enums import DBType, DBWRType, ErrorType
from common.utils.gtime import GTime
from negotiation.chat.service.chat_engine import ChatSession
class IChatSessionRepository(ABC):
@abstractmethod
async def get(self, session_id: Optional[str]) -> Optional[ChatSession]:
"""세션 조회(자사 company_id 스코프). 없으면 None."""
pass
@abstractmethod
async def save(self, session: ChatSession) -> ErrorType:
"""진행 상태 upsert(재시작/멀티워커 안전)."""
pass
class ChatSessionRepository(IChatSessionRepository):
def __init__(self, company_id: str):
self.company_id = company_id
async def get(self, session_id: Optional[str]) -> Optional[ChatSession]:
if not session_id:
return None
def _q(s: AsyncSession):
stmt = select(ChatSessionRow).where(
ChatSessionRow.session_id == session_id,
ChatSessionRow.company_id == self.company_id,
).limit(1)
return DB_SESSION_MNG.execute(s, stmt)
err, rows = await DB_SESSION_MNG.execute_lambda(DBType.MAIN.value, DBWRType.DB_READ.value, _q)
if err != ErrorType.SUCCESS or not rows:
return None
r = rows[0]
return ChatSession(
session_id=str(r.session_id), tenant_id=r.tenant_id, company_id=r.company_id,
rq_type=r.rq_type, step=r.step, context=dict(r.context or {}),
used_action_ids=set(r.used_action_ids or []), action_space_size=r.action_space_size,
ended=r.ended,
)
async def save(self, session: ChatSession) -> ErrorType:
values = dict(
session_id=session.session_id, company_id=session.company_id, tenant_id=session.tenant_id,
rq_type=session.rq_type, step=session.step, context=session.context,
used_action_ids=sorted(session.used_action_ids), action_space_size=session.action_space_size,
ended=session.ended, updated_at=GTime.UTC(),
)
def _do(s: AsyncSession):
stmt = pg_insert(ChatSessionRow.__table__).values(**values).on_conflict_do_update(
index_elements=[ChatSessionRow.session_id],
set_={k: values[k] for k in ("step", "context", "used_action_ids", "ended", "updated_at")},
)
return DB_SESSION_MNG.add(s, stmt)
return await DB_SESSION_MNG.execute_lambda_run([DBType.MAIN.value], [_do])