Files
contact-front/src/app/(pages)/(main)/list/contact/page.tsx

252 lines
8.9 KiB
TypeScript

'use client'
import { Suspense, useEffect, useMemo, useRef, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { ArrowLeft, CalendarClock, RefreshCw } from "lucide-react";
import { useMounted } from "@kri/common/hooks";
import { LoadingOverlayAdapter } from "@/components/app-shell/LoadingOverlayAdapter";
import { Button } from "@/components/ui/button";
import { useAuth } from "@/hooks/useAuth";
import { useDialog } from "@/hooks/useDialog";
import { useSelectedProject } from "@/hooks/useSelectedProject";
import { useListDetailQuery, useListHeaderQuery, useListReserveByUserQuery, useUpdateListMutation } from "@/query/list";
import { useProjectInfoQuery, useResultCodesQuery } from "@/query/project";
import ListContactInfoPanel, { buildInitialValues } from "@/components/list-contact/ListContactInfoPanel";
import ListContactEventPanel from "@/components/list-contact/ListContactEventPanel";
import ListUpdateHistoryPanel from "@/components/list-contact/ListUpdateHistoryPanel";
import ReservationListDialog from "@/components/dialog/ReservationListDialog";
import { createEmptyListFilter, type listHeader } from "@/types/list";
import type { ResultCode } from "@/types/project";
import { isManager } from "@/utils/userRole";
import {useCtiCallPhase} from "@/hooks/useCtiCallPhase";
import {CTI_CALL_PHASE} from "@/const/ctiConst";
const CALL_NAVIGATION_GUARD_KEY = "__listContactCallNavigationGuard";
const ListContactPageContent = () => {
const router = useRouter();
const searchParams = useSearchParams();
const sid = searchParams.get("sid") ?? "";
const mounted = useMounted();
const { auth } = useAuth();
const { selectedProject } = useSelectedProject();
const { isDialogOpen, showDialog } = useDialog();
const prjctIdx = selectedProject?.prjctIdx ?? 0;
const prjctCd = selectedProject?.prjctCd ?? "";
const itrntPrjctCd = selectedProject?.itrntPrjctCd ?? "";
const userId = auth?.user?.userId ?? "";
const userRole = auth?.user?.userRole ?? 0;
const ctiCallPhase = useCtiCallPhase();
const shouldBlockNavigation = CTI_CALL_PHASE.includes(ctiCallPhase);
const allowPageExitRef = useRef(false);
const queriesEnabled = mounted && prjctIdx > 0;
const enabled = queriesEnabled && !!sid;
useEffect(() => {
if (!shouldBlockNavigation) return;
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
if (allowPageExitRef.current) return;
event.preventDefault();
event.returnValue = true;
};
window.addEventListener("beforeunload", handleBeforeUnload);
return () => window.removeEventListener("beforeunload", handleBeforeUnload);
}, [shouldBlockNavigation]);
useEffect(() => {
const hasGuardEntry = window.history.state?.[CALL_NAVIGATION_GUARD_KEY] === true;
if (!shouldBlockNavigation) {
if (hasGuardEntry) window.history.back();
return;
}
let isRestoringHistory = false;
if (!hasGuardEntry) {
window.history.pushState(
{
...window.history.state,
[CALL_NAVIGATION_GUARD_KEY]: true,
},
"",
window.location.href,
);
}
const handlePopState = () => {
if (isRestoringHistory) {
isRestoringHistory = false;
return;
}
const shouldLeave = window.confirm("통화 중입니다. 현재 페이지를 떠나시겠습니까?");
if (shouldLeave) {
allowPageExitRef.current = true;
window.history.back();
return;
}
isRestoringHistory = true;
window.history.forward();
};
window.addEventListener("popstate", handlePopState);
return () => window.removeEventListener("popstate", handlePopState);
}, [shouldBlockNavigation]);
const projectInfoQuery = useProjectInfoQuery(prjctIdx, queriesEnabled);
const listHeaderQuery = useListHeaderQuery(prjctIdx, queriesEnabled);
const listDetailQuery = useListDetailQuery(prjctIdx, sid, enabled);
const resultCodesQuery = useResultCodesQuery(prjctIdx, queriesEnabled);
const updateListMutation = useUpdateListMutation(prjctIdx);
const reservationDialogOpen = isDialogOpen('reservationListDialog');
const reserveByUserQuery = useListReserveByUserQuery(prjctIdx, userId, reservationDialogOpen);
const listHeaders = useMemo<listHeader[]>(() => listHeaderQuery.data ?? [], [listHeaderQuery.data]);
const resultCodeArray = useMemo<ResultCode[]>(() => resultCodesQuery.data ?? [], [resultCodesQuery.data]);
const [isEditing, setIsEditing] = useState(false);
const initialFormValues = useMemo(
() => buildInitialValues(listHeaders, listDetailQuery.data),
[listHeaders, listDetailQuery.data],
);
const [formValues, setFormValues] = useState<Record<number, string>>(initialFormValues);
useEffect(() => {
setFormValues(initialFormValues);
}, [initialFormValues]);
useEffect(() => {
if (sid) return;
alert("sid가 없으면 진행할 수 없습니다.");
router.back();
}, [sid, router]);
const handleNavigateToSid = (nextSid: string) => {
if(shouldBlockNavigation){
alert("통화 중에는 이동할 수 없습니다.");
return;
}
router.push(`/list/contact?sid=${encodeURIComponent(nextSid)}`);
};
const handleGoToListManage = () => {
if(shouldBlockNavigation){
alert("통화 중에는 이동할 수 없습니다.");
return;
}
router.push("/list/manage");
};
const handleFieldChange = (listHderId: number, value: string) => {
setFormValues((prev) => ({ ...prev, [listHderId]: value }));
};
const handleToggleEdit = async () => {
if (!isEditing) {
setIsEditing(true);
return;
}
try {
await updateListMutation.mutateAsync({
updateContents: Object.fromEntries(Object.entries(formValues)),
listFilter: { ...createEmptyListFilter(), sidSet: [sid] },
});
alert("저장되었습니다.");
setIsEditing(false);
listDetailQuery.refetch();
} catch (e) {
console.error(e);
}
};
if (!sid) return null;
if (!mounted || !selectedProject) return <LoadingOverlayAdapter force />;
return (
<div className="space-y-6 text-sm">
<div className="flex items-center gap-3 w-1/2 pr-5">
<Button type="button" variant="outline" size="icon" onClick={handleGoToListManage} aria-label="목록으로">
<ArrowLeft className="h-4 w-4" />
</Button>
<h1 className="text-2xl font-bold tracking-tight">컨택 진행</h1>
<span className="text-2xl font-bold tracking-tight">SID: {sid}</span>
<Button
type="button"
variant="ghost"
size="icon-sm"
disabled={listDetailQuery.isFetching}
aria-label="리스트 정보 새로고침"
title="리스트 정보 새로고침"
onClick={() => listDetailQuery.refetch()}
>
<RefreshCw className={`h-4 w-4 ${listDetailQuery.isFetching ? "animate-spin" : ""}`} />
</Button>
<div className="ml-auto flex items-center gap-2">
<Button type="button" variant="outline" className="gap-2" onClick={() => showDialog('reservationListDialog')}>
<CalendarClock className="h-4 w-4" />
예약리스트 조회
</Button>
<Button type="button" disabled={updateListMutation.isPending} onClick={handleToggleEdit}>
{isEditing ? '저장' : '수정'}
</Button>
</div>
</div>
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<div className="h-[80vh] space-y-4 overflow-y-auto">
<ListContactInfoPanel
prjctIdx={prjctIdx}
sid={sid}
itrntPrjctCd={itrntPrjctCd}
userRole={userRole}
isEditing={isEditing}
listHeaders={listHeaders}
detail={listDetailQuery.data}
surveys={projectInfoQuery.data?.surveys ?? []}
callerTelNum={projectInfoQuery.data?.callerTelNum}
resultCodes={resultCodeArray}
formValues={formValues}
onFieldChange={handleFieldChange}
onSaved={() => listDetailQuery.refetch()}
/>
{isManager(userRole) ? (
<ListUpdateHistoryPanel prjctIdx={prjctIdx} sid={sid} listHeaders={listHeaders} />
) : null}
</div>
<ListContactEventPanel
prjctIdx={prjctIdx}
sid={sid}
prjctCd={prjctCd}
userId={userId}
userRole={userRole}
resultCodes={resultCodeArray}
useFF={projectInfoQuery.data?.ff ?? false}
useContactSenario={projectInfoQuery.data?.useContactSenario ?? false}
contactSenario={projectInfoQuery.data?.contactSenario}
/>
</div>
<ReservationListDialog reservations={reserveByUserQuery.data ?? []} onSelectReservation={handleNavigateToSid} />
</div>
)
}
const ListContactPage = () => (
<Suspense fallback={null}>
<ListContactPageContent />
</Suspense>
);
export default ListContactPage;