260727_01_ENH: 전화 걸기 ws 틀어막기, 선택 항목만인경우 선택된 것이 없으면 오류
This commit is contained in:
@@ -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<typeof setInterval> | 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<CtiCallContext>;
|
||||
@@ -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<CtiCall>;
|
||||
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<PersistedCtiState>;
|
||||
@@ -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<ListCallHistSession>(
|
||||
const result = await nextApi.get<ListCallHist>(
|
||||
`/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<string, unknown>, options: { clearContextAfter: boolean }) => {
|
||||
if (!currentCallContext) {
|
||||
const markUserHangup = async (agentSessionId: string) => {
|
||||
if (activeCall?.agentSessionId !== agentSessionId) return;
|
||||
|
||||
try {
|
||||
const updated = await nextApi.patch<boolean>(
|
||||
`/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<string, unknown>, 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<string, unknown>, 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<ListCallHist>(`/list-call-hist/${prjctIdx}/${sid}`, body)
|
||||
.put<ListCallHist>(`/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<string, string>) => {
|
||||
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 });
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user