Compare commits

..

3 Commits

8 changed files with 128 additions and 29 deletions

View File

@@ -2,6 +2,7 @@
import { useEffect, useMemo, useState } from 'react' import { useEffect, useMemo, useState } from 'react'
import type { PaginationState } from '@tanstack/react-table' import type { PaginationState } from '@tanstack/react-table'
import { useQueryClient } from '@tanstack/react-query'
import { useRouter } from 'next/navigation' import { useRouter } from 'next/navigation'
import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter' import { LoadingOverlayAdapter } from '@/components/app-shell/LoadingOverlayAdapter'
import { useMounted } from "@kri/common/hooks"; import { useMounted } from "@kri/common/hooks";
@@ -77,6 +78,7 @@ const createEmptySearchUiState = (): ListSearchUiState => ({
const ListManagePage = () => { const ListManagePage = () => {
const router = useRouter() const router = useRouter()
const queryClient = useQueryClient()
const mounted = useMounted() const mounted = useMounted()
const { auth } = useAuth() const { auth } = useAuth()
const { showDialog } = useDialog() const { showDialog } = useDialog()
@@ -139,6 +141,17 @@ const ListManagePage = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [mounted, isSelectedProjectHydrated, restoreResolved]) }, [mounted, isSelectedProjectHydrated, restoreResolved])
// 브라우저 뒤로가기(popstate)는 Next.js가 이 페이지를 재마운트하지 않고 재사용할 수 있어
// refetchOnMount만으로는 최신 데이터를 보장 못한다. popstate는 브라우저 네이티브 이벤트라
// 재마운트 여부와 무관하게 항상 발생하므로, 여기서 명시적으로 무효화한다.
useEffect(() => {
const handlePopState = () => {
void queryClient.invalidateQueries({ queryKey: ['list', 'search-filter'] })
}
window.addEventListener('popstate', handlePopState)
return () => window.removeEventListener('popstate', handlePopState)
}, [queryClient])
const restoredForThisProject = restoredVisit?.prjctIdx === prjctIdx ? restoredVisit : undefined const restoredForThisProject = restoredVisit?.prjctIdx === prjctIdx ? restoredVisit : undefined
const selectedSidSet = useMemo( const selectedSidSet = useMemo(

View File

@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";
import { KriHeader } from "@/components/layout/KriHeader"; import { KriHeader } from "@/components/layout/KriHeader";
import type { TopMenuItem } from "@/config/menu.types"; import type { TopMenuItem } from "@/config/menu.types";
import type { LoginUser } from "@kri/common"; import type { LoginUser } from "@kri/common";
import { useInternalInfoQuery } from "@/query/internal";
interface AppHeaderProps { interface AppHeaderProps {
isMain: boolean; isMain: boolean;
@@ -40,6 +41,9 @@ export function AppHeader({
increaseFontSize, increaseFontSize,
onOpenReserveSearch, onOpenReserveSearch,
}: AppHeaderProps) { }: AppHeaderProps) {
const internalInfoQuery = useInternalInfoQuery(!!userInfo);
const seatNo = internalInfoQuery.data?.clientId ?? "";
return ( return (
<KriHeader <KriHeader
logo={ logo={
@@ -82,7 +86,10 @@ export function AppHeader({
<Button variant="ghost" size="icon-lg" onClick={onOpenReserveSearch} title="예약 내역 조회"> <Button variant="ghost" size="icon-lg" onClick={onOpenReserveSearch} title="예약 내역 조회">
<CalendarClock className="size-6" /> <CalendarClock className="size-6" />
</Button> </Button>
<span className="hidden text-sm text-gray-600 sm:inline">{userInfo?.userName || ""}</span> <span className="hidden text-sm text-gray-600 sm:inline">
{userInfo?.userName || ""}
{seatNo ? ` (${seatNo})` : ""}
</span>
<Button variant="ghost" size="sm" className="gap-2" onClick={() => onNavigate("/logout")}> <Button variant="ghost" size="sm" className="gap-2" onClick={() => onNavigate("/logout")}>
<LogOut className="h-4 w-4" /> <LogOut className="h-4 w-4" />
<span className="hidden sm:inline">로그아웃</span> <span className="hidden sm:inline">로그아웃</span>

View File

@@ -124,6 +124,12 @@ export function AssignTargetList({
return ( return (
<div className="flex h-[78vh] flex-col border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm"> <div className="flex h-[78vh] flex-col border border-gray-200 rounded-lg overflow-hidden bg-white shadow-sm">
{summary ? (
<div className="shrink-0 border-b border-gray-200 bg-gray-50 px-3 py-1 text-lg font-semibold text-gray-700">
전체 {summary.totalCount}건 · 미배정 {summary.unassignedCount}건
</div>
) : null}
{canFilterByCmpn ? ( {canFilterByCmpn ? (
<div className="shrink-0 border-b border-gray-200 p-2"> <div className="shrink-0 border-b border-gray-200 p-2">
<KriMultiSelect <KriMultiSelect
@@ -139,12 +145,6 @@ export function AssignTargetList({
</div> </div>
) : null} ) : null}
{summary ? (
<div className="shrink-0 border-b border-gray-200 bg-gray-50 px-3 py-1 text-lg font-semibold text-gray-700">
전체 {summary.totalCount}건 · 미배정 {summary.unassignedCount}건
</div>
) : null}
<div className="flex-1 overflow-y-auto"> <div className="flex-1 overflow-y-auto">
<table className="w-full table-fixed"> <table className="w-full table-fixed">
<colgroup> <colgroup>

View File

@@ -57,6 +57,9 @@ export const buildInitialValues = (listHeaders: listHeader[], detail?: ListSearc
} }
const disabledContrastClass = 'bg-white disabled:opacity-100 disabled:text-foreground disabled:bg-muted/60' const disabledContrastClass = 'bg-white disabled:opacity-100 disabled:text-foreground disabled:bg-muted/60'
// Input/textarea는 수정 불가 상태에서도 드래그 선택/복사가 가능해야 해서 disabled 대신 readOnly를 쓴다.
// disabled는 공용 Input 컴포넌트의 disabled:pointer-events-none 때문에 마우스 이벤트 자체를 못 받는다.
const readOnlyContrastClass = 'bg-white read-only:text-foreground read-only:bg-muted/60'
const getCallButtonLabel = (isDialing: boolean, isOnCall: boolean) => { const getCallButtonLabel = (isDialing: boolean, isOnCall: boolean) => {
if (isDialing) return '거는 중' if (isDialing) return '거는 중'
@@ -189,9 +192,9 @@ const ListContactInfoPanel = ({
return ( return (
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}> <FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
<textarea <textarea
className={`flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed ${disabledContrastClass}`} className={`flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${readOnlyContrastClass}`}
value={value} value={value}
disabled={!editable} readOnly={!editable}
onChange={(e) => onChange(e.target.value)} onChange={(e) => onChange(e.target.value)}
/> />
</FieldRow> </FieldRow>
@@ -204,9 +207,9 @@ const ListContactInfoPanel = ({
<div className="flex gap-2"> <div className="flex gap-2">
<Input <Input
value={formatKoreanPhoneNumber(value)} value={formatKoreanPhoneNumber(value)}
disabled={!editable} readOnly={!editable}
onChange={(e) => onChange(e.target.value.replace(/\D/g, ''))} onChange={(e) => onChange(e.target.value.replace(/\D/g, ''))}
className={disabledContrastClass} className={readOnlyContrastClass}
/> />
<Button <Button
type="button" type="button"
@@ -245,9 +248,9 @@ const ListContactInfoPanel = ({
<div className="flex gap-2"> <div className="flex gap-2">
<Input <Input
value={value} value={value}
disabled={!editable} readOnly={!editable}
onChange={(e) => onChange(e.target.value)} onChange={(e) => onChange(e.target.value)}
className={disabledContrastClass} className={readOnlyContrastClass}
/> />
<Button <Button
type="button" type="button"
@@ -327,9 +330,9 @@ const ListContactInfoPanel = ({
<FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}> <FieldRow key={header.listHderId} label={header.listHderNm} editable={canEditField}>
<Input <Input
value={value} value={value}
disabled={!editable} readOnly={!editable}
onChange={(e) => onChange(e.target.value)} onChange={(e) => onChange(e.target.value)}
className={disabledContrastClass} className={readOnlyContrastClass}
/> />
</FieldRow> </FieldRow>
) )

View File

@@ -1,5 +1,6 @@
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 { HttpError } from "@kri/common/http";
import { CTI_AGENT_GROUP, CTI_ON_CALL_STATUSES } from "@/const/ctiConst"; import { CTI_AGENT_GROUP, CTI_ON_CALL_STATUSES } from "@/const/ctiConst";
import type { import type {
ListCallCloseRequest, ListCallCloseRequest,
@@ -250,6 +251,9 @@ const restoreCtiState = (agentLoginId: string) => {
return true; return true;
}; };
const fetchCallHistBySession = (agentSessionId: string) =>
nextApi.get<ListCallHist>(`/list-call-hist/session/${encodeURIComponent(agentSessionId)}`);
const recoverLastCallHistId = async (agentLoginId: string) => { const recoverLastCallHistId = async (agentLoginId: string) => {
const targetCall = const targetCall =
activeCall?.agentSessionId ? activeCall : activeCall?.agentSessionId ? activeCall :
@@ -259,11 +263,40 @@ const recoverLastCallHistId = async (agentLoginId: string) => {
const agentSessionId = targetCall.agentSessionId; const agentSessionId = targetCall.agentSessionId;
const callContext = targetCall.context; const callContext = targetCall.context;
let result: ListCallHist;
try { try {
const result = await nextApi.get<ListCallHist>( result = await fetchCallHistBySession(agentSessionId);
`/list-call-hist/session/${encodeURIComponent(agentSessionId)}`, } catch (firstError) {
); // call-start 저장(PUT)이 아직 커밋되기 전에 재연결 복구용 조회가 먼저 도착하는 레이스가 있을 수 있어,
// 바로 포기하지 않고 짧게 대기 후 한 번 더 시도한다.
await new Promise((resolve) => setTimeout(resolve, 1000));
try {
result = await fetchCallHistBySession(agentSessionId);
} catch (secondError) {
console.warn("[CTI][TEMP_LOG] failed to recover call history after retry", {
agentSessionId,
firstError,
secondError,
}); // TEMP_CTI_LOG
// 재시도까지 404(진짜로 존재하지 않는 세션)로 확인된 경우에만 phantom 상태를 정리한다.
// 다른 오류(네트워크 문제 등)는 통화가 실제로 살아있을 수 있으니 그대로 둔다.
const isConfirmedNotFound = secondError instanceof HttpError && secondError.status === 404;
if (isConfirmedNotFound && currentAgentLoginId === agentLoginId) {
if (closingCall?.agentSessionId === agentSessionId) {
closingCall = null;
} else if (activeCall?.agentSessionId === agentSessionId) {
activeCall = null;
agentStatus = null;
}
persistCtiState();
notify();
}
return;
}
}
try {
const isSameCall = const isSameCall =
currentAgentLoginId === agentLoginId && currentAgentLoginId === agentLoginId &&
(activeCall?.agentSessionId === agentSessionId || (activeCall?.agentSessionId === agentSessionId ||
@@ -484,11 +517,21 @@ const handleIncomingMessage = (raw: unknown) => {
const eventAgentSessionId = String(parsed.AgntSessionID ?? ""); const eventAgentSessionId = String(parsed.AgntSessionID ?? "");
const isClosingCall = const isClosingCall =
eventAgentSessionId !== "" && eventAgentSessionId === closingCall?.agentSessionId; eventAgentSessionId !== "" && eventAgentSessionId === closingCall?.agentSessionId;
// saveCallHistory가 activeCall/closingCall에서 컨텍스트를 동기적으로 먼저 읽어가므로,
// 아래에서 activeCall을 비우기 전에 반드시 먼저 호출해야 한다(순서 변경 금지).
saveCallHistory(parsed, "close");
if (!isClosingCall) { if (!isClosingCall) {
callClosedReceived = true; callClosedReceived = true;
setAgentStatus(null); setAgentStatus(null);
// CallClosed는 통화가 끝났다는 CTI 서버의 확정 신호이므로, 이력 저장(백엔드 API) 성공 여부와
// 무관하게 로컬 상태는 즉시 비운다. 저장이 실패해도 이 처리를 기다리다 UI가 "통화 중"에
// 멈춰있으면 안 된다. 세션ID가 일치할 때만 비워서, 그 사이 새 통화가 시작된 경우를 보호한다.
if (eventAgentSessionId !== "" && activeCall?.agentSessionId === eventAgentSessionId) {
activeCall = null;
persistCtiState();
notify();
}
} }
saveCallHistory(parsed, "close");
break; break;
} }
default: default:

View File

@@ -1,24 +1,49 @@
import {keepPreviousData, useQuery} from "@tanstack/react-query"; import { keepPreviousData, useQuery } from "@tanstack/react-query";
import {qk} from "@/query/key/keys"; import { qk } from "@/query/key/keys";
import {internalApi} from "@/lib/http-client"; import { internalApi } from "@/lib/http-client";
import {InternalInfo} from "@/types/internal"; import { InternalInfo } from "@/types/internal";
const DEFAULT_INTERNAL_INFO: InternalInfo = { const DEFAULT_INTERNAL_INFO: InternalInfo = {
success: false,
clientId: "", clientId: "",
internalNo: "", internalNo: "",
externalNo: "", externalNo: "",
clientIp: "", clientIp: "",
}; };
function parseInternalInfo(value: unknown): InternalInfo {
if (!value || typeof value !== "object") {
throw new TypeError("Invalid internal API response.");
}
const response = value as Record<string, unknown>;
if (
typeof response.success !== "boolean" ||
typeof response.clientId !== "string" ||
typeof response.internalNo !== "string" ||
typeof response.externalNo !== "string" ||
typeof response.clientIp !== "string"
) {
throw new TypeError("Invalid internal API response.");
}
return {
success: response.success,
clientId: response.clientId,
internalNo: response.internalNo,
externalNo: response.externalNo,
clientIp: response.clientIp,
};
}
export function useInternalInfoQuery(enabled?: boolean) { export function useInternalInfoQuery(enabled?: boolean) {
return useQuery({ return useQuery({
queryKey: qk.internalInfo(), queryKey: qk.internalInfo(),
queryFn: async (): Promise<InternalInfo> => { queryFn: async (): Promise<InternalInfo> => {
try { try {
return await internalApi.get<InternalInfo>( const response = await internalApi.get<unknown>(`/new-contact-api.asp`);
`/new-contact-get-info.asp`, return parseInternalInfo(response);
); } catch {
} catch (error) {
//내부 정보 조회 실패 //내부 정보 조회 실패
return DEFAULT_INTERNAL_INFO; return DEFAULT_INTERNAL_INFO;
} }
@@ -28,4 +53,4 @@ export function useInternalInfoQuery(enabled?: boolean) {
placeholderData: keepPreviousData, // 검색 중 빈 배열로 깜빡임 방지 placeholderData: keepPreviousData, // 검색 중 빈 배열로 깜빡임 방지
meta: { ignoreGlobalLoading: true }, // 원하면 전역 오버레이 제외(네가 이미 메타 방식 쓰고 있었지) meta: { ignoreGlobalLoading: true }, // 원하면 전역 오버레이 제외(네가 이미 메타 방식 쓰고 있었지)
}); });
} }

View File

@@ -74,6 +74,8 @@ export function useListSearchQuery(prjctIdx: number, request: ListSearchRequest,
enabled, enabled,
staleTime: 0, staleTime: 0,
refetchOnMount: "always", refetchOnMount: "always",
// 다른 탭/창에 갔다가 이 탭으로 돌아왔을 때(컨택 진행 화면을 새 탭으로 열어 작업한 경우 등) 최신 결과를 보여주기 위함.
refetchOnWindowFocus: true,
placeholderData: keepPreviousData, placeholderData: keepPreviousData,
meta: { ignoreGlobalLoading: false }, meta: { ignoreGlobalLoading: false },
}); });
@@ -149,7 +151,10 @@ export function useUploadListItemFileMutation(prjctIdx: number, sid: string) {
return nextApi.postForm<void>(`/list/item-file-upload/${prjctIdx}/${encodeURIComponent(sid)}`, formData); return nextApi.postForm<void>(`/list/item-file-upload/${prjctIdx}/${encodeURIComponent(sid)}`, formData);
}, },
onSuccess: async () => { onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: qk.listDetail(prjctIdx, sid) }); await Promise.all([
queryClient.invalidateQueries({ queryKey: qk.listDetail(prjctIdx, sid) }),
queryClient.invalidateQueries({ queryKey: ["list", "search-filter"] }),
]);
}, },
}); });
} }
@@ -247,6 +252,7 @@ export function useAddListEventMutation(prjctIdx: number, sid: string) {
await Promise.all([ await Promise.all([
queryClient.invalidateQueries({ queryKey: qk.listDetail(prjctIdx, sid) }), queryClient.invalidateQueries({ queryKey: qk.listDetail(prjctIdx, sid) }),
queryClient.invalidateQueries({ queryKey: qk.listEventHistory(prjctIdx, sid) }), queryClient.invalidateQueries({ queryKey: qk.listEventHistory(prjctIdx, sid) }),
queryClient.invalidateQueries({ queryKey: ["list", "search-filter"] }),
]); ]);
}, },
}); });
@@ -261,6 +267,7 @@ export function useDeleteListEventMutation(prjctIdx: number, sid: string) {
await Promise.all([ await Promise.all([
queryClient.invalidateQueries({ queryKey: qk.listDetail(prjctIdx, sid) }), queryClient.invalidateQueries({ queryKey: qk.listDetail(prjctIdx, sid) }),
queryClient.invalidateQueries({ queryKey: qk.listEventHistory(prjctIdx, sid) }), queryClient.invalidateQueries({ queryKey: qk.listEventHistory(prjctIdx, sid) }),
queryClient.invalidateQueries({ queryKey: ["list", "search-filter"] }),
]); ]);
}, },
}); });

View File

@@ -1,4 +1,5 @@
export type InternalInfo = { export type InternalInfo = {
success: boolean;
clientId: string; clientId: string;
internalNo: string; internalNo: string;
externalNo: string; externalNo: string;