[refactor] backend services/router 정리 — chat 분리·staticmethod 집약·protocol 문서화·테스트 보강
- router: 채팅 라우터/프로토콜을 negotiation/ 에서 chat/ 으로 분리(git mv, URL 유지). chat_protocol.py → chat/protocol.py (폴더당 protocol.py convention 복원), router 등록·import 갱신. - chat_service: 순수 헬퍼/매퍼를 모듈 함수 → 클래스 @staticmethod 로 이동하고 클래스 상단에 집약. - protocol: Req 모델 + 코드/enum 필드에 Field(description=...) 추가(Swagger 노출), Req 문자열 필드에 max_length(DB 컬럼 정합) 추가 → 초과 입력이 DB 오류 대신 422. - models: updated_at 에 onupdate 추가 → UPDATE 시 자동 갱신(negodata convention 일치). - tests: negotiation reject e2e 6케이스 + chat 순수 헬퍼 단위 4케이스 추가(45→55 passed). - enums: 장황한 주석/docstring 축약(코드값 변경 없음). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
b4dc862912
commit
1a933409a3
10 files changed
+261
-177
No files matched your search
@@ -0,0 +1,58 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from fastapi.security import HTTPAuthorizationCredentials
|
||||
|
||||
from common.models.gmodel import UserInfo
|
||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, security
|
||||
from services.chat_service import ChatService
|
||||
from .protocol import Req_ChatSend, Res_ChatInit, Res_ChatMessages, Res_ChatSend
|
||||
|
||||
# URL 은 협상 세션의 하위 리소스라 prefix 는 /v1/negotiation 유지(파일만 chat/ 로 분리).
|
||||
router = APIRouter(prefix="/v1/negotiation", tags=["Chat"], responses={404: {"description": "Not found"}})
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/sessions/{session_id}/chat/init",
|
||||
response_model=Res_ChatInit,
|
||||
summary="채팅 진입(상품·견적 메타)",
|
||||
description="채팅 화면 진입용. 상품/견적 정보 + 현재 세션 상태 + 마감 시각(타이머)을 반환한다. 소유(공급사) 검증.",
|
||||
)
|
||||
async def chat_init(
|
||||
session_id: str,
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: ChatService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.init(user_info, credentials.credentials, session_id))
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/sessions/{session_id}/chat/messages",
|
||||
response_model=Res_ChatMessages,
|
||||
summary="대화 히스토리",
|
||||
description="세션의 대화 말풍선 목록(seq 오름차순). 비어 있고 협상중이면 오프닝 메시지를 생성해 포함한다.",
|
||||
)
|
||||
async def chat_messages(
|
||||
session_id: str,
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: ChatService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.messages(user_info, credentials.credentials, session_id))
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/sessions/{session_id}/chat/send",
|
||||
response_model=Res_ChatSend,
|
||||
summary="협상 한 턴 전송",
|
||||
description="유저 입력을 보내고 agent 가 만든 봇 응답 1건을 반환한다(append-only). 종료 시 세션 입찰을 확정한다.",
|
||||
)
|
||||
async def chat_send(
|
||||
session_id: str,
|
||||
req: Req_ChatSend,
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: ChatService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(
|
||||
await service.send(user_info, credentials.credentials, session_id, req.user_input_type, req.user_input)
|
||||
)
|
||||
@@ -0,0 +1,96 @@
|
||||
"""채팅(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 = ""
|
||||
md_email: str = ""
|
||||
md_phone_number: str = ""
|
||||
item_code: str = ""
|
||||
item_name: str = ""
|
||||
item_spec: str = ""
|
||||
item_moq: str = ""
|
||||
item_model: str = ""
|
||||
item_maker: str = ""
|
||||
item_isVAT: bool = False
|
||||
item_lead_time: str = ""
|
||||
item_display_date: str = ""
|
||||
item_delivery_type: str = ""
|
||||
final_price: int = 0
|
||||
nego_start_date: str = ""
|
||||
nego_end_date: str = ""
|
||||
supplier_name: str = ""
|
||||
supplier_manager_name: str = ""
|
||||
supplier_manager_email: str = ""
|
||||
supplier_manager_phone: str = ""
|
||||
delivery_type: Optional[str] = None
|
||||
|
||||
|
||||
# 말풍선 한 건. sender 는 ChatSender 정수 코드(1=BOT, 2=USER)로 내려가고 라벨 매핑은 프론트가 한다.
|
||||
class ChatMessage(WebPacketProtocol):
|
||||
chat_id: str = ""
|
||||
session_id: str = ""
|
||||
seq: int = 0
|
||||
sender: int = Field(0, description="발신자 코드 (ChatSender: 1=BOT, 2=USER)")
|
||||
script: str = ""
|
||||
user_input_type: Optional[str] = Field(None, description="유저 입력 종류: text|percent|price")
|
||||
step: str = ""
|
||||
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 = False
|
||||
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 = ""
|
||||
session_status: int = Field(0, description="세션 상태 코드 (SessionStatus: 1=생성 2=진행중 3=완료 4=미참여 5=거부)")
|
||||
quotation_id: str = ""
|
||||
quotation_end_time: str = Field("", description="견적 마감 시각 (ISO 8601, 타이머용)")
|
||||
quotation_memo: str = ""
|
||||
item_id: str = ""
|
||||
item_name: str = ""
|
||||
item_code: str = ""
|
||||
item_image: str = ""
|
||||
item_price: int = 0
|
||||
item_model_name: str = ""
|
||||
item_maker_name: str = ""
|
||||
item_spec: str = ""
|
||||
item_lead_time: str = ""
|
||||
item_min_order_quantity: str = ""
|
||||
item_vat_yn: Optional[bool] = None
|
||||
item_delivery_fee_yn: Optional[bool] = None
|
||||
|
||||
|
||||
# 대화 히스토리(재진입 복원)
|
||||
class Res_ChatMessages(Res_WebPacketProtocol):
|
||||
items: list[ChatMessage] = []
|
||||
|
||||
|
||||
# 한 턴 전송. 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] = None
|
||||
session_status: int = 0
|
||||
Reference in new issue
Block a user