o2o-negosium-original/backend/router/v1/chat/protocol.py
Mina Choi 6eb4dc26f8 [feat] negosium·negodata: 협상 거부 흐름 정리 + 오프라인 계약가 낙찰 + 견적 상세 리모델링
협상 불가 사유를 내면 500 이 나고, 거부 폼은 목록·채팅이 따로 놀았으며,
제출한 내용을 다시 볼 방법이 없었다. 결렬 건은 협력사가 낸 거부가를 계약가로
간주해 낙찰시켜 절감 통계가 음수로 뒤집힐 수 있었고, 견적 상세는 판정 가격이
세 곳에 흩어져 대화 탭에선 아예 보이지 않았다.

agent
- 결렬 종료 로깅 크래시 수정 — _log 를 action_id 기반으로 되돌리고 선택 근거
  (Q·UCB·방문수)는 decision/policy 가 있을 때만 채운다. 종료 행은 카드 선택이
  없고 policy.update 뒤라 값을 넣으면 학습 화면 집계가 오염된다

negosium
- 거부 폼을 목록·채팅 공용 컴포넌트 하나로 통일(사유 3종 + 공급 희망가·의견 선택)
- 거부 사유 열람 — 목록에 '거부 사유 보기'(부가정보 보기와 같은 규격), 채팅
  재진입 시 대화 끝에 거부 내역 카드. 목록·채팅 init 응답에 reject_reason·reject_price 추가
- 자유 입력 거부("협상 포기합니다")가 사유 NULL 로 저장되던 문제 수정 — 폼 마커가
  없으면 원문을 사유로 쓰고, 문장 속 숫자를 희망가로 오인하지 않는다
- koreanNumber 를 전역 lib 으로 이동(공용 폼이 쓴다)

negodata
- 직접 낙찰에 계약가 입력 — 결렬·미응찰 건을 오프라인으로 다시 협상한 결과를
  담당자가 확정해 넣는다. 후보는 초청 협력사 전부(가격 미제출도 포함),
  계약가는 sessions.custom.offline_award 에 근거·작성자·시각과 함께 남긴다
- 통계 계약가 = 담당자 확정가 우선, 없으면 투찰가. 거부가를 계약가로 치던 파생 제거.
  KPI 에 오프라인 반영 건수 추가
- 견적 상세 리모델링 — 가격 레일(앵커링가/투찰현황 · 목표가 · 타결 상한가 · 결과가)을
  시트에 고정해 접힘·탭 전환에도 남기고, 스펙트럼에 타결 판정선과 구간색 추가.
  라벨은 폭을 실측해 두 레인으로 배치(겹침 불가). 상품·마감시각 등 전 행 동일 컬럼 제거,
  협상현황에 부가정보 노출, 1:1 은 협력사·세션상태를 결과 밴드로 올림

테스트: negosium 58 · negodata 110 통과. 프론트 빌드/린트 통과.
2026-08-12 10:25:26 +09:00

102 lines
6.8 KiB
Python

"""채팅(chat) 라우터 프로토콜 — backend ↔ 프론트 계약.
agent Res_Chat → 이 ChatMessage 매핑:
step→step, client_step→display_step, script→script,
input_mode→next_input_mode, input_options→next_input_type, chat_end→chat_end,
bot_chat_type→bot_chat_type, indicator_value→indicator_value.
summary(요약카드 데이터)는 backend 가 비즈니스 데이터로 조립해 채운다.
"""
from typing import Optional
from pydantic import Field
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
# 협상 결과 요약 카드(summaryRSP/summaryCM)에 표시할 데이터. 종료 스텝에서만 채워 내려간다.
# 필드명은 프론트 ChatSummary 타입과 1:1 (item_isVAT 등 camelCase 유지).
class ChatSummary(WebPacketProtocol):
md_name: str = Field("", description="견적 담당 MD(고객사 담당자) 이름")
md_email: str = Field("", description="MD 이메일")
md_phone_number: str = Field("", description="MD 연락처")
item_code: str = Field("", description="상품 코드")
item_name: str = Field("", description="상품명")
item_spec: str = Field("", description="상품 규격")
item_moq: str = Field("", description="최소 주문 수량")
item_model: str = Field("", description="모델명")
item_maker: str = Field("", description="제조사")
item_isVAT: bool = Field(False, description="VAT 포함 여부")
item_lead_time: str = Field("", description="배송 리드타임(일)")
item_display_date: str = Field("", description="상품 게시일(견적 시작 시각, ISO 8601)")
item_delivery_type: str = Field("", description="상품 기본 배송유형 라벨(선택값 없을 때 폴백용)")
final_price: int = Field(0, description="최종 제시가(원)")
nego_start_date: str = Field("", description="협상 시작 시각(견적 시작, ISO 8601)")
nego_end_date: str = Field("", description="협상 종료 시각(견적 마감, ISO 8601)")
supplier_name: str = Field("", description="공급사명")
supplier_manager_name: str = Field("", description="공급사 담당자 이름")
supplier_manager_email: str = Field("", description="공급사 담당자 이메일")
supplier_manager_phone: str = Field("", description="공급사 담당자 연락처")
delivery_type: Optional[str] = Field(None, description="재견적 '배송형태선택'에서 공급사가 고른 배송형태 라벨(재협상은 단계 없어 null)")
# 말풍선 한 건. sender 는 ChatSender 정수 코드(1=BOT, 2=USER)로 내려가고 라벨 매핑은 프론트가 한다.
class ChatMessage(WebPacketProtocol):
chat_id: str = Field("", description="채팅 메시지 식별자(uuid)")
session_id: str = Field("", description="소속 협상 세션 uuid")
seq: int = Field(0, description="세션 내 메시지 순번")
sender: int = Field(0, description="발신자 코드 (ChatSender: 1=BOT, 2=USER)")
script: str = Field("", description="말풍선 본문 텍스트")
user_input_type: Optional[str] = Field(None, description="유저 입력 종류: text|percent|price")
step: str = Field("", description="agent 내부 단계 코드")
display_step: str = Field("", description="agent client_step (표시용 단계)")
next_input_mode: Optional[str] = Field(None, description="다음 입력 모드: confirm|yes_no|percent|price|delivery_type")
next_input_type: Optional[list[str]] = Field(None, description="다음 입력 선택지(버튼 라벨)")
chat_end: bool = Field(False, description="이 메시지로 협상이 종료되는지 여부")
indicator_value: Optional[float] = Field(None, description="협상 지표(1~99). 가격협상 턴에 표시")
bot_chat_type: Optional[str] = Field(None, description="폼 종류: summaryRSP|summaryCM|rejectRSP|rejectCM|indicator")
summary: Optional[ChatSummary] = Field(None, description="summaryRSP/summaryCM 일 때만 채워짐")
# 채팅 진입 — 상품/견적 메타 + 현재 세션 상태 + 마감 시각(타이머용)
class Res_ChatInit(Res_WebPacketProtocol):
session_id: str = Field("", description="협상 세션 uuid")
session_status: int = Field(0, description="세션 상태 코드 (SessionStatus: 1=생성 2=진행중 3=완료 4=미참여 5=거부)")
quotation_id: str = Field("", description="소속 견적 uuid")
qt_number: str = Field("", description="견적번호(EST-...)")
quotation_end_time: str = Field("", description="견적 마감 시각 (ISO 8601, 타이머용)")
quotation_memo: str = Field("", description="견적 메모")
item_id: str = Field("", description="상품 uuid")
item_name: str = Field("", description="상품명")
item_code: str = Field("", description="상품 코드")
item_image: str = Field("", description="상품 이미지 URL")
item_price: int = Field(0, description="상품 가격(원)")
item_model_name: str = Field("", description="모델명")
item_maker_name: str = Field("", description="제조사")
item_spec: str = Field("", description="상품 규격")
item_lead_time: str = Field("", description="배송 리드타임(일)")
item_min_order_quantity: str = Field("", description="최소 주문 수량")
item_vat_yn: Optional[bool] = Field(None, description="VAT 포함 여부(미설정 시 null)")
item_delivery_fee_yn: Optional[bool] = Field(None, description="배송비 포함 여부(미설정 시 null)")
custom: dict = Field(default_factory=dict, description="협상완료 부가정보 기존 입력값(sessions.custom). 재진입 시 폼 프리필용")
reject_reason: str = Field("", description="협상 거부 시 제출한 사유. 거부 건이 아니면 빈 문자열")
reject_price: Optional[int] = Field(None, description="협상 거부 시 함께 낸 공급 희망 가격(원). 미입력이면 null")
labels: dict = Field(default_factory=dict, description="회사 커스텀 라벨(companies.settings.labels). 상품 상세 필드명(예: lead_time) 치환용. 없으면 프론트 기본값")
# 대화 히스토리(재진입 복원)
class Res_ChatMessages(Res_WebPacketProtocol):
items: list[ChatMessage] = Field(default_factory=list, description="대화 말풍선 목록 (seq 오름차순)")
# 한 턴 전송. user_input 은 버튼 텍스트 또는 가격/퍼센트 문자열.
class Req_ChatSend(WebPacketProtocol):
user_input_type: Optional[str] = Field(None, description="유저 입력 종류: text|percent|price")
user_input: str = Field("", description="버튼 선택 텍스트 또는 가격/퍼센트 문자열")
# append-only: 새 봇 메시지 1건 + 갱신된 세션 상태만 반환(전체 refetch 회피)
class Res_ChatSend(Res_WebPacketProtocol):
message: Optional[ChatMessage] = Field(None, description="새로 생성된 봇 메시지 1건(append-only)")
session_status: int = Field(0, description="갱신된 세션 상태 코드 (SessionStatus)")