260727_01_ENH: 전화 걸기 ws 틀어막기, 선택 항목만인경우 선택된 것이 없으면 오류
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
'use client'
|
'use client'
|
||||||
|
|
||||||
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
|
import { Suspense, useEffect, useMemo, useState } from "react";
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
import { ArrowLeft, CalendarClock, RefreshCw } from "lucide-react";
|
import { ArrowLeft, CalendarClock, RefreshCw } from "lucide-react";
|
||||||
import { useMounted } from "@kri/common/hooks";
|
import { useMounted } from "@kri/common/hooks";
|
||||||
@@ -37,25 +37,25 @@ const ListContactPageContent = () => {
|
|||||||
|
|
||||||
// 이 페이지 진입 시의 prjctIdx를 기준으로 기록해두고, 이후 외부(프로젝트 선택기 등)에서
|
// 이 페이지 진입 시의 prjctIdx를 기준으로 기록해두고, 이후 외부(프로젝트 선택기 등)에서
|
||||||
// prjctIdx가 바뀌면 더 이상 현재 sid가 유효하지 않으므로 목록 관리 화면으로 내보낸다.
|
// prjctIdx가 바뀌면 더 이상 현재 sid가 유효하지 않으므로 목록 관리 화면으로 내보낸다.
|
||||||
// isStaleProject는 렌더 시점에 ref를 직접 비교해서, 리다이렉트 effect가 돌기 전에도
|
// isStaleProject는 렌더 시점에 기준 프로젝트와 비교해서, 리다이렉트 effect가 돌기 전에도
|
||||||
// 아래 쿼리들이 잘못된 prjctIdx+sid 조합으로 요청을 보내 에러 alert를 띄우는 걸 막는다.
|
// 아래 쿼리들이 잘못된 prjctIdx+sid 조합으로 요청을 보내 에러 alert를 띄우는 걸 막는다.
|
||||||
const baselinePrjctIdx = useRef<number | null>(null);
|
const [baselinePrjctIdx, setBaselinePrjctIdx] = useState<number | null>(null);
|
||||||
const isStaleProject = baselinePrjctIdx.current !== null && baselinePrjctIdx.current !== prjctIdx;
|
const isStaleProject = baselinePrjctIdx !== null && baselinePrjctIdx !== prjctIdx;
|
||||||
const queriesEnabled = mounted && prjctIdx > 0 && !isStaleProject;
|
const queriesEnabled = mounted && prjctIdx > 0 && !isStaleProject;
|
||||||
const enabled = queriesEnabled && !!sid;
|
const enabled = queriesEnabled && !!sid;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!mounted || prjctIdx <= 0) return;
|
if (!mounted || prjctIdx <= 0) return;
|
||||||
|
|
||||||
if (baselinePrjctIdx.current === null) {
|
if (baselinePrjctIdx === null) {
|
||||||
baselinePrjctIdx.current = prjctIdx;
|
setBaselinePrjctIdx(prjctIdx);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (baselinePrjctIdx.current !== prjctIdx) {
|
if (baselinePrjctIdx !== prjctIdx) {
|
||||||
router.replace('/list/manage');
|
router.replace('/list/manage');
|
||||||
}
|
}
|
||||||
}, [prjctIdx, mounted, router]);
|
}, [baselinePrjctIdx, prjctIdx, mounted, router]);
|
||||||
|
|
||||||
const projectInfoQuery = useProjectInfoQuery(prjctIdx, queriesEnabled);
|
const projectInfoQuery = useProjectInfoQuery(prjctIdx, queriesEnabled);
|
||||||
const listHeaderQuery = useListHeaderQuery(prjctIdx, queriesEnabled);
|
const listHeaderQuery = useListHeaderQuery(prjctIdx, queriesEnabled);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import {NextRequest, NextResponse} from "next/server";
|
|||||||
import {RouteContext} from "@/types/common";
|
import {RouteContext} from "@/types/common";
|
||||||
import {createContactApi} from "@/lib/http-server";
|
import {createContactApi} from "@/lib/http-server";
|
||||||
import {errorToResponse} from "@kri/common/http";
|
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) => {
|
export const GET = async (_req: NextRequest, context: RouteContext) => {
|
||||||
try {
|
try {
|
||||||
@@ -25,8 +25,8 @@ export const GET = async (_req: NextRequest, context: RouteContext) => {
|
|||||||
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
export const PUT = async (req: NextRequest, context: RouteContext) => {
|
||||||
try {
|
try {
|
||||||
const { slug = [] } = await context.params;
|
const { slug = [] } = await context.params;
|
||||||
const [prjctIdx, sid] = slug;
|
const [prjctIdx, sid, action] = slug;
|
||||||
if (!prjctIdx || !sid) {
|
if (!prjctIdx || !sid || (action !== "call-start" && action !== "call-close")) {
|
||||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
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 contactApi = await createContactApi();
|
||||||
const result = await contactApi.put(`/list-call-hist/${prjctIdx}/${sid}`, body);
|
const result = await contactApi.put<ListCallHist>(
|
||||||
|
`/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<boolean>(
|
||||||
|
`/list-call-hist/hangup/${encodeURIComponent(agentSessionId)}`,
|
||||||
|
);
|
||||||
return NextResponse.json(result, { status: 200 });
|
return NextResponse.json(result, { status: 200 });
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
return errorToResponse(error);
|
return errorToResponse(error);
|
||||||
|
|||||||
@@ -12,8 +12,13 @@ export type ApplyFilterOptionValue = ListFilterTarget
|
|||||||
* alert 후 진행을 막아야 하는 호출부에서 공통으로 사용한다.
|
* alert 후 진행을 막아야 하는 호출부에서 공통으로 사용한다.
|
||||||
*/
|
*/
|
||||||
export const validateApplyFilterTarget = (value: ApplyFilterOptionValue, filterSummary?: string[]): boolean => {
|
export const validateApplyFilterTarget = (value: ApplyFilterOptionValue, filterSummary?: string[]): boolean => {
|
||||||
if (value === 'filtered' && (filterSummary?.length ?? 0) === 0) {
|
if (["selected", "filtered"].includes(value) && (filterSummary?.length ?? 0) === 0) {
|
||||||
alert('적용된 필터가 없습니다. 필터를 적용해 주세요.')
|
const alertText: string =
|
||||||
|
value === "selected" ?
|
||||||
|
"선택된 항목이 없습니다. 항목을 선택해 주세요"
|
||||||
|
: "적용된 필터가 없습니다. 필터를 적용해 주세요."
|
||||||
|
|
||||||
|
alert(alertText)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
|
|||||||
@@ -21,8 +21,7 @@ import SurveyQrDialog from '@/components/dialog/SurveyQrDialog'
|
|||||||
import SingleMessageSendDialog from '@/components/dialog/SingleMessageSendDialog'
|
import SingleMessageSendDialog from '@/components/dialog/SingleMessageSendDialog'
|
||||||
import { ctiClient } from '@/lib/cti/ctiClient'
|
import { ctiClient } from '@/lib/cti/ctiClient'
|
||||||
import { useCtiConnectionStatus } from '@/hooks/useCtiConnectionStatus'
|
import { useCtiConnectionStatus } from '@/hooks/useCtiConnectionStatus'
|
||||||
import { useCtiAgentStatus } from '@/hooks/useCtiAgentStatus'
|
import { useCtiCallPhase } from '@/hooks/useCtiCallPhase'
|
||||||
import { CTI_ON_CALL_STATUSES } from '@/const/ctiConst'
|
|
||||||
import { cn } from '@/lib/utils'
|
import { cn } from '@/lib/utils'
|
||||||
import { downloadFile } from '@kri/common/browser'
|
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 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 }) => (
|
const FieldRow = ({ label, children }: { label: string; children: ReactNode }) => (
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Label className="w-24 shrink-0 text-sm font-bold text-foreground">{label}</Label>
|
<Label className="w-24 shrink-0 text-sm font-bold text-foreground">{label}</Label>
|
||||||
@@ -98,8 +109,9 @@ const ListContactInfoPanel = ({
|
|||||||
const [qrTargetUrl, setQrTargetUrl] = useState('')
|
const [qrTargetUrl, setQrTargetUrl] = useState('')
|
||||||
const ctiConnectionStatus = useCtiConnectionStatus()
|
const ctiConnectionStatus = useCtiConnectionStatus()
|
||||||
const isCtiReady = ctiConnectionStatus === 'open'
|
const isCtiReady = ctiConnectionStatus === 'open'
|
||||||
const ctiAgentStatus = useCtiAgentStatus()
|
const ctiCallPhase = useCtiCallPhase()
|
||||||
const isOnCall = ctiAgentStatus !== null && (CTI_ON_CALL_STATUSES as readonly string[]).includes(ctiAgentStatus)
|
const isDialing = ctiCallPhase === 'dialing'
|
||||||
|
const isOnCall = ctiCallPhase === 'active'
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isOnCall) return
|
if (!isOnCall) return
|
||||||
@@ -148,12 +160,13 @@ const ListContactInfoPanel = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleCall = (telNum: string, listHderId: number) => {
|
const handleCall = (telNum: string, listHderId: number) => {
|
||||||
if (!isCtiReady) return
|
if (!isCtiReady || isDialing) return
|
||||||
// CTI_HANGUP_PENDING_VENDOR: 외주사 Hangup 명령 동작 확인 후 통화 중 버튼을 활성화하면 즉시 사용할 수 있다.
|
// CTI_HANGUP_PENDING_VENDOR: 외주사 Hangup 명령 동작 확인 후 통화 중 버튼을 활성화하면 즉시 사용할 수 있다.
|
||||||
if (isOnCall) {
|
if (isOnCall) {
|
||||||
ctiClient.hangup()
|
ctiClient.hangup()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!telNum) return
|
if (!telNum) return
|
||||||
ctiClient.makeCall({ dialNumber: telNum, prjctIdx, sid: Number(sid), listHderId, aniNumber: callerTelNum ?? '' })
|
ctiClient.makeCall({ dialNumber: telNum, prjctIdx, sid: Number(sid), listHderId, aniNumber: callerTelNum ?? '' })
|
||||||
}
|
}
|
||||||
@@ -218,12 +231,12 @@ const ListContactInfoPanel = ({
|
|||||||
type="button"
|
type="button"
|
||||||
variant="outline"
|
variant="outline"
|
||||||
className={cn('shrink-0 gap-2', isOnCall && 'bg-accent text-accent-foreground')}
|
className={cn('shrink-0 gap-2', isOnCall && 'bg-accent text-accent-foreground')}
|
||||||
disabled={!isCtiReady || isOnCall}
|
disabled={!isCtiReady || isDialing}
|
||||||
title={!isCtiReady ? '전화 시스템에 연결되어 있지 않습니다.' : undefined}
|
title={getCallButtonTitle(isCtiReady, isDialing)}
|
||||||
onClick={() => handleCall(value, header.listHderId)}
|
onClick={() => handleCall(value, header.listHderId)}
|
||||||
>
|
>
|
||||||
<Phone className="h-4 w-4" />
|
<Phone className="h-4 w-4" />
|
||||||
{isOnCall ? '통화중' : '전화'}
|
{getCallButtonLabel(isDialing, isOnCall)}
|
||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -235,6 +248,11 @@ const ListContactInfoPanel = ({
|
|||||||
발송
|
발송
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
{(isDialing || isOnCall) &&
|
||||||
|
<p className="text-sm text-red-600 font-medium mt-1">
|
||||||
|
⚠️ 전화를 끊어야만 통화 종료가 기록됩니다.
|
||||||
|
</p>
|
||||||
|
}
|
||||||
</FieldRow>
|
</FieldRow>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,5 +5,5 @@ export const CTI_AGENT_STATUS = {
|
|||||||
BREAK: "11",
|
BREAK: "11",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
// WS 서버가 ZCommand: "AgentStatusChanged"로 보내는 CTIAgentStatus 값 중, 통화 중으로 간주할 값들
|
// WS 서버가 보내는 CTIAgentStatus 값 중 통화 중 또는 통화 중 재로그인 대기로 간주할 값들
|
||||||
export const CTI_ON_CALL_STATUSES = ["2", "3"] as const;
|
export const CTI_ON_CALL_STATUSES = ["0", "2", "3"] as const;
|
||||||
|
|||||||
@@ -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);
|
|
||||||
}
|
|
||||||
13
src/hooks/useCtiCallPhase.ts
Normal file
13
src/hooks/useCtiCallPhase.ts
Normal file
@@ -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<CtiCallPhase>(
|
||||||
|
ctiClient.subscribe,
|
||||||
|
ctiClient.getCallPhase,
|
||||||
|
() => "idle",
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,21 +1,25 @@
|
|||||||
import { clientEnv } from "@/lib/env.client";
|
import { clientEnv } from "@/lib/env.client";
|
||||||
import { nextApi } from "@/lib/http-client";
|
import { nextApi } from "@/lib/http-client";
|
||||||
import { CTI_AGENT_GROUP, CTI_AGENT_STATUS } from "@/const/ctiConst";
|
import { CTI_AGENT_GROUP, CTI_ON_CALL_STATUSES } from "@/const/ctiConst";
|
||||||
import type { ListCallHist, ListCallHistRequest, ListCallHistSession } from "@/types/list";
|
import type {
|
||||||
|
ListCallCloseRequest,
|
||||||
|
ListCallHist,
|
||||||
|
ListCallStartRequest,
|
||||||
|
} from "@/types/list";
|
||||||
import { getLocalStorage, removeLocalStorage, setLocalStorage } from "@/store/storage/secure-storage";
|
import { getLocalStorage, removeLocalStorage, setLocalStorage } from "@/store/storage/secure-storage";
|
||||||
import { StorageKeys } from "@/store/storage/storage-keys";
|
import { StorageKeys } from "@/store/storage/storage-keys";
|
||||||
|
|
||||||
// TEMP_CTI_LOG: 배포 후 CTI 연동 오류를 콘솔에서 바로 확인하기 위한 임시 로그.
|
// TEMP_CTI_LOG: 배포 후 CTI 연동 오류를 콘솔에서 바로 확인하기 위한 임시 로그.
|
||||||
// 안정화되면 "TEMP_CTI_LOG"로 검색해서 이 파일의 관련 로그를 전부 제거할 것.
|
// 안정화되면 "TEMP_CTI_LOG"로 검색해서 이 파일의 관련 로그를 전부 제거할 것.
|
||||||
|
|
||||||
export type CtiLoginParams = {
|
type CtiLoginParams = {
|
||||||
agentLoginId: string;
|
agentLoginId: string;
|
||||||
agentPhone: string;
|
agentPhone: string;
|
||||||
aniNumber: string;
|
aniNumber: string;
|
||||||
agentName: string;
|
agentName: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type CtiMakeCallParams = {
|
type CtiMakeCallParams = {
|
||||||
dialNumber: string;
|
dialNumber: string;
|
||||||
prjctIdx: number;
|
prjctIdx: number;
|
||||||
sid: number;
|
sid: number;
|
||||||
@@ -23,7 +27,8 @@ export type CtiMakeCallParams = {
|
|||||||
aniNumber: string;
|
aniNumber: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type CtiConnectionState = "idle" | "connecting" | "open" | "closed";
|
type CtiConnectionState = "idle" | "connecting" | "open" | "closed";
|
||||||
|
export type CtiCallPhase = "idle" | "dialing" | "active";
|
||||||
|
|
||||||
type CtiCallContext = {
|
type CtiCallContext = {
|
||||||
prjctIdx: number;
|
prjctIdx: number;
|
||||||
@@ -31,18 +36,25 @@ type CtiCallContext = {
|
|||||||
listHderId: number;
|
listHderId: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type CtiCall = {
|
||||||
|
context: CtiCallContext;
|
||||||
|
agentSessionId: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
type PersistedCtiState = {
|
type PersistedCtiState = {
|
||||||
version: 1;
|
version: 2;
|
||||||
agentLoginId: string;
|
agentLoginId: string;
|
||||||
agentStatus: string | null;
|
agentStatus: string | null;
|
||||||
currentCallContext: CtiCallContext | null;
|
activeCall: CtiCall | null;
|
||||||
|
closingCall: CtiCall | null;
|
||||||
lastCallContext: CtiCallContext | null;
|
lastCallContext: CtiCallContext | null;
|
||||||
agentSessionId: string | null;
|
|
||||||
lastCallHistId: number | null;
|
lastCallHistId: number | null;
|
||||||
|
hangupRequested: boolean;
|
||||||
|
callClosedReceived: boolean;
|
||||||
updatedAt: number;
|
updatedAt: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
const CTI_STATE_VERSION = 1;
|
const CTI_STATE_VERSION = 2;
|
||||||
const CTI_STATE_TTL_MS = 24 * 60 * 60 * 1000;
|
const CTI_STATE_TTL_MS = 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
let socket: WebSocket | null = null;
|
let socket: WebSocket | null = null;
|
||||||
@@ -51,10 +63,13 @@ let currentAgentLoginId: string | null = null;
|
|||||||
let currentConnectionKey: string | null = null;
|
let currentConnectionKey: string | null = null;
|
||||||
let currentLoginParams: CtiLoginParams | null = null;
|
let currentLoginParams: CtiLoginParams | null = null;
|
||||||
let agentStatus: string | 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 lastCallContext: CtiCallContext | null = null;
|
||||||
let currentAgentSessionId: string | null = null;
|
|
||||||
let lastCallHistId: number | 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>();
|
const listeners = new Set<() => void>();
|
||||||
|
|
||||||
@@ -62,6 +77,18 @@ const notify = () => {
|
|||||||
listeners.forEach((listener) => listener());
|
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 => {
|
const isCallContext = (value: unknown): value is CtiCallContext => {
|
||||||
if (typeof value !== "object" || value === null) return false;
|
if (typeof value !== "object" || value === null) return false;
|
||||||
const context = value as Partial<CtiCallContext>;
|
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 => {
|
const isPersistedCtiState = (value: unknown): value is PersistedCtiState => {
|
||||||
if (typeof value !== "object" || value === null) return false;
|
if (typeof value !== "object" || value === null) return false;
|
||||||
const state = value as Partial<PersistedCtiState>;
|
const state = value as Partial<PersistedCtiState>;
|
||||||
@@ -82,10 +118,12 @@ const isPersistedCtiState = (value: unknown): value is PersistedCtiState => {
|
|||||||
state.version === CTI_STATE_VERSION &&
|
state.version === CTI_STATE_VERSION &&
|
||||||
typeof state.agentLoginId === "string" &&
|
typeof state.agentLoginId === "string" &&
|
||||||
(state.agentStatus === null || typeof state.agentStatus === "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.lastCallContext === null || isCallContext(state.lastCallContext)) &&
|
||||||
(state.agentSessionId === null || typeof state.agentSessionId === "string") &&
|
|
||||||
(state.lastCallHistId === null || typeof state.lastCallHistId === "number") &&
|
(state.lastCallHistId === null || typeof state.lastCallHistId === "number") &&
|
||||||
|
typeof state.hangupRequested === "boolean" &&
|
||||||
|
typeof state.callClosedReceived === "boolean" &&
|
||||||
typeof state.updatedAt === "number"
|
typeof state.updatedAt === "number"
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
@@ -96,10 +134,12 @@ const persistCtiState = () => {
|
|||||||
version: CTI_STATE_VERSION,
|
version: CTI_STATE_VERSION,
|
||||||
agentLoginId: currentAgentLoginId,
|
agentLoginId: currentAgentLoginId,
|
||||||
agentStatus,
|
agentStatus,
|
||||||
currentCallContext,
|
activeCall,
|
||||||
|
closingCall,
|
||||||
lastCallContext,
|
lastCallContext,
|
||||||
agentSessionId: currentAgentSessionId,
|
|
||||||
lastCallHistId,
|
lastCallHistId,
|
||||||
|
hangupRequested,
|
||||||
|
callClosedReceived,
|
||||||
updatedAt: Date.now(),
|
updatedAt: Date.now(),
|
||||||
} satisfies PersistedCtiState);
|
} satisfies PersistedCtiState);
|
||||||
};
|
};
|
||||||
@@ -116,27 +156,34 @@ const restoreCtiState = (agentLoginId: string) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
agentStatus = stored.agentStatus;
|
agentStatus = stored.agentStatus;
|
||||||
currentCallContext = stored.currentCallContext;
|
activeCall = stored.activeCall;
|
||||||
|
closingCall = stored.closingCall;
|
||||||
lastCallContext = stored.lastCallContext;
|
lastCallContext = stored.lastCallContext;
|
||||||
currentAgentSessionId = stored.agentSessionId;
|
|
||||||
lastCallHistId = stored.lastCallHistId;
|
lastCallHistId = stored.lastCallHistId;
|
||||||
|
hangupRequested = stored.hangupRequested;
|
||||||
|
callClosedReceived = stored.callClosedReceived;
|
||||||
notify();
|
notify();
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
const recoverLastCallHistId = async (agentLoginId: string) => {
|
const recoverLastCallHistId = async (agentLoginId: string) => {
|
||||||
const agentSessionId = currentAgentSessionId;
|
const targetCall =
|
||||||
const callContext = currentCallContext ?? lastCallContext;
|
activeCall?.agentSessionId ? activeCall :
|
||||||
if (!agentSessionId || lastCallHistId !== null || !callContext) return;
|
closingCall?.agentSessionId ? closingCall :
|
||||||
|
null;
|
||||||
|
if (!targetCall?.agentSessionId) return;
|
||||||
|
const agentSessionId = targetCall.agentSessionId;
|
||||||
|
const callContext = targetCall.context;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await nextApi.get<ListCallHistSession>(
|
const result = await nextApi.get<ListCallHist>(
|
||||||
`/list-call-hist/session/${encodeURIComponent(agentSessionId)}`,
|
`/list-call-hist/session/${encodeURIComponent(agentSessionId)}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
const isSameCall =
|
const isSameCall =
|
||||||
currentAgentLoginId === agentLoginId &&
|
currentAgentLoginId === agentLoginId &&
|
||||||
currentAgentSessionId === agentSessionId &&
|
(activeCall?.agentSessionId === agentSessionId ||
|
||||||
|
closingCall?.agentSessionId === agentSessionId) &&
|
||||||
result.agentSessionId === agentSessionId &&
|
result.agentSessionId === agentSessionId &&
|
||||||
result.prjctIdx === callContext.prjctIdx &&
|
result.prjctIdx === callContext.prjctIdx &&
|
||||||
result.sid === callContext.sid &&
|
result.sid === callContext.sid &&
|
||||||
@@ -153,7 +200,24 @@ const recoverLastCallHistId = async (agentLoginId: string) => {
|
|||||||
|
|
||||||
lastCallContext = callContext;
|
lastCallContext = callContext;
|
||||||
setLastCallHistId(result.listCallHistIdx);
|
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) {
|
} catch (error) {
|
||||||
console.warn("[CTI][TEMP_LOG] failed to recover call history", { agentSessionId, error }); // TEMP_CTI_LOG
|
console.warn("[CTI][TEMP_LOG] failed to recover call history", { agentSessionId, error }); // TEMP_CTI_LOG
|
||||||
}
|
}
|
||||||
@@ -164,8 +228,18 @@ const setConnectionState = (next: CtiConnectionState) => {
|
|||||||
notify();
|
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) => {
|
const setAgentStatus = (next: string | null) => {
|
||||||
agentStatus = next;
|
agentStatus = next;
|
||||||
|
if (next !== null && next !== "0") {
|
||||||
|
stopReconnectLoop();
|
||||||
|
}
|
||||||
persistCtiState();
|
persistCtiState();
|
||||||
notify();
|
notify();
|
||||||
};
|
};
|
||||||
@@ -176,20 +250,47 @@ const setLastCallHistId = (next: number | null) => {
|
|||||||
notify();
|
notify();
|
||||||
};
|
};
|
||||||
|
|
||||||
// 통화 세션 시작(StartSessionRecord)/종료(CallClosed) 시 리스트 통화 이력 저장 API로 전달한다.
|
const markUserHangup = async (agentSessionId: string) => {
|
||||||
// listHderId/prjctIdx/sid는 WS 메시지에 없어서 makeCall 시점에 캐시해둔 currentCallContext에서 가져온다.
|
if (activeCall?.agentSessionId !== agentSessionId) return;
|
||||||
// clearContextAfter=false: StartSessionRecord는 같은 통화의 CallClosed가 이어서 오므로 컨텍스트를 유지한다.
|
|
||||||
const saveCallHistory = (parsed: Record<string, unknown>, options: { clearContextAfter: boolean }) => {
|
try {
|
||||||
if (!currentCallContext) {
|
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
|
console.warn("[CTI][TEMP_LOG] call history event received but no call context cached", parsed); // TEMP_CTI_LOG
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const callContext = currentCallContext;
|
const callContext = targetCall.context;
|
||||||
const { prjctIdx, sid, listHderId } = callContext;
|
const { prjctIdx, sid, listHderId } = callContext;
|
||||||
const startTime = typeof parsed.StartTime === "string" ? parsed.StartTime : "";
|
const startTime = typeof parsed.StartTime === "string" ? parsed.StartTime : "";
|
||||||
|
|
||||||
const body: ListCallHistRequest = {
|
const startBody: ListCallStartRequest = {
|
||||||
listHderId,
|
listHderId,
|
||||||
destNum: String(parsed.DestPhone ?? ""),
|
destNum: String(parsed.DestPhone ?? ""),
|
||||||
agentNum: String(parsed.AgentPhone ?? ""),
|
agentNum: String(parsed.AgentPhone ?? ""),
|
||||||
@@ -198,42 +299,51 @@ const saveCallHistory = (parsed: Record<string, unknown>, options: { clearContex
|
|||||||
destSessionId: String(parsed.DestSessionID ?? ""),
|
destSessionId: String(parsed.DestSessionID ?? ""),
|
||||||
callTy: String(parsed.CallType ?? ""),
|
callTy: String(parsed.CallType ?? ""),
|
||||||
startDt: startTime.replace(" ", "T"),
|
startDt: startTime.replace(" ", "T"),
|
||||||
totalTime: Number(parsed.TotalTime ?? 0),
|
|
||||||
talkTime: Number(parsed.TalkTime ?? 0),
|
|
||||||
mediaServerId: Number(parsed.MediaServerID ?? 0),
|
mediaServerId: Number(parsed.MediaServerID ?? 0),
|
||||||
mediaServerName: String(parsed.MediaServerName ?? ""),
|
mediaServerName: String(parsed.MediaServerName ?? ""),
|
||||||
recordFileName: String(parsed.RecordFileName ?? ""),
|
recordFileName: String(parsed.RecordFileName ?? ""),
|
||||||
};
|
};
|
||||||
|
const body: ListCallStartRequest | ListCallCloseRequest =
|
||||||
currentAgentSessionId = body.agentSessionId || currentAgentSessionId;
|
phase === "close"
|
||||||
persistCtiState();
|
? {
|
||||||
|
...startBody,
|
||||||
if (
|
totalTime: Number(parsed.TotalTime ?? 0),
|
||||||
options.clearContextAfter &&
|
talkTime: Number(parsed.TalkTime ?? 0),
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
: startBody;
|
||||||
|
|
||||||
console.log("[CTI][TEMP_LOG] saving call history", { prjctIdx, sid, body }); // TEMP_CTI_LOG
|
if (!isClosingCall) {
|
||||||
|
activeCall = {
|
||||||
|
...targetCall,
|
||||||
|
agentSessionId: body.agentSessionId || targetCall.agentSessionId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
persistCtiState();
|
||||||
|
notify();
|
||||||
|
|
||||||
|
const action = phase === "start" ? "call-start" : "call-close";
|
||||||
|
console.log(`[CTI][TEMP_LOG] saving ${action}`, { prjctIdx, sid, body }); // TEMP_CTI_LOG
|
||||||
nextApi
|
nextApi
|
||||||
.put<ListCallHist>(`/list-call-hist/${prjctIdx}/${sid}`, body)
|
.put<ListCallHist>(`/list-call-hist/${prjctIdx}/${sid}/${action}`, body)
|
||||||
.then((result) => {
|
.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;
|
lastCallContext = callContext;
|
||||||
setLastCallHistId(result?.listCallHistIdx ?? null);
|
setLastCallHistId(result?.listCallHistIdx ?? null);
|
||||||
if (options.clearContextAfter && currentCallContext === callContext) {
|
if (phase === "start" && hangupRequested && body.agentSessionId) {
|
||||||
currentCallContext = null;
|
void markUserHangup(body.agentSessionId);
|
||||||
|
}
|
||||||
|
if (phase === "close") {
|
||||||
|
if (closingCall?.agentSessionId === body.agentSessionId) {
|
||||||
|
closingCall = null;
|
||||||
|
} else if (activeCall?.agentSessionId === body.agentSessionId) {
|
||||||
|
activeCall = null;
|
||||||
|
}
|
||||||
persistCtiState();
|
persistCtiState();
|
||||||
|
notify();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.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) {
|
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": {
|
case "AgentStatusChanged": {
|
||||||
const status = parsed.CTIAgentStatus == null ? null : String(parsed.CTIAgentStatus);
|
const status = parsed.CTIAgentStatus == null ? null : String(parsed.CTIAgentStatus);
|
||||||
console.log("[CTI][TEMP_LOG] AgentStatusChanged ->", status); // TEMP_CTI_LOG
|
console.log("[CTI][TEMP_LOG] AgentStatusChanged ->", status); // TEMP_CTI_LOG
|
||||||
@@ -261,13 +384,27 @@ const handleIncomingMessage = (raw: unknown) => {
|
|||||||
case "StartSessionRecord": {
|
case "StartSessionRecord": {
|
||||||
console.log("[CTI][TEMP_LOG] StartSessionRecord ->", parsed); // TEMP_CTI_LOG
|
console.log("[CTI][TEMP_LOG] StartSessionRecord ->", parsed); // TEMP_CTI_LOG
|
||||||
setAgentStatus("2");
|
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;
|
break;
|
||||||
}
|
}
|
||||||
case "CallClosed": {
|
case "CallClosed": {
|
||||||
console.log("[CTI][TEMP_LOG] CallClosed ->", parsed); // TEMP_CTI_LOG
|
console.log("[CTI][TEMP_LOG] CallClosed ->", parsed); // TEMP_CTI_LOG
|
||||||
|
const eventAgentSessionId = String(parsed.AgntSessionID ?? "");
|
||||||
|
const isClosingCall =
|
||||||
|
eventAgentSessionId !== "" && eventAgentSessionId === closingCall?.agentSessionId;
|
||||||
|
if (!isClosingCall) {
|
||||||
|
callClosedReceived = true;
|
||||||
setAgentStatus(null);
|
setAgentStatus(null);
|
||||||
saveCallHistory(parsed, { clearContextAfter: true });
|
}
|
||||||
|
saveCallHistory(parsed, "close");
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
@@ -287,6 +424,18 @@ const send = (command: Record<string, string>) => {
|
|||||||
socket.send(JSON.stringify(command));
|
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 = () => {
|
const teardownSocket = () => {
|
||||||
if (socket) {
|
if (socket) {
|
||||||
console.log("[CTI][TEMP_LOG] teardownSocket, readyState =", socket.readyState); // TEMP_CTI_LOG
|
console.log("[CTI][TEMP_LOG] teardownSocket, readyState =", socket.readyState); // TEMP_CTI_LOG
|
||||||
@@ -312,14 +461,76 @@ const logout = () => {
|
|||||||
currentAgentLoginId = null;
|
currentAgentLoginId = null;
|
||||||
currentConnectionKey = null;
|
currentConnectionKey = null;
|
||||||
currentLoginParams = null;
|
currentLoginParams = null;
|
||||||
currentCallContext = null;
|
activeCall = null;
|
||||||
|
closingCall = null;
|
||||||
lastCallContext = null;
|
lastCallContext = null;
|
||||||
currentAgentSessionId = null;
|
hangupRequested = false;
|
||||||
|
callClosedReceived = false;
|
||||||
|
stopReconnectLoop();
|
||||||
setAgentStatus(null);
|
setAgentStatus(null);
|
||||||
setLastCallHistId(null);
|
setLastCallHistId(null);
|
||||||
if (shouldClearPersistedState) removeLocalStorage(StorageKeys.CtiState);
|
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) => {
|
const connectAndLogin = (params: CtiLoginParams) => {
|
||||||
console.log("[CTI][TEMP_LOG] connectAndLogin called with", params); // TEMP_CTI_LOG
|
console.log("[CTI][TEMP_LOG] connectAndLogin called with", params); // TEMP_CTI_LOG
|
||||||
|
|
||||||
@@ -344,45 +555,10 @@ const connectAndLogin = (params: CtiLoginParams) => {
|
|||||||
currentAgentLoginId = params.agentLoginId;
|
currentAgentLoginId = params.agentLoginId;
|
||||||
currentConnectionKey = key;
|
currentConnectionKey = key;
|
||||||
currentLoginParams = params;
|
currentLoginParams = params;
|
||||||
|
|
||||||
const restored = restoreCtiState(params.agentLoginId);
|
const restored = restoreCtiState(params.agentLoginId);
|
||||||
if (restored) void recoverLastCallHistId(params.agentLoginId);
|
if (restored) void recoverLastCallHistId(params.agentLoginId);
|
||||||
setConnectionState("connecting");
|
openSocketAndLogin(params);
|
||||||
|
|
||||||
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 = {
|
export const ctiClient = {
|
||||||
@@ -393,16 +569,27 @@ export const ctiClient = {
|
|||||||
return () => listeners.delete(listener);
|
return () => listeners.delete(listener);
|
||||||
},
|
},
|
||||||
getConnectionState: () => connectionState,
|
getConnectionState: () => connectionState,
|
||||||
getAgentStatus: () => agentStatus,
|
getCallPhase,
|
||||||
getLastCallHistId: () => lastCallHistId,
|
|
||||||
getLastCallHistIdFor: (prjctIdx: number, sid: number) =>
|
getLastCallHistIdFor: (prjctIdx: number, sid: number) =>
|
||||||
lastCallContext?.prjctIdx === prjctIdx && lastCallContext.sid === sid ? lastCallHistId : null,
|
lastCallContext?.prjctIdx === prjctIdx && lastCallContext.sid === sid ? lastCallHistId : null,
|
||||||
makeCall: (params: CtiMakeCallParams) => {
|
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
|
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;
|
lastCallContext = null;
|
||||||
currentAgentSessionId = null;
|
hangupRequested = false;
|
||||||
|
callClosedReceived = false;
|
||||||
setLastCallHistId(null); // 새 통화 시작, 이전 통화의 listCallHistIdx는 더 이상 유효하지 않음
|
setLastCallHistId(null); // 새 통화 시작, 이전 통화의 listCallHistIdx는 더 이상 유효하지 않음
|
||||||
send({
|
send({
|
||||||
ZCommand: "MakeCall",
|
ZCommand: "MakeCall",
|
||||||
@@ -411,22 +598,24 @@ export const ctiClient = {
|
|||||||
ANINumber: params.aniNumber,
|
ANINumber: params.aniNumber,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
hangup: requireAgent((agentLoginId) => {
|
hangup: () => {
|
||||||
// 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) => {
|
|
||||||
if (!currentAgentLoginId) return;
|
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 });
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -260,7 +260,7 @@ export type ListReserve = {
|
|||||||
regDt: string;
|
regDt: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ListCallHistRequest = {
|
export type ListCallStartRequest = {
|
||||||
listHderId: number;
|
listHderId: number;
|
||||||
destNum: string;
|
destNum: string;
|
||||||
agentNum: string;
|
agentNum: string;
|
||||||
@@ -269,30 +269,27 @@ export type ListCallHistRequest = {
|
|||||||
destSessionId: string;
|
destSessionId: string;
|
||||||
callTy: string;
|
callTy: string;
|
||||||
startDt: string;
|
startDt: string;
|
||||||
totalTime: number;
|
|
||||||
talkTime: number;
|
|
||||||
mediaServerId: number;
|
mediaServerId: number;
|
||||||
mediaServerName: string;
|
mediaServerName: string;
|
||||||
recordFileName: string;
|
recordFileName: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ListCallHist = ListCallHistRequest & {
|
export type ListCallCloseRequest = ListCallStartRequest & {
|
||||||
|
totalTime: number;
|
||||||
|
talkTime: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ListCallHist = ListCallCloseRequest & {
|
||||||
listCallHistIdx: number;
|
listCallHistIdx: number;
|
||||||
prjctIdx: number;
|
prjctIdx: number;
|
||||||
sid: number;
|
sid: number;
|
||||||
|
callStatus: 2 | 4 | 9;
|
||||||
endDt?: string;
|
endDt?: string;
|
||||||
regUser: string;
|
regUser: string;
|
||||||
regDt: string;
|
regDt: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ListCallHistSession = {
|
export type ListCallHistSession = ListCallHist;
|
||||||
listCallHistIdx: number;
|
|
||||||
agentSessionId: string;
|
|
||||||
destSessionId: string;
|
|
||||||
prjctIdx: number;
|
|
||||||
sid: number;
|
|
||||||
listHderId: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ListReserveRequest = {
|
export type ListReserveRequest = {
|
||||||
prjctIdx: number;
|
prjctIdx: number;
|
||||||
|
|||||||
Reference in New Issue
Block a user