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 });
|
||||
},
|
||||
};
|
||||
18
src/lib/datetime.ts
Normal file
18
src/lib/datetime.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
export const RESERVE_MINUTE_STEP = 5
|
||||
|
||||
export const getNearestFutureDateTime = (stepMinutes = RESERVE_MINUTE_STEP): string => {
|
||||
const now = new Date()
|
||||
const remainder = now.getMinutes() % stepMinutes
|
||||
if (remainder !== 0) {
|
||||
now.setMinutes(now.getMinutes() + (stepMinutes - remainder))
|
||||
}
|
||||
now.setSeconds(0, 0)
|
||||
|
||||
const year = now.getFullYear()
|
||||
const month = String(now.getMonth() + 1).padStart(2, '0')
|
||||
const day = String(now.getDate()).padStart(2, '0')
|
||||
const hour = String(now.getHours()).padStart(2, '0')
|
||||
const minute = String(now.getMinutes()).padStart(2, '0')
|
||||
|
||||
return `${year}-${month}-${day}T${hour}:${minute}`
|
||||
}
|
||||
@@ -8,4 +8,8 @@ export const clientEnv = createEnv({
|
||||
API_INTERNAL: env.required("NEXT_PUBLIC_API_INTERNAL", process.env.NEXT_PUBLIC_API_INTERNAL),
|
||||
|
||||
STORE_KEY: env.required("NEXT_PUBLIC_STORE_KEY", process.env.NEXT_PUBLIC_STORE_KEY),
|
||||
|
||||
REQUEST_SVC: env.required("NEXT_PUBLIC_REQUEST_SVC", process.env.NEXT_PUBLIC_REQUEST_SVC),
|
||||
|
||||
CTI_WS_URL: env.required("NEXT_PUBLIC_CTI_WS_URL", process.env.NEXT_PUBLIC_CTI_WS_URL),
|
||||
});
|
||||
|
||||
@@ -20,14 +20,17 @@ export const createContactApi = () => {
|
||||
return createServerApi(serverEnv.API_CONTACT_SERVER);
|
||||
};
|
||||
|
||||
//Todo: Front에서 바로 붙지 말고 Backend를 통해서 처리 하도록 수정 필요
|
||||
export const createNotihubApi = () => {
|
||||
return createServerApi(serverEnv.API_NOTIHUB_SERVER);
|
||||
};
|
||||
|
||||
//Todo: Front에서 바로 붙지 말고 Backend를 통해서 처리 하도록 수정 필요
|
||||
export const createIntranetApi = () => {
|
||||
return createServerApi(serverEnv.API_INTRANET_SERVER);
|
||||
};
|
||||
|
||||
//Todo: Front에서 바로 붙지 말고 Backend를 통해서 처리 하도록 수정 필요
|
||||
export const createKartApi = () => {
|
||||
return createServerApi(serverEnv.API_KART_SERVER, {
|
||||
"X-API-Key": serverEnv.KART_API_KEY,
|
||||
|
||||
3
src/lib/surveyUrl.ts
Normal file
3
src/lib/surveyUrl.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
// project.surveyUrl에 들어있는 [$SID] 치환 토큰을 실제 sid로 바꾼다.
|
||||
// 참고: src/app/(pages)/(main)/project/info/page.tsx의 sidParam = 'sid=[$SID]'와 동일한 토큰.
|
||||
export const substituteSurveyUrl = (surveyUrl: string, sid: string) => surveyUrl.replaceAll("[$SID]", sid);
|
||||
Reference in New Issue
Block a user