260714_01_ENH: 테스트 서버에서 기동 후 중간 테스트를 위한 커밋
This commit is contained in:
260
src/lib/cti/ctiClient.ts
Normal file
260
src/lib/cti/ctiClient.ts
Normal file
@@ -0,0 +1,260 @@
|
||||
import { clientEnv } from "@/lib/env.client";
|
||||
import { nextApi } from "@/lib/http-client";
|
||||
import { CTI_AGENT_GROUP, CTI_AGENT_STATUS } from "@/const/ctiConst";
|
||||
import type { ListCallHistRequest } from "@/types/list";
|
||||
|
||||
// TEMP_CTI_LOG: 배포 후 CTI 연동 오류를 콘솔에서 바로 확인하기 위한 임시 로그.
|
||||
// 안정화되면 "TEMP_CTI_LOG"로 검색해서 이 파일의 관련 로그를 전부 제거할 것.
|
||||
|
||||
export type CtiLoginParams = {
|
||||
agentLoginId: string;
|
||||
agentPhone: string;
|
||||
aniNumber: string;
|
||||
agentName: string;
|
||||
};
|
||||
|
||||
export type CtiMakeCallParams = {
|
||||
dialNumber: string;
|
||||
prjctIdx: number;
|
||||
sid: number;
|
||||
listHderId: number;
|
||||
};
|
||||
|
||||
export type CtiConnectionState = "idle" | "connecting" | "open" | "closed";
|
||||
|
||||
type CtiCallContext = {
|
||||
prjctIdx: number;
|
||||
sid: number;
|
||||
listHderId: number;
|
||||
};
|
||||
|
||||
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 currentCallContext: CtiCallContext | null = null;
|
||||
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
const notify = () => {
|
||||
listeners.forEach((listener) => listener());
|
||||
};
|
||||
|
||||
const setConnectionState = (next: CtiConnectionState) => {
|
||||
connectionState = next;
|
||||
notify();
|
||||
};
|
||||
|
||||
const setAgentStatus = (next: string | null) => {
|
||||
agentStatus = next;
|
||||
notify();
|
||||
};
|
||||
|
||||
// 통화 종료(CallClosed) 시 리스트 통화 이력 저장 API로 전달한다.
|
||||
// listHderId/prjctIdx/sid는 WS 메시지에 없어서 makeCall 시점에 캐시해둔 currentCallContext에서 가져온다.
|
||||
const saveCallHistory = (parsed: Record<string, unknown>) => {
|
||||
if (!currentCallContext) {
|
||||
console.warn("[CTI][TEMP_LOG] CallClosed received but no call context cached", parsed); // TEMP_CTI_LOG
|
||||
return;
|
||||
}
|
||||
|
||||
const { prjctIdx, sid, listHderId } = currentCallContext;
|
||||
const startTime = typeof parsed.StartTime === "string" ? parsed.StartTime : "";
|
||||
|
||||
const body: ListCallHistRequest = {
|
||||
listHderId,
|
||||
destNum: String(parsed.DestPhone ?? ""),
|
||||
agentNum: String(parsed.AgentPhone ?? ""),
|
||||
aniNum: String(parsed.ANINumber ?? ""),
|
||||
agentSessionId: String(parsed.AgntSessionID ?? ""),
|
||||
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 ?? ""),
|
||||
};
|
||||
|
||||
console.log("[CTI][TEMP_LOG] saving call history", { prjctIdx, sid, body }); // TEMP_CTI_LOG
|
||||
nextApi.put(`/list-call-hist/${prjctIdx}/${sid}`, body).catch((error) => {
|
||||
console.error("[CTI][TEMP_LOG] failed to save call history", error); // TEMP_CTI_LOG
|
||||
});
|
||||
|
||||
currentCallContext = null;
|
||||
};
|
||||
|
||||
// WS 서버 -> 클라이언트로 오는 메시지는 ZCommand가 기준값이다.
|
||||
// 새로운 서버 이벤트에 대한 후속 조치가 필요하면 여기 case를 추가한다.
|
||||
const handleIncomingMessage = (raw: unknown) => {
|
||||
if (typeof raw !== "string") return;
|
||||
|
||||
let parsed: Record<string, unknown>;
|
||||
try {
|
||||
parsed = JSON.parse(raw);
|
||||
} catch {
|
||||
console.warn("[CTI][TEMP_LOG] failed to parse incoming message", raw); // TEMP_CTI_LOG
|
||||
return;
|
||||
}
|
||||
|
||||
switch (parsed.ZCommand) {
|
||||
case "AgentStatusChanged": {
|
||||
const status = parsed.CTIAgentStatus == null ? null : String(parsed.CTIAgentStatus);
|
||||
console.log("[CTI][TEMP_LOG] AgentStatusChanged ->", status); // TEMP_CTI_LOG
|
||||
setAgentStatus(status);
|
||||
break;
|
||||
}
|
||||
case "CallClosed": {
|
||||
console.log("[CTI][TEMP_LOG] CallClosed ->", parsed); // TEMP_CTI_LOG
|
||||
saveCallHistory(parsed);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const buildKey = (params: CtiLoginParams) =>
|
||||
`${params.agentLoginId}|${params.agentPhone}|${params.aniNumber}|${params.agentName}`;
|
||||
|
||||
const send = (command: Record<string, string>) => {
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
||||
console.warn("[CTI][TEMP_LOG] send skipped, socket not open", command); // TEMP_CTI_LOG
|
||||
return;
|
||||
}
|
||||
console.log("[CTI][TEMP_LOG] send ->", command); // TEMP_CTI_LOG
|
||||
socket.send(JSON.stringify(command));
|
||||
};
|
||||
|
||||
const teardownSocket = () => {
|
||||
if (socket) {
|
||||
console.log("[CTI][TEMP_LOG] teardownSocket, readyState =", socket.readyState); // TEMP_CTI_LOG
|
||||
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");
|
||||
setAgentStatus(null);
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
console.log("[CTI][TEMP_LOG] logout called, currentAgentLoginId =", currentAgentLoginId, "connectionState =", connectionState); // TEMP_CTI_LOG
|
||||
if (currentAgentLoginId && connectionState === "open") {
|
||||
send({ ZCommand: "Logout", AgentLoginID: currentAgentLoginId });
|
||||
}
|
||||
teardownSocket();
|
||||
currentAgentLoginId = null;
|
||||
currentConnectionKey = null;
|
||||
currentLoginParams = null;
|
||||
currentCallContext = null;
|
||||
};
|
||||
|
||||
const connectAndLogin = (params: CtiLoginParams) => {
|
||||
console.log("[CTI][TEMP_LOG] connectAndLogin called with", params); // TEMP_CTI_LOG
|
||||
|
||||
if (!params.agentLoginId) {
|
||||
console.warn("[CTI][TEMP_LOG] connectAndLogin skipped, empty agentLoginId"); // TEMP_CTI_LOG
|
||||
return;
|
||||
}
|
||||
|
||||
const key = buildKey(params);
|
||||
if (currentConnectionKey === key && (connectionState === "open" || connectionState === "connecting")) {
|
||||
console.log("[CTI][TEMP_LOG] connectAndLogin skipped, already connected/connecting with same params"); // TEMP_CTI_LOG
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentAgentLoginId && currentAgentLoginId !== params.agentLoginId) {
|
||||
console.log("[CTI][TEMP_LOG] switching agent from", currentAgentLoginId, "to", params.agentLoginId); // TEMP_CTI_LOG
|
||||
logout();
|
||||
} else {
|
||||
teardownSocket();
|
||||
}
|
||||
|
||||
currentAgentLoginId = params.agentLoginId;
|
||||
currentConnectionKey = key;
|
||||
currentLoginParams = params;
|
||||
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);
|
||||
};
|
||||
|
||||
export const ctiClient = {
|
||||
connectAndLogin,
|
||||
logout,
|
||||
subscribe: (listener: () => void) => {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
getConnectionState: () => connectionState,
|
||||
getAgentStatus: () => agentStatus,
|
||||
makeCall: (params: CtiMakeCallParams) => {
|
||||
if (!currentAgentLoginId || !currentLoginParams) return;
|
||||
console.log("[CTI][TEMP_LOG] makeCall", params); // TEMP_CTI_LOG
|
||||
currentCallContext = { prjctIdx: params.prjctIdx, sid: params.sid, listHderId: params.listHderId };
|
||||
send({
|
||||
ZCommand: "MakeCall",
|
||||
AgentLoginID: currentAgentLoginId,
|
||||
DialNumber: params.dialNumber,
|
||||
ANINumber: currentLoginParams.aniNumber,
|
||||
});
|
||||
},
|
||||
hangup: requireAgent((agentLoginId) => {
|
||||
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) => {
|
||||
if (!currentAgentLoginId) return;
|
||||
console.log("[CTI][TEMP_LOG] setRecordStamp", { tag }); // TEMP_CTI_LOG
|
||||
send({ ZCommand: "SetRecordStamp", AgentLoginID: currentAgentLoginId, Tag: tag });
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user