From 157ba6155d51b509bc4e82154f4d5ef10feccefe Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Mon, 27 Jul 2026 16:37:26 +0900 Subject: [PATCH] =?UTF-8?q?260727=5F01=5FENH:=20=EC=A0=84=ED=99=94=20?= =?UTF-8?q?=EA=B1=B8=EA=B8=B0=20ws=20=ED=8B=80=EC=96=B4=EB=A7=89=EA=B8=B0,?= =?UTF-8?q?=20=EC=84=A0=ED=83=9D=20=ED=95=AD=EB=AA=A9=EB=A7=8C=EC=9D=B8?= =?UTF-8?q?=EA=B2=BD=EC=9A=B0=20=EC=84=A0=ED=83=9D=EB=90=9C=20=EA=B2=83?= =?UTF-8?q?=EC=9D=B4=20=EC=97=86=EC=9C=BC=EB=A9=B4=20=EC=98=A4=EB=A5=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/(pages)/(main)/list/contact/page.tsx | 16 +- .../api/list-call-hist/[[...slug]]/route.ts | 29 +- .../ListDialogOption/ApplyFilterOption.tsx | 9 +- .../list-contact/ListContactInfoPanel.tsx | 34 +- src/const/ctiConst.ts | 4 +- src/hooks/useCtiAgentStatus.ts | 8 - src/hooks/useCtiCallPhase.ts | 13 + src/lib/cti/ctiClient.ts | 417 +++++++++++++----- src/types/list.ts | 21 +- 9 files changed, 393 insertions(+), 158 deletions(-) delete mode 100644 src/hooks/useCtiAgentStatus.ts create mode 100644 src/hooks/useCtiCallPhase.ts diff --git a/src/app/(pages)/(main)/list/contact/page.tsx b/src/app/(pages)/(main)/list/contact/page.tsx index e288594..b0f16d1 100644 --- a/src/app/(pages)/(main)/list/contact/page.tsx +++ b/src/app/(pages)/(main)/list/contact/page.tsx @@ -1,6 +1,6 @@ 'use client' -import { Suspense, useEffect, useMemo, useRef, useState } from "react"; +import { Suspense, useEffect, useMemo, useState } from "react"; import { useRouter, useSearchParams } from "next/navigation"; import { ArrowLeft, CalendarClock, RefreshCw } from "lucide-react"; import { useMounted } from "@kri/common/hooks"; @@ -37,25 +37,25 @@ const ListContactPageContent = () => { // 이 페이지 진입 시의 prjctIdx를 기준으로 기록해두고, 이후 외부(프로젝트 선택기 등)에서 // prjctIdx가 바뀌면 더 이상 현재 sid가 유효하지 않으므로 목록 관리 화면으로 내보낸다. - // isStaleProject는 렌더 시점에 ref를 직접 비교해서, 리다이렉트 effect가 돌기 전에도 + // isStaleProject는 렌더 시점에 기준 프로젝트와 비교해서, 리다이렉트 effect가 돌기 전에도 // 아래 쿼리들이 잘못된 prjctIdx+sid 조합으로 요청을 보내 에러 alert를 띄우는 걸 막는다. - const baselinePrjctIdx = useRef(null); - const isStaleProject = baselinePrjctIdx.current !== null && baselinePrjctIdx.current !== prjctIdx; + const [baselinePrjctIdx, setBaselinePrjctIdx] = useState(null); + const isStaleProject = baselinePrjctIdx !== null && baselinePrjctIdx !== prjctIdx; const queriesEnabled = mounted && prjctIdx > 0 && !isStaleProject; const enabled = queriesEnabled && !!sid; useEffect(() => { if (!mounted || prjctIdx <= 0) return; - if (baselinePrjctIdx.current === null) { - baselinePrjctIdx.current = prjctIdx; + if (baselinePrjctIdx === null) { + setBaselinePrjctIdx(prjctIdx); return; } - if (baselinePrjctIdx.current !== prjctIdx) { + if (baselinePrjctIdx !== prjctIdx) { router.replace('/list/manage'); } - }, [prjctIdx, mounted, router]); + }, [baselinePrjctIdx, prjctIdx, mounted, router]); const projectInfoQuery = useProjectInfoQuery(prjctIdx, queriesEnabled); const listHeaderQuery = useListHeaderQuery(prjctIdx, queriesEnabled); diff --git a/src/app/api/list-call-hist/[[...slug]]/route.ts b/src/app/api/list-call-hist/[[...slug]]/route.ts index 459d428..b096cab 100644 --- a/src/app/api/list-call-hist/[[...slug]]/route.ts +++ b/src/app/api/list-call-hist/[[...slug]]/route.ts @@ -2,7 +2,7 @@ import {NextRequest, NextResponse} from "next/server"; import {RouteContext} from "@/types/common"; import {createContactApi} from "@/lib/http-server"; import {errorToResponse} from "@kri/common/http"; -import type {ListCallHistSession} from "@/types/list"; +import type {ListCallHist, ListCallHistSession} from "@/types/list"; export const GET = async (_req: NextRequest, context: RouteContext) => { try { @@ -25,8 +25,8 @@ export const GET = async (_req: NextRequest, context: RouteContext) => { export const PUT = async (req: NextRequest, context: RouteContext) => { try { const { slug = [] } = await context.params; - const [prjctIdx, sid] = slug; - if (!prjctIdx || !sid) { + const [prjctIdx, sid, action] = slug; + if (!prjctIdx || !sid || (action !== "call-start" && action !== "call-close")) { return NextResponse.json({ message: "Not found" }, { status: 404 }); } @@ -36,7 +36,28 @@ export const PUT = async (req: NextRequest, context: RouteContext) => { } const contactApi = await createContactApi(); - const result = await contactApi.put(`/list-call-hist/${prjctIdx}/${sid}`, body); + const result = await contactApi.put( + `/list-call-hist/${prjctIdx}/${sid}/${action}`, + body, + ); + return NextResponse.json(result, { status: 200 }); + } catch (error: unknown) { + return errorToResponse(error); + } +}; + +export const PATCH = async (_req: NextRequest, context: RouteContext) => { + try { + const { slug = [] } = await context.params; + const [action, agentSessionId] = slug; + if (action !== "hangup" || !agentSessionId) { + return NextResponse.json({ message: "Not found" }, { status: 404 }); + } + + const contactApi = await createContactApi(); + const result = await contactApi.patch( + `/list-call-hist/hangup/${encodeURIComponent(agentSessionId)}`, + ); return NextResponse.json(result, { status: 200 }); } catch (error: unknown) { return errorToResponse(error); diff --git a/src/components/dialog/ListDialogOption/ApplyFilterOption.tsx b/src/components/dialog/ListDialogOption/ApplyFilterOption.tsx index b480fe0..fd3cfeb 100644 --- a/src/components/dialog/ListDialogOption/ApplyFilterOption.tsx +++ b/src/components/dialog/ListDialogOption/ApplyFilterOption.tsx @@ -12,8 +12,13 @@ export type ApplyFilterOptionValue = ListFilterTarget * alert 후 진행을 막아야 하는 호출부에서 공통으로 사용한다. */ export const validateApplyFilterTarget = (value: ApplyFilterOptionValue, filterSummary?: string[]): boolean => { - if (value === 'filtered' && (filterSummary?.length ?? 0) === 0) { - alert('적용된 필터가 없습니다. 필터를 적용해 주세요.') + if (["selected", "filtered"].includes(value) && (filterSummary?.length ?? 0) === 0) { + const alertText: string = + value === "selected" ? + "선택된 항목이 없습니다. 항목을 선택해 주세요" + : "적용된 필터가 없습니다. 필터를 적용해 주세요." + + alert(alertText) return false } return true diff --git a/src/components/list-contact/ListContactInfoPanel.tsx b/src/components/list-contact/ListContactInfoPanel.tsx index b450c99..e1c18f4 100644 --- a/src/components/list-contact/ListContactInfoPanel.tsx +++ b/src/components/list-contact/ListContactInfoPanel.tsx @@ -21,8 +21,7 @@ import SurveyQrDialog from '@/components/dialog/SurveyQrDialog' import SingleMessageSendDialog from '@/components/dialog/SingleMessageSendDialog' import { ctiClient } from '@/lib/cti/ctiClient' import { useCtiConnectionStatus } from '@/hooks/useCtiConnectionStatus' -import { useCtiAgentStatus } from '@/hooks/useCtiAgentStatus' -import { CTI_ON_CALL_STATUSES } from '@/const/ctiConst' +import { useCtiCallPhase } from '@/hooks/useCtiCallPhase' import { cn } from '@/lib/utils' import { downloadFile } from '@kri/common/browser' @@ -67,6 +66,18 @@ export const buildInitialValues = (listHeaders: listHeader[], detail?: ListSearc const disabledContrastClass = 'disabled:opacity-100 disabled:text-foreground disabled:bg-muted/60' +const getCallButtonLabel = (isDialing: boolean, isOnCall: boolean) => { + if (isDialing) return '거는 중' + if (isOnCall) return '전화 끊기' + return '전화' +} + +const getCallButtonTitle = (isCtiReady: boolean, isDialing: boolean) => { + if (!isCtiReady) return '전화 시스템에 연결되어 있지 않습니다.' + if (isDialing) return '전화를 거는 중입니다.' + return undefined +} + const FieldRow = ({ label, children }: { label: string; children: ReactNode }) => (
@@ -98,8 +109,9 @@ const ListContactInfoPanel = ({ const [qrTargetUrl, setQrTargetUrl] = useState('') const ctiConnectionStatus = useCtiConnectionStatus() const isCtiReady = ctiConnectionStatus === 'open' - const ctiAgentStatus = useCtiAgentStatus() - const isOnCall = ctiAgentStatus !== null && (CTI_ON_CALL_STATUSES as readonly string[]).includes(ctiAgentStatus) + const ctiCallPhase = useCtiCallPhase() + const isDialing = ctiCallPhase === 'dialing' + const isOnCall = ctiCallPhase === 'active' useEffect(() => { if (!isOnCall) return @@ -148,12 +160,13 @@ const ListContactInfoPanel = ({ } const handleCall = (telNum: string, listHderId: number) => { - if (!isCtiReady) return + if (!isCtiReady || isDialing) return // CTI_HANGUP_PENDING_VENDOR: 외주사 Hangup 명령 동작 확인 후 통화 중 버튼을 활성화하면 즉시 사용할 수 있다. if (isOnCall) { ctiClient.hangup() return } + if (!telNum) return ctiClient.makeCall({ dialNumber: telNum, prjctIdx, sid: Number(sid), listHderId, aniNumber: callerTelNum ?? '' }) } @@ -218,12 +231,12 @@ const ListContactInfoPanel = ({ type="button" variant="outline" className={cn('shrink-0 gap-2', isOnCall && 'bg-accent text-accent-foreground')} - disabled={!isCtiReady || isOnCall} - title={!isCtiReady ? '전화 시스템에 연결되어 있지 않습니다.' : undefined} + disabled={!isCtiReady || isDialing} + title={getCallButtonTitle(isCtiReady, isDialing)} onClick={() => handleCall(value, header.listHderId)} > - {isOnCall ? '통화중' : '전화'} + {getCallButtonLabel(isDialing, isOnCall)}
+ {(isDialing || isOnCall) && +

+ ⚠️ 전화를 끊어야만 통화 종료가 기록됩니다. +

+ } ) } diff --git a/src/const/ctiConst.ts b/src/const/ctiConst.ts index dc7fc51..92a3fd6 100644 --- a/src/const/ctiConst.ts +++ b/src/const/ctiConst.ts @@ -5,5 +5,5 @@ export const CTI_AGENT_STATUS = { BREAK: "11", } as const; -// WS 서버가 ZCommand: "AgentStatusChanged"로 보내는 CTIAgentStatus 값 중, 통화 중으로 간주할 값들 -export const CTI_ON_CALL_STATUSES = ["2", "3"] as const; +// WS 서버가 보내는 CTIAgentStatus 값 중 통화 중 또는 통화 중 재로그인 대기로 간주할 값들 +export const CTI_ON_CALL_STATUSES = ["0", "2", "3"] as const; diff --git a/src/hooks/useCtiAgentStatus.ts b/src/hooks/useCtiAgentStatus.ts deleted file mode 100644 index ceebff9..0000000 --- a/src/hooks/useCtiAgentStatus.ts +++ /dev/null @@ -1,8 +0,0 @@ -"use client"; - -import { useSyncExternalStore } from "react"; -import { ctiClient } from "@/lib/cti/ctiClient"; - -export function useCtiAgentStatus() { - return useSyncExternalStore(ctiClient.subscribe, ctiClient.getAgentStatus, () => null); -} diff --git a/src/hooks/useCtiCallPhase.ts b/src/hooks/useCtiCallPhase.ts new file mode 100644 index 0000000..ca1782a --- /dev/null +++ b/src/hooks/useCtiCallPhase.ts @@ -0,0 +1,13 @@ +"use client"; + +import { useSyncExternalStore } from "react"; +import { ctiClient } from "@/lib/cti/ctiClient"; +import type { CtiCallPhase } from "@/lib/cti/ctiClient"; + +export function useCtiCallPhase(): CtiCallPhase { + return useSyncExternalStore( + ctiClient.subscribe, + ctiClient.getCallPhase, + () => "idle", + ); +} diff --git a/src/lib/cti/ctiClient.ts b/src/lib/cti/ctiClient.ts index 4ae2175..f058322 100644 --- a/src/lib/cti/ctiClient.ts +++ b/src/lib/cti/ctiClient.ts @@ -1,21 +1,25 @@ import { clientEnv } from "@/lib/env.client"; import { nextApi } from "@/lib/http-client"; -import { CTI_AGENT_GROUP, CTI_AGENT_STATUS } from "@/const/ctiConst"; -import type { ListCallHist, ListCallHistRequest, ListCallHistSession } from "@/types/list"; +import { CTI_AGENT_GROUP, CTI_ON_CALL_STATUSES } from "@/const/ctiConst"; +import type { + ListCallCloseRequest, + ListCallHist, + ListCallStartRequest, +} from "@/types/list"; import { getLocalStorage, removeLocalStorage, setLocalStorage } from "@/store/storage/secure-storage"; import { StorageKeys } from "@/store/storage/storage-keys"; // TEMP_CTI_LOG: 배포 후 CTI 연동 오류를 콘솔에서 바로 확인하기 위한 임시 로그. // 안정화되면 "TEMP_CTI_LOG"로 검색해서 이 파일의 관련 로그를 전부 제거할 것. -export type CtiLoginParams = { +type CtiLoginParams = { agentLoginId: string; agentPhone: string; aniNumber: string; agentName: string; }; -export type CtiMakeCallParams = { +type CtiMakeCallParams = { dialNumber: string; prjctIdx: number; sid: number; @@ -23,7 +27,8 @@ export type CtiMakeCallParams = { aniNumber: string; }; -export type CtiConnectionState = "idle" | "connecting" | "open" | "closed"; +type CtiConnectionState = "idle" | "connecting" | "open" | "closed"; +export type CtiCallPhase = "idle" | "dialing" | "active"; type CtiCallContext = { prjctIdx: number; @@ -31,18 +36,25 @@ type CtiCallContext = { listHderId: number; }; +type CtiCall = { + context: CtiCallContext; + agentSessionId: string | null; +}; + type PersistedCtiState = { - version: 1; + version: 2; agentLoginId: string; agentStatus: string | null; - currentCallContext: CtiCallContext | null; + activeCall: CtiCall | null; + closingCall: CtiCall | null; lastCallContext: CtiCallContext | null; - agentSessionId: string | null; lastCallHistId: number | null; + hangupRequested: boolean; + callClosedReceived: boolean; updatedAt: number; }; -const CTI_STATE_VERSION = 1; +const CTI_STATE_VERSION = 2; const CTI_STATE_TTL_MS = 24 * 60 * 60 * 1000; let socket: WebSocket | null = null; @@ -51,10 +63,13 @@ let currentAgentLoginId: string | null = null; let currentConnectionKey: string | null = null; let currentLoginParams: CtiLoginParams | null = null; let agentStatus: string | null = null; -let currentCallContext: CtiCallContext | null = null; +let activeCall: CtiCall | null = null; +let closingCall: CtiCall | null = null; let lastCallContext: CtiCallContext | null = null; -let currentAgentSessionId: string | null = null; let lastCallHistId: number | null = null; +let hangupRequested = false; +let callClosedReceived = false; +let reconnectIntervalId: ReturnType | null = null; const listeners = new Set<() => void>(); @@ -62,6 +77,18 @@ const notify = () => { listeners.forEach((listener) => listener()); }; +const hasActiveSession = () => activeCall?.agentSessionId != null; + +const getCallPhase = (): CtiCallPhase => { + if (!activeCall) return "idle"; + return hasActiveSession() ? "active" : "dialing"; +}; + +const isCallInProgress = () => + hasActiveSession() || + (agentStatus !== null && + (CTI_ON_CALL_STATUSES as readonly string[]).includes(agentStatus)); + const isCallContext = (value: unknown): value is CtiCallContext => { if (typeof value !== "object" || value === null) return false; const context = value as Partial; @@ -75,6 +102,15 @@ const isCallContext = (value: unknown): value is CtiCallContext => { ); }; +const isCtiCall = (value: unknown): value is CtiCall => { + if (typeof value !== "object" || value === null) return false; + const call = value as Partial; + return ( + isCallContext(call.context) && + (call.agentSessionId === null || typeof call.agentSessionId === "string") + ); +}; + const isPersistedCtiState = (value: unknown): value is PersistedCtiState => { if (typeof value !== "object" || value === null) return false; const state = value as Partial; @@ -82,10 +118,12 @@ const isPersistedCtiState = (value: unknown): value is PersistedCtiState => { state.version === CTI_STATE_VERSION && typeof state.agentLoginId === "string" && (state.agentStatus === null || typeof state.agentStatus === "string") && - (state.currentCallContext === null || isCallContext(state.currentCallContext)) && + (state.activeCall === null || isCtiCall(state.activeCall)) && + (state.closingCall === null || isCtiCall(state.closingCall)) && (state.lastCallContext === null || isCallContext(state.lastCallContext)) && - (state.agentSessionId === null || typeof state.agentSessionId === "string") && (state.lastCallHistId === null || typeof state.lastCallHistId === "number") && + typeof state.hangupRequested === "boolean" && + typeof state.callClosedReceived === "boolean" && typeof state.updatedAt === "number" ); }; @@ -96,10 +134,12 @@ const persistCtiState = () => { version: CTI_STATE_VERSION, agentLoginId: currentAgentLoginId, agentStatus, - currentCallContext, + activeCall, + closingCall, lastCallContext, - agentSessionId: currentAgentSessionId, lastCallHistId, + hangupRequested, + callClosedReceived, updatedAt: Date.now(), } satisfies PersistedCtiState); }; @@ -116,27 +156,34 @@ const restoreCtiState = (agentLoginId: string) => { } agentStatus = stored.agentStatus; - currentCallContext = stored.currentCallContext; + activeCall = stored.activeCall; + closingCall = stored.closingCall; lastCallContext = stored.lastCallContext; - currentAgentSessionId = stored.agentSessionId; lastCallHistId = stored.lastCallHistId; + hangupRequested = stored.hangupRequested; + callClosedReceived = stored.callClosedReceived; notify(); return true; }; const recoverLastCallHistId = async (agentLoginId: string) => { - const agentSessionId = currentAgentSessionId; - const callContext = currentCallContext ?? lastCallContext; - if (!agentSessionId || lastCallHistId !== null || !callContext) return; + const targetCall = + activeCall?.agentSessionId ? activeCall : + closingCall?.agentSessionId ? closingCall : + null; + if (!targetCall?.agentSessionId) return; + const agentSessionId = targetCall.agentSessionId; + const callContext = targetCall.context; try { - const result = await nextApi.get( + const result = await nextApi.get( `/list-call-hist/session/${encodeURIComponent(agentSessionId)}`, ); const isSameCall = currentAgentLoginId === agentLoginId && - currentAgentSessionId === agentSessionId && + (activeCall?.agentSessionId === agentSessionId || + closingCall?.agentSessionId === agentSessionId) && result.agentSessionId === agentSessionId && result.prjctIdx === callContext.prjctIdx && result.sid === callContext.sid && @@ -153,7 +200,24 @@ const recoverLastCallHistId = async (agentLoginId: string) => { lastCallContext = callContext; setLastCallHistId(result.listCallHistIdx); - console.log("[CTI][TEMP_LOG] recovered listCallHistIdx ->", result.listCallHistIdx); // TEMP_CTI_LOG + console.log("[CTI][TEMP_LOG] recovered call history ->", result); // TEMP_CTI_LOG + + if (result.callStatus === 4 || result.callStatus === 9) { + if (closingCall?.agentSessionId === agentSessionId) { + closingCall = null; + } else if (activeCall?.agentSessionId === agentSessionId) { + activeCall = null; + agentStatus = null; + callClosedReceived = true; + } + persistCtiState(); + notify(); + return; + } + + if (hangupRequested && activeCall?.agentSessionId === agentSessionId) { + void markUserHangup(agentSessionId); + } } catch (error) { console.warn("[CTI][TEMP_LOG] failed to recover call history", { agentSessionId, error }); // TEMP_CTI_LOG } @@ -164,8 +228,18 @@ const setConnectionState = (next: CtiConnectionState) => { notify(); }; +const stopReconnectLoop = () => { + if (reconnectIntervalId === null) return; + clearInterval(reconnectIntervalId); + reconnectIntervalId = null; + console.log("[CTI][TEMP_LOG] reconnect loop stopped, agentStatus =", agentStatus); // TEMP_CTI_LOG +}; + const setAgentStatus = (next: string | null) => { agentStatus = next; + if (next !== null && next !== "0") { + stopReconnectLoop(); + } persistCtiState(); notify(); }; @@ -176,20 +250,47 @@ const setLastCallHistId = (next: number | null) => { notify(); }; -// 통화 세션 시작(StartSessionRecord)/종료(CallClosed) 시 리스트 통화 이력 저장 API로 전달한다. -// listHderId/prjctIdx/sid는 WS 메시지에 없어서 makeCall 시점에 캐시해둔 currentCallContext에서 가져온다. -// clearContextAfter=false: StartSessionRecord는 같은 통화의 CallClosed가 이어서 오므로 컨텍스트를 유지한다. -const saveCallHistory = (parsed: Record, options: { clearContextAfter: boolean }) => { - if (!currentCallContext) { +const markUserHangup = async (agentSessionId: string) => { + if (activeCall?.agentSessionId !== agentSessionId) return; + + try { + const updated = await nextApi.patch( + `/list-call-hist/hangup/${encodeURIComponent(agentSessionId)}`, + ); + if (updated && activeCall?.agentSessionId === agentSessionId) { + const completedCall = activeCall; + closingCall = completedCall; + lastCallContext = completedCall.context; + activeCall = null; + persistCtiState(); + notify(); + } + console.log("[CTI][TEMP_LOG] user hangup saved ->", updated); // TEMP_CTI_LOG + } catch (error) { + console.error("[CTI][TEMP_LOG] failed to save user hangup", { agentSessionId, error }); // TEMP_CTI_LOG + } +}; + +// 통화 세션 시작(StartSessionRecord)/종료(CallClosed)를 각각 전용 통화 이력 API로 전달한다. +// listHderId/prjctIdx/sid는 WS 메시지에 없어서 makeCall 시점에 캐시해둔 activeCall에서 가져온다. +const saveCallHistory = (parsed: Record, phase: "start" | "close") => { + const eventAgentSessionId = String(parsed.AgntSessionID ?? ""); + const isClosingCall = + phase === "close" && + eventAgentSessionId !== "" && + eventAgentSessionId === closingCall?.agentSessionId; + const targetCall = isClosingCall ? closingCall : activeCall; + + if (!targetCall) { console.warn("[CTI][TEMP_LOG] call history event received but no call context cached", parsed); // TEMP_CTI_LOG return; } - const callContext = currentCallContext; + const callContext = targetCall.context; const { prjctIdx, sid, listHderId } = callContext; const startTime = typeof parsed.StartTime === "string" ? parsed.StartTime : ""; - const body: ListCallHistRequest = { + const startBody: ListCallStartRequest = { listHderId, destNum: String(parsed.DestPhone ?? ""), agentNum: String(parsed.AgentPhone ?? ""), @@ -198,42 +299,51 @@ const saveCallHistory = (parsed: Record, options: { clearContex destSessionId: String(parsed.DestSessionID ?? ""), callTy: String(parsed.CallType ?? ""), startDt: startTime.replace(" ", "T"), - totalTime: Number(parsed.TotalTime ?? 0), - talkTime: Number(parsed.TalkTime ?? 0), mediaServerId: Number(parsed.MediaServerID ?? 0), mediaServerName: String(parsed.MediaServerName ?? ""), recordFileName: String(parsed.RecordFileName ?? ""), }; + const body: ListCallStartRequest | ListCallCloseRequest = + phase === "close" + ? { + ...startBody, + totalTime: Number(parsed.TotalTime ?? 0), + talkTime: Number(parsed.TalkTime ?? 0), + } + : startBody; - currentAgentSessionId = body.agentSessionId || currentAgentSessionId; - persistCtiState(); - - if ( - options.clearContextAfter && - body.totalTime <= 0 && - body.talkTime <= 0 && - body.recordFileName.trim() === "" - ) { - console.warn( - "[CTI][TEMP_LOG] CallClosed has no backend endDt marker (totalTime, talkTime, recordFileName)", - parsed, - ); // TEMP_CTI_LOG + if (!isClosingCall) { + activeCall = { + ...targetCall, + agentSessionId: body.agentSessionId || targetCall.agentSessionId, + }; } + persistCtiState(); + notify(); - console.log("[CTI][TEMP_LOG] saving call history", { prjctIdx, sid, body }); // TEMP_CTI_LOG + const action = phase === "start" ? "call-start" : "call-close"; + console.log(`[CTI][TEMP_LOG] saving ${action}`, { prjctIdx, sid, body }); // TEMP_CTI_LOG nextApi - .put(`/list-call-hist/${prjctIdx}/${sid}`, body) + .put(`/list-call-hist/${prjctIdx}/${sid}/${action}`, body) .then((result) => { - console.log("[CTI][TEMP_LOG] call history saved, listCallHistIdx =", result?.listCallHistIdx); // TEMP_CTI_LOG + console.log(`[CTI][TEMP_LOG] ${action} saved, listCallHistIdx =`, result?.listCallHistIdx); // TEMP_CTI_LOG lastCallContext = callContext; setLastCallHistId(result?.listCallHistIdx ?? null); - if (options.clearContextAfter && currentCallContext === callContext) { - currentCallContext = null; + if (phase === "start" && hangupRequested && body.agentSessionId) { + void markUserHangup(body.agentSessionId); + } + if (phase === "close") { + if (closingCall?.agentSessionId === body.agentSessionId) { + closingCall = null; + } else if (activeCall?.agentSessionId === body.agentSessionId) { + activeCall = null; + } persistCtiState(); + notify(); } }) .catch((error) => { - console.error("[CTI][TEMP_LOG] failed to save call history", error); // TEMP_CTI_LOG + console.error(`[CTI][TEMP_LOG] failed to save ${action}`, error); // TEMP_CTI_LOG }); }; @@ -252,6 +362,19 @@ const handleIncomingMessage = (raw: unknown) => { } switch (parsed.ZCommand) { + case "Login": { + const status = parsed.CTIAgentStatus == null ? null : String(parsed.CTIAgentStatus); + console.log("[CTI][TEMP_LOG] Login response ->", status, parsed.CTIAgentStatusName); // TEMP_CTI_LOG + if(status !== null){ + setAgentStatus(status); + } + + break; + } + case "Logout": { + console.log("[CTI][TEMP_LOG] Logout response ->", parsed.CTIAgentStatus, parsed.CTIAgentStatusName); // TEMP_CTI_LOG + break; + } case "AgentStatusChanged": { const status = parsed.CTIAgentStatus == null ? null : String(parsed.CTIAgentStatus); console.log("[CTI][TEMP_LOG] AgentStatusChanged ->", status); // TEMP_CTI_LOG @@ -261,13 +384,27 @@ const handleIncomingMessage = (raw: unknown) => { case "StartSessionRecord": { console.log("[CTI][TEMP_LOG] StartSessionRecord ->", parsed); // TEMP_CTI_LOG setAgentStatus("2"); - saveCallHistory(parsed, { clearContextAfter: false }); + saveCallHistory(parsed, "start"); + break; + } + case "HangUp": + case "Hangup": { + console.log("[CTI][TEMP_LOG] HangUp response ->", parsed); // TEMP_CTI_LOG + if (agentStatus === "0") { + startReconnectUntilAgentStatusChanges(); + } break; } case "CallClosed": { console.log("[CTI][TEMP_LOG] CallClosed ->", parsed); // TEMP_CTI_LOG - setAgentStatus(null); - saveCallHistory(parsed, { clearContextAfter: true }); + const eventAgentSessionId = String(parsed.AgntSessionID ?? ""); + const isClosingCall = + eventAgentSessionId !== "" && eventAgentSessionId === closingCall?.agentSessionId; + if (!isClosingCall) { + callClosedReceived = true; + setAgentStatus(null); + } + saveCallHistory(parsed, "close"); break; } default: @@ -287,6 +424,18 @@ const send = (command: Record) => { socket.send(JSON.stringify(command)); }; +const sendLogin = (params: CtiLoginParams) => { + console.log("[CTI][TEMP_LOG] sending Login"); // TEMP_CTI_LOG + send({ + ZCommand: "Login", + AgentLoginID: params.agentLoginId, + AgentName: params.agentName, + AgentGroup: CTI_AGENT_GROUP, + ANINumber: params.aniNumber, + AgentPhone: params.agentPhone, + }); +}; + const teardownSocket = () => { if (socket) { console.log("[CTI][TEMP_LOG] teardownSocket, readyState =", socket.readyState); // TEMP_CTI_LOG @@ -312,14 +461,76 @@ const logout = () => { currentAgentLoginId = null; currentConnectionKey = null; currentLoginParams = null; - currentCallContext = null; + activeCall = null; + closingCall = null; lastCallContext = null; - currentAgentSessionId = null; + hangupRequested = false; + callClosedReceived = false; + stopReconnectLoop(); setAgentStatus(null); setLastCallHistId(null); if (shouldClearPersistedState) removeLocalStorage(StorageKeys.CtiState); }; +const openSocketAndLogin = (params: CtiLoginParams) => { + setConnectionState("connecting"); + console.log("[CTI][TEMP_LOG] opening websocket ->", clientEnv.CTI_WS_URL); // TEMP_CTI_LOG + + const ws = new WebSocket(clientEnv.CTI_WS_URL); + socket = ws; + + ws.onopen = () => { + setConnectionState("open"); + sendLogin(params); + }; + + ws.onmessage = (event) => { + console.log("[CTI][TEMP_LOG] message <-", event.data); // TEMP_CTI_LOG + handleIncomingMessage(event.data); + }; + + ws.onerror = (event) => { + console.error("[CTI][TEMP_LOG] websocket error", event); // TEMP_CTI_LOG + }; + + ws.onclose = (event) => { + setConnectionState("closed"); + console.log("[CTI][TEMP_LOG] websocket closed, code =", event.code, "reason =", event.reason, "wasClean =", event.wasClean); // TEMP_CTI_LOG + }; +}; + +const reconnectAndLogin = () => { + const params = currentLoginParams; + if (!params) { + console.warn("[CTI][TEMP_LOG] reconnectAndLogin skipped, no login params"); // TEMP_CTI_LOG + return; + } + + console.log("[CTI][TEMP_LOG] reconnectAndLogin called"); // TEMP_CTI_LOG + teardownSocket(); + currentAgentLoginId = params.agentLoginId; + currentConnectionKey = buildKey(params); + openSocketAndLogin(params); +}; + +const startReconnectUntilAgentStatusChanges = () => { + if (agentStatus !== null && agentStatus !== "0") { + stopReconnectLoop(); + return; + } + if (reconnectIntervalId !== null) return; + + console.log("[CTI][TEMP_LOG] reconnect loop started, interval = 3000ms"); // TEMP_CTI_LOG + reconnectAndLogin(); + reconnectIntervalId = setInterval(() => { + if (agentStatus !== null && agentStatus !== "0") { + stopReconnectLoop(); + return; + } + reconnectAndLogin(); + }, 3000); +}; + const connectAndLogin = (params: CtiLoginParams) => { console.log("[CTI][TEMP_LOG] connectAndLogin called with", params); // TEMP_CTI_LOG @@ -344,45 +555,10 @@ const connectAndLogin = (params: CtiLoginParams) => { currentAgentLoginId = params.agentLoginId; currentConnectionKey = key; currentLoginParams = params; + const restored = restoreCtiState(params.agentLoginId); if (restored) void recoverLastCallHistId(params.agentLoginId); - setConnectionState("connecting"); - - console.log("[CTI][TEMP_LOG] opening websocket ->", clientEnv.CTI_WS_URL); // TEMP_CTI_LOG - const ws = new WebSocket(clientEnv.CTI_WS_URL); - socket = ws; - - ws.onopen = () => { - setConnectionState("open"); - console.log("[CTI][TEMP_LOG] websocket open, sending Login"); // TEMP_CTI_LOG - send({ - ZCommand: "Login", - AgentLoginID: params.agentLoginId, - AgentName: params.agentName, - AgentGroup: CTI_AGENT_GROUP, - ANINumber: params.aniNumber, - AgentPhone: params.agentPhone, - }); - }; - - ws.onmessage = (event) => { - console.log("[CTI][TEMP_LOG] message <-", event.data); // TEMP_CTI_LOG - handleIncomingMessage(event.data); - }; - - ws.onerror = (event) => { - console.error("[CTI][TEMP_LOG] websocket error", event); // TEMP_CTI_LOG - }; - - ws.onclose = (event) => { - setConnectionState("closed"); - console.log("[CTI][TEMP_LOG] websocket closed, code =", event.code, "reason =", event.reason, "wasClean =", event.wasClean); // TEMP_CTI_LOG - }; -}; - -const requireAgent = (fn: (agentLoginId: string) => void) => () => { - if (!currentAgentLoginId) return; - fn(currentAgentLoginId); + openSocketAndLogin(params); }; export const ctiClient = { @@ -393,16 +569,27 @@ export const ctiClient = { return () => listeners.delete(listener); }, getConnectionState: () => connectionState, - getAgentStatus: () => agentStatus, - getLastCallHistId: () => lastCallHistId, + getCallPhase, getLastCallHistIdFor: (prjctIdx: number, sid: number) => lastCallContext?.prjctIdx === prjctIdx && lastCallContext.sid === sid ? lastCallHistId : null, makeCall: (params: CtiMakeCallParams) => { - if (!currentAgentLoginId || !currentLoginParams) return; + if (!currentAgentLoginId) return; + if (isCallInProgress()) { + console.warn("[CTI][TEMP_LOG] makeCall skipped, call is already in progress"); // TEMP_CTI_LOG + return; + } console.log("[CTI][TEMP_LOG] makeCall", params); // TEMP_CTI_LOG - currentCallContext = { prjctIdx: params.prjctIdx, sid: params.sid, listHderId: params.listHderId }; + activeCall = { + context: { + prjctIdx: params.prjctIdx, + sid: params.sid, + listHderId: params.listHderId, + }, + agentSessionId: null, + }; lastCallContext = null; - currentAgentSessionId = null; + hangupRequested = false; + callClosedReceived = false; setLastCallHistId(null); // 새 통화 시작, 이전 통화의 listCallHistIdx는 더 이상 유효하지 않음 send({ ZCommand: "MakeCall", @@ -411,22 +598,24 @@ export const ctiClient = { ANINumber: params.aniNumber, }); }, - hangup: requireAgent((agentLoginId) => { - // CTI_HANGUP_PENDING_VENDOR: 외주사와 ZCommand/동작 확인 후 UI 활성화 예정. - console.log("[CTI][TEMP_LOG] hangup"); // TEMP_CTI_LOG - send({ ZCommand: "Hangup", AgentLoginID: agentLoginId }); - }), - setReady: requireAgent((agentLoginId) => { - console.log("[CTI][TEMP_LOG] setReady"); // TEMP_CTI_LOG - send({ ZCommand: "SetAgentStatus", AgentLoginID: agentLoginId, CTIAgentStatus: CTI_AGENT_STATUS.READY }); - }), - setBreak: requireAgent((agentLoginId) => { - console.log("[CTI][TEMP_LOG] setBreak"); // TEMP_CTI_LOG - send({ ZCommand: "SetAgentStatus", AgentLoginID: agentLoginId, CTIAgentStatus: CTI_AGENT_STATUS.BREAK }); - }), - setRecordStamp: (tag: string) => { + hangup: () => { if (!currentAgentLoginId) return; - console.log("[CTI][TEMP_LOG] setRecordStamp", { tag }); // TEMP_CTI_LOG - send({ ZCommand: "SetRecordStamp", AgentLoginID: currentAgentLoginId, Tag: tag }); + + const agentSessionId = activeCall?.agentSessionId; + if (!agentSessionId || hangupRequested || callClosedReceived) { + console.warn("[CTI][TEMP_LOG] hangup skipped, active session is missing or hangup was already requested", { + agentStatus, + activeCall, + hangupRequested, + callClosedReceived, + }); // TEMP_CTI_LOG + return; + } + + hangupRequested = true; + persistCtiState(); + void markUserHangup(agentSessionId); + console.log("[CTI][TEMP_LOG] hangup"); // TEMP_CTI_LOG + send({ ZCommand: "HangUp", AgentLoginID: currentAgentLoginId }); }, }; diff --git a/src/types/list.ts b/src/types/list.ts index f63dda4..26ab43e 100644 --- a/src/types/list.ts +++ b/src/types/list.ts @@ -260,7 +260,7 @@ export type ListReserve = { regDt: string; }; -export type ListCallHistRequest = { +export type ListCallStartRequest = { listHderId: number; destNum: string; agentNum: string; @@ -269,30 +269,27 @@ export type ListCallHistRequest = { destSessionId: string; callTy: string; startDt: string; - totalTime: number; - talkTime: number; mediaServerId: number; mediaServerName: string; recordFileName: string; }; -export type ListCallHist = ListCallHistRequest & { +export type ListCallCloseRequest = ListCallStartRequest & { + totalTime: number; + talkTime: number; +}; + +export type ListCallHist = ListCallCloseRequest & { listCallHistIdx: number; prjctIdx: number; sid: number; + callStatus: 2 | 4 | 9; endDt?: string; regUser: string; regDt: string; }; -export type ListCallHistSession = { - listCallHistIdx: number; - agentSessionId: string; - destSessionId: string; - prjctIdx: number; - sid: number; - listHderId: number; -}; +export type ListCallHistSession = ListCallHist; export type ListReserveRequest = { prjctIdx: number; -- 2.49.0.windows.1