[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:
민헌andClaude Opus 4.8 committed 2026-06-25 11:07:54 +09:00
1 parent b4dc862912
commit 1a933409a3
10 files changed
+261 -177

No files matched your search

+40
View File
@@ -14,6 +14,7 @@ import pytest_asyncio
from sqlalchemy import text
from services.agent_client import AgentTurn, IAgentClient, get_agent_client
from services.chat_service import ChatService
TEST_LOGIN_ID = "pytest_chat_user"
TEST_PW = "pytest1234"
@@ -358,3 +359,42 @@ async def test_init_marks_expired_created_as_not_participated(client, chat_seed,
assert body["result"]["success"] is True
assert body["session_status"] == 4 # 미참여로 정리되어 내려옴
assert await _session_status(db_engine, sid) == 4 # DB 도 전이됨
# ---- 순수 헬퍼 단위 테스트 (DB 불필요, ChatService @staticmethod) ----------
def test_parse_price():
assert ChatService._parse_price("530,000원") == 530000 # 콤마/통화기호 제거
assert ChatService._parse_price("abc") is None
assert ChatService._parse_price("") is None
assert ChatService._parse_price(None) is None
def test_in_price_range():
assert ChatService._in_price_range(100000, 100000) is True
assert ChatService._in_price_range(29000, 100000) is False # floor(0.3) 미만
assert ChatService._in_price_range(180000, 100000) is False # ceil(1.7) 초과
assert ChatService._in_price_range(50000, None) is True # 목표가 없으면 양수면 통과
assert ChatService._in_price_range(0, None) is False
def test_input_matches_mode():
f = ChatService._input_matches_mode
assert f(None, "x", "text") is True # 직전 메타 없음 → 제약 없음
assert f({}, "x", "price") is True # input_mode 없음
assert f({"input_mode": "price"}, "100", "price") is True
assert f({"input_mode": "price"}, "예", "text") is False # price 단계에 텍스트
assert f({"input_mode": "percent"}, "5", "percent") is True
assert f({"input_mode": "yes_no"}, "예", "text") is True
assert f({"input_mode": "yes_no"}, "100", "price") is False # 버튼 단계에 가격 숫자
assert f({"input_mode": "delivery_type"}, "픽업", "text") is True
def test_resolve_bot_chat_type():
f = ChatService._resolve_bot_chat_type
assert f(1, "협상완료") == "summaryRSP" # 재협상
assert f(2, "협상완료") == "summaryCM" # 재견적
assert f(1, "협상실패") == "rejectRSP"
assert f(2, "협상실패") == "rejectCM"
assert f(2, "결과제출") == "summaryCM"
assert f(1, "가격협상") is None # 일반 step
assert f(1, None) is None
+57
View File
@@ -97,6 +97,22 @@ async def _participate(client, token, session_id):
return await client.post(f"/v1/negotiation/sessions/{session_id}/participate", headers={"Authorization": f"Bearer {token}"})
async def _reject(client, token, session_id, reason):
return await client.post(
f"/v1/negotiation/sessions/{session_id}/reject",
headers={"Authorization": f"Bearer {token}"},
json={"reject_reason": reason},
)
async def _session_reject(db_engine, session_id):
async with db_engine.begin() as conn:
return (await conn.execute(
text("SELECT status, reject_reason FROM negotiation.sessions WHERE session_id = :sid"),
{"sid": session_id},
)).first()
async def _session_status(db_engine, session_id):
async with db_engine.begin() as conn:
return (await conn.execute(text("SELECT status FROM negotiation.sessions WHERE session_id = :sid"), {"sid": session_id})).scalar()
@@ -209,3 +225,44 @@ async def test_participate_session_not_found(client, nego_seed):
token = await _login_token(client)
r = await _participate(client, token, str(uuid.uuid4()))
assert r.json()["result"]["code"] == 1304 # NEGO_NOT_FOUND
# ---- 거부 -------------------------------------------------------------------
async def test_reject_success(client, nego_seed, db_engine):
token = await _login_token(client)
sid = nego_seed["sids"]["B"] # 협상중 → 거부 가능
r = await _reject(client, token, sid, "단종 상품입니다")
assert r.json()["result"]["success"] is True
assert r.json()["session_id"] == str(sid)
status, reason = await _session_reject(db_engine, sid)
assert status == 5 and reason == "단종 상품입니다" # REJECTED + 사유 저장
async def test_reject_empty_reason(client, nego_seed):
token = await _login_token(client)
r = await _reject(client, token, nego_seed["sids"]["B"], " ") # 공백만 → 사유 없음
assert r.json()["result"]["code"] == 101 # INVALID_REQUEST_DATA
async def test_reject_forbidden_other_supplier(client, nego_seed):
token = await _login_token(client)
r = await _reject(client, token, nego_seed["sids"]["X"], "사유") # 타 공급사 세션
assert r.json()["result"]["code"] == 1300 # NEGO_FORBIDDEN
async def test_reject_not_participable_when_done(client, nego_seed):
token = await _login_token(client)
r = await _reject(client, token, nego_seed["sids"]["C"], "사유") # 협상완료(3) → 거부 불가
assert r.json()["result"]["code"] == 1301 # NEGO_NOT_PARTICIPABLE
async def test_reject_session_not_found(client, nego_seed):
token = await _login_token(client)
r = await _reject(client, token, str(uuid.uuid4()), "사유")
assert r.json()["result"]["code"] == 1304 # NEGO_NOT_FOUND
async def test_reject_requires_auth(client, nego_seed):
sid = nego_seed["sids"]["B"]
r = await client.post(f"/v1/negotiation/sessions/{sid}/reject", json={"reject_reason": "사유"})
assert r.status_code in (401, 403)