feat(backend): 협상 채팅(chat) API + agent 위임
- /v1/negotiation/sessions/{id}/chat/{init,messages,send} 추가
- agent(9500) 위임 어댑터(IAgentClient) + mock(use_mock) 격리 → agent 미연동 시 1402 graceful degrade
- negotiation.chats 메시지 영속화(meta JSONB) + 종료 시 세션 입찰/거부 확정(단일 트랜잭션)
- 동시전송 가드(유저 메시지 pre-claim/CHAT_IN_PROGRESS) + 실패 시 롤백, 마감/만료 분기, init 만료 정리
- ChatSender enum, chat 에러코드(1400~1403), chats ORM 모델, AgentConfig
- 테스트 10건(test_chat.py), AGENT_INTEGRATION.md 연동 규약 문서
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
d199c1dec1
commit
dcce82a630
14 files changed
+1124
-2
No files matched your search
@@ -0,0 +1,153 @@
|
||||
"""협상 에이전트(agent, 포트 9500) 호출 클라이언트.
|
||||
|
||||
backend 는 /chat 한 턴을 agent 로 위임한다(README: "backend 가 /chat 을 agent 로 위임").
|
||||
agent 의 계약(Req_Chat/Res_Chat)에 맞춘 어댑터. agent 가 아직 없거나 로컬에서 미연동일 때를 위해
|
||||
mock 구현을 두고 config(AgentConfig.use_mock) 로 선택한다 — 이 격리 덕에 backend/프론트를
|
||||
agent 완성 여부와 무관하게 통합 테스트할 수 있다.
|
||||
|
||||
agent 응답(Res_Chat) → AgentTurn 매핑:
|
||||
step, client_step, script, input_mode(=next_input_mode), input_options(=next_input_type),
|
||||
chat_end, outcome, card_id, indicator_value.
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
|
||||
from common.logger import LOG
|
||||
from config.server_configs import agent_config
|
||||
|
||||
|
||||
@dataclass
|
||||
class AgentTurn:
|
||||
"""agent 한 턴 응답(Res_Chat) 의 backend 표현."""
|
||||
|
||||
session_id: Optional[str] = None
|
||||
step: str = ""
|
||||
client_step: str = ""
|
||||
script: str = ""
|
||||
input_mode: Optional[str] = None # 프론트 next_input_mode 로 매핑
|
||||
input_options: Optional[list[str]] = None # 프론트 next_input_type 로 매핑
|
||||
chat_end: bool = False
|
||||
outcome: Optional[str] = None # "success" | "failure" (종료 시)
|
||||
card_id: Optional[str] = None
|
||||
indicator_value: Optional[float] = None
|
||||
ok: bool = True # agent 호출 성공 여부 (False 면 CHAT_AGENT_UNAVAILABLE)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AgentChatContext:
|
||||
"""새 세션 시작 시 agent 에 주입하는 협상 컨텍스트. 기존 세션이면 user_input 만 의미 있다."""
|
||||
|
||||
tenant_id: str # X-Tenant-ID = 견적(갑) 회사 company_id
|
||||
rq_type: str = "재협상" # 재협상 | 재견적
|
||||
target_price: int = 0 # 갑 목표 매입가(원)
|
||||
anchor_price: int = 0 # 앵커링가(목표가보다 낮음)
|
||||
turn: int = 0 # 직전까지의 봇 턴 수(mock 진행용; 실제 agent 는 무시)
|
||||
extra: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
class IAgentClient(ABC):
|
||||
@abstractmethod
|
||||
async def chat(self, session_id: Optional[str], user_input: Optional[str], ctx: AgentChatContext) -> AgentTurn:
|
||||
"""협상 한 턴. session_id 없으면 새 세션 시작. user_input 으로 진행(버튼 텍스트/가격)."""
|
||||
...
|
||||
|
||||
|
||||
class HttpAgentClient(IAgentClient):
|
||||
"""실제 agent(9500) 위임 구현. agent POST /v1/chat 호출."""
|
||||
|
||||
async def chat(self, session_id: Optional[str], user_input: Optional[str], ctx: AgentChatContext) -> AgentTurn:
|
||||
import httpx # 지연 import — mock 모드에서는 httpx 의존을 강제하지 않는다.
|
||||
|
||||
body = {
|
||||
"session_id": session_id, # 핸드오프 #1: agent 가 이 값을 세션 키로 그대로 사용해야 함
|
||||
"rq_type": ctx.rq_type,
|
||||
"user_input": user_input,
|
||||
"target_price": ctx.target_price,
|
||||
"anchor_price": ctx.anchor_price,
|
||||
}
|
||||
headers = {"X-Tenant-ID": ctx.tenant_id} # 핸드오프 #2
|
||||
try:
|
||||
async with httpx.AsyncClient(base_url=agent_config.base_url, timeout=agent_config.timeout_sec) as cli:
|
||||
resp = await cli.post("/v1/chat", json=body, headers=headers)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(f"[AgentClient] agent 호출 실패: {ex}")
|
||||
return AgentTurn(ok=False)
|
||||
|
||||
return AgentTurn(
|
||||
session_id=data.get("session_id"),
|
||||
step=data.get("step") or "",
|
||||
client_step=data.get("client_step") or "",
|
||||
script=data.get("script") or "",
|
||||
input_mode=data.get("input_mode"),
|
||||
input_options=data.get("input_options"),
|
||||
chat_end=bool(data.get("chat_end", False)),
|
||||
outcome=data.get("outcome"),
|
||||
card_id=data.get("card_id"),
|
||||
indicator_value=data.get("indicator_value"),
|
||||
ok=True,
|
||||
)
|
||||
|
||||
|
||||
class MockAgentClient(IAgentClient):
|
||||
"""agent 미연동용 결정론적 mock. ctx.turn(직전 봇 턴 수)으로 협상 단계를 진행한다.
|
||||
|
||||
플로우(핵심만): 0=인사(확인) → 1=품목안내(확인) → 2=가격협상(가격입력) → 3+=수락/종료.
|
||||
"""
|
||||
|
||||
_SCRIPT = [
|
||||
("서비스안내", "협상에 참여해 주셔서 감사합니다. 시작하시겠어요?", "confirm", ["네, 시작할게요"]),
|
||||
("협상품목안내", "협상 품목을 확인해 주세요. 가격 협상을 진행할까요?", "confirm", ["가격 협상 진행"]),
|
||||
("가격협상", "희망 공급가를 입력해 주세요.", "price", None),
|
||||
]
|
||||
|
||||
async def chat(self, session_id: Optional[str], user_input: Optional[str], ctx: AgentChatContext) -> AgentTurn:
|
||||
sid = session_id or "mock-session"
|
||||
turn = ctx.turn
|
||||
|
||||
# 공급사가 협상 포기/거부 의사를 밝히면 실패로 종료(거부)한다.
|
||||
if user_input and ("포기" in user_input or "거부" in user_input):
|
||||
return AgentTurn(
|
||||
session_id=sid, step="협상종료", client_step="협상종료",
|
||||
script="협상이 종료되었습니다.", input_mode=None, input_options=None,
|
||||
chat_end=True, outcome="failure",
|
||||
)
|
||||
|
||||
if turn < len(self._SCRIPT):
|
||||
step, script, mode, options = self._SCRIPT[turn]
|
||||
return AgentTurn(
|
||||
session_id=sid, step=step, client_step=step, script=script,
|
||||
input_mode=mode, input_options=options, chat_end=False,
|
||||
)
|
||||
|
||||
# 가격 제시 이후: 목표가 이하면 수락 종료, 아니면 한 번 더 제안 요청
|
||||
price = _parse_price(user_input)
|
||||
if price is not None and ctx.target_price and price <= ctx.target_price:
|
||||
return AgentTurn(
|
||||
session_id=sid, step="협상종료", client_step="협상종료",
|
||||
script=f"제안하신 {price:,}원으로 합의되었습니다. 감사합니다.",
|
||||
input_mode=None, input_options=None, chat_end=True, outcome="success",
|
||||
card_id="NGC-MOCK", indicator_value=100.0,
|
||||
)
|
||||
return AgentTurn(
|
||||
session_id=sid, step="가격협상", client_step="가격협상",
|
||||
script="조금 더 조정된 가격을 제안해 주시겠어요?",
|
||||
input_mode="price", input_options=None, chat_end=False,
|
||||
card_id="NGC-MOCK", indicator_value=50.0,
|
||||
)
|
||||
|
||||
|
||||
def _parse_price(text: Optional[str]) -> Optional[int]:
|
||||
"""'1,500원' / '1500' 등에서 정수 가격을 파싱한다. 실패 시 None."""
|
||||
if not text:
|
||||
return None
|
||||
digits = "".join(ch for ch in text if ch.isdigit())
|
||||
return int(digits) if digits else None
|
||||
|
||||
|
||||
def get_agent_client() -> IAgentClient:
|
||||
"""config 에 따라 mock/실제 클라이언트를 반환한다(FastAPI Depends 용)."""
|
||||
return MockAgentClient() if agent_config.use_mock else HttpAgentClient()
|
||||
@@ -0,0 +1,334 @@
|
||||
"""ChatService — 채팅 페이지 오케스트레이션.
|
||||
|
||||
backend 가 협상 한 턴을 agent(9500) 로 위임하고, 말풍선 로그(negotiation.chats)를 영속화하며,
|
||||
종료 시 세션 상태(negotiation.sessions)를 전이한다. agent 는 외부 고정 계약(agent_client 어댑터).
|
||||
|
||||
- init : 상품/견적 메타 + 현재 세션 상태 (타이머용 마감 시각 포함)
|
||||
- messages : 대화 히스토리 복원. 비어 있고 협상중이면 agent 오프닝 한 턴을 seed(지연 생성).
|
||||
- send : (검증 → 유저 메시지 저장 → agent 위임 → 봇 메시지 저장 → 종료 시 입찰 확정) 단일 트랜잭션.
|
||||
append-only — 새 봇 메시지 1건만 반환(전체 refetch 회피).
|
||||
"""
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import chats, items, quotations, sessions
|
||||
from common.enums import ChatSender, DBWRType, ErrorType, QuotationStatus, SessionStatus
|
||||
from common.models.gmodel import UserInfo
|
||||
from crud.chat_crud import ChatCRUD, IChatCRUD
|
||||
from crud.session_crud import ISessionCRUD, SessionCRUD
|
||||
from router.v1.negotiation.chat_protocol import ChatMessage, Res_ChatInit, Res_ChatMessages, Res_ChatSend
|
||||
from services.agent_client import AgentChatContext, IAgentClient, get_agent_client
|
||||
from services.auth_service import AuthService
|
||||
|
||||
|
||||
# 가격 허용 범위 배수(목표가 기준). 범위를 벗어난 제시가는 CHAT_PRICE_OUT_OF_RANGE 로 막는다.
|
||||
PRICE_FLOOR_RATIO = 0.3
|
||||
PRICE_CEIL_RATIO = 1.7
|
||||
|
||||
|
||||
class ChatService:
|
||||
def __init__(
|
||||
self,
|
||||
auth: AuthService = Depends(AuthService),
|
||||
session_crud: ISessionCRUD = Depends(SessionCRUD),
|
||||
chat_crud: IChatCRUD = Depends(ChatCRUD),
|
||||
agent: IAgentClient = Depends(get_agent_client),
|
||||
):
|
||||
self.auth = auth
|
||||
self.session_crud = session_crud
|
||||
self.chat_crud = chat_crud
|
||||
self.agent = agent
|
||||
|
||||
# ---- 공통 전처리 ----------------------------------------------------
|
||||
async def _auth_and_own_session(self, user_info: UserInfo, access_token: str, session_id_str: str):
|
||||
"""인증 → 세션 로드 → 소유(공급사) 검증. (SUCCESS, sess) 또는 (err, None)."""
|
||||
err_type, info = await self.auth.authenticate(user_info, access_token)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, None
|
||||
try:
|
||||
session_id = uuid.UUID(session_id_str)
|
||||
except (ValueError, TypeError):
|
||||
return ErrorType.NEGO_NOT_FOUND, None
|
||||
|
||||
err_type, sess = await DB_SESSION_MNG.execute_lambda(
|
||||
sessions.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.get_session_by_id(s, session_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or sess is None:
|
||||
return ErrorType.NEGO_NOT_FOUND, None
|
||||
if str(sess.supplier_id) != info.supplier_id:
|
||||
return ErrorType.NEGO_FORBIDDEN, None
|
||||
return ErrorType.SUCCESS, sess
|
||||
|
||||
# ---- init -----------------------------------------------------------
|
||||
async def init(self, user_info: UserInfo, access_token: str, session_id_str: str) -> Res_ChatInit:
|
||||
res = Res_ChatInit()
|
||||
err_type, sess = await self._auth_and_own_session(user_info, access_token, session_id_str)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
err_type, quote = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.get_quotation_by_id(s, sess.quotation_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or quote is None:
|
||||
res.result.SetResult(ErrorType.NEGO_NOT_FOUND)
|
||||
return res
|
||||
|
||||
err_type, item = await DB_SESSION_MNG.execute_lambda(
|
||||
items.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.chat_crud.get_item_by_id(s, sess.item_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or item is None:
|
||||
res.result.SetResult(ErrorType.NEGO_NOT_FOUND)
|
||||
return res
|
||||
|
||||
# 마감 시간 초과 + 협상생성이면 미참여로 정리 (participate 와 동일 일관성).
|
||||
end = quote.end_time
|
||||
if end is not None and end.tzinfo is None:
|
||||
end = end.replace(tzinfo=timezone.utc)
|
||||
if end is not None and end < datetime.now(timezone.utc) and sess.status == SessionStatus.CREATED.value:
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[sessions.DBType()],
|
||||
[lambda s: self.session_crud.update_session_status(s, sess.session_id, SessionStatus.NOT_PARTICIPATED.value)],
|
||||
)
|
||||
sess.status = SessionStatus.NOT_PARTICIPATED.value
|
||||
|
||||
res.session_id = str(sess.session_id)
|
||||
res.session_status = sess.status
|
||||
res.quotation_id = str(sess.quotation_id)
|
||||
res.quotation_end_time = quote.end_time.isoformat(timespec="seconds") if quote.end_time else ""
|
||||
res.quotation_memo = quote.memo or ""
|
||||
res.item_id = str(item.item_id)
|
||||
res.item_name = item.name or ""
|
||||
res.item_code = item.code or ""
|
||||
res.item_image = item.image_url or ""
|
||||
res.item_price = item.price or 0
|
||||
res.item_model_name = item.model_name or ""
|
||||
res.item_maker_name = item.manufacturer or ""
|
||||
res.item_spec = item.spec or ""
|
||||
res.item_lead_time = str(item.lead_time) if item.lead_time is not None else ""
|
||||
res.item_min_order_quantity = item.moq or ""
|
||||
res.item_vat_yn = item.vat_yn
|
||||
res.item_delivery_fee_yn = item.delivery_fee_yn
|
||||
return res
|
||||
|
||||
# ---- messages -------------------------------------------------------
|
||||
async def messages(self, user_info: UserInfo, access_token: str, session_id_str: str) -> Res_ChatMessages:
|
||||
res = Res_ChatMessages()
|
||||
err_type, sess = await self._auth_and_own_session(user_info, access_token, session_id_str)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
err_type, rows = await DB_SESSION_MNG.execute_lambda(
|
||||
chats.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.chat_crud.list_by_session(s, sess.session_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 비어 있고 협상중이면 agent 오프닝 한 턴을 seed (재진입 시 인사 메시지 보존)
|
||||
if not rows and sess.status == SessionStatus.IN_PROGRESS.value:
|
||||
opening = await self._seed_opening(sess)
|
||||
if opening is not None:
|
||||
res.items = [opening]
|
||||
return res
|
||||
|
||||
res.items = [self._row_to_message(r) for r in rows]
|
||||
return res
|
||||
|
||||
async def _seed_opening(self, sess) -> Optional[ChatMessage]:
|
||||
"""오프닝(턴0) 봇 메시지를 agent 로 생성하고 seq=1 로 저장한다. 동시 진입 충돌은 무시(유니크가 방어)."""
|
||||
ctx = self._agent_context(sess, turn=0)
|
||||
turn = await self.agent.chat(session_id=str(sess.session_id), user_input=None, ctx=ctx)
|
||||
if not turn.ok:
|
||||
return None
|
||||
bot = self._build_bot_chat(sess, seq=1, turn=turn)
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[chats.DBType()], [lambda s: self.chat_crud.insert_message(s, bot)]
|
||||
)
|
||||
return self._chat_to_message(bot)
|
||||
|
||||
# ---- send (핵심) ----------------------------------------------------
|
||||
async def send(self, user_info: UserInfo, access_token: str, session_id_str: str, user_input_type: Optional[str], user_input: str) -> Res_ChatSend:
|
||||
res = Res_ChatSend()
|
||||
|
||||
err_type, sess = await self._auth_and_own_session(user_info, access_token, session_id_str)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 협상중이 아니면 대화 불가
|
||||
if sess.status != SessionStatus.IN_PROGRESS.value:
|
||||
res.result.SetResult(ErrorType.CHAT_NOT_IN_PROGRESS)
|
||||
return res
|
||||
|
||||
# 견적 마감/시간 검증
|
||||
err_type, quote = await DB_SESSION_MNG.execute_lambda(
|
||||
quotations.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.session_crud.get_quotation_by_id(s, sess.quotation_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or quote is None:
|
||||
res.result.SetResult(ErrorType.NEGO_NOT_FOUND)
|
||||
return res
|
||||
if quote.status == QuotationStatus.CLOSED.value:
|
||||
res.result.SetResult(ErrorType.NEGO_QUOTATION_CLOSED)
|
||||
return res
|
||||
end = quote.end_time
|
||||
if end is not None and end.tzinfo is None:
|
||||
end = end.replace(tzinfo=timezone.utc)
|
||||
if end is not None and end < datetime.now(timezone.utc):
|
||||
res.result.SetResult(ErrorType.NEGO_DEADLINE_PASSED)
|
||||
return res
|
||||
|
||||
# 가격 입력이면 범위 검증
|
||||
price = _parse_price(user_input) if user_input_type == "price" else None
|
||||
if user_input_type == "price":
|
||||
if price is None or not _in_price_range(price, sess.target_price):
|
||||
res.result.SetResult(ErrorType.CHAT_PRICE_OUT_OF_RANGE)
|
||||
return res
|
||||
|
||||
# 직전 메시지(seq/sender) — 동시전송 가드 + seq 채번
|
||||
err_type, (max_seq, last_sender) = await DB_SESSION_MNG.execute_lambda(
|
||||
chats.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.chat_crud.get_last(s, sess.session_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
# 직전이 유저 메시지면 이전 턴이 아직 처리 중(봇 응답 미도착) → 중복 전송 거절
|
||||
if last_sender == ChatSender.USER.value:
|
||||
res.result.SetResult(ErrorType.CHAT_IN_PROGRESS)
|
||||
return res
|
||||
|
||||
err_type, turn_no = await DB_SESSION_MNG.execute_lambda(
|
||||
chats.DBType(), DBWRType.DB_READ.value,
|
||||
lambda s: self.chat_crud.count_bot_messages(s, sess.session_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 유저 메시지 선점(pre-claim): (session_id, seq) 부분 유니크로 동시 전송을 직렬화한다.
|
||||
# 경합에서 밀리면(같은 seq 충돌) agent 를 호출하지 않고 CHAT_IN_PROGRESS 로 거절 → 중복 진행 방지.
|
||||
user_msg = self._build_user_chat(sess, seq=max_seq + 1, user_input=user_input, user_input_type=user_input_type, price=price)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[chats.DBType()], [lambda s: self.chat_crud.insert_message(s, user_msg)]
|
||||
)
|
||||
if err_type == ErrorType.DB_ALREADY_SAME_KEY:
|
||||
res.result.SetResult(ErrorType.CHAT_IN_PROGRESS)
|
||||
return res
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# agent 위임 (한 턴). 실패 시 선점한 유저 메시지를 롤백 → 재시도 가능.
|
||||
ctx = self._agent_context(sess, turn=turn_no)
|
||||
turn = await self.agent.chat(session_id=str(sess.session_id), user_input=user_input, ctx=ctx)
|
||||
if not turn.ok:
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[chats.DBType()], [lambda s: self.chat_crud.soft_delete_message(s, user_msg.chat_id)]
|
||||
)
|
||||
res.result.SetResult(ErrorType.CHAT_AGENT_UNAVAILABLE)
|
||||
return res
|
||||
|
||||
# 봇 메시지 + 종료 시 확정(성공=DONE+입찰가 / 실패=REJECTED+거부사유·제시가). 한 트랜잭션.
|
||||
bot_msg = self._build_bot_chat(sess, seq=max_seq + 2, turn=turn)
|
||||
funcs = [lambda s: self.chat_crud.insert_message(s, bot_msg)]
|
||||
new_status = sess.status
|
||||
if turn.chat_end:
|
||||
if turn.outcome == "success":
|
||||
new_status = SessionStatus.DONE.value
|
||||
bid = price if price is not None else sess.target_price
|
||||
funcs.append(lambda s: self.chat_crud.finalize_session(s, sess.session_id, new_status, bid_price=bid))
|
||||
else:
|
||||
new_status = SessionStatus.REJECTED.value
|
||||
funcs.append(lambda s: self.chat_crud.finalize_session(
|
||||
s, sess.session_id, new_status,
|
||||
reject_reason=(user_input or None), reject_price=price,
|
||||
))
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run([chats.DBType()], funcs)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
# 봇 저장 실패 시에도 선점 유저 메시지를 롤백해 stuck(CHAT_IN_PROGRESS) 방지.
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[chats.DBType()], [lambda s: self.chat_crud.soft_delete_message(s, user_msg.chat_id)]
|
||||
)
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
res.message = self._chat_to_message(bot_msg)
|
||||
res.session_status = new_status
|
||||
return res
|
||||
|
||||
# ---- 빌더 / 매퍼 ----------------------------------------------------
|
||||
def _agent_context(self, sess, turn: int) -> AgentChatContext:
|
||||
# 핸드오프 #2/#5: X-Tenant-ID 는 견적(갑) 회사 company_id 여야 한다.
|
||||
# 현재 quotation.user_id 만 보유 → 정확한 company_id 해석(company.users 조회)은 agent 연동 시 보완.
|
||||
tenant_id = "" # mock 은 무시. 실제 연동 시 quotation 의 buyer company_id 로 채운다.
|
||||
rq_type = "재협상" if sess.qt_type == 1 else "재견적"
|
||||
anchor = int(sess.target_price * 0.99) if sess.target_price else 0
|
||||
return AgentChatContext(
|
||||
tenant_id=tenant_id, rq_type=rq_type,
|
||||
target_price=int(sess.target_price or 0), anchor_price=anchor, turn=turn,
|
||||
)
|
||||
|
||||
def _build_user_chat(self, sess, seq: int, user_input: str, user_input_type: Optional[str], price: Optional[int]) -> chats:
|
||||
return chats(
|
||||
chat_id=uuid.uuid4(), session_id=sess.session_id, seq=seq,
|
||||
sender=ChatSender.USER.value,
|
||||
target_price=int(price) if price is not None else 0,
|
||||
meta={"script": user_input, "user_input_type": user_input_type},
|
||||
)
|
||||
|
||||
def _build_bot_chat(self, sess, seq: int, turn) -> chats:
|
||||
return chats(
|
||||
chat_id=uuid.uuid4(), session_id=sess.session_id, seq=seq,
|
||||
sender=ChatSender.BOT.value,
|
||||
target_price=int(sess.target_price or 0),
|
||||
meta={
|
||||
"script": turn.script, "step": turn.step, "client_step": turn.client_step,
|
||||
"input_mode": turn.input_mode, "input_options": turn.input_options,
|
||||
"chat_end": turn.chat_end, "card_id": turn.card_id,
|
||||
},
|
||||
)
|
||||
|
||||
def _chat_to_message(self, c: chats) -> ChatMessage:
|
||||
"""방금 만든 chats 객체 → 응답 ChatMessage (DB 재조회 없이)."""
|
||||
meta = c.meta or {}
|
||||
return ChatMessage(
|
||||
chat_id=str(c.chat_id), session_id=str(c.session_id), seq=c.seq, sender=c.sender,
|
||||
script=meta.get("script") or "",
|
||||
user_input_type=meta.get("user_input_type"),
|
||||
step=meta.get("step") or "",
|
||||
display_step=meta.get("client_step") or "",
|
||||
next_input_mode=meta.get("input_mode"),
|
||||
next_input_type=meta.get("input_options"),
|
||||
chat_end=bool(meta.get("chat_end", False)),
|
||||
)
|
||||
|
||||
def _row_to_message(self, r) -> ChatMessage:
|
||||
"""DB 행(chats) → 응답 ChatMessage."""
|
||||
return self._chat_to_message(r)
|
||||
|
||||
|
||||
# ---- 가격 유틸 ----------------------------------------------------------
|
||||
def _parse_price(text: Optional[str]) -> Optional[int]:
|
||||
if not text:
|
||||
return None
|
||||
digits = "".join(ch for ch in text if ch.isdigit())
|
||||
return int(digits) if digits else None
|
||||
|
||||
|
||||
def _in_price_range(price: int, target_price: Optional[int]) -> bool:
|
||||
if not target_price:
|
||||
return price > 0
|
||||
return int(target_price * PRICE_FLOOR_RATIO) <= price <= int(target_price * PRICE_CEIL_RATIO)
|
||||
Reference in new issue
Block a user