Merge branch 'main' of https://gitea.o2o.kr/Negosium/o2o-negosium
This commit is contained in:
commit
a52321e68d
159 files changed
+4921
-655
No files matched your search
@@ -2,12 +2,16 @@ import time
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.middleware.gzip import GZipMiddleware
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.logger import LOG
|
||||
from common.utils.gtime import GTime
|
||||
from config.server_configs import web_server_config
|
||||
import router.v1.auth.account
|
||||
import router.v1.negotiation.session
|
||||
import router.v1.negotiation.chat
|
||||
|
||||
API_SERVER_START_TIME = GTime.UTCStr()
|
||||
|
||||
@@ -22,6 +26,17 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
app = FastAPI(title="Negosium Api Server", lifespan=lifespan)
|
||||
|
||||
# CORS: config 의 cors_origins 가 있을 때만 적용(브라우저 프론트 호출 허용).
|
||||
# 명시적 오리진을 쓰므로 allow_credentials=True 가능(쿠키/Authorization 헤더 허용).
|
||||
if web_server_config.cors_origins:
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=web_server_config.cors_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Accept-Encoding: gzip 요청에 대해 1000 bytes 이상 응답을 압축.
|
||||
app.add_middleware(GZipMiddleware, minimum_size=1000)
|
||||
|
||||
@@ -42,3 +57,5 @@ async def healthz():
|
||||
|
||||
# 각 도메인 라우터를 등록한다. 새 기능 추가 시 router.v1.<domain>.<file> 를 import 후 include.
|
||||
app.include_router(router.v1.auth.account.router)
|
||||
app.include_router(router.v1.negotiation.session.router)
|
||||
app.include_router(router.v1.negotiation.chat.router)
|
||||
@@ -1,12 +1,15 @@
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from fastapi.security import HTTPAuthorizationCredentials
|
||||
|
||||
from common.models.gmodel import UserInfo
|
||||
from router.v1.validator.dependencies import IsValidAccessToken, IsValidRefreshToken, RemoveNoneResponse
|
||||
from router.v1.validator.dependencies import (
|
||||
IsValidAccessToken,
|
||||
IsValidRefreshToken,
|
||||
RemoveNoneResponse,
|
||||
security,
|
||||
)
|
||||
from services.auth_service import AuthService
|
||||
from .protocol import Req_CreateAccount, Req_Login, Res_CreateAccount, Res_Login, Res_RefreshToken
|
||||
|
||||
security = HTTPBearer()
|
||||
from .protocol import Req_CreateAccount, Req_Login, Res_CreateAccount, Res_Login, Res_Logout, Res_Me, Res_RefreshToken
|
||||
|
||||
# 라우터(MVC 의 컨트롤러). 요청 검증 -> service 호출 -> RemoveNoneResponse 반환만 담당.
|
||||
router = APIRouter(prefix="/v1/auth", tags=["Auth"], responses={404: {"description": "Not found"}})
|
||||
@@ -17,26 +20,49 @@ async def login(request: Request, req: Req_Login, service: AuthService = Depends
|
||||
return RemoveNoneResponse(await service.attempt_login(req.id, req.pw, request.client.host))
|
||||
|
||||
|
||||
@router.post(path="/create", response_model=Res_CreateAccount, summary="계정 생성", description="새 계정을 생성한다.")
|
||||
# TODO: 계정 생성은 관리자/매니저 권한으로 제한할 가능성이 있음(현재는 비보호).
|
||||
@router.post(path="/create", response_model=Res_CreateAccount, summary="계정 생성", description="supplier_id 소속의 유저를 생성한다(공급사 존재를 앱에서 검증).")
|
||||
async def create_account(request: Request, req: Req_CreateAccount, service: AuthService = Depends()):
|
||||
return RemoveNoneResponse(await service.create_account(req.id, req.pw, req.nickname, request.client.host))
|
||||
return RemoveNoneResponse(
|
||||
await service.create_account(
|
||||
req.supplier_id, req.id, req.pw, req.name, req.email, req.contact_number, req.role, request.client.host
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/refresh_token",
|
||||
dependencies=[Depends(IsValidRefreshToken)],
|
||||
response_model=Res_RefreshToken,
|
||||
summary="액세스 토큰 갱신",
|
||||
description="refresh 토큰으로 access 토큰을 재발급한다.",
|
||||
description="refresh 토큰으로 access 토큰을 재발급한다. su_id DB 존재/활성 + 저장 토큰 대조를 service 에서 확인한다.",
|
||||
)
|
||||
async def refresh_token(service: AuthService = Depends(), credentials: HTTPAuthorizationCredentials = Depends(security)):
|
||||
return RemoveNoneResponse(await service.refresh_token(credentials.credentials))
|
||||
async def refresh_token(
|
||||
user_info: UserInfo = Depends(IsValidRefreshToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: AuthService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.refresh_token(user_info, credentials.credentials))
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/logout",
|
||||
response_model=Res_Logout,
|
||||
summary="로그아웃",
|
||||
description="저장된 access/refresh 토큰을 폐기한다. 이후 보호 요청·재발급이 차단된다(단일 세션).",
|
||||
)
|
||||
async def logout(user_info: UserInfo = Depends(IsValidAccessToken), service: AuthService = Depends()):
|
||||
return RemoveNoneResponse(await service.logout(user_info))
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/me",
|
||||
summary="내 정보 (보호된 엔드포인트 예시)",
|
||||
description="유효한 access 토큰이 있어야 호출 가능. 토큰 검증 결과 UserInfo 를 주입받는다.",
|
||||
response_model=Res_Me,
|
||||
summary="내 정보 (보호된 엔드포인트)",
|
||||
description="access 토큰 검증(validator) 후 su_id DB 존재/활성 + 저장 토큰 대조를 service 에서 확인해 반환한다.",
|
||||
)
|
||||
async def me(user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||
return {"uid": user_info.uid, "id": user_info.id, "nickname": user_info.nickname}
|
||||
async def me(
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: AuthService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.get_me(user_info, credentials.credentials))
|
||||
@@ -1,5 +1,3 @@
|
||||
from pydantic import Field
|
||||
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
@@ -14,21 +12,41 @@ class Req_Login(AuthProtocol):
|
||||
|
||||
|
||||
class Res_Login(Res_WebPacketProtocol):
|
||||
uid: int = Field(0, description="user uid", json_schema_extra={"format": "int64"})
|
||||
nickname: str = ""
|
||||
su_id: str = ""
|
||||
name: str = "" # 유저 개인 이름
|
||||
supplier_id: str = "" # 소속 공급사(partner.suppliers)
|
||||
supplier_name: str = "" # 공급사명
|
||||
role: int = 0
|
||||
access_token: str = ""
|
||||
refresh_token: str = ""
|
||||
|
||||
|
||||
class Req_CreateAccount(AuthProtocol):
|
||||
id: str = ""
|
||||
supplier_id: str = "" # 소속 공급사(partner.suppliers.supplier_id)
|
||||
id: str = "" # 로그인 ID
|
||||
pw: str = ""
|
||||
nickname: str = ""
|
||||
name: str = ""
|
||||
email: str = ""
|
||||
contact_number: str = ""
|
||||
role: int = 1 # 1=user, 2=manager (UserRole)
|
||||
|
||||
|
||||
class Res_CreateAccount(Res_WebPacketProtocol):
|
||||
uid: int = Field(0, description="생성된 user uid", json_schema_extra={"format": "int64"})
|
||||
su_id: str = ""
|
||||
|
||||
|
||||
class Res_RefreshToken(Res_WebPacketProtocol):
|
||||
access_token: str = ""
|
||||
|
||||
|
||||
class Res_Me(Res_WebPacketProtocol):
|
||||
su_id: str = ""
|
||||
id: str = ""
|
||||
name: str = ""
|
||||
supplier_id: str = ""
|
||||
supplier_name: str = ""
|
||||
role: int = 0
|
||||
|
||||
|
||||
class Res_Logout(Res_WebPacketProtocol):
|
||||
pass
|
||||
@@ -0,0 +1,57 @@
|
||||
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 .chat_protocol import Req_ChatSend, Res_ChatInit, Res_ChatMessages, Res_ChatSend
|
||||
|
||||
router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation 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,66 @@
|
||||
"""채팅(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.
|
||||
indicator/summary/reject 는 이번 범위 외(예약 필드, 기본 None).
|
||||
"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
# 말풍선 한 건. sender 는 ChatSender 정수 코드(1=BOT, 2=USER)로 내려가고 라벨 매핑은 프론트가 한다.
|
||||
class ChatMessage(WebPacketProtocol):
|
||||
chat_id: str = ""
|
||||
session_id: str = ""
|
||||
seq: int = 0
|
||||
sender: int = 0 # ChatSender 코드
|
||||
script: str = ""
|
||||
user_input_type: Optional[str] = None # 유저 입력 종류: text|percent|price
|
||||
step: str = ""
|
||||
display_step: str = "" # agent client_step
|
||||
next_input_mode: Optional[str] = None # confirm|yes_no|percent|price|delivery_type
|
||||
next_input_type: Optional[list[str]] = None # 다음 입력 선택지
|
||||
chat_end: bool = False
|
||||
indicator_value: Optional[float] = None # (범위 외 예약) 협상 지표
|
||||
bot_chat_type: Optional[str] = None # (범위 외 예약) indicator|summary 등
|
||||
|
||||
|
||||
# 채팅 진입 — 상품/견적 메타 + 현재 세션 상태 + 마감 시각(타이머용)
|
||||
class Res_ChatInit(Res_WebPacketProtocol):
|
||||
session_id: str = ""
|
||||
session_status: int = 0 # SessionStatus 코드
|
||||
quotation_id: str = ""
|
||||
quotation_end_time: str = "" # 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] = None # text|percent|price
|
||||
user_input: str = ""
|
||||
|
||||
|
||||
# append-only: 새 봇 메시지 1건 + 갱신된 세션 상태만 반환(전체 refetch 회피)
|
||||
class Res_ChatSend(Res_WebPacketProtocol):
|
||||
message: Optional[ChatMessage] = None
|
||||
session_status: int = 0
|
||||
@@ -0,0 +1,33 @@
|
||||
from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
# 협상 세션 목록 행. status/qt_type 은 정수 코드로 내려가고 라벨 매핑은 프론트가 한다.
|
||||
class ListItem(WebPacketProtocol):
|
||||
session_id: str = ""
|
||||
session_status: int = 0 # SessionStatus 코드
|
||||
qt_type: int = 0 # QtType 코드 (1=재협상, 2=재견적)
|
||||
qt_number: str = ""
|
||||
qt_end_time: str = "" # ISO 8601 (마감 시각)
|
||||
item_code: str = ""
|
||||
item_name: str = ""
|
||||
model_name: str = ""
|
||||
maker_name: str = ""
|
||||
|
||||
|
||||
class Res_SessionList(Res_WebPacketProtocol):
|
||||
items: list[ListItem] = []
|
||||
total: int = 0
|
||||
page: int = 0
|
||||
page_size: int = 0
|
||||
|
||||
|
||||
class Res_Participate(Res_WebPacketProtocol):
|
||||
session_id: str = "" # 참여 성공한 세션 (채팅 진입용)
|
||||
|
||||
|
||||
class Req_Reject(WebPacketProtocol):
|
||||
reject_reason: str = "" # 거부 사유 (단종/품절 프리셋 라벨 또는 기타 직접 입력)
|
||||
|
||||
|
||||
class Res_Reject(Res_WebPacketProtocol):
|
||||
session_id: str = "" # 거부 처리된 세션
|
||||
@@ -0,0 +1,63 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from fastapi.security import HTTPAuthorizationCredentials
|
||||
|
||||
from common.models.gmodel import UserInfo
|
||||
from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, security
|
||||
from services.negotiation_service import NegotiationService
|
||||
from .protocol import Req_Reject, Res_Participate, Res_Reject, Res_SessionList
|
||||
|
||||
router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation"], responses={404: {"description": "Not found"}})
|
||||
|
||||
|
||||
@router.get(
|
||||
path="/sessions",
|
||||
response_model=Res_SessionList,
|
||||
summary="협상 세션 목록",
|
||||
description="로그인한 공급사의 협상 세션 목록. 필터(status/qt_type, 정수 코드)·마감일 정렬·페이지네이션 지원.",
|
||||
)
|
||||
async def list_sessions(
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: NegotiationService = Depends(),
|
||||
status: Optional[int] = Query(None, description="세션 상태 코드 (SessionStatus)"),
|
||||
qt_type: Optional[int] = Query(None, description="견적 유형 코드 (QtType: 1=재협상, 2=재견적)"),
|
||||
order: str = Query("asc", description="마감일 정렬: asc(임박순)/desc"),
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(20, ge=1, le=100),
|
||||
):
|
||||
return RemoveNoneResponse(
|
||||
await service.list_sessions(user_info, credentials.credentials, status, qt_type, order, page, page_size)
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/sessions/{session_id}/participate",
|
||||
response_model=Res_Participate,
|
||||
summary="협상 참여",
|
||||
description="세션에 참여한다. 소유(공급사)·세션상태·견적마감·마감시간 검증 후 협상생성→협상중, 견적→견적진행중으로 전이.",
|
||||
)
|
||||
async def participate(
|
||||
session_id: str,
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: NegotiationService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.participate(user_info, credentials.credentials, session_id))
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/sessions/{session_id}/reject",
|
||||
response_model=Res_Reject,
|
||||
summary="협상 거부",
|
||||
description="세션 참여를 거부한다. 소유(공급사)·세션상태(완료/미참여/거부 불가)·견적마감·마감시간 검증 후 협상거부로 전이하고 사유를 저장.",
|
||||
)
|
||||
async def reject(
|
||||
session_id: str,
|
||||
req: Req_Reject,
|
||||
user_info: UserInfo = Depends(IsValidAccessToken),
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
service: NegotiationService = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.reject(user_info, credentials.credentials, session_id, req.reject_reason))
|
||||
@@ -88,8 +88,7 @@ def DecodeRefreshToken(jwt_token: str) -> UserInfo:
|
||||
return __decode_token(jwt_token, JWT_REFRESH_SECRET, EXCEPTION_REFRESH_TOKEN_EXPIRED)
|
||||
|
||||
|
||||
# ---- Depends 용 토큰 검증기 ------------------------------------------------
|
||||
# 보호된 엔드포인트에서 dependencies=[Depends(IsValidAccessToken)] 로 사용.
|
||||
# ---- Depends 용 토큰 검증기 (디코드만; DB 존재/활성 검증은 service 가 담당) -----
|
||||
async def IsValidAccessToken(credentials: HTTPAuthorizationCredentials = Depends(security)) -> UserInfo:
|
||||
return DecodeAccessToken(credentials.credentials)
|
||||
|
||||
|
||||
Reference in new issue
Block a user