import { clientEnv } from "@/lib/env.client"; import { nextApi } from "@/lib/http-client"; import { HttpError } from "@kri/common/http"; import { CTI_AGENT_GROUP, CTI_AUTO_RECONNECT_BASE_MS, CTI_AUTO_RECONNECT_JITTER_MS, CTI_AUTO_RECONNECT_MAX_MS, CTI_DIALING_TIMEOUT_MS, CTI_ERROR_ALERT_THROTTLE_MS, CTI_HANGUP_TIMEOUT_MS, CTI_HISTORY_RETRY_MS, CTI_LOGIN_TIMEOUT_MS, CTI_ON_CALL_STATUSES, CTI_STATE_TTL_MS, } from "@/const/ctiConst"; import type { ListCallCloseRequest, ListCallHist, } from "@/types/list"; import { getLocalStorage, removeLocalStorage, setLocalStorage } from "@/store/storage/secure-storage"; import { StorageKeys } from "@/store/storage/storage-keys"; type CtiLoginParams = { agentLoginId: string; agentPhone: string; aniNumber: string; agentName: string; }; type CtiMakeCallParams = { dialNumber: string; prjctIdx: number; sid: string; listHderId: number; aniNumber: string; }; type CtiConnectionState = "idle" | "connecting" | "open" | "closed"; export type CtiCallPhase = "idle" | "dialing" | "active" | "ending"; type CtiCallContext = { prjctIdx: number; sid: string; listHderId: number; }; type CtiCall = { context: CtiCallContext; agentSessionId: string | null; // makeCall 시각. 이 값이 없는 dialing 상태(이전 버전 저장분)는 복원 시 만료된 것으로 본다. dialStartedAt?: number; pendingStart?: ListCallCloseRequest; }; type PendingCallClose = { call: CtiCall; // null은 재로그인 11로 확인한 종료 이벤트 유실 통화다. body: ListCallCloseRequest | null; attempted?: boolean; }; type PersistedCtiState = { version: 3; agentLoginId: string; agentStatus: string | null; activeCall: CtiCall | null; closingCall: CtiCall | null; lastCallContext: CtiCallContext | null; lastCallHistId: number | null; hangupRequested: boolean; callClosedReceived: boolean; updatedAt: number; pendingCallCloses?: PendingCallClose[]; completedSessionIds?: string[]; latestCall?: CtiCall | null; }; type LegacyCtiCallContext = Omit & { sid: number; }; type LegacyCtiCall = Omit & { context: LegacyCtiCallContext; }; type LegacyPersistedCtiState = Omit< PersistedCtiState, "version" | "activeCall" | "closingCall" | "lastCallContext" > & { version: 2; activeCall: LegacyCtiCall | null; closingCall: LegacyCtiCall | null; lastCallContext: LegacyCtiCallContext | null; }; const CTI_STATE_VERSION = 3; let socket: WebSocket | null = null; let connectionState: CtiConnectionState = "idle"; let currentAgentLoginId: string | null = null; let currentConnectionKey: string | null = null; let currentLoginParams: CtiLoginParams | null = null; let agentStatus: string | null = null; let activeCall: CtiCall | null = null; let closingCall: CtiCall | null = null; let lastCallContext: CtiCallContext | null = null; let lastCallHistId: number | null = null; let hangupRequested = false; let callClosedReceived = false; let autoReconnectTimeoutId: ReturnType | null = null; let autoReconnectAttempt = 0; let dialingTimeoutId: ReturnType | null = null; let loginTimeoutId: ReturnType | null = null; let hangupTimeoutId: ReturnType | null = null; let historyRetryTimeoutId: ReturnType | null = null; let pendingCallCloses: PendingCallClose[] = []; let completedSessionIds: string[] = []; let latestCall: CtiCall | null = null; let loginCompleted = false; let recoveryCall: CtiCall | null = null; let ownerGeneration = 0; const closingRequests = new Set(); const notifiedCloseFailures = new WeakSet(); const startingRequests = new Map>(); let savedStarts = new WeakSet(); const lastErrorAlertAt = new Map(); const listeners = new Set<() => void>(); const notify = () => { listeners.forEach((listener) => listener()); }; const hasActiveSession = () => activeCall?.agentSessionId != null; const getCallPhase = (): CtiCallPhase => { if (!activeCall) return agentStatus === "3" ? "active" : "idle"; if (hangupRequested) return "ending"; return hasActiveSession() ? "active" : "dialing"; }; const isCallInProgress = () => activeCall !== null || (agentStatus !== null && (CTI_ON_CALL_STATUSES as readonly string[]).includes(agentStatus)); const getDialingRemainingMs = (call: CtiCall) => call.dialStartedAt === undefined ? 0 : Math.max(CTI_DIALING_TIMEOUT_MS - (Date.now() - call.dialStartedAt), 0); const clearDialingTimeout = () => { if (dialingTimeoutId === null) return; clearTimeout(dialingTimeoutId); dialingTimeoutId = null; }; // 발신 대기는 남은 시간만 유지한다. 세션 이벤트를 받으면 이 타이머를 해제한다. const scheduleDialingTimeout = () => { clearDialingTimeout(); const dialingCall = activeCall; if (!dialingCall || dialingCall.agentSessionId != null) return; dialingTimeoutId = setTimeout(() => { dialingTimeoutId = null; if (activeCall !== dialingCall) return; console.warn("[CTI] 발신 대기 시간이 초과되어 상태를 해제합니다."); activeCall = null; agentStatus = null; persistCtiState(); notify(); }, getDialingRemainingMs(dialingCall)); }; const isCallContext = (value: unknown): value is CtiCallContext => { if (typeof value !== "object" || value === null) return false; const context = value as Partial; return ( typeof context.prjctIdx === "number" && Number.isFinite(context.prjctIdx) && typeof context.sid === "string" && context.sid.length > 0 && typeof context.listHderId === "number" && Number.isFinite(context.listHderId) ); }; const isLegacyCallContext = (value: unknown): value is LegacyCtiCallContext => { if (typeof value !== "object" || value === null) return false; const context = value as Partial; return ( typeof context.prjctIdx === "number" && Number.isFinite(context.prjctIdx) && typeof context.sid === "number" && Number.isFinite(context.sid) && typeof context.listHderId === "number" && Number.isFinite(context.listHderId) ); }; 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") && (call.dialStartedAt === undefined || typeof call.dialStartedAt === "number") && (call.pendingStart === undefined || (isCloseRequest(call.pendingStart) && call.pendingStart.agentSessionId === call.agentSessionId)) ); }; const isLegacyCtiCall = (value: unknown): value is LegacyCtiCall => { if (typeof value !== "object" || value === null) return false; const call = value as Partial; return ( isLegacyCallContext(call.context) && (call.agentSessionId === null || typeof call.agentSessionId === "string") ); }; const isCloseRequest = (value: unknown): value is ListCallCloseRequest => { if (typeof value !== "object" || value === null) return false; const body = value as Partial; return ( [body.listHderId, body.mediaServerId, body.totalTime, body.talkTime].every( (item) => typeof item === "number" && Number.isFinite(item) && item >= 0, ) && [body.destNum, body.agentNum, body.aniNum, body.agentSessionId, body.destSessionId, body.callTy, body.startDt, body.mediaServerName, body.recordFileName].every( (item) => typeof item === "string", ) && typeof body.agentSessionId === "string" && body.agentSessionId.length > 0 ); }; const isPendingCallClose = (value: unknown): value is PendingCallClose => { if (typeof value !== "object" || value === null) return false; const pending = value as Partial; return isCtiCall(pending.call) && pending.call.agentSessionId !== null && (pending.body === null || (isCloseRequest(pending.body) && pending.body.agentSessionId === pending.call.agentSessionId)) && (pending.attempted === undefined || typeof pending.attempted === "boolean"); }; const isPersistedCtiState = (value: unknown): value is PersistedCtiState => { if (typeof value !== "object" || value === null) return false; const state = value as Partial; return ( state.version === CTI_STATE_VERSION && typeof state.agentLoginId === "string" && (state.agentStatus === null || typeof state.agentStatus === "string") && (state.activeCall === null || isCtiCall(state.activeCall)) && (state.closingCall === null || isCtiCall(state.closingCall)) && (state.lastCallContext === null || isCallContext(state.lastCallContext)) && (state.lastCallHistId === null || typeof state.lastCallHistId === "number") && typeof state.hangupRequested === "boolean" && typeof state.callClosedReceived === "boolean" && typeof state.updatedAt === "number" && (state.pendingCallCloses === undefined || (Array.isArray(state.pendingCallCloses) && state.pendingCallCloses.every(isPendingCallClose))) && (state.completedSessionIds === undefined || (Array.isArray(state.completedSessionIds) && state.completedSessionIds.every((id) => typeof id === "string"))) && (state.latestCall === undefined || state.latestCall === null || isCtiCall(state.latestCall)) ); }; const isLegacyPersistedCtiState = (value: unknown): value is LegacyPersistedCtiState => { if (typeof value !== "object" || value === null) return false; const state = value as Partial; return ( state.version === 2 && typeof state.agentLoginId === "string" && (state.agentStatus === null || typeof state.agentStatus === "string") && (state.activeCall === null || isLegacyCtiCall(state.activeCall)) && (state.closingCall === null || isLegacyCtiCall(state.closingCall)) && (state.lastCallContext === null || isLegacyCallContext(state.lastCallContext)) && (state.lastCallHistId === null || typeof state.lastCallHistId === "number") && typeof state.hangupRequested === "boolean" && typeof state.callClosedReceived === "boolean" && typeof state.updatedAt === "number" ); }; const migrateLegacyCallContext = (context: LegacyCtiCallContext): CtiCallContext => ({ ...context, sid: String(context.sid), }); const migrateLegacyCall = (call: LegacyCtiCall | null): CtiCall | null => call ? { ...call, context: migrateLegacyCallContext(call.context), } : null; const toPersistedCtiState = (value: unknown): PersistedCtiState | null => { if (isPersistedCtiState(value)) return value; if (!isLegacyPersistedCtiState(value)) return null; return { ...value, version: CTI_STATE_VERSION, activeCall: migrateLegacyCall(value.activeCall), closingCall: migrateLegacyCall(value.closingCall), lastCallContext: value.lastCallContext ? migrateLegacyCallContext(value.lastCallContext) : null, }; }; const persistCtiState = () => { if (!currentAgentLoginId) return; setLocalStorage(StorageKeys.CtiState, { version: CTI_STATE_VERSION, agentLoginId: currentAgentLoginId, agentStatus, activeCall, closingCall, lastCallContext, lastCallHistId, hangupRequested, callClosedReceived, updatedAt: Date.now(), pendingCallCloses, completedSessionIds, latestCall, } satisfies PersistedCtiState); }; const restoreCtiState = (agentLoginId: string) => { const stored = getLocalStorage(StorageKeys.CtiState); const persistedState = toPersistedCtiState(stored); if ( !persistedState || persistedState.agentLoginId !== agentLoginId || Date.now() - persistedState.updatedAt > CTI_STATE_TTL_MS ) { if (stored !== null) removeLocalStorage(StorageKeys.CtiState); return false; } agentStatus = persistedState.agentStatus; activeCall = persistedState.activeCall; closingCall = persistedState.closingCall; lastCallContext = persistedState.lastCallContext; lastCallHistId = persistedState.lastCallHistId; // 이전 연결에서 보낸 종료 명령은 새 연결에서 재시도할 수 있다. hangupRequested = false; callClosedReceived = false; pendingCallCloses = persistedState.pendingCallCloses ?? []; completedSessionIds = persistedState.completedSessionIds ?? []; const storedLatest = persistedState.latestCall; latestCall = activeCall ?? (storedLatest ? [closingCall, ...pendingCallCloses.map((pending) => pending.call)].find( (call) => call?.agentSessionId === storedLatest.agentSessionId, ) ?? storedLatest : closingCall ?? pendingCallCloses.at(-1)?.call ?? null); // 거는 중 새로고침은 dialing을 유지해 재발신을 막고, 타임아웃이 지난 dialing만 정리한다. const isDialingExpired = activeCall !== null && activeCall.agentSessionId == null && getDialingRemainingMs(activeCall) === 0; if (isDialingExpired) { activeCall = null; agentStatus = null; } if (persistedState !== stored || isDialingExpired) persistCtiState(); scheduleDialingTimeout(); notify(); return true; }; const fetchCallHistBySession = (agentSessionId: string) => nextApi.get(`/list-call-hist/session/${encodeURIComponent(agentSessionId)}`); const matchesHistory = (call: CtiCall, result: ListCallHist) => result.agentSessionId === call.agentSessionId && result.prjctIdx === call.context.prjctIdx && result.sid === call.context.sid && result.listHderId === call.context.listHderId; const updateCallHistoryId = (call: CtiCall, result: ListCallHist) => { if (latestCall !== call || !matchesHistory(call, result)) return; lastCallContext = call.context; lastCallHistId = result.listCallHistIdx; persistCtiState(); notify(); }; // 404는 권한 부족이나 저장 지연일 수도 있어 통화 정보를 삭제하지 않는다. const recoverLastCallHistId = async (call: CtiCall) => { if (!call.agentSessionId) return; const generation = ownerGeneration; try { const result = await fetchCallHistBySession(call.agentSessionId); if (ownerGeneration === generation) updateCallHistoryId(call, result); } catch { console.warn("[CTI] 통화 이력 조회 실패: 통화 상태를 유지합니다."); } }; const setConnectionState = (next: CtiConnectionState) => { connectionState = next; notify(); }; const clearAutoReconnect = () => { if (autoReconnectTimeoutId !== null) clearTimeout(autoReconnectTimeoutId); autoReconnectTimeoutId = null; }; const clearLoginTimeout = () => { if (loginTimeoutId !== null) clearTimeout(loginTimeoutId); loginTimeoutId = null; }; const clearHangupRequest = () => { if (hangupTimeoutId !== null) clearTimeout(hangupTimeoutId); hangupTimeoutId = null; hangupRequested = false; }; // 일반 소켓 단절에만 backoff를 적용한다. 종료 후 강제 재로그인 루프는 사용하지 않는다. const scheduleAutoReconnect = () => { if (!currentLoginParams || autoReconnectTimeoutId !== null) return; const delay = Math.min(CTI_AUTO_RECONNECT_BASE_MS * 2 ** Math.min(autoReconnectAttempt, 4), CTI_AUTO_RECONNECT_MAX_MS) + Math.random() * CTI_AUTO_RECONNECT_JITTER_MS; autoReconnectAttempt += 1; autoReconnectTimeoutId = setTimeout(() => { autoReconnectTimeoutId = null; if (currentLoginParams) connectAndLogin(currentLoginParams); }, delay); }; const setAgentStatus = (next: string | null) => { agentStatus = next; persistCtiState(); notify(); }; const rememberCompletedSession = (id: string) => { completedSessionIds = [...completedSessionIds.filter((item) => item !== id), id].slice(-50); }; const scheduleHistoryRetry = () => { if (historyRetryTimeoutId !== null || !currentAgentLoginId) return; historyRetryTimeoutId = setTimeout(() => { historyRetryTimeoutId = null; if (loginCompleted) flushPendingCallCloses(); }, CTI_HISTORY_RETRY_MS); }; const finishPendingClose = (pending: PendingCallClose) => { if (pending.call.agentSessionId) rememberCompletedSession(pending.call.agentSessionId); pendingCallCloses = pendingCallCloses.filter((item) => item !== pending); persistCtiState(); notify(); }; // 실패한 종료 저장은 세션별로 보존하고 새 통화 상태와 독립적으로 재처리한다. const savePendingClose = async (pending: PendingCallClose) => { if (closingRequests.has(pending)) return; const agentSessionId = pending.call.agentSessionId; if (!agentSessionId) return; const generation = ownerGeneration; const isCurrent = () => ownerGeneration === generation && pendingCallCloses.includes(pending); closingRequests.add(pending); try { await startingRequests.get(pending.call); if (!isCurrent()) return; if (pending.body === null) { // 시작 저장도 실패했었다면 보존한 요청을 먼저 복구한다. GET 404만으로 새 이력을 만들지는 않는다. if (pending.call.pendingStart) { const { prjctIdx, sid } = pending.call.context; const restored = await nextApi.put( `/list-call-hist/${prjctIdx}/${encodeURIComponent(sid)}/call-start`, pending.call.pendingStart); if (!isCurrent()) return; if (!matchesHistory(pending.call, restored)) throw new Error("통화 시작 복구 응답 불일치"); delete pending.call.pendingStart; updateCallHistoryId(pending.call, restored); persistCtiState(); } const result = await fetchCallHistBySession(agentSessionId); if (!isCurrent()) return; if (!matchesHistory(pending.call, result)) throw new Error("통화 이력 불일치"); updateCallHistoryId(pending.call, result); // 조회 중 Talking/CallClosed가 도착했다면 이전 판단을 사용하지 않는다. if (pending.body === null && activeCall?.agentSessionId !== agentSessionId) { if (result.callStatus !== 4 && result.callStatus !== 9) { const updated = await nextApi.patch(`/list-call-hist/hangup/${encodeURIComponent(agentSessionId)}`); if (!isCurrent()) return; if (!updated && pending.body === null) { const checked = await fetchCallHistBySession(agentSessionId); if (!isCurrent()) return; if (!matchesHistory(pending.call, checked) || (checked.callStatus !== 4 && checked.callStatus !== 9)) { throw new Error("종료 이력 보정 미완료"); } } } if (pending.body === null) { finishPendingClose(pending); return; } } } const body = pending.body; if (!body || !isCurrent()) return; // 응답만 유실된 재시도는 중복 PUT에 의한 endDt 변경을 줄인다. if (pending.attempted) { try { const result = await fetchCallHistBySession(agentSessionId); if (!isCurrent()) return; if (matchesHistory(pending.call, result) && result.callStatus === 4 && result.totalTime === body.totalTime && result.talkTime === body.talkTime && result.recordFileName === body.recordFileName) { updateCallHistoryId(pending.call, result); finishPendingClose(pending); return; } } catch (error) { if (!(error instanceof HttpError && error.status === 404)) throw error; } } if (!isCurrent()) return; pending.attempted = true; persistCtiState(); const { prjctIdx, sid } = pending.call.context; const result = await nextApi.put( `/list-call-hist/${prjctIdx}/${encodeURIComponent(sid)}/call-close`, body); if (!isCurrent()) return; if (!matchesHistory(pending.call, result)) throw new Error("종료 저장 응답 불일치"); updateCallHistoryId(pending.call, result); finishPendingClose(pending); } catch { if (isCurrent()) { console.warn("[CTI] 종료 이력 저장 실패: 재시도할 정보를 보존합니다."); if (!notifiedCloseFailures.has(pending)) { notifiedCloseFailures.add(pending); alertUnhandledError("CallHistory", "종료 이력 저장을 재시도합니다."); } scheduleHistoryRetry(); } } finally { closingRequests.delete(pending); } }; const flushPendingCallCloses = () => { pendingCallCloses.forEach((pending) => void savePendingClose(pending)); }; const queueCallClose = (call: CtiCall, body: ListCallCloseRequest | null) => { let pending = pendingCallCloses.find((item) => item.call.agentSessionId === call.agentSessionId); if (pending) { // 실제 종료 이벤트는 재로그인 11에 의한 판단보다 우선한다. if (body) pending.body = body; } else { pending = { call, body }; pendingCallCloses.push(pending); } persistCtiState(); void savePendingClose(pending); }; const buildCallBody = (parsed: Record, call: CtiCall): ListCallCloseRequest | null => { const text = (key: string) => typeof parsed[key] === "string" ? parsed[key] : ""; const body: ListCallCloseRequest = { listHderId: call.context.listHderId, destNum: text("DestPhone"), agentNum: text("AgentPhone"), aniNum: text("ANINumber"), agentSessionId: text("AgntSessionID"), destSessionId: text("DestSessionID"), callTy: text("CallType"), startDt: text("StartTime").replace(" ", "T"), mediaServerId: Number(parsed.MediaServerID ?? 0), mediaServerName: text("MediaServerName"), recordFileName: text("RecordFileName"), totalTime: Number(parsed.TotalTime ?? 0), talkTime: Number(parsed.TalkTime ?? 0), }; return isCloseRequest(body) && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(body.startDt) ? body : null; }; const saveCallStart = (parsed: Record, call: CtiCall) => { if (savedStarts.has(call) || startingRequests.has(call)) return; const body = buildCallBody(parsed, call); if (!body) { alertUnhandledError("StartSessionRecord", "통화 시작 정보가 올바르지 않습니다."); return; } const { prjctIdx, sid } = call.context; const generation = ownerGeneration; call.pendingStart = body; persistCtiState(); const request = nextApi.put( `/list-call-hist/${prjctIdx}/${encodeURIComponent(sid)}/call-start`, body, ).then((result) => { if (ownerGeneration !== generation) return; if (!matchesHistory(call, result)) throw new Error("통화 시작 저장 응답 불일치"); savedStarts.add(call); delete call.pendingStart; updateCallHistoryId(call, result); persistCtiState(); }).catch(() => { if (ownerGeneration === generation) alertUnhandledError("CallHistory", "통화 시작 이력을 저장하지 못했습니다."); }).finally(() => { startingRequests.delete(call); }); startingRequests.set(call, request); }; const findEventCall = (agentSessionId: string): CtiCall | null => { if (!agentSessionId || completedSessionIds.includes(agentSessionId)) return null; if (activeCall?.agentSessionId === agentSessionId) return activeCall; if (closingCall?.agentSessionId === agentSessionId) return closingCall; const pending = pendingCallCloses.find((item) => item.call.agentSessionId === agentSessionId); if (pending) return pending.call; return activeCall?.agentSessionId === null ? activeCall : null; }; const acceptSessionEvent = (parsed: Record) => { const id = typeof parsed.AgntSessionID === "string" ? parsed.AgntSessionID : ""; const call = findEventCall(id); if (!call) return null; call.agentSessionId = id; return call; }; const alertUnhandledError = (zCommand: string, errMsg: string) => { const now = Date.now(); const lastAt = lastErrorAlertAt.get(zCommand); if (lastAt !== undefined && now - lastAt < CTI_ERROR_ALERT_THROTTLE_MS) return; lastErrorAlertAt.set(zCommand, now); const detail = errMsg ? `\n(${errMsg})` : ""; alert(`${zCommand} 오류가 발생했습니다. 관리자에게 문의하세요.${detail}`); }; // WS 서버 -> 클라이언트로 오는 메시지는 ZCommand가 기준값이다. // 새로운 서버 이벤트에 대한 후속 조치가 필요하면 여기 case를 추가한다. // 이번 소켓의 이벤트만 처리하며, 다른 상담원·완료된 세션은 현재 통화에 연결하지 않는다. const handleIncomingMessage = (raw: unknown) => { if (typeof raw !== "string") return; let value: unknown; try { value = JSON.parse(raw); } catch { return; } if (typeof value !== "object" || value === null || Array.isArray(value)) return; const parsed = value as Record; if (parsed.AgentLoginID != null && String(parsed.AgentLoginID) !== currentAgentLoginId) return; const command = parsed.ZCommand; if (typeof command !== "string") return; const errMsg = typeof parsed.ErrMsg === "string" ? parsed.ErrMsg.trim() : ""; if (errMsg || command.includes("Error")) { if (command === "HangUp" || command === "Hangup" || command === "HangUpError" || command === "HangupError") { clearHangupRequest(); persistCtiState(); notify(); } if (command === "MakeCallError" && activeCall?.agentSessionId === null) { clearDialingTimeout(); activeCall = null; setAgentStatus(null); } alertUnhandledError(command, errMsg); return; } if (command === "Login") { const status = parsed.CTIAgentStatus == null ? null : String(parsed.CTIAgentStatus); if (status === null || !/^(0|1|2|3|4|8|10|11|12)$/.test(status)) return; clearLoginTimeout(); loginCompleted = true; autoReconnectAttempt = 0; clearHangupRequest(); setAgentStatus(status); const call = recoveryCall; recoveryCall = null; if (status === "11" && call?.agentSessionId && (activeCall === call || closingCall === call)) { // 통화가 유지됐다면 Talking이 재전송된다. 11은 단절 중 종료된 복원 대상에만 적용한다. if (activeCall === call) activeCall = null; if (closingCall === call) closingCall = null; clearDialingTimeout(); queueCallClose(call, null); } else if (call?.agentSessionId) { void recoverLastCallHistId(call); } persistCtiState(); setConnectionState("open"); flushPendingCallCloses(); return; } if (!loginCompleted) return; switch (command) { case "AgentStatusChanged": { if (parsed.CTIAgentStatus != null) setAgentStatus(String(parsed.CTIAgentStatus)); break; } case "Ringing": case "Dialing": { if (activeCall && activeCall.agentSessionId === null) { setAgentStatus(command === "Ringing" ? "8" : "2"); } break; } case "StartSessionRecord": { const call = acceptSessionEvent(parsed); if (!call || call !== activeCall) break; clearDialingTimeout(); callClosedReceived = false; if (agentStatus !== "3") setAgentStatus("2"); saveCallStart(parsed, call); break; } case "Talking": { const call = acceptSessionEvent(parsed); if (!call) { if (typeof parsed.AgntSessionID === "string" && completedSessionIds.includes(parsed.AgntSessionID)) break; setAgentStatus("3"); alertUnhandledError("Talking", "통화 대상 정보를 복원할 수 없습니다."); break; } // 종료 데이터가 이미 있으면 지연된 Talking으로 통화를 재개하지 않는다. const pending = pendingCallCloses.find((item) => item.call === call); if (pending?.body) break; if (activeCall && activeCall !== call) break; pendingCallCloses = pendingCallCloses.filter((item) => item !== pending); activeCall = call; if (closingCall === call) closingCall = null; latestCall = call; clearDialingTimeout(); callClosedReceived = false; setAgentStatus("3"); void recoverLastCallHistId(call); break; } case "CallClosed": { const call = acceptSessionEvent(parsed); if (!call) break; const body = buildCallBody(parsed, call); if (!body) { alertUnhandledError("CallClosed", "종료 이벤트 정보가 올바르지 않습니다."); break; } if (activeCall === call) { clearHangupRequest(); clearDialingTimeout(); activeCall = null; callClosedReceived = true; agentStatus = "4"; } if (closingCall === call) closingCall = null; queueCallClose(call, body); notify(); break; } case "HangUp": case "Hangup": case "Logout": break; } }; const buildKey = (params: CtiLoginParams) => `${params.agentLoginId}|${params.agentPhone}|${params.aniNumber}|${params.agentName}`; const send = (command: Record): boolean => { if (!socket || socket.readyState !== WebSocket.OPEN) return false; try { socket.send(JSON.stringify(command)); console.log("[CTI][TEMP_LOG] send ->", command); // TEMP_CTI_LOG return true; } catch { return false; } }; const teardownSocket = () => { clearLoginTimeout(); clearHangupRequest(); loginCompleted = false; if (socket) { socket.onopen = null; socket.onerror = null; socket.onclose = null; socket.onmessage = null; if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) socket.close(); socket = null; } setConnectionState("idle"); }; const logout = () => { const shouldClearPersistedState = currentAgentLoginId !== null; if (currentAgentLoginId && loginCompleted) send({ ZCommand: "Logout", AgentLoginID: currentAgentLoginId }); ownerGeneration += 1; teardownSocket(); clearAutoReconnect(); clearDialingTimeout(); if (historyRetryTimeoutId !== null) clearTimeout(historyRetryTimeoutId); historyRetryTimeoutId = null; currentAgentLoginId = null; currentConnectionKey = null; currentLoginParams = null; activeCall = null; closingCall = null; recoveryCall = null; latestCall = null; pendingCallCloses = []; completedSessionIds = []; startingRequests.clear(); savedStarts = new WeakSet(); closingRequests.clear(); lastCallContext = null; lastCallHistId = null; callClosedReceived = false; agentStatus = null; autoReconnectAttempt = 0; if (shouldClearPersistedState) removeLocalStorage(StorageKeys.CtiState); notify(); }; const openSocketAndLogin = (params: CtiLoginParams) => { setConnectionState("connecting"); const ws = new WebSocket(clientEnv.CTI_WS_URL); socket = ws; ws.onopen = () => { if (socket !== ws) return; send({ ZCommand: "Login", AgentLoginID: params.agentLoginId, AgentName: params.agentName, AgentGroup: CTI_AGENT_GROUP, ANINumber: params.aniNumber, AgentPhone: params.agentPhone }); }; ws.onmessage = (event) => { if (socket === ws) { console.log("[CTI][TEMP_LOG] message <-", event.data); // TEMP_CTI_LOG handleIncomingMessage(event.data); } }; ws.onerror = () => console.warn("[CTI] WebSocket 연결 오류"); ws.onclose = () => { if (socket !== ws) return; clearLoginTimeout(); clearHangupRequest(); loginCompleted = false; setConnectionState("closed"); scheduleAutoReconnect(); }; // 소켓이 열렸어도 Login 응답이 없으면 전화 명령을 허용하지 않고 일반 복구 경로로 재시도한다. loginTimeoutId = setTimeout(() => { if (socket !== ws || loginCompleted) return; teardownSocket(); setConnectionState("closed"); scheduleAutoReconnect(); }, CTI_LOGIN_TIMEOUT_MS); }; const connectAndLogin = (params: CtiLoginParams) => { if (!params.agentLoginId) return; const key = buildKey(params); if (currentConnectionKey === key && (connectionState === "open" || connectionState === "connecting")) return; clearAutoReconnect(); if (currentAgentLoginId && currentAgentLoginId !== params.agentLoginId) logout(); const shouldRestore = currentAgentLoginId === null; teardownSocket(); currentAgentLoginId = params.agentLoginId; currentConnectionKey = key; currentLoginParams = params; if (shouldRestore) restoreCtiState(params.agentLoginId); recoveryCall = activeCall ?? closingCall; openSocketAndLogin(params); }; const suspendForPageHide = () => { if (!currentLoginParams) return; clearAutoReconnect(); if (currentAgentLoginId && loginCompleted && !isCallInProgress()) { send({ ZCommand: "Logout", AgentLoginID: currentAgentLoginId }); } persistCtiState(); teardownSocket(); }; const resumeFromPageShow = () => { if (currentLoginParams && connectionState !== "open" && connectionState !== "connecting") { connectAndLogin(currentLoginParams); } }; export const ctiClient = { connectAndLogin, logout, suspendForPageHide, resumeFromPageShow, subscribe: (listener: () => void) => { listeners.add(listener); return () => listeners.delete(listener); }, getConnectionState: () => connectionState, getCallPhase, getLastCallHistIdFor: (prjctIdx: number, sid: string) => lastCallContext?.prjctIdx === prjctIdx && lastCallContext.sid === sid ? lastCallHistId : null, makeCall: (params: CtiMakeCallParams) => { if (!currentAgentLoginId || !loginCompleted || connectionState !== "open" || isCallInProgress()) return; const call: CtiCall = { context: { prjctIdx: params.prjctIdx, sid: params.sid, listHderId: params.listHderId }, agentSessionId: null, dialStartedAt: Date.now(), }; activeCall = call; latestCall = call; clearHangupRequest(); callClosedReceived = false; lastCallContext = null; lastCallHistId = null; if (!send({ ZCommand: "MakeCall", AgentLoginID: currentAgentLoginId, DialNumber: params.dialNumber, ANINumber: params.aniNumber })) { activeCall = null; alertUnhandledError("MakeCall", "전화 시스템에 연결되어 있지 않습니다."); } else { agentStatus = "2"; scheduleDialingTimeout(); } persistCtiState(); notify(); }, hangup: () => { if (!currentAgentLoginId || !loginCompleted || !activeCall?.agentSessionId || hangupRequested || callClosedReceived) return; if (!send({ ZCommand: "HangUp", AgentLoginID: currentAgentLoginId })) { alertUnhandledError("HangUp", "전화 시스템에 연결되어 있지 않습니다. 다시 시도해주세요."); return; } hangupRequested = true; persistCtiState(); notify(); // 종료 이벤트를 기다린다. 응답이 없으면 재요청만 허용하고 종료를 임의로 확정하지 않는다. hangupTimeoutId = setTimeout(() => { clearHangupRequest(); persistCtiState(); notify(); alertUnhandledError("HangUp", "통화 종료가 확인되지 않았습니다. 다시 시도해주세요."); }, CTI_HANGUP_TIMEOUT_MS); }, };