Files
gwcf-review-front/src/app/(pages)/(main)/monitoring/page.tsx

342 lines
12 KiB
TypeScript

"use client";
import {useEffect, useMemo, useState} from "react";
import {Button} from "@/components/ui/button";
import {FilterSelect} from "@/components/gwcf/FilterSelect";
import {MonitoringVisitDialog} from "@/components/dialog/MonitoringVisitDialog";
import {MonitoringPerformanceDetailDialog} from "@/components/dialog/MonitoringPerformanceDetailDialog";
import {DataTable} from "@/components/data-table/DataTable";
import {DataTableColumn} from "@/components/data-table/DataTable.type";
import {usePerformanceDetailQuery, usePerformanceListQuery} from "@/query/performance";
import {useCodesQuery} from "@/query/code";
import {useSaveArrivalMutation, useSaveDepartureMutation} from "@/query/monitoring";
import {MonitoringGpsRequest, PerformanceFull} from "@/types/gwcf";
import {useAuth} from "@/hooks/useAuth";
import {useDialog} from "@/hooks/useDialog";
import {useMounted} from "@/hooks/useMounted";
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
import {toLocalDateString} from "@/lib/gwcf/date";
import {
getMonitoringDisplayRow, getMonitoringDisplayStatus, isAssignConfirmed,
} from "@/lib/gwcf/performance-status";
import {PERFORMANCE_FIELD_LABELS} from "@/lib/gwcf/field-labels";
import {getCodeLabel} from "@/lib/gwcf/view";
import {StatusPill} from "@/components/gwcf/StatusPill";
const today = toLocalDateString();
const todayTime = new Date(`${today}T00:00:00`).getTime();
const toDateTime = (date?: string | null) => {
const normalizedDate = date?.trim();
if (!normalizedDate) return Number.POSITIVE_INFINITY;
const time = new Date(`${normalizedDate}T00:00:00`).getTime();
return Number.isNaN(time) ? Number.POSITIVE_INFINITY : time;
};
const canSaveMonitoringVisit = (date?: string | null) => {
const time = toDateTime(date);
return Number.isFinite(time) && todayTime >= time;
};
const compareMonitoringSchedule = (a: PerformanceFull, b: PerformanceFull) => {
const aTime = toDateTime(a.performanceMonitoringSchedule?.monitoringDate);
const bTime = toDateTime(b.performanceMonitoringSchedule?.monitoringDate);
const aDistance = Math.abs(aTime - todayTime);
const bDistance = Math.abs(bTime - todayTime);
if (aDistance !== bDistance) return aDistance - bDistance;
const aFuture = aTime >= todayTime;
const bFuture = bTime >= todayTime;
if (aFuture !== bFuture) return aFuture ? -1 : 1;
return a.performanceName.localeCompare(b.performanceName, "ko");
};
const getGpsErrorMessage = (error: unknown) => {
if (error && typeof error === "object" && "code" in error) {
const code = Number((error as GeolocationPositionError).code);
if (code === 1) return "GPS 권한이 거부되었습니다. 브라우저 위치 권한을 허용해 주세요.";
if (code === 2) return "현재 위치를 확인할 수 없습니다. GPS 상태를 확인해 주세요.";
if (code === 3) return "GPS 위치 확인 시간이 초과되었습니다. 다시 시도해 주세요.";
}
return error instanceof Error ? error.message : "GPS 정보를 확인할 수 없습니다.";
};
const emptyGps = (): MonitoringGpsRequest => ({
gpsLatitude: null,
gpsLongitude: null,
gpsAccuracyM: null,
gpsRaw: {
unavailable: true,
},
});
const MonitoringPage = () => {
const mounted = useMounted();
const {auth} = useAuth();
const {isDialogOpen, showDialog, hideDialog} = useDialog();
const departureMutation = useSaveDepartureMutation();
const arrivalMutation = useSaveArrivalMutation();
const {data = [], refetch: refetchPerformanceList} = usePerformanceListQuery();
const {data: codes} = useCodesQuery();
const userId = auth.user?.userId;
const [selectedId, setSelectedId] = useState<number | null>(null);
const [visitMode, setVisitMode] = useState<"departure" | "arrival">("departure");
const refreshMonitoringList = () => {
void refetchPerformanceList();
};
const assignedItems = useMemo(() => {
if (!userId) return [];
return data.filter((item) =>
item.performanceAssignList?.some((assign) => assign.assignUser === userId && isAssignConfirmed(assign))
);
}, [data, userId]);
const sortedItems = useMemo(() => {
return [...assignedItems].sort(compareMonitoringSchedule);
}, [assignedItems]);
const selected = useMemo(() => {
return sortedItems.find((item) => item.id === selectedId) ?? sortedItems[0] ?? null;
}, [selectedId, sortedItems]);
const selectedMonitoringRow = useMemo(() => {
if (!selected || !userId) return undefined;
return ([0, 1] as const)
.map((index) => getMonitoringDisplayRow(selected, index))
.find((row) => row.userId === userId);
}, [selected, userId]);
const hasDeparture = Boolean(selectedMonitoringRow?.slot.timeline.departure || selectedMonitoringRow?.slot.visit?.length);
const hasArrival = Boolean(selectedMonitoringRow?.slot.timeline.arrival);
const canSaveVisit = canSaveMonitoringVisit(selected?.performanceMonitoringSchedule?.monitoringDate);
const columns = useMemo<DataTableColumn<PerformanceFull>[]>(() => [
{
accessorKey: "performanceName",
header: PERFORMANCE_FIELD_LABELS.performanceName,
cell: ({row}) => {
if (!row.original || !userId) return undefined;
const prow = ([0, 1] as const)
.map((index) => getMonitoringDisplayRow(row.original, index))
.find((item) => item.userId === userId);
const latestVisit = prow?.slot.visit?.[0];
const status = prow
? getMonitoringDisplayStatus(
prow,
getCodeLabel(codes, "monitoring_visit_status", latestVisit?.monitoringVisitStatus),
getCodeLabel(codes, "review_status", prow?.review?.reviewStatus)
)
: {label: "미배치", variant: "danger" as const};
return (
<div className="max-w-[180px] whitespace-normal py-2 text-sm font-semibold leading-5">
{row.original.performanceName}<br/>
<StatusPill variant={status.variant}>{status.label}</StatusPill>
</div>
)
},
},
{
id: "monitoringDate",
header: PERFORMANCE_FIELD_LABELS.monitoringDate,
cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringDate?.slice(5) ?? "",
},
{
id: "monitoringTime",
header: PERFORMANCE_FIELD_LABELS.monitoringTimeInfo,
cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringTimeInfo || "-",
},
], [codes]);
const visitOpen = isDialogOpen("monitoringVisitDialog");
const detailOpen = isDialogOpen("monitoringDetailDialog");
const {data: detailData} = usePerformanceDetailQuery(selectedId ?? 0, Boolean(selectedId && detailOpen));
const openVisit = (mode: "departure" | "arrival") => {
setVisitMode(mode);
showDialog("monitoringVisitDialog");
};
const getGps = (): Promise<MonitoringGpsRequest> => {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error("GPS를 사용할 수 없습니다."));
return;
}
navigator.geolocation.getCurrentPosition(
(position) => {
const {latitude, longitude, accuracy} = position.coords;
resolve({
gpsLatitude: latitude,
gpsLongitude: longitude,
gpsAccuracyM: accuracy,
gpsRaw: {
latitude,
longitude,
accuracy,
timestamp: position.timestamp,
},
});
},
(error) => reject(error),
{enableHighAccuracy: true, timeout: 10000, maximumAge: 0}
);
});
};
useEffect(() => {
if (!mounted || !navigator.geolocation) return;
navigator.geolocation.getCurrentPosition(
() => undefined,
() => undefined,
{enableHighAccuracy: true, timeout: 10000, maximumAge: 0}
);
}, [mounted]);
const saveVisit = async (files?: File[]) => {
if (!selected) return;
if (visitMode === "arrival" && (!files || files.length === 0)) {
alert("도착 저장 시 증빙사진을 선택해 주세요.");
return;
}
try {
const gps = await getGps().catch((error) => {
const fallback = emptyGps();
return {
...fallback,
gpsRaw: {
...fallback.gpsRaw,
errorMessage: getGpsErrorMessage(error),
},
};
});
if (visitMode === "departure") {
await departureMutation.mutateAsync({performanceId: selected.id, gps});
alert("출발 정보가 저장되었습니다.");
} else {
await arrivalMutation.mutateAsync({performanceId: selected.id, gps, files});
alert("도착 정보가 저장되었습니다.");
}
hideDialog("monitoringVisitDialog");
refreshMonitoringList();
} catch (error) {
const message = error instanceof Error ? error.message : "저장 중 오류가 발생했습니다.";
alert(message);
}
};
if(!mounted) return <LoadingOverlay force={true} />
return (
<div className="mx-auto min-h-[calc(100vh-160px)] max-w-[430px] bg-white shadow-sm sm:border">
<main className="space-y-3 p-3">
<FilterSelect
value={selected ? String(selected.id) : ""}
onChange={(value) => {
setSelectedId(Number(value));
refreshMonitoringList();
}}
options={sortedItems.map((item) => ({
codeGroup: "performance",
codeValue: item.id,
codeGroupLabel: "사업",
codeLabel: item.performanceName,
memo: "",
}))}
placeholder="모니터링 사업 선택"
className="w-full"
useClear={false}
/>
{selected && (
<section className="rounded-md border">
<div className="border-b bg-muted px-3 py-2 text-center font-semibold">
{[selected.performanceMonitoringSchedule?.monitoringDate, selected.performanceMonitoringSchedule?.monitoringTimeInfo].filter(Boolean).join(" ")}
</div>
<div className="grid grid-cols-[80px_1fr] border-b">
<div className="bg-muted px-3 py-2 text-sm font-semibold">{PERFORMANCE_FIELD_LABELS.performanceName}</div>
<div className="px-3 py-2 text-sm">{selected.performanceName}</div>
</div>
<div className="grid grid-cols-[80px_1fr]">
<div className="bg-muted px-3 py-2 text-sm font-semibold">{PERFORMANCE_FIELD_LABELS.monitoringAddress}</div>
<div className="px-3 py-2 text-sm">{selected.performanceMonitoringSchedule?.monitoringAddress}</div>
</div>
</section>
)}
{selected && (
<div>
{!hasDeparture ? (
<Button type="button" className="w-full" disabled={!canSaveVisit} onClick={() => openVisit("departure")}>출발</Button>
) : (
<Button type="button" className="w-full" disabled={!canSaveVisit || hasArrival} onClick={() => openVisit("arrival")}>도착</Button>
)}
</div>
)}
<section className="space-y-2 overflow-x-auto">
<div className="text-sm font-semibold text-muted-foreground">모니터링 목록</div>
<DataTable
columns={columns}
data={sortedItems}
getRowId={(row) => String(row.id)}
selectMode="click-event"
onRowClick={(item) => {
setSelectedId(item.id);
showDialog("monitoringDetailDialog");
}}
highlightRowIds={selected ? [String(selected.id)] : []}
defaultPageSize={10}
pageSizeOptions={[10, 20, 30]}
paginationItemsToDisplay={3}
/>
</section>
</main>
<MonitoringVisitDialog
open={visitOpen}
onOpenChange={(open) => {
if (open) {
showDialog("monitoringVisitDialog");
return;
}
hideDialog("monitoringVisitDialog");
refreshMonitoringList();
}}
performance={selected}
mode={visitMode}
onSubmit={saveVisit}
isSubmitting={departureMutation.isPending || arrivalMutation.isPending}
/>
<MonitoringPerformanceDetailDialog
open={detailOpen}
onOpenChange={(open) => {
if (open) {
showDialog("monitoringDetailDialog");
return;
}
hideDialog("monitoringDetailDialog");
refreshMonitoringList();
}}
performance={detailData ?? selected}
codes={codes}
userId={userId}
/>
</div>
);
};
export default MonitoringPage;