feat(frontend): 채팅 페이지 API 연동 + KST 시각 표시
- apis/chat 모듈(api/queries/mutations/keys/type) + useChatController(append-only send 주입) - useChatStore 재배선, list→chat session_id 라우팅 연결, mock 제거 - 마감/종료/권한 시 입력 잠금·목록 복귀, 가격범위 인라인 에러, CHAT_IN_PROGRESS 처리 - list 마감일 KST(Asia/Seoul) 고정 표시(lib/datetime formatKstDateTime) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
dcce82a630
commit
ce536b43d6
19 files changed
+406
-184
No files matched your search
@@ -1,10 +1,10 @@
|
||||
import { useChatInit } from '@/features/chat/hooks/useChatInit'
|
||||
import { useChatController } from '@/features/chat/hooks/useChatController'
|
||||
import { ChatSection } from '@/features/chat/components/ChatSection'
|
||||
import { MenuSection } from '@/features/chat/components/menu/MenuSection'
|
||||
|
||||
// 콘텐츠 영역: 채팅 + 우측 메뉴. mock 데이터를 스토어에 적재한다.
|
||||
export function ChatContainer() {
|
||||
useChatInit()
|
||||
// 콘텐츠 영역: 채팅 + 우측 메뉴. session_id 로 init/messages 를 적재하고 전송을 주입한다.
|
||||
export function ChatContainer({ sessionId }: { sessionId: string }) {
|
||||
useChatController(sessionId)
|
||||
return (
|
||||
<div className="flex flex-1 min-h-0 w-full">
|
||||
<ChatSection />
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { useChatInitQuery, useChatMessagesQuery, useChatSendMutation, mapMessage } from '@/apis/chat'
|
||||
import { ErrorCode, getApiErrorMessage, isApiError } from '@/apis/types'
|
||||
import { toast } from '@/lib'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
import type { ChatMessage, UserInputType } from '@/features/chat/types'
|
||||
|
||||
// 더 이상 대화를 이어갈 수 없는(세션 종료/마감/권한) 코드 → 입력 잠금 후 목록으로 복귀.
|
||||
const TERMINAL_CODES = new Set<number>([
|
||||
ErrorCode.CHAT_NOT_IN_PROGRESS,
|
||||
ErrorCode.NEGO_QUOTATION_CLOSED,
|
||||
ErrorCode.NEGO_DEADLINE_PASSED,
|
||||
ErrorCode.NEGO_FORBIDDEN,
|
||||
ErrorCode.NEGO_NOT_FOUND,
|
||||
])
|
||||
|
||||
let tempSeq = 0
|
||||
|
||||
// 낙관적 유저 말풍선 생성 (전송 즉시 표시). 서버 확정 메시지는 send 응답으로 append 한다.
|
||||
function makeUserMessage(text: string, inputType: UserInputType): ChatMessage {
|
||||
return {
|
||||
chat_id: `temp-user-${tempSeq++}`,
|
||||
sender: 'user',
|
||||
bot_chat_type: null,
|
||||
user_input_type: inputType,
|
||||
script: text,
|
||||
chat_end: false,
|
||||
next_input_mode: null,
|
||||
next_input_type: null,
|
||||
step: '',
|
||||
display_step: '',
|
||||
summary: null,
|
||||
indicator_value: null,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 채팅 페이지 컨트롤러: init/messages 조회를 스토어에 적재하고,
|
||||
* append-only 전송 구현을 스토어에 주입한다. (mock 을 대체)
|
||||
*/
|
||||
export function useChatController(sessionId: string) {
|
||||
const navigate = useNavigate()
|
||||
const setInitData = useChatInitStore((s) => s.setInitData)
|
||||
const initQuery = useChatInitQuery(sessionId)
|
||||
const messagesQuery = useChatMessagesQuery(sessionId)
|
||||
const sendMutation = useChatSendMutation(sessionId)
|
||||
|
||||
// init 메타 → 스토어
|
||||
useEffect(() => {
|
||||
if (initQuery.data) setInitData(initQuery.data)
|
||||
}, [initQuery.data, setInitData])
|
||||
|
||||
// 대화 히스토리 → 스토어 (진입 1회)
|
||||
useEffect(() => {
|
||||
if (messagesQuery.data) useChatStore.getState().setMessages(messagesQuery.data)
|
||||
}, [messagesQuery.data])
|
||||
|
||||
// sessionId + 전송 구현 주입
|
||||
useEffect(() => {
|
||||
const store = useChatStore.getState()
|
||||
store.setSessionId(sessionId)
|
||||
|
||||
store.bindSend((text, inputType = 'text') => {
|
||||
const optimistic = makeUserMessage(text, inputType)
|
||||
store.appendMessage(optimistic)
|
||||
store.setIsLoading(true)
|
||||
store.setPriceErrorMessage('')
|
||||
|
||||
sendMutation.mutate(
|
||||
{ user_input: text, user_input_type: inputType === 'text' ? null : inputType },
|
||||
{
|
||||
onSuccess: (data) => {
|
||||
const s = useChatStore.getState()
|
||||
if (data.message) s.appendMessage(mapMessage(data.message))
|
||||
s.setIsLoading(false)
|
||||
},
|
||||
onError: (error) => {
|
||||
const s = useChatStore.getState()
|
||||
// 낙관적 메시지 롤백 (서버에 저장되지 않음)
|
||||
s.setMessages(s.messages.filter((m) => m.chat_id !== optimistic.chat_id))
|
||||
s.setIsLoading(false)
|
||||
const code = isApiError(error) ? error.code : 0
|
||||
|
||||
// 가격 범위 초과: 입력창 인라인 에러로 표시(페이지 유지)
|
||||
if (code === ErrorCode.CHAT_PRICE_OUT_OF_RANGE) {
|
||||
s.setPriceErrorMessage(getApiErrorMessage(error))
|
||||
return
|
||||
}
|
||||
|
||||
toast.error(getApiErrorMessage(error, '협상 처리 중 오류가 발생했습니다.'))
|
||||
|
||||
// 마감/종료/권한 등 더 진행 불가한 상태면 잠시 후 목록으로 복귀
|
||||
if (TERMINAL_CODES.has(code)) {
|
||||
s.bindSend(null) // 입력 잠금(추가 전송 차단)
|
||||
setTimeout(() => navigate('/list'), 1500)
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
return () => {
|
||||
useChatStore.getState().reset()
|
||||
}
|
||||
}, [sessionId, sendMutation, navigate])
|
||||
|
||||
return {
|
||||
isInitLoading: initQuery.isLoading || messagesQuery.isLoading,
|
||||
initError: initQuery.error ?? messagesQuery.error,
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { useEffect } from 'react'
|
||||
import { useChatStore } from '@/features/chat/stores/useChatStore'
|
||||
import { useChatInitStore } from '@/features/chat/stores/useChatInitStore'
|
||||
import { MOCK_CHAT_INIT } from '@/features/chat/mocks/mockChatInit'
|
||||
import { MOCK_MESSAGES } from '@/features/chat/mocks/mockMessages'
|
||||
|
||||
// mock 세션/대화 데이터를 스토어에 적재 (추후 API 조회로 교체)
|
||||
export function useChatInit() {
|
||||
const setInitData = useChatInitStore((s) => s.setInitData)
|
||||
const setMessages = useChatStore((s) => s.setMessages)
|
||||
|
||||
useEffect(() => {
|
||||
setInitData(MOCK_CHAT_INIT)
|
||||
setMessages(MOCK_MESSAGES)
|
||||
}, [setInitData, setMessages])
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
// 마감까지 남은 시간 'HH시간 MM분 SS초'. 지났으면 종료 문구, 잘못된 값은 '-'.
|
||||
// 남은 시간은 "절대 시각 간 차이(duration)"라 타임존과 무관하다. 백엔드가 UTC(+00:00 오프셋 포함)로
|
||||
// 내려주므로 new Date 파싱이 정확하면 KST 변환이 따로 필요 없다(날짜로 "표시"할 때만 KST 고정 필요 → lib/datetime).
|
||||
export function getTimeRemaining(targetDateTime: string | Date): string {
|
||||
const now = Date.now()
|
||||
const target = new Date(targetDateTime).getTime()
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
import type { ChatInitData } from '@/features/chat/types'
|
||||
|
||||
// 마감까지 카운트다운이 보이도록 현재 시각 기준 미래로 설정
|
||||
const END_TIME = new Date(Date.now() + 95 * 60 * 1000).toISOString()
|
||||
|
||||
// 임시 세션/상품 데이터 (API 연동 전)
|
||||
export const MOCK_CHAT_INIT: ChatInitData = {
|
||||
session_id: 's-001',
|
||||
item_id: 'item-001',
|
||||
quotation_id: 'qt-001',
|
||||
item_name: '사무용 노트북 14인치',
|
||||
item_code: 'IMK-10231',
|
||||
item_image: '',
|
||||
item_price: 1350000,
|
||||
item_model_name: 'NB-1400-PRO',
|
||||
item_maker_name: '삼성전자',
|
||||
item_vat_yn: 'VAT별도',
|
||||
item_delivery_fee_yn: 'N',
|
||||
item_min_order_quantity: '10 EA',
|
||||
item_lead_time: '7일',
|
||||
item_spec: 'Intel Core i7 / 16GB RAM / 512GB SSD / 14인치 FHD',
|
||||
quotation_memo:
|
||||
'납기 엄수 부탁드립니다.\n세금계산서는 월말 일괄 발행합니다.\n상세 사양은 첨부 문서를 확인해주세요.',
|
||||
quotation_end_time: END_TIME,
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
import type { ChatMessage, ChatSummary } from '@/features/chat/types'
|
||||
|
||||
// 전 메시지 템플릿을 한눈에 보기 위한 쇼케이스 목 대화 (실제 협상 흐름 아님)
|
||||
|
||||
const SUMMARY: ChatSummary = {
|
||||
md_name: '김엠디',
|
||||
item_moq: '10 EA',
|
||||
md_email: 'md@example.com',
|
||||
item_code: 'IMK-10231',
|
||||
item_name: '사무용 노트북 14인치',
|
||||
item_spec: 'Intel Core i7 / 16GB / 512GB SSD',
|
||||
item_isVAT: false,
|
||||
item_maker: '삼성전자',
|
||||
item_model: 'NB-1400-PRO',
|
||||
final_price: 1200000,
|
||||
nego_end_date: '2026년 06월 17일 14시 30분',
|
||||
supplier_name: '대한상사',
|
||||
item_lead_time: '7일',
|
||||
md_phone_number: '02-1234-5678',
|
||||
nego_start_date: '2026년 06월 17일 14시 00분',
|
||||
item_display_date: '2026년 06월 10일',
|
||||
item_delivery_type: '협력사배송',
|
||||
supplier_manager_name: '이담당',
|
||||
supplier_manager_email: 'sales@example.com',
|
||||
delivery_type: '협력사배송',
|
||||
}
|
||||
|
||||
const base = {
|
||||
bot_chat_type: null,
|
||||
user_input_type: null,
|
||||
script: null,
|
||||
chat_end: false,
|
||||
next_input_mode: null,
|
||||
next_input_type: null,
|
||||
summary: null,
|
||||
indicator_value: null,
|
||||
} as const
|
||||
|
||||
export const MOCK_MESSAGES: ChatMessage[] = [
|
||||
{
|
||||
...base,
|
||||
chat_id: 'm1',
|
||||
sender: 'bot',
|
||||
script:
|
||||
'안녕하세요, 협상을 시작하겠습니다. 본 협상은 자동으로 진행되며, 안내에 따라 응답해주시면 됩니다.',
|
||||
step: '서비스안내',
|
||||
display_step: '서비스안내',
|
||||
},
|
||||
{
|
||||
...base,
|
||||
chat_id: 'm2',
|
||||
sender: 'bot',
|
||||
bot_chat_type: 'indicator',
|
||||
indicator_value: 62,
|
||||
script: '현재까지의 협상 성공률은 아래와 같습니다.',
|
||||
step: '가격협상',
|
||||
display_step: '가격협상',
|
||||
},
|
||||
{
|
||||
...base,
|
||||
chat_id: 'm3',
|
||||
sender: 'user',
|
||||
user_input_type: 'price',
|
||||
script: '1,200,000원',
|
||||
step: '가격협상',
|
||||
display_step: '가격협상',
|
||||
},
|
||||
{
|
||||
...base,
|
||||
chat_id: 'm4',
|
||||
sender: 'bot',
|
||||
bot_chat_type: 'summaryCM',
|
||||
summary: SUMMARY,
|
||||
script: '제시해주신 금액으로 투찰 결과를 요약해드립니다.',
|
||||
step: '가격협상',
|
||||
display_step: '가격협상',
|
||||
},
|
||||
{
|
||||
...base,
|
||||
chat_id: 'm5',
|
||||
sender: 'bot',
|
||||
bot_chat_type: 'summaryRSP',
|
||||
summary: SUMMARY,
|
||||
script: '협상이 완료되었습니다. 최종 결과를 요약해드립니다.',
|
||||
step: '협상종료',
|
||||
display_step: '협상종료',
|
||||
},
|
||||
{
|
||||
...base,
|
||||
chat_id: 'm6',
|
||||
sender: 'bot',
|
||||
bot_chat_type: 'rejectCM',
|
||||
script: '제시 금액이 수용되지 않았습니다. 최종 공급 희망 가격과 배송 형태를 입력해주세요.',
|
||||
step: '가격협상',
|
||||
display_step: '가격협상',
|
||||
},
|
||||
{
|
||||
...base,
|
||||
chat_id: 'm7',
|
||||
sender: 'bot',
|
||||
script: '추가로 제시할 가격이 있다면 입력해주세요.',
|
||||
next_input_mode: 'price',
|
||||
step: '가격협상',
|
||||
display_step: '가격협상',
|
||||
},
|
||||
]
|
||||
@@ -2,24 +2,39 @@ import { create } from 'zustand'
|
||||
import type { ChatMessage, UserButtonConfig, UserInputType } from '@/features/chat/types'
|
||||
import { deriveUserButtonConfig } from '@/features/chat/lib/userButtonConfig'
|
||||
|
||||
type SendFn = (text: string, inputType?: UserInputType) => void
|
||||
|
||||
type ChatStore = {
|
||||
sessionId: string
|
||||
messages: ChatMessage[]
|
||||
userButtonConfig: UserButtonConfig
|
||||
isLoading: boolean
|
||||
priceErrorMessage: string
|
||||
setSessionId: (sessionId: string) => void
|
||||
setMessages: (messages: ChatMessage[]) => void
|
||||
appendMessage: (message: ChatMessage) => void
|
||||
setIsLoading: (isLoading: boolean) => void
|
||||
setPriceErrorMessage: (message: string) => void
|
||||
sendMessage: (text: string, inputType?: UserInputType) => void
|
||||
// 실제 전송 구현은 컨트롤러(useChatController)가 React Query 와 함께 주입한다.
|
||||
bindSend: (fn: SendFn | null) => void
|
||||
sendMessage: SendFn
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
let mockSeq = 0
|
||||
|
||||
export const useChatStore = create<ChatStore>((set, get) => ({
|
||||
messages: [],
|
||||
userButtonConfig: { type: '', text: '' },
|
||||
const initial = {
|
||||
sessionId: '',
|
||||
messages: [] as ChatMessage[],
|
||||
userButtonConfig: { type: '' } as UserButtonConfig,
|
||||
isLoading: false,
|
||||
priceErrorMessage: '',
|
||||
}
|
||||
|
||||
let sendImpl: SendFn | null = null
|
||||
|
||||
export const useChatStore = create<ChatStore>((set, get) => ({
|
||||
...initial,
|
||||
|
||||
setSessionId: (sessionId) => set({ sessionId }),
|
||||
|
||||
setMessages: (messages) =>
|
||||
set((s) => ({
|
||||
@@ -27,6 +42,12 @@ export const useChatStore = create<ChatStore>((set, get) => ({
|
||||
userButtonConfig: deriveUserButtonConfig(messages, s.isLoading, s.priceErrorMessage),
|
||||
})),
|
||||
|
||||
appendMessage: (message) =>
|
||||
set((s) => {
|
||||
const messages = [...s.messages, message]
|
||||
return { messages, userButtonConfig: deriveUserButtonConfig(messages, s.isLoading, s.priceErrorMessage) }
|
||||
}),
|
||||
|
||||
setIsLoading: (isLoading) =>
|
||||
set((s) => ({
|
||||
isLoading,
|
||||
@@ -39,25 +60,17 @@ export const useChatStore = create<ChatStore>((set, get) => ({
|
||||
userButtonConfig: deriveUserButtonConfig(s.messages, s.isLoading, priceErrorMessage),
|
||||
})),
|
||||
|
||||
// mock: API 미연동이라 사용자 메시지를 로컬에 추가만 한다 (실제 협상 진행 로직 없음)
|
||||
bindSend: (fn) => {
|
||||
sendImpl = fn
|
||||
},
|
||||
|
||||
sendMessage: (text, inputType = 'text') => {
|
||||
const { messages } = get()
|
||||
const last = messages[messages.length - 1]
|
||||
const userMsg: ChatMessage = {
|
||||
chat_id: `mock-user-${mockSeq++}`,
|
||||
sender: 'user',
|
||||
bot_chat_type: null,
|
||||
user_input_type: inputType,
|
||||
script: text,
|
||||
chat_end: false,
|
||||
next_input_mode: null,
|
||||
next_input_type: null,
|
||||
step: last?.step ?? '',
|
||||
display_step: last?.display_step ?? '',
|
||||
summary: null,
|
||||
indicator_value: null,
|
||||
}
|
||||
const next = [...messages, userMsg]
|
||||
set({ messages: next, priceErrorMessage: '', userButtonConfig: deriveUserButtonConfig(next, false, '') })
|
||||
if (get().isLoading) return
|
||||
sendImpl?.(text, inputType)
|
||||
},
|
||||
|
||||
reset: () => {
|
||||
sendImpl = null
|
||||
set({ ...initial })
|
||||
},
|
||||
}))
|
||||
@@ -1,8 +1,6 @@
|
||||
// 'YYYY-MM-DD HH:mm'. 빈 값 '-', 파싱 실패 시 원본.
|
||||
import { formatKstDateTime } from '@/lib'
|
||||
|
||||
// 'YYYY-MM-DD HH:mm' (KST 고정). 백엔드 UTC 직렬화를 한국 시간으로 표시한다.
|
||||
export function formatDateTime(value: string): string {
|
||||
if (!value) return '-'
|
||||
const d = new Date(value)
|
||||
if (Number.isNaN(d.getTime())) return value
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
return formatKstDateTime(value)
|
||||
}
|
||||
Reference in new issue
Block a user