Merge pull request 'develop' (#1) from develop into master
Reviewed-on: #1
This commit is contained in:
@@ -2,4 +2,5 @@ NEXT_PUBLIC_ENV=prod
|
||||
NEXT_PUBLIC_API_BASE=https://test-gwcf-review.kric.com/api
|
||||
|
||||
ENV=prod
|
||||
API_BACK_SERVER=http://127.0.0.1:6105/api/v1
|
||||
API_BACK_SERVER=http://127.0.0.1:6105/api/v1
|
||||
NOTI_HUB_SERVER=https://noti-hub.kric.com/api/v1
|
||||
@@ -2,4 +2,5 @@ NEXT_PUBLIC_ENV=local
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:6104/api
|
||||
|
||||
ENV=local
|
||||
API_BACK_SERVER=http://localhost:6105/api/v1
|
||||
API_BACK_SERVER=http://localhost:6105/api/v1
|
||||
NOTI_HUB_SERVER=https://noti-hub.kric.com/api/v1
|
||||
@@ -2,4 +2,5 @@ NEXT_PUBLIC_ENV=prod
|
||||
NEXT_PUBLIC_API_BASE=https://gwcf-review.kric.com/api
|
||||
|
||||
ENV=prod
|
||||
API_BACK_SERVER=http://127.0.0.1:6105/api/v1
|
||||
API_BACK_SERVER=http://127.0.0.1:6105/api/v1
|
||||
NOTI_HUB_SERVER=https://noti-hub.kric.com/api/v1
|
||||
21
components.json
Normal file
21
components.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema.json",
|
||||
"style": "new-york",
|
||||
"rsc": true,
|
||||
"tsx": true,
|
||||
"tailwind": {
|
||||
"config": "",
|
||||
"css": "src/app/globals.css",
|
||||
"baseColor": "neutral",
|
||||
"cssVariables": true,
|
||||
"prefix": ""
|
||||
},
|
||||
"aliases": {
|
||||
"components": "@/components",
|
||||
"utils": "@/lib/utils",
|
||||
"ui": "@/components/ui",
|
||||
"lib": "@/lib",
|
||||
"hooks": "@/hooks"
|
||||
},
|
||||
"iconLibrary": "lucide"
|
||||
}
|
||||
@@ -4,6 +4,9 @@ const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
output: "standalone",
|
||||
reactCompiler: true,
|
||||
experimental: {
|
||||
proxyClientMaxBodySize: "100mb",
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
|
||||
591
package-lock.json
generated
591
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -16,14 +16,16 @@
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.1.1",
|
||||
"crypto-js": "^4.2.0",
|
||||
"date-fns": "^4.4.0",
|
||||
"echarts": "^6.0.0",
|
||||
"echarts-for-react": "^3.0.5",
|
||||
"exceljs": "^4.4.0",
|
||||
"jotai": "^2.16.2",
|
||||
"lucide-react": "^0.562.0",
|
||||
"next": "16.2.7",
|
||||
"radix-ui": "^1.5.0",
|
||||
"radix-ui": "^1.6.0",
|
||||
"react": "19.2.4",
|
||||
"react-day-picker": "^10.0.1",
|
||||
"react-dom": "19.2.4",
|
||||
"shadcn": "^4.1.0",
|
||||
"sonner": "^2.0.7",
|
||||
|
||||
BIN
public/icon-excel.png
Normal file
BIN
public/icon-excel.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 8.6 KiB |
217
src/app/(pages)/(main)/assign/page.tsx
Normal file
217
src/app/(pages)/(main)/assign/page.tsx
Normal file
@@ -0,0 +1,217 @@
|
||||
"use client";
|
||||
|
||||
import {useEffect, useMemo, useRef, useState} from "react";
|
||||
import {Search} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {MultiFilterSelect} from "@/components/gwcf/MultiFilterSelect";
|
||||
import {PagePanel} from "@/components/gwcf/PagePanel";
|
||||
import {DataTable} from "@/components/data-table/DataTable";
|
||||
import {DataTableColumn} from "@/components/data-table/DataTable.type";
|
||||
import {SmsSendDialog} from "@/components/dialog/SmsSendDialog";
|
||||
import {AssignMonitoringDialog} from "@/components/dialog/AssignMonitoringDialog";
|
||||
import {useCodesQuery} from "@/query/code";
|
||||
import {usePerformanceListQuery} from "@/query/performance";
|
||||
import {
|
||||
useMonitoringApplyUserCountsQuery,
|
||||
useMonitoringApplyUsersQuery,
|
||||
useSaveMonitoringAssignMutation,
|
||||
} from "@/query/assign";
|
||||
import {filterPerformance, getCodeLabel} from "@/lib/gwcf/view";
|
||||
import {MONITORING_ASSIGN_TYPE} from "@/lib/gwcf/performance-status";
|
||||
import {PerformanceAssign, PerformanceFull} from "@/types/gwcf";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import {SMS_TEMPLATE_IDS} from "@/query/notification";
|
||||
import {buildPerformanceSmsParams} from "@/lib/gwcf/notification";
|
||||
|
||||
const AssignPage = () => {
|
||||
const mounted = useMounted();
|
||||
const {data: codes} = useCodesQuery();
|
||||
const {isDialogOpen, showDialog, hideDialog} = useDialog();
|
||||
const {data = [], refetch: refetchPerformanceList} = usePerformanceListQuery();
|
||||
const {data: applyCounts = [], refetch: refetchApplyCounts} = useMonitoringApplyUserCountsQuery();
|
||||
const saveAssignMutation = useSaveMonitoringAssignMutation();
|
||||
const suppressAssignCloseRef = useRef(false);
|
||||
|
||||
const [filters, setFilters] = useState({
|
||||
businessType: [] as string[],
|
||||
area: [] as string[],
|
||||
monitoringDate: "",
|
||||
keyword: "",
|
||||
});
|
||||
const [selected, setSelected] = useState<PerformanceFull | null>(null);
|
||||
const smsAddParam = useMemo(() => selected ? buildPerformanceSmsParams(selected) : {}, [selected]);
|
||||
|
||||
const [assignSaveTargetIds, setAssignSaveTargetIds] = useState<string[]>([]);
|
||||
const [smsTargetIds, setSmsTargetIds] = useState<string[]>([]);
|
||||
|
||||
const refreshAssignList = () => {
|
||||
void refetchPerformanceList();
|
||||
void refetchApplyCounts();
|
||||
};
|
||||
|
||||
const updateFilters = (updater: (prev: typeof filters) => typeof filters) => {
|
||||
setFilters(updater);
|
||||
refreshAssignList();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
hideDialog("assignMonitoringDialog");
|
||||
hideDialog("assignSmsSendDialog");
|
||||
setSelected(null);
|
||||
setAssignSaveTargetIds([]);
|
||||
setSmsTargetIds([]);
|
||||
}, []);
|
||||
|
||||
const assignOpen = isDialogOpen("assignMonitoringDialog");
|
||||
const smsOpen = isDialogOpen("assignSmsSendDialog");
|
||||
const selectedPerformanceId = selected?.id ?? 0;
|
||||
const {data: applyUsers = []} = useMonitoringApplyUsersQuery(selectedPerformanceId, assignOpen && selectedPerformanceId > 0);
|
||||
const smsTargetUsers = useMemo(
|
||||
() => applyUsers
|
||||
.filter((applyUser) => smsTargetIds.includes(applyUser.userId))
|
||||
.map((applyUser) => applyUser.user),
|
||||
[applyUsers, smsTargetIds]
|
||||
);
|
||||
|
||||
const applyCountMap = useMemo(() => {
|
||||
return new Map(applyCounts.map((item) => [String(item.performanceId), item.applyCnt]));
|
||||
}, [applyCounts]);
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
return data
|
||||
.filter((item) => filterPerformance(item, filters))
|
||||
.sort((a, b) => {
|
||||
const aDate = a.performanceMonitoringSchedule?.monitoringDate ?? "";
|
||||
const bDate = b.performanceMonitoringSchedule?.monitoringDate ?? "";
|
||||
return bDate.localeCompare(aDate);
|
||||
});
|
||||
}, [data, filters]);
|
||||
|
||||
const openAssign = (performance: PerformanceFull) => {
|
||||
suppressAssignCloseRef.current = false;
|
||||
setSelected(performance);
|
||||
showDialog("assignMonitoringDialog");
|
||||
};
|
||||
|
||||
const applySavedAssignsToSelected = (performanceId: number, monitoringAssigns: PerformanceAssign[]) => {
|
||||
setSelected((prev) => {
|
||||
if (!prev || prev.id !== performanceId) return prev;
|
||||
|
||||
return {
|
||||
...prev,
|
||||
performanceAssignList: [
|
||||
...(prev.performanceAssignList ?? []).filter((assign) => assign.assignType !== MONITORING_ASSIGN_TYPE),
|
||||
...monitoringAssigns,
|
||||
],
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const getMonitoringAssigns = (performance: PerformanceFull) => {
|
||||
return (performance.performanceAssignList ?? []).filter((assign) => assign.assignType === MONITORING_ASSIGN_TYPE);
|
||||
};
|
||||
|
||||
const columns = useMemo<DataTableColumn<PerformanceFull>[]>(() => [
|
||||
{accessorKey: "id", header: "연번", cell: ({row}) => row.original.id, enableSorting: true},
|
||||
{accessorKey: "performanceName", header: "사업명", enableSorting: true},
|
||||
{id: "area", header: "지역", cell: ({row}) => getCodeLabel(codes, "area", row.original.performanceArea)},
|
||||
{accessorKey: "performanceDtInfo", header: "사업 일정"},
|
||||
{accessorKey: "performanceTimeInfo", header: "운영 시간"},
|
||||
{id: "monitoringDate", header: "모니터링 일정", cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringDate ?? "", enableSorting: true},
|
||||
{id: "monitoringTime", header: "모니터링 시간", cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringTimeInfo ?? ""},
|
||||
{id: "applyCount", header: "신청자 수", cell: ({row}) => applyCountMap.get(String(row.original.id)) ?? 0, enableSorting: true},
|
||||
{id: "requestCount", header: "확정요청 수", cell: ({row}) => getMonitoringAssigns(row.original).length},
|
||||
{id: "confirmedCount", header: "확정인원 수", cell: ({row}) => getMonitoringAssigns(row.original).filter((assign) => assign.assignConfirm).length},
|
||||
], [applyCountMap, codes]);
|
||||
|
||||
if(!mounted) return <LoadingOverlay force={true} />
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PagePanel>
|
||||
<div className="grid gap-2 md:grid-cols-[160px_160px_180px_1fr_auto]">
|
||||
<MultiFilterSelect value={filters.businessType} onChange={(value) => updateFilters((prev) => ({...prev, businessType: value}))} options={codes.business_type} placeholder="사업 유형" />
|
||||
<MultiFilterSelect value={filters.area} onChange={(value) => updateFilters((prev) => ({...prev, area: value}))} options={codes.area} placeholder="지역" />
|
||||
<Input type="date" value={filters.monitoringDate} onChange={(event) => updateFilters((prev) => ({...prev, monitoringDate: event.target.value}))} />
|
||||
<Input value={filters.keyword} onChange={(event) => updateFilters((prev) => ({...prev, keyword: event.target.value}))} placeholder="연번 or 사업명" />
|
||||
<Button type="button" variant="outline" onClick={refreshAssignList}>
|
||||
<Search className="h-4 w-4" />
|
||||
검색
|
||||
</Button>
|
||||
</div>
|
||||
</PagePanel>
|
||||
|
||||
<PagePanel className="overflow-x-auto">
|
||||
<DataTable columns={columns} data={filteredData} getRowId={(row) => String(row.id)} selectMode="click-event" onRowClick={openAssign} defaultPageSize={10} />
|
||||
</PagePanel>
|
||||
|
||||
<AssignMonitoringDialog
|
||||
open={assignOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (open) {
|
||||
showDialog("assignMonitoringDialog");
|
||||
return;
|
||||
}
|
||||
|
||||
if (suppressAssignCloseRef.current) return;
|
||||
|
||||
hideDialog("assignMonitoringDialog");
|
||||
refreshAssignList();
|
||||
}}
|
||||
selected={selected}
|
||||
codes={codes}
|
||||
applyUsers={applyUsers}
|
||||
isSavingAssign={saveAssignMutation.isPending}
|
||||
onSaveAssign={(performanceId, userIds) =>
|
||||
saveAssignMutation.mutate(
|
||||
{performanceId, userIds},
|
||||
{onSuccess: (monitoringAssigns) => applySavedAssignsToSelected(performanceId, monitoringAssigns)}
|
||||
)
|
||||
}
|
||||
onOpenSms={(assignUserIds, smsUserIds) => {
|
||||
suppressAssignCloseRef.current = true;
|
||||
setAssignSaveTargetIds(assignUserIds);
|
||||
setSmsTargetIds(smsUserIds);
|
||||
showDialog("assignSmsSendDialog", false);
|
||||
}}
|
||||
/>
|
||||
|
||||
<SmsSendDialog
|
||||
open={smsOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (open) {
|
||||
suppressAssignCloseRef.current = true;
|
||||
showDialog("assignSmsSendDialog", false);
|
||||
return;
|
||||
}
|
||||
|
||||
hideDialog("assignSmsSendDialog");
|
||||
refreshAssignList();
|
||||
window.setTimeout(() => {
|
||||
suppressAssignCloseRef.current = false;
|
||||
}, 0);
|
||||
}}
|
||||
title="확정 문자 발송"
|
||||
templateIdx={SMS_TEMPLATE_IDS.ASSIGN_CONFIRM}
|
||||
newMessageTemplateIdx={SMS_TEMPLATE_IDS.CUSTOM}
|
||||
selectedUsers={smsTargetUsers}
|
||||
addParams={smsAddParam}
|
||||
isBeforeSendPending={saveAssignMutation.isPending}
|
||||
onBeforeDefaultTemplateSend={async () => {
|
||||
if (!selected) throw new Error("공연 정보가 없습니다.");
|
||||
const monitoringAssigns = await saveAssignMutation.mutateAsync({
|
||||
performanceId: selected.id,
|
||||
userIds: assignSaveTargetIds,
|
||||
});
|
||||
applySavedAssignsToSelected(selected.id, monitoringAssigns);
|
||||
}}
|
||||
onSent={refreshAssignList}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AssignPage;
|
||||
@@ -12,7 +12,7 @@ export default async function MainLayoutWrapper({
|
||||
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value;
|
||||
|
||||
if (!accessToken) {
|
||||
//redirect("/logout");
|
||||
redirect("/logout");
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,9 +1,314 @@
|
||||
'use client'
|
||||
"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,
|
||||
} from "@/lib/gwcf/performance-status";
|
||||
|
||||
const today = toLocalDateString();
|
||||
const todayTime = new Date(`${today}T00:00:00`).getTime();
|
||||
|
||||
const toDateTime = (date?: string) => {
|
||||
if (!date) return Number.POSITIVE_INFINITY;
|
||||
const time = new Date(`${date}T00:00:00`).getTime();
|
||||
return Number.isNaN(time) ? Number.POSITIVE_INFINITY : 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 = () => {
|
||||
return (
|
||||
<div>MonitoringPage</div>
|
||||
);
|
||||
}
|
||||
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;
|
||||
|
||||
export default MonitoringPage;
|
||||
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 && assign.assignConfirm)
|
||||
);
|
||||
}, [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 columns = useMemo<DataTableColumn<PerformanceFull>[]>(() => [
|
||||
{
|
||||
accessorKey: "performanceName",
|
||||
header: "사업명",
|
||||
cell: ({row}) => (
|
||||
<div className="max-w-[180px] whitespace-normal py-2 text-sm font-semibold leading-5">
|
||||
{row.original.performanceName}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "monitoringDate",
|
||||
header: "일정",
|
||||
cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringDate?.slice(5) || "-",
|
||||
},
|
||||
{
|
||||
id: "monitoringTime",
|
||||
header: "시간",
|
||||
cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringTimeInfo || "-",
|
||||
},
|
||||
], []);
|
||||
|
||||
const visitOpen = isDialogOpen("monitoringVisitDialog");
|
||||
const detailOpen = isDialogOpen("monitoringDetailDialog");
|
||||
const {data: detailData} = usePerformanceDetailQuery(selected?.id ?? 0, Boolean(selected?.id && 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}
|
||||
</div>
|
||||
<div className="grid grid-cols-[80px_1fr] border-b">
|
||||
<div className="bg-muted px-3 py-2 text-sm font-semibold">사업명</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">장소</div>
|
||||
<div className="px-3 py-2 text-sm">{selected.performanceMonitoringSchedule?.monitoringAddress}</div>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{selected && (
|
||||
<div>
|
||||
{!hasDeparture ? (
|
||||
<Button type="button" className="w-full" onClick={() => openVisit("departure")}>출발</Button>
|
||||
) : (
|
||||
<Button type="button" className="w-full" disabled={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;
|
||||
|
||||
@@ -4,7 +4,6 @@ import {useAuth} from "@/hooks/useAuth";
|
||||
import {useEffect} from "react";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {MONITORING_USER_ROLE} from "@/config/gwcf.config";
|
||||
import {useRouter} from "next/navigation";
|
||||
|
||||
const MainPage = () => {
|
||||
|
||||
@@ -1,9 +1,479 @@
|
||||
'use client'
|
||||
"use client";
|
||||
|
||||
import {useCallback, useMemo, useRef, useState} from "react";
|
||||
import {Search, Upload} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {DatePicker} from "@/components/common/DatePicker";
|
||||
import {MultiFilterSelect} from "@/components/gwcf/MultiFilterSelect";
|
||||
import {PagePanel} from "@/components/gwcf/PagePanel";
|
||||
import {StatusPill} from "@/components/gwcf/StatusPill";
|
||||
import {ExcelRegisterDialog} from "@/components/dialog/ExcelRegisterDialog";
|
||||
import {PerformanceDetailDialog} from "@/components/dialog/PerformanceDetailDialog";
|
||||
import {DataTable} from "@/components/data-table/DataTable";
|
||||
import {DataTableColumn} from "@/components/data-table/DataTable.type";
|
||||
import {useCodesQuery} from "@/query/code";
|
||||
import {
|
||||
useDownloadAssignExcelTemplateMutation,
|
||||
useDownloadPerformanceExcelTemplateMutation,
|
||||
useExportPerformanceMutation,
|
||||
usePerformanceDetailQuery,
|
||||
usePerformanceListQuery,
|
||||
useUpdatePerformanceMutation,
|
||||
useUploadPerformanceExcelMutation,
|
||||
} from "@/query/performance";
|
||||
import {useUploadWrittenAssignExcelMutation} from "@/query/assign";
|
||||
import {useDownloadReviewOriginalMutation, useDownloadReviewPdfMutation} from "@/query/review";
|
||||
import {filterPerformance, getCodeLabel, isInternalRole, isWrittenReviewerRole} from "@/lib/gwcf/view";
|
||||
import {
|
||||
getMonitoringDisplayRow,
|
||||
getMonitoringDisplayStatus,
|
||||
getMonitoringFilterValue as getMonitoringStatusFilterValue,
|
||||
getMonitoringRecordedAt,
|
||||
getMonitoringRecordedUser,
|
||||
getReviewByType,
|
||||
getReviewFilterValue as getReviewStatusFilterValue,
|
||||
getReviewStatusDisplay,
|
||||
getWrittenReviewRows,
|
||||
getWrittenReviewerSimpleReviewStatusDisplay,
|
||||
isReviewComplete,
|
||||
LOCAL_GOVERNMENT_REVIEW_TYPE,
|
||||
statusFilterOptions, getCompleteRecordedAt, getReviewRecordedAt,
|
||||
} from "@/lib/gwcf/performance-status";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import {Code, PerformanceFull, PerformanceReview} from "@/types/gwcf";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {
|
||||
downloadBlob,
|
||||
downloadExcelBuffer, getReviewOriginalDownloadName,
|
||||
getReviewPdfDownloadName,
|
||||
openWrittenReviewWindow,
|
||||
} from "@/lib/gwcf/file";
|
||||
import ExcelDownloadButton from "@/components/common/ExcelDownloadButton";
|
||||
|
||||
type PerformanceFilters = {
|
||||
businessType: string[];
|
||||
genre: string[];
|
||||
area: string[];
|
||||
startMonth: string[];
|
||||
monitoringDate: string;
|
||||
localReviewStatus: string[];
|
||||
monitoring1Status: string[];
|
||||
monitoring2Status: string[];
|
||||
writtenReviewStatus: string[];
|
||||
keyword: string;
|
||||
};
|
||||
|
||||
const monthOptions: Code[] = Array.from({length: 12}, (_, index) => ({
|
||||
codeGroup: "month",
|
||||
codeValue: index + 1,
|
||||
codeGroupLabel: "사업 수행 월",
|
||||
codeLabel: `${index + 1}월`,
|
||||
memo: "",
|
||||
}));
|
||||
|
||||
const PerformancePage = () => {
|
||||
return (
|
||||
<div>PerformancePage</div>
|
||||
);
|
||||
}
|
||||
const mounted = useMounted();
|
||||
const {auth} = useAuth();
|
||||
const userRole = auth.user?.userRole;
|
||||
const userId = auth.user?.userId;
|
||||
const canEdit = isInternalRole(userRole);
|
||||
const isWrittenReviewer = isWrittenReviewerRole(userRole);
|
||||
const {isDialogOpen, showDialog, hideDialog} = useDialog();
|
||||
|
||||
export default PerformancePage;
|
||||
const {data: codes} = useCodesQuery();
|
||||
const {data = [], refetch: refetchPerformanceList} = usePerformanceListQuery();
|
||||
const updateMutation = useUpdatePerformanceMutation();
|
||||
const performanceUploadMutation = useUploadPerformanceExcelMutation();
|
||||
const writtenAssignUploadMutation = useUploadWrittenAssignExcelMutation();
|
||||
const performanceTemplateMutation = useDownloadPerformanceExcelTemplateMutation();
|
||||
const writtenAssignTemplateMutation = useDownloadAssignExcelTemplateMutation();
|
||||
const exportMutation = useExportPerformanceMutation();
|
||||
const reviewPdfMutation = useDownloadReviewPdfMutation();
|
||||
const reviewOriginalMutation = useDownloadReviewOriginalMutation();
|
||||
|
||||
const [filters, setFilters] = useState<PerformanceFilters>({
|
||||
businessType: [],
|
||||
genre: [],
|
||||
area: [],
|
||||
startMonth: [],
|
||||
monitoringDate: "",
|
||||
localReviewStatus: [],
|
||||
monitoring1Status: [],
|
||||
monitoring2Status: [],
|
||||
writtenReviewStatus: [],
|
||||
keyword: "",
|
||||
});
|
||||
const [selectedId, setSelectedId] = useState<number | null>(null);
|
||||
const lastSelectedRef = useRef<number | null>(null);
|
||||
|
||||
const detailOpen = isDialogOpen("performanceDetailDialog");
|
||||
const performanceRegisterOpen = isDialogOpen("performanceExcelRegisterDialog");
|
||||
const assignWrittenOpen = isDialogOpen("assignWrittenExcelDialog");
|
||||
const {data: detailData} = usePerformanceDetailQuery(selectedId ?? 0, Boolean(selectedId && detailOpen && !isWrittenReviewer));
|
||||
|
||||
const refreshPerformanceList = () => {
|
||||
void refetchPerformanceList();
|
||||
};
|
||||
|
||||
const updateFilters = (updater: (prev: PerformanceFilters) => PerformanceFilters) => {
|
||||
setFilters(updater);
|
||||
refreshPerformanceList();
|
||||
};
|
||||
|
||||
const handlePerformanceDetailOpenChange = (open: boolean) => {
|
||||
if (open) {
|
||||
showDialog("performanceDetailDialog");
|
||||
return;
|
||||
}
|
||||
|
||||
hideDialog("performanceDetailDialog");
|
||||
refreshPerformanceList();
|
||||
};
|
||||
|
||||
const handlePerformanceRegisterOpenChange = (open: boolean) => {
|
||||
if (open) {
|
||||
showDialog("performanceExcelRegisterDialog");
|
||||
return;
|
||||
}
|
||||
|
||||
hideDialog("performanceExcelRegisterDialog");
|
||||
refreshPerformanceList();
|
||||
};
|
||||
|
||||
const handleAssignWrittenOpenChange = (open: boolean) => {
|
||||
if (open) {
|
||||
showDialog("assignWrittenExcelDialog");
|
||||
return;
|
||||
}
|
||||
|
||||
hideDialog("assignWrittenExcelDialog");
|
||||
refreshPerformanceList();
|
||||
};
|
||||
const matchesStatus = (filter: string[], value: string) => filter.length === 0 || filter.includes(value);
|
||||
|
||||
const localReviewStatusOptions = isWrittenReviewer
|
||||
? [statusFilterOptions.incomplete, statusFilterOptions.done]
|
||||
: [statusFilterOptions.pending, statusFilterOptions.done];
|
||||
const monitoringStatusOptions = isWrittenReviewer
|
||||
? [statusFilterOptions.incomplete, statusFilterOptions.done]
|
||||
: [statusFilterOptions.pending, statusFilterOptions.departed, statusFilterOptions.arrived, statusFilterOptions.done];
|
||||
const writtenReviewStatusOptions = isWrittenReviewer
|
||||
? [statusFilterOptions.incomplete, statusFilterOptions.done]
|
||||
: [statusFilterOptions.pending, statusFilterOptions.inProgress, statusFilterOptions.done];
|
||||
|
||||
const getVisibleWrittenReviewRow = useCallback((performance: PerformanceFull) => {
|
||||
const rows = getWrittenReviewRows(performance);
|
||||
if (!isWrittenReviewer) return rows[0];
|
||||
return rows.find((row) => row.userId === userId && row.assign);
|
||||
}, [isWrittenReviewer, userId]);
|
||||
|
||||
const filteredData = useMemo(() => {
|
||||
return data.filter((item) => {
|
||||
if (isWrittenReviewer && !getVisibleWrittenReviewRow(item)) return false;
|
||||
|
||||
const localReview = getReviewByType(item, LOCAL_GOVERNMENT_REVIEW_TYPE)?.review;
|
||||
const writtenReviewRow = getVisibleWrittenReviewRow(item);
|
||||
const monitoring1Row = getMonitoringDisplayRow(item, 0);
|
||||
const monitoring1LatestVisit = monitoring1Row.slot.visit?.[0];
|
||||
const monitoring2Row = getMonitoringDisplayRow(item, 1);
|
||||
const monitoring2LatestVisit = monitoring2Row.slot.visit?.[0];
|
||||
|
||||
return (
|
||||
filterPerformance(item, {
|
||||
businessType: filters.businessType,
|
||||
genre: filters.genre,
|
||||
area: filters.area,
|
||||
monitoringDate: filters.monitoringDate,
|
||||
keyword: filters.keyword,
|
||||
}) &&
|
||||
matchesStatus(filters.startMonth, String(item.performanceStartMonth)) &&
|
||||
matchesStatus(filters.localReviewStatus, getReviewStatusFilterValue(
|
||||
localReview,
|
||||
getCodeLabel(codes, "review_status", localReview?.reviewStatus),
|
||||
{isWrittenReviewer, alwaysAssigned: true}
|
||||
)) &&
|
||||
matchesStatus(filters.monitoring1Status, getMonitoringStatusFilterValue(
|
||||
monitoring1Row,
|
||||
getCodeLabel(codes, "monitoring_visit_status", monitoring1LatestVisit?.monitoringVisitStatus),
|
||||
getCodeLabel(codes, "review_status", monitoring1Row.review?.reviewStatus),
|
||||
isWrittenReviewer
|
||||
)) &&
|
||||
matchesStatus(filters.monitoring2Status, getMonitoringStatusFilterValue(
|
||||
monitoring2Row,
|
||||
getCodeLabel(codes, "monitoring_visit_status", monitoring2LatestVisit?.monitoringVisitStatus),
|
||||
getCodeLabel(codes, "review_status", monitoring2Row.review?.reviewStatus),
|
||||
isWrittenReviewer
|
||||
)) &&
|
||||
matchesStatus(filters.writtenReviewStatus, getReviewStatusFilterValue(
|
||||
writtenReviewRow?.review,
|
||||
getCodeLabel(codes, "review_status", writtenReviewRow?.review?.reviewStatus),
|
||||
{isWrittenReviewer, allowInProgress: true, assigned: Boolean(writtenReviewRow?.assign)}
|
||||
))
|
||||
);
|
||||
});
|
||||
}, [codes, data, filters, getVisibleWrittenReviewRow, isWrittenReviewer]);
|
||||
|
||||
const openDetail = (performance: PerformanceFull) => {
|
||||
if (isWrittenReviewer) return;
|
||||
lastSelectedRef.current = performance.id;
|
||||
setSelectedId(performance.id);
|
||||
showDialog("performanceDetailDialog");
|
||||
};
|
||||
|
||||
const downloadReviewPdf = async (performanceId: number, review?: PerformanceReview) => {
|
||||
if (!review || !isReviewComplete(review)) return;
|
||||
if (!review.regUser) return;
|
||||
const buffer = await reviewPdfMutation.mutateAsync({performanceId, reviewType: review.reviewType, userId: review.regUser});
|
||||
downloadBlob(buffer, getReviewPdfDownloadName(performanceId, review.reviewType, review.pdfFileName), "application/pdf");
|
||||
};
|
||||
|
||||
const downloadReviewOriginal = async (performanceId: number, review?: PerformanceReview) => {
|
||||
if (!review || !isReviewComplete(review)) return;
|
||||
if (!review.regUser) return;
|
||||
const buffer = await reviewOriginalMutation.mutateAsync({performanceId, reviewType: review.reviewType, userId: review.regUser});
|
||||
downloadBlob(buffer, getReviewOriginalDownloadName(performanceId, review.reviewType, review.uploadFileName));
|
||||
};
|
||||
|
||||
const openWrittenReviewLink = (performanceId: number, userId?: string, complete = false) => {
|
||||
openWrittenReviewWindow(performanceId, userId, complete);
|
||||
};
|
||||
|
||||
const renderReviewStatus = ({
|
||||
performance,
|
||||
review,
|
||||
userId,
|
||||
useWrittenLink = false,
|
||||
alwaysAssigned = false,
|
||||
noTooltip = false,
|
||||
}: {
|
||||
performance: PerformanceFull;
|
||||
review?: PerformanceReview;
|
||||
userId?: string;
|
||||
useWrittenLink?: boolean;
|
||||
alwaysAssigned?: boolean;
|
||||
noTooltip?: boolean;
|
||||
}) => {
|
||||
const label = getCodeLabel(codes, "review_status", review?.reviewStatus);
|
||||
const display = isWrittenReviewer
|
||||
? getWrittenReviewerSimpleReviewStatusDisplay(review, false, label)
|
||||
: getReviewStatusDisplay(label, review, alwaysAssigned || Boolean(review));
|
||||
const complete = isReviewComplete(review);
|
||||
const onClick = !useWrittenLink && isReviewComplete(review)
|
||||
? () => downloadReviewOriginal(performance.id, review)
|
||||
: useWrittenLink
|
||||
? () => openWrittenReviewLink(performance.id, userId, complete)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<div className="flex min-w-24 justify-center text-xs">
|
||||
<StatusPill
|
||||
variant={display.variant}
|
||||
onClick={onClick}
|
||||
tooltip={useWrittenLink || noTooltip ? undefined : (
|
||||
<div className="space-y-1">
|
||||
<div>사용자: {userId || "-"}</div>
|
||||
<div>기록일시: {getReviewRecordedAt(review)}</div>
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
{display.label}
|
||||
</StatusPill>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const renderMonitoringStatus = (performance: PerformanceFull, index: 0 | 1) => {
|
||||
const row = getMonitoringDisplayRow(performance, index);
|
||||
const latestVisit = row.slot.visit?.[0];
|
||||
const display = getMonitoringDisplayStatus(
|
||||
row,
|
||||
getCodeLabel(codes, "monitoring_visit_status", latestVisit?.monitoringVisitStatus),
|
||||
getCodeLabel(codes, "review_status", row.review?.reviewStatus),
|
||||
isWrittenReviewer
|
||||
);
|
||||
const assignUser = row.slot.assign?.assignUser ?? "";
|
||||
const visitUser = getMonitoringRecordedUser(latestVisit);
|
||||
|
||||
return (
|
||||
<div className="flex min-w-24 justify-center text-xs">
|
||||
<StatusPill
|
||||
variant={display.variant}
|
||||
onClick={isReviewComplete(row.review) ? () => downloadReviewOriginal(performance.id, row.review) : undefined}
|
||||
tooltip={isWrittenReviewer ? undefined : (
|
||||
<div className="space-y-1">
|
||||
<div>사용자: {visitUser === "-" ? assignUser : visitUser}</div>
|
||||
<div>출발: {getMonitoringRecordedAt(row.slot.timeline.departure)}</div>
|
||||
<div>도착: {getMonitoringRecordedAt(row.slot.timeline.arrival)}</div>
|
||||
<div>완료: {getCompleteRecordedAt(row.review)}</div>
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
{display.label}
|
||||
</StatusPill>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const columns = useMemo<DataTableColumn<PerformanceFull>[]>(() => [
|
||||
{accessorKey: "id", header: "연번", cell: ({row}) => row.original.id, enableSorting: true},
|
||||
{id: "businessType", header: "사업 유형", cell: ({row}) => getCodeLabel(codes, "business_type", row.original.businessType)},
|
||||
{id: "genre", header: "분야(장르)", cell: ({row}) => getCodeLabel(codes, "genre", row.original.performanceGenre)},
|
||||
{id: "area", header: "지역", cell: ({row}) => getCodeLabel(codes, "area", row.original.performanceArea)},
|
||||
{accessorKey: "artistName", header: "단체(인)명", enableSorting: true},
|
||||
{accessorKey: "performanceName", header: "사업명", enableSorting: true},
|
||||
{id: "startMonth", header: "사업 수행 월", cell: ({row}) => `${row.original.performanceStartMonth}월`, enableSorting: true},
|
||||
{accessorKey: "performanceDtInfo", header: "사업 일정"},
|
||||
{accessorKey: "performanceTimeInfo", header: "운영 시간"},
|
||||
...(!isWrittenReviewer ? [{
|
||||
id: "monitoringDate",
|
||||
header: "모니터링 일정",
|
||||
cell: ({row}) => row.original.performanceMonitoringSchedule?.monitoringDate ?? "",
|
||||
enableSorting: true,
|
||||
} satisfies DataTableColumn<PerformanceFull>] : []),
|
||||
{
|
||||
id: "localReview",
|
||||
header: "지자체 평가",
|
||||
cell: ({row}) => {
|
||||
const found = getReviewByType(row.original, LOCAL_GOVERNMENT_REVIEW_TYPE);
|
||||
return renderReviewStatus({
|
||||
performance: row.original,
|
||||
review: found?.review,
|
||||
userId: found?.userId,
|
||||
alwaysAssigned: true,
|
||||
noTooltip: isWrittenReviewer,
|
||||
});
|
||||
},
|
||||
},
|
||||
{id: "monitoring1", header: "모니터링 1", cell: ({row}) => renderMonitoringStatus(row.original, 0)},
|
||||
{id: "monitoring2", header: "모니터링 2", cell: ({row}) => renderMonitoringStatus(row.original, 1)},
|
||||
{
|
||||
id: "writtenReview",
|
||||
header: "서면 평가",
|
||||
cell: ({row}) => {
|
||||
const found = getVisibleWrittenReviewRow(row.original);
|
||||
return renderReviewStatus({
|
||||
performance: row.original,
|
||||
review: found?.review,
|
||||
userId: found?.userId,
|
||||
useWrittenLink: isWrittenReviewer,
|
||||
alwaysAssigned: Boolean(found?.assign),
|
||||
});
|
||||
},
|
||||
},
|
||||
], [codes, getVisibleWrittenReviewRow, isWrittenReviewer]);
|
||||
|
||||
const downloadPerformanceTemplate = async () => {
|
||||
const buffer = await performanceTemplateMutation.mutateAsync();
|
||||
downloadExcelBuffer(buffer, "사업 등록 template.xlsx");
|
||||
};
|
||||
|
||||
const downloadWrittenAssignTemplate = async () => {
|
||||
const buffer = await writtenAssignTemplateMutation.mutateAsync();
|
||||
downloadExcelBuffer(buffer, "서면 평가 배정 template.xlsx");
|
||||
};
|
||||
|
||||
const downloadPerformance = async () => {
|
||||
const performanceIds = filteredData.map((performance) => performance.id);
|
||||
|
||||
if (performanceIds.length === 0) {
|
||||
alert("다운로드할 사업 정보가 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
const buffer = await exportMutation.mutateAsync({performanceIds});
|
||||
downloadExcelBuffer(buffer, "사업 정보.xlsx");
|
||||
};
|
||||
|
||||
if(!mounted) return <LoadingOverlay force={true} />
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<PagePanel>
|
||||
<div className="space-y-2">
|
||||
<div className={isWrittenReviewer ? "grid gap-2 md:grid-cols-[280px_170px_140px_140px_1fr_auto]" : "grid gap-2 md:grid-cols-[280px_170px_140px_140px_140px_1fr_auto]"}>
|
||||
<MultiFilterSelect value={filters.businessType} onChange={(value) => updateFilters((prev) => ({...prev, businessType: value}))} options={codes.business_type} placeholder="사업 유형" />
|
||||
<MultiFilterSelect value={filters.genre} onChange={(value) => updateFilters((prev) => ({...prev, genre: value}))} options={codes.genre} placeholder="분야(장르)" />
|
||||
<MultiFilterSelect value={filters.area} onChange={(value) => updateFilters((prev) => ({...prev, area: value}))} options={codes.area} placeholder="지역" />
|
||||
<MultiFilterSelect value={filters.startMonth} onChange={(value) => updateFilters((prev) => ({...prev, startMonth: value}))} options={monthOptions} placeholder="사업 수행 월" />
|
||||
{!isWrittenReviewer && (
|
||||
<DatePicker value={filters.monitoringDate} onChange={(value) => updateFilters((prev) => ({...prev, monitoringDate: value}))} placeholder="모니터링 일정" />
|
||||
)}
|
||||
<Input value={filters.keyword} onChange={(event) => updateFilters((prev) => ({...prev, keyword: event.target.value}))} placeholder="연번 or 사업명" />
|
||||
<Button type="button" variant="outline" onClick={refreshPerformanceList}>
|
||||
<Search className="h-4 w-4" />
|
||||
검색
|
||||
</Button>
|
||||
</div>
|
||||
<div className="grid gap-2 md:grid-cols-[183px_183px_183px_183px]">
|
||||
<MultiFilterSelect value={filters.localReviewStatus} onChange={(value) => updateFilters((prev) => ({...prev, localReviewStatus: value}))} options={localReviewStatusOptions} placeholder="지자체 평가 상태" />
|
||||
<MultiFilterSelect value={filters.monitoring1Status} onChange={(value) => updateFilters((prev) => ({...prev, monitoring1Status: value}))} options={monitoringStatusOptions} placeholder="모니터링1 상태" />
|
||||
<MultiFilterSelect value={filters.monitoring2Status} onChange={(value) => updateFilters((prev) => ({...prev, monitoring2Status: value}))} options={monitoringStatusOptions} placeholder="모니터링2 상태" />
|
||||
<MultiFilterSelect value={filters.writtenReviewStatus} onChange={(value) => updateFilters((prev) => ({...prev, writtenReviewStatus: value}))} options={writtenReviewStatusOptions} placeholder="서면평가 상태" />
|
||||
</div>
|
||||
</div>
|
||||
</PagePanel>
|
||||
|
||||
<PagePanel>
|
||||
{!isWrittenReviewer && (
|
||||
<div className="mb-3 flex justify-end gap-2">
|
||||
{canEdit && (
|
||||
<>
|
||||
<Button type="button" onClick={() => showDialog("performanceExcelRegisterDialog")}>
|
||||
<Upload className="h-4 w-4" />
|
||||
사업 등록
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => showDialog("assignWrittenExcelDialog")}>
|
||||
서면 평가 배정
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<ExcelDownloadButton requestExcelExport={downloadPerformance} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={filteredData}
|
||||
getRowId={(row) => String(row.id)}
|
||||
selectMode={isWrittenReviewer ? "none" : "click-event"}
|
||||
onRowClick={isWrittenReviewer ? undefined : openDetail}
|
||||
defaultPageSize={10}
|
||||
/>
|
||||
</PagePanel>
|
||||
|
||||
{!isWrittenReviewer && (
|
||||
<PerformanceDetailDialog
|
||||
open={detailOpen}
|
||||
onOpenChange={handlePerformanceDetailOpenChange}
|
||||
performance={detailData ?? data.find((item) => item.id === selectedId) ?? null}
|
||||
codes={codes}
|
||||
canEdit={canEdit}
|
||||
onSave={(draft) => updateMutation.mutate(draft)}
|
||||
/>
|
||||
)}
|
||||
|
||||
<ExcelRegisterDialog
|
||||
open={performanceRegisterOpen}
|
||||
onOpenChange={handlePerformanceRegisterOpenChange}
|
||||
title="사업 등록"
|
||||
onDownloadTemplate={downloadPerformanceTemplate}
|
||||
onUpload={(file) => performanceUploadMutation.mutateAsync(file)}
|
||||
isUploading={performanceUploadMutation.isPending}
|
||||
/>
|
||||
|
||||
<ExcelRegisterDialog
|
||||
open={assignWrittenOpen}
|
||||
onOpenChange={handleAssignWrittenOpenChange}
|
||||
title="서면 평가 위원 배정"
|
||||
onDownloadTemplate={downloadWrittenAssignTemplate}
|
||||
onUpload={(file) => writtenAssignUploadMutation.mutateAsync(file)}
|
||||
isUploading={writtenAssignUploadMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PerformancePage;
|
||||
|
||||
@@ -1,9 +1,322 @@
|
||||
'use client'
|
||||
"use client";
|
||||
|
||||
const UserPage = () => {
|
||||
return (
|
||||
<div>UserPage</div>
|
||||
);
|
||||
import {MouseEvent, ReactNode, useEffect, useMemo, useRef, useState} from "react";
|
||||
import {Search, Send, Upload} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {FilterSelect} from "@/components/gwcf/FilterSelect";
|
||||
import {MultiFilterSelect} from "@/components/gwcf/MultiFilterSelect";
|
||||
import {PagePanel} from "@/components/gwcf/PagePanel";
|
||||
import {ExcelRegisterDialog} from "@/components/dialog/ExcelRegisterDialog";
|
||||
import {SmsSendDialog} from "@/components/dialog/SmsSendDialog";
|
||||
import {DataTable} from "@/components/data-table/DataTable";
|
||||
import {DataTableColumn} from "@/components/data-table/DataTable.type";
|
||||
import {useCodesQuery} from "@/query/code";
|
||||
import {useAssignUserCountsQuery} from "@/query/assign";
|
||||
import {
|
||||
useDeleteUserMutation,
|
||||
useDownloadUserExcelTemplateMutation,
|
||||
useExportUserMutation,
|
||||
useUpdateUserMutation,
|
||||
useUploadUsersExcelMutation,
|
||||
useUsersQuery,
|
||||
} from "@/query/user";
|
||||
import {filterUser, getDetailValue, ROLE} from "@/lib/gwcf/view";
|
||||
import {Code, UserFull} from "@/types/gwcf";
|
||||
import {SMS_TEMPLATE_IDS} from "@/query/notification";
|
||||
import {useDialog} from "@/hooks/useDialog";
|
||||
import {useMounted} from "@/hooks/useMounted";
|
||||
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
|
||||
import {downloadExcelBuffer} from "@/lib/gwcf/file";
|
||||
import ExcelDownloadButton from "@/components/common/ExcelDownloadButton";
|
||||
|
||||
type UserTab = "monitoring" | "written";
|
||||
type UserFilters = {area: string[]; gender: string[]; genre: string[]; keyword: string};
|
||||
|
||||
const tabRole: Record<UserTab, number> = {
|
||||
monitoring: ROLE.MONITORING,
|
||||
written: ROLE.WRITTEN_REVIEWER,
|
||||
};
|
||||
|
||||
function StopCell({children}: {children: ReactNode}) {
|
||||
const stop = (event: MouseEvent<HTMLDivElement>) => event.stopPropagation();
|
||||
return <div onClick={stop}>{children}</div>;
|
||||
}
|
||||
|
||||
export default UserPage;
|
||||
const getOptionLabel = (options: Code[], value: string) => {
|
||||
if (!value) return "";
|
||||
return options.find((option) => String(option.codeValue) === value)?.codeLabel ?? value;
|
||||
};
|
||||
|
||||
const UserPage = () => {
|
||||
const mounted = useMounted();
|
||||
const {data: codes} = useCodesQuery();
|
||||
const {data: assignCounts = [], refetch: refetchAssignCounts} = useAssignUserCountsQuery();
|
||||
const {isDialogOpen, showDialog, hideDialog} = useDialog();
|
||||
const [tab, setTab] = useState<UserTab>("monitoring");
|
||||
const [selectedIds, setSelectedIds] = useState<string[]>([]);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [, forceDraftRender] = useState(0);
|
||||
const draftRef = useRef<UserFull | null>(null);
|
||||
const [filters, setFilters] = useState<UserFilters>({area: [], gender: [], genre: [], keyword: ""});
|
||||
|
||||
const userRole = tabRole[tab];
|
||||
const {data = [], refetch: refetchUsers} = useUsersQuery(userRole);
|
||||
const updateMutation = useUpdateUserMutation();
|
||||
const deleteMutation = useDeleteUserMutation();
|
||||
const uploadMutation = useUploadUsersExcelMutation(userRole);
|
||||
const templateMutation = useDownloadUserExcelTemplateMutation(userRole);
|
||||
const exportMutation = useExportUserMutation();
|
||||
|
||||
const assignCountMap = useMemo(() => new Map(assignCounts.map((item) => [item.assignUser, item.assignCount])), [assignCounts]);
|
||||
|
||||
const refreshUserList = () => {
|
||||
void refetchUsers();
|
||||
void refetchAssignCounts();
|
||||
};
|
||||
|
||||
const updateFilters = (updater: (prev: UserFilters) => UserFilters) => {
|
||||
setFilters(updater);
|
||||
refreshUserList();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedIds([]);
|
||||
setEditingId(null);
|
||||
draftRef.current = null;
|
||||
forceDraftRender((prev) => prev + 1);
|
||||
setFilters({area: [], gender: [], genre: [], keyword: ""});
|
||||
}, [tab]);
|
||||
|
||||
const filteredData = useMemo(() => data.filter((user) => filterUser(user, filters)), [data, filters]);
|
||||
const smsTargetUsers = useMemo(
|
||||
() => data.filter((user) => selectedIds.includes(user.userId)),
|
||||
[data, selectedIds]
|
||||
);
|
||||
|
||||
const startEdit = (user: UserFull) => {
|
||||
setEditingId(user.userId);
|
||||
draftRef.current = {...user, userDetail: {...user.userDetail}};
|
||||
forceDraftRender((prev) => prev + 1);
|
||||
};
|
||||
|
||||
const updateDraft = (updater: (prev: UserFull) => UserFull) => {
|
||||
if (!draftRef.current) return;
|
||||
draftRef.current = updater(draftRef.current);
|
||||
forceDraftRender((prev) => prev + 1);
|
||||
};
|
||||
|
||||
const updateDetail = (key: string, value: string) => {
|
||||
updateDraft((prev) => ({...prev, userDetail: {...prev.userDetail, [key]: value}}));
|
||||
};
|
||||
|
||||
const saveEdit = () => {
|
||||
if (!draftRef.current) return;
|
||||
updateMutation.mutate(draftRef.current, {
|
||||
onSuccess: () => {
|
||||
alert("사용자 정보가 수정되었습니다.");
|
||||
setEditingId(null);
|
||||
draftRef.current = null;
|
||||
forceDraftRender((prev) => prev + 1);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const deleteUser = (userId: string) => {
|
||||
if (!confirm("사용자 정보가 완전히 지워집니다 정말로 삭제 하시겠습니까?")) return;
|
||||
deleteMutation.mutate(userId, {
|
||||
onSuccess: () => alert("사용자 정보가 삭제되었습니다."),
|
||||
});
|
||||
};
|
||||
|
||||
const downloadTemplate = async () => {
|
||||
const buffer = await templateMutation.mutateAsync();
|
||||
downloadExcelBuffer(buffer, tab === "monitoring" ? "모니터링 요원 template.xlsx" : "서면 평가위원 template.xlsx");
|
||||
};
|
||||
|
||||
const downloadUsers = async () => {
|
||||
const userIds = filteredData.map((user) => user.userId);
|
||||
|
||||
if (userIds.length === 0) {
|
||||
alert("다운로드할 사용자가 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
const buffer = await exportMutation.mutateAsync({userRole, userIds});
|
||||
downloadExcelBuffer(buffer, tab === "monitoring" ? "모니터링 요원.xlsx" : "서면 평가위원.xlsx");
|
||||
};
|
||||
|
||||
const renderEditableCell = (user: UserFull, key: string, fallbackKeys: string[], type: "text" | "select" = "text", options: Code[] = []) => {
|
||||
const draft = draftRef.current;
|
||||
const isEditing = editingId === user.userId && draft;
|
||||
const source = isEditing ? draft.userDetail : user.userDetail;
|
||||
const value = getDetailValue(source, [key, ...fallbackKeys]);
|
||||
|
||||
if (!isEditing) return type === "select" ? (getOptionLabel(options, value) || "-") : (value || "-");
|
||||
|
||||
if (type === "select") {
|
||||
return (
|
||||
<StopCell>
|
||||
<FilterSelect value={value} onChange={(next) => updateDetail(key, next)} options={options} placeholder="선택" className="w-full min-w-28" />
|
||||
</StopCell>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<StopCell>
|
||||
<Input value={value} onChange={(event) => updateDetail(key, event.target.value)} />
|
||||
</StopCell>
|
||||
);
|
||||
};
|
||||
|
||||
const columns = useMemo<DataTableColumn<UserFull>[]>(() => {
|
||||
const commonColumns: DataTableColumn<UserFull>[] = [
|
||||
{accessorKey: "userId", header: "ID", enableSorting: true},
|
||||
{id: "password", header: "PW", cell: () => "****"},
|
||||
];
|
||||
|
||||
const monitoringColumns: DataTableColumn<UserFull>[] = [
|
||||
{id: "participationCount", header: "참여 횟수", cell: ({row}) => assignCountMap.get(row.original.userId) ?? 0, enableSorting: true},
|
||||
{id: "area", header: "지역", cell: ({row}) => renderEditableCell(row.original, "area", ["userArea", "region"], "select", codes.area)},
|
||||
{id: "gender", header: "성별", cell: ({row}) => renderEditableCell(row.original, "gender", ["userGender"], "select", codes.gender)},
|
||||
{id: "age", header: "연령", cell: ({row}) => renderEditableCell(row.original, "age", ["userAge"])},
|
||||
{id: "tel", header: "연락처", cell: ({row}) => renderEditableCell(row.original, "tel", ["phone", "userTel"])},
|
||||
{id: "email", header: "이메일", cell: ({row}) => renderEditableCell(row.original, "email", ["userEmail"])},
|
||||
{id: "hasCar", header: "자차 여부", cell: ({row}) => renderEditableCell(row.original, "userHasCar", ["has_car", "hasCar"], "select", codes.has_car)},
|
||||
];
|
||||
|
||||
const writtenColumns: DataTableColumn<UserFull>[] = [
|
||||
{id: "genre", header: "장르", cell: ({row}) => renderEditableCell(row.original, "userGenre", ["genre", "reviewGenre"], "select", codes.genre)},
|
||||
{id: "tel", header: "연락처", cell: ({row}) => renderEditableCell(row.original, "tel", ["phone", "userTel"])},
|
||||
{id: "email", header: "이메일", cell: ({row}) => renderEditableCell(row.original, "email", ["userEmail"])},
|
||||
];
|
||||
|
||||
const actionColumns: DataTableColumn<UserFull>[] = [
|
||||
{
|
||||
id: "memo",
|
||||
header: "메모",
|
||||
cell: ({row}) => {
|
||||
const draft = draftRef.current;
|
||||
return editingId === row.original.userId && draft ? (
|
||||
<StopCell>
|
||||
<Input value={draft.memo} onChange={(event) => updateDraft((prev) => ({...prev, memo: event.target.value}))} />
|
||||
</StopCell>
|
||||
) : row.original.memo;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "edit",
|
||||
header: "수정",
|
||||
cell: ({row}) => (
|
||||
<StopCell>
|
||||
{editingId === row.original.userId ? (
|
||||
<Button type="button" size="xs" onClick={saveEdit}>저장</Button>
|
||||
) : (
|
||||
<Button type="button" size="xs" variant="outline" onClick={() => startEdit(row.original)}>수정</Button>
|
||||
)}
|
||||
</StopCell>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "delete",
|
||||
header: "삭제",
|
||||
cell: ({row}) => (
|
||||
<StopCell>
|
||||
<Button type="button" size="xs" variant="destructive" onClick={() => deleteUser(row.original.userId)}>삭제</Button>
|
||||
</StopCell>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
return [...commonColumns, ...(tab === "monitoring" ? monitoringColumns : writtenColumns), ...actionColumns];
|
||||
}, [assignCountMap, codes, editingId, tab]);
|
||||
|
||||
if(!mounted) return <LoadingOverlay force={true} />
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" variant={tab === "monitoring" ? "default" : "outline"} onClick={() => setTab("monitoring")}>모니터링</Button>
|
||||
<Button type="button" variant={tab === "written" ? "default" : "outline"} onClick={() => setTab("written")}>서면평가</Button>
|
||||
</div>
|
||||
|
||||
<PagePanel>
|
||||
<div className="grid gap-2 md:grid-cols-[160px_160px_1fr_auto]">
|
||||
{tab === "monitoring" ? (
|
||||
<>
|
||||
<MultiFilterSelect value={filters.area} onChange={(value) => updateFilters((prev) => ({...prev, area: value}))} options={codes.area} placeholder="지역" />
|
||||
<MultiFilterSelect value={filters.gender} onChange={(value) => updateFilters((prev) => ({...prev, gender: value}))} options={codes.gender} placeholder="성별" />
|
||||
</>
|
||||
) : (
|
||||
<MultiFilterSelect value={filters.genre} onChange={(value) => updateFilters((prev) => ({...prev, genre: value}))} options={codes.genre} placeholder="장르" className="md:col-span-2" />
|
||||
)}
|
||||
<Input value={filters.keyword} onChange={(event) => updateFilters((prev) => ({...prev, keyword: event.target.value}))} placeholder={tab === "monitoring" ? "ID or 연락처 or 이메일" : "ID or 이름 or 연락처 or 이메일"} />
|
||||
<Button type="button" variant="outline" onClick={refreshUserList}>
|
||||
<Search className="h-4 w-4" />
|
||||
검색
|
||||
</Button>
|
||||
</div>
|
||||
</PagePanel>
|
||||
|
||||
<PagePanel className="overflow-x-auto">
|
||||
<div className="flex gap-2 justify-end mb-3">
|
||||
{tab === "monitoring" && (
|
||||
<Button type="button" variant="outline" onClick={() => showDialog("userSmsSendDialog")} disabled={selectedIds.length === 0}>
|
||||
<Send className="h-4 w-4" />
|
||||
문자 발송
|
||||
</Button>
|
||||
)}
|
||||
<Button type="button" onClick={() => showDialog("userExcelRegisterDialog")}>
|
||||
<Upload className="h-4 w-4" />
|
||||
계정 등록
|
||||
</Button>
|
||||
<ExcelDownloadButton requestExcelExport={downloadUsers} />
|
||||
</div>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={filteredData}
|
||||
getRowId={(row) => row.userId}
|
||||
selectMode={tab === "monitoring" ? "multi" : "none"}
|
||||
onRowSelectionChange={(rows) => setSelectedIds(rows.map((row) => row.userId))}
|
||||
defaultPageSize={10}
|
||||
/>
|
||||
</PagePanel>
|
||||
|
||||
<ExcelRegisterDialog
|
||||
open={isDialogOpen("userExcelRegisterDialog")}
|
||||
onOpenChange={(open) => {
|
||||
if (open) {
|
||||
showDialog("userExcelRegisterDialog");
|
||||
return;
|
||||
}
|
||||
|
||||
hideDialog("userExcelRegisterDialog");
|
||||
refreshUserList();
|
||||
}}
|
||||
title="계정 등록"
|
||||
onDownloadTemplate={downloadTemplate}
|
||||
onUpload={(file) => uploadMutation.mutateAsync(file)}
|
||||
isUploading={uploadMutation.isPending}
|
||||
/>
|
||||
|
||||
<SmsSendDialog
|
||||
open={isDialogOpen("userSmsSendDialog")}
|
||||
onOpenChange={(open) => {
|
||||
if (open) {
|
||||
showDialog("userSmsSendDialog");
|
||||
return;
|
||||
}
|
||||
|
||||
hideDialog("userSmsSendDialog");
|
||||
refreshUserList();
|
||||
}}
|
||||
templateIdx={SMS_TEMPLATE_IDS.ACCOUNT_MONITORING}
|
||||
newMessageTemplateIdx={SMS_TEMPLATE_IDS.CUSTOM}
|
||||
selectedUsers={smsTargetUsers}
|
||||
onSent={refreshUserList}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserPage;
|
||||
|
||||
67
src/app/(pages)/file-preview/page.tsx
Normal file
67
src/app/(pages)/file-preview/page.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
type FilePreviewPageProps = {
|
||||
searchParams: Promise<{
|
||||
src?: string;
|
||||
title?: string;
|
||||
type?: "pdf" | "image";
|
||||
images?: string;
|
||||
}>;
|
||||
};
|
||||
|
||||
const parseImages = (images?: string) => {
|
||||
if (!images) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(images);
|
||||
return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === "string") : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const isAllowedSrc = (src: string) => src.startsWith("/api/review/pdf/") || src.startsWith("/api/file/");
|
||||
|
||||
export default async function FilePreviewPage({ searchParams }: FilePreviewPageProps) {
|
||||
const params = await searchParams;
|
||||
const title = params.title ?? "파일 미리보기";
|
||||
const images = parseImages(params.images);
|
||||
const src = params.src ?? "";
|
||||
const type = params.type ?? (images.length > 0 ? "image" : "pdf");
|
||||
|
||||
return (
|
||||
<main className="flex min-h-screen flex-col bg-background text-foreground">
|
||||
<header className="flex h-14 shrink-0 items-center justify-between border-b border-border bg-card px-4">
|
||||
<h1 className="truncate text-base font-medium text-foreground">{title}</h1>
|
||||
</header>
|
||||
|
||||
{type === "image" ? (
|
||||
<div className="grid flex-1 gap-4 overflow-auto p-4 md:grid-cols-2">
|
||||
{images.filter(isAllowedSrc).map((imageSrc, index) => (
|
||||
<figure
|
||||
key={`${imageSrc}-${index}`}
|
||||
className="rounded-lg border border-border bg-card p-3 shadow-sm"
|
||||
>
|
||||
<img
|
||||
src={imageSrc}
|
||||
alt={`${title} ${index + 1}`}
|
||||
className="mx-auto max-h-[80vh] rounded border border-border bg-white object-contain"
|
||||
/>
|
||||
<figcaption className="mt-2 truncate text-xs text-muted-foreground">
|
||||
{decodeURIComponent(imageSrc.split("/").pop() ?? "")}
|
||||
</figcaption>
|
||||
</figure>
|
||||
))}
|
||||
{images.length === 0 && (
|
||||
<div className="col-span-full flex min-h-80 items-center justify-center text-sm text-muted-foreground">
|
||||
미리보기할 이미지가 없습니다.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : isAllowedSrc(src) ? (
|
||||
<iframe src={src} title={title} className="min-h-0 flex-1 bg-white" />
|
||||
) : (
|
||||
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
|
||||
미리보기 경로가 올바르지 않습니다.
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
116
src/app/api/assign/[[...slug]]/route.ts
Normal file
116
src/app/api/assign/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,116 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createBackApi} from "@/lib/server-api";
|
||||
import {ExcelUploadResult} from "@/types/common";
|
||||
import {AssignUserCount, MonitoringApplyUser, PerformanceApplyCount, PerformanceAssign} from "@/types/gwcf";
|
||||
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
void req;
|
||||
const {slug = []} = await context.params;
|
||||
const [action, subAction, performanceId] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (action === "monitoring" && subAction === "apply-users" && performanceId === "count" && slug.length === 3) {
|
||||
const result = await backApi.get<PerformanceApplyCount[]>("/assign/monitoring/apply-users/count");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "monitoring" && subAction === "apply-users" && performanceId && slug.length === 3) {
|
||||
const result = await backApi.get<MonitoringApplyUser[]>(`/assign/monitoring/apply-users/${encodeURIComponent(performanceId)}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "users" && subAction === "count" && slug.length === 2) {
|
||||
const result = await backApi.get<AssignUserCount[]>("/assign/users/count");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, second, third] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (action === "monitoring" && slug.length === 1) {
|
||||
const body = await req.json();
|
||||
const result = await backApi.post<PerformanceAssign[]>("/assign/monitoring", body);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "confirm" && second && third && slug.length === 3) {
|
||||
const result = await backApi.post<string>(
|
||||
`/assign/confirm/${encodeURIComponent(second)}/${encodeURIComponent(third)}`
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if(action === "written" && second === "excel-template"){
|
||||
const result = await backApi.post<ArrayBuffer>(
|
||||
"/assign/written/excel/template",
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
|
||||
return new NextResponse(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "written" && second === "excel-upload" && slug.length === 2) {
|
||||
const formData = await req.formData();
|
||||
const file = formData.get("file") as File | null;
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json({ message: "file field is required." }, { status: 400 });
|
||||
}
|
||||
|
||||
const backendForm = new FormData();
|
||||
backendForm.append("file", file, file.name);
|
||||
|
||||
const result = await backApi.postForm<ExcelUploadResult>(
|
||||
"/assign/written/excel/upload",
|
||||
backendForm
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PATCH = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
void req;
|
||||
const {slug = []} = await context.params;
|
||||
const [action, performanceId, userId] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if ((action === "confirm" || action === "cancel") && performanceId && userId && slug.length === 3) {
|
||||
await backApi.patch<void>(
|
||||
`/assign/${action}/${encodeURIComponent(performanceId)}/${encodeURIComponent(userId)}`
|
||||
);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
25
src/app/api/code/[[...slug]]/route.ts
Normal file
25
src/app/api/code/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createBackApi} from "@/lib/server-api";
|
||||
import {Code} from "@/types/gwcf";
|
||||
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [codeGroup] = slug;
|
||||
|
||||
if (!codeGroup || slug.length !== 1) {
|
||||
return NextResponse.json({ message: "codeGroup is required." }, { status: 400 });
|
||||
}
|
||||
|
||||
const backApi = await createBackApi();
|
||||
const result = await backApi.get<Code[]>(`/code/${encodeURIComponent(codeGroup)}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
55
src/app/api/file/[[...slug]]/route.ts
Normal file
55
src/app/api/file/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createBackApi} from "@/lib/server-api";
|
||||
import {serverEnv} from "@/lib/env.server";
|
||||
|
||||
const contentTypeByExt = (fileName: string) => {
|
||||
const ext = fileName.split(".").pop()?.toLowerCase();
|
||||
if (ext === "jpg" || ext === "jpeg") return "image/jpeg";
|
||||
if (ext === "png") return "image/png";
|
||||
if (ext === "gif") return "image/gif";
|
||||
if (ext === "webp") return "image/webp";
|
||||
if (ext === "pdf") return "application/pdf";
|
||||
return "application/octet-stream";
|
||||
};
|
||||
|
||||
export const GET = async (
|
||||
_req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [type, first, second, ...rest] = slug;
|
||||
const fileName = rest.join("/");
|
||||
|
||||
if (!type || !first || !second || !fileName || rest.length === 0) {
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
}
|
||||
|
||||
const backApi = await createBackApi();
|
||||
const basePath = type === "visit"
|
||||
? `/visit-file/${encodeURIComponent(first)}/${encodeURIComponent(second)}`
|
||||
: type === "review"
|
||||
? `/review-file/${encodeURIComponent(first)}/${encodeURIComponent(second)}`
|
||||
: "";
|
||||
|
||||
if (!basePath) {
|
||||
return NextResponse.json({message: "Not found"}, {status: 404});
|
||||
}
|
||||
|
||||
const encodedFileName = fileName.split("/").map((part) => encodeURIComponent(part)).join("/");
|
||||
const backOrigin = new URL(serverEnv.API_BACK_SERVER).origin;
|
||||
const result = await backApi.get<ArrayBuffer>(`${backOrigin}${basePath}/${encodedFileName}`, {expectBinary: true});
|
||||
|
||||
return new NextResponse(result, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": contentTypeByExt(fileName),
|
||||
"Content-Disposition": `inline; filename="${encodeURIComponent(fileName)}"`,
|
||||
},
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
96
src/app/api/kon/[[...slug]]/route.ts
Normal file
96
src/app/api/kon/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createBackApi} from "@/lib/server-api";
|
||||
import {PerformanceCompact} from "@/types/gwcf";
|
||||
|
||||
const ALLOWED_ORIGIN = "https://kon.kric.com";
|
||||
|
||||
const corsHeaders = {
|
||||
"Access-Control-Allow-Origin": ALLOWED_ORIGIN,
|
||||
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||
"Vary": "Origin",
|
||||
};
|
||||
|
||||
const getRequestOrigin = (req: NextRequest) => {
|
||||
const origin = req.headers.get("origin");
|
||||
if (origin) {
|
||||
return origin;
|
||||
}
|
||||
|
||||
const referer = req.headers.get("referer");
|
||||
if (!referer) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return new URL(referer).origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const isAllowedOrigin = (req: NextRequest) => {
|
||||
return getRequestOrigin(req) === ALLOWED_ORIGIN;
|
||||
};
|
||||
|
||||
const withCors = (response: NextResponse) => {
|
||||
Object.entries(corsHeaders).forEach(([key, value]) => {
|
||||
response.headers.set(key, value);
|
||||
});
|
||||
return response;
|
||||
};
|
||||
|
||||
export const OPTIONS = async (req: NextRequest) => {
|
||||
if (!isAllowedOrigin(req)) {
|
||||
return withCors(NextResponse.json({ message: "Forbidden" }, { status: 403 }));
|
||||
}
|
||||
|
||||
return new NextResponse(null, {
|
||||
status: 204,
|
||||
headers: corsHeaders,
|
||||
});
|
||||
};
|
||||
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
if (!isAllowedOrigin(req)) {
|
||||
return withCors(NextResponse.json({ message: "Forbidden" }, { status: 403 }));
|
||||
}
|
||||
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if(action === "assign-confirm" && slug.length === 3) {
|
||||
const result = await backApi.post<string>(
|
||||
`/assign/confirm/${encodeURIComponent(slug[1])}/${encodeURIComponent(slug[2])}`
|
||||
);
|
||||
return withCors(NextResponse.json(result, { status: 200 }));
|
||||
}
|
||||
|
||||
if(action === "performance-list") {
|
||||
const result = await backApi.get<PerformanceCompact[]>(`/performance/list/compact`)
|
||||
return withCors(NextResponse.json(result, { status: 200 }));
|
||||
}
|
||||
|
||||
if (action === "written-review-start" && slug.length === 3) {
|
||||
await backApi.post<void>(`/review/start/${encodeURIComponent(slug[1])}/${encodeURIComponent(slug[3])}`);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
if (action === "written-reviewend" && slug.length === 3) {
|
||||
await backApi.post<void>(`/review/end/${encodeURIComponent(slug[1])}/${encodeURIComponent(slug[2])}`);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return withCors(NextResponse.json({ message: "Not found" }, { status: 404 }));
|
||||
|
||||
} catch (error: unknown) {
|
||||
return withCors(errorToResponse(error));
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import {createBackApi} from "@/lib/server-api";
|
||||
import {LoginRequest, LoginResponse} from "@/types/auth";
|
||||
import {serverEnv} from "@/lib/env.server";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {CookieKeys} from "@/store/cookie/cookie-keys";
|
||||
|
||||
export const POST = async (req: NextRequest) => {
|
||||
try {
|
||||
@@ -11,7 +12,7 @@ export const POST = async (req: NextRequest) => {
|
||||
const result = await backApi.post<LoginResponse>("/auth/login", body);
|
||||
|
||||
const res = NextResponse.json(result.user, { status: 200 });
|
||||
res.cookies.set("access_token", result.accessToken, {
|
||||
res.cookies.set(CookieKeys.AuthToken, result.accessToken, {
|
||||
httpOnly: true,
|
||||
secure: serverEnv.ENV === "prod",
|
||||
sameSite: "lax",
|
||||
|
||||
100
src/app/api/monitoring/[[...slug]]/route.ts
Normal file
100
src/app/api/monitoring/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createBackApi} from "@/lib/server-api";
|
||||
import {MonitoringGpsRequest, PerformanceMonitoringVisit} from "@/types/gwcf";
|
||||
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
void req;
|
||||
const {slug = []} = await context.params;
|
||||
const [action, subAction, third, fourth, fifth] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (action === "visit" && subAction === "evidence" && third && fourth && slug.length === 4) {
|
||||
const result = await backApi.get<PerformanceMonitoringVisit[]>(
|
||||
`/monitoring/visit/evidence/${encodeURIComponent(third)}/${encodeURIComponent(fourth)}`
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "visit" && subAction === "evidence" && third === "zip" && fourth && fifth && slug.length === 5) {
|
||||
const result = await backApi.get<ArrayBuffer>(
|
||||
`/monitoring/visit/evidence/zip/${encodeURIComponent(fourth)}/${encodeURIComponent(fifth)}`,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
|
||||
return new NextResponse(result, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/zip",
|
||||
"Content-Disposition": `attachment; filename="evidence_${fourth}_${fifth}.zip";`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, subAction, performanceId] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (action === "visit" && subAction === "departure" && performanceId && slug.length === 3) {
|
||||
const body = await req.json().catch(() => null) as MonitoringGpsRequest | null;
|
||||
if (!body) {
|
||||
return NextResponse.json({ message: "Request body is required." }, { status: 400 });
|
||||
}
|
||||
|
||||
const result = await backApi.post<PerformanceMonitoringVisit>(
|
||||
`/monitoring/visit/departure/${encodeURIComponent(performanceId)}`,
|
||||
body
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "visit" && subAction === "arrival" && performanceId && slug.length === 3) {
|
||||
const formData = await req.formData();
|
||||
const gpsPart = formData.get("gps");
|
||||
|
||||
if (!gpsPart) {
|
||||
return NextResponse.json({ message: "gps field is required." }, { status: 400 });
|
||||
}
|
||||
|
||||
const backendForm = new FormData();
|
||||
|
||||
if (gpsPart instanceof File) {
|
||||
backendForm.append("gps", gpsPart, gpsPart.name);
|
||||
} else {
|
||||
backendForm.append("gps", new Blob([String(gpsPart)], {type: "application/json"}));
|
||||
}
|
||||
|
||||
formData.getAll("files").forEach((file) => {
|
||||
if (file instanceof File) {
|
||||
backendForm.append("files", file, file.name);
|
||||
}
|
||||
});
|
||||
|
||||
const result = await backApi.postForm<PerformanceMonitoringVisit>(
|
||||
`/monitoring/visit/arrival/${encodeURIComponent(performanceId)}`,
|
||||
backendForm
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
117
src/app/api/notification/[[...slug]]/route.ts
Normal file
117
src/app/api/notification/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createNotiHubApi} from "@/lib/server-api";
|
||||
import {
|
||||
BulkSendResponse,
|
||||
SaveTemplateRequest,
|
||||
SendSmsBulkRequest,
|
||||
Template,
|
||||
} from "@/types/notification";
|
||||
|
||||
export const GET = async (
|
||||
_req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, templateIdx] = slug;
|
||||
|
||||
if (action !== "template" || !templateIdx) {
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const notiHubApi = await createNotiHubApi();
|
||||
const template = await notiHubApi.get<Template>(`/template/${encodeURIComponent(templateIdx)}`);
|
||||
|
||||
return NextResponse.json(template, { status: 200 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PATCH = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
|
||||
if (action !== "template") {
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null) as SaveTemplateRequest | null;
|
||||
if (!body || !body.tmplatIdx) {
|
||||
return NextResponse.json({ message: "Template request body is invalid." }, { status: 400 });
|
||||
}
|
||||
|
||||
const notiHubApi = await createNotiHubApi();
|
||||
const current = await notiHubApi.get<Template>(`/template/${body.tmplatIdx}`);
|
||||
const next: Template = {
|
||||
...current,
|
||||
tmplatNm: body.tmplatNm,
|
||||
tmplatTitle: body.tmplatTitle,
|
||||
tmplatBody: body.tmplatBody,
|
||||
sendTel: body.sendTel,
|
||||
};
|
||||
|
||||
await notiHubApi.patch<void>("/template", next);
|
||||
|
||||
return NextResponse.json(next, { status: 200 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
|
||||
if (action !== "sms-bulk") {
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
const body = await req.json().catch(() => null) as SendSmsBulkRequest | null;
|
||||
if (
|
||||
!body ||
|
||||
!body.templateIdx ||
|
||||
!body.reqstCmpn ||
|
||||
!body.reqstUser ||
|
||||
!body.reqstSvc ||
|
||||
!Array.isArray(body.destinations) ||
|
||||
body.destinations.length === 0
|
||||
) {
|
||||
return NextResponse.json({ message: "SMS request body is invalid." }, { status: 400 });
|
||||
}
|
||||
|
||||
const notiHubApi = await createNotiHubApi();
|
||||
const template = await notiHubApi.get<Template>(`/template/${body.templateIdx}`);
|
||||
|
||||
const bulkSendKey = await notiHubApi.put<string>("/send-sms/create/bulk", {
|
||||
reqstCmpn: body.reqstCmpn,
|
||||
reqstUser: body.reqstUser,
|
||||
reqstSvc: body.reqstSvc,
|
||||
prjctCd: template.itrntPrjctCd,
|
||||
tmplatIdx: template.tmplatIdx,
|
||||
resve: false,
|
||||
trgtCnt: body.destinations.length,
|
||||
});
|
||||
|
||||
const result = await notiHubApi.post<BulkSendResponse>("/send-sms/bulk", {
|
||||
sendTel: template.sendTel,
|
||||
sendNm: template.sendNm,
|
||||
bulkSendKey,
|
||||
destInfoList: body.destinations,
|
||||
});
|
||||
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
146
src/app/api/performance/[[...slug]]/route.ts
Normal file
146
src/app/api/performance/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createBackApi} from "@/lib/server-api";
|
||||
import {ExcelUploadResult} from "@/types/common";
|
||||
import {PerformanceCompact, PerformanceFull} from "@/types/gwcf";
|
||||
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (action === "list" && slug.length === 1) {
|
||||
const result = await backApi.get<PerformanceFull[]>("/performance/list");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "list" && slug[1] === "compact" && slug.length === 2) {
|
||||
const result = await backApi.get<PerformanceCompact[]>("/performance/list/compact");
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (slug.length === 1 && action) {
|
||||
const result = await backApi.get<PerformanceFull>(`/performance/${encodeURIComponent(action)}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (action === "excel-upload" && slug.length === 1) {
|
||||
const formData = await req.formData();
|
||||
const file = formData.get("file") as File | null;
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json({ message: "file field is required." }, { status: 400 });
|
||||
}
|
||||
|
||||
const backendForm = new FormData();
|
||||
backendForm.append("file", file, file.name);
|
||||
|
||||
const result = await backApi.postForm<ExcelUploadResult>(
|
||||
"/performance/excel/upload",
|
||||
backendForm
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "excel-template" && slug.length === 1) {
|
||||
const result = await backApi.post<ArrayBuffer>(
|
||||
"/performance/excel/template",
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
|
||||
return new NextResponse(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "excel-download" && slug.length === 1) {
|
||||
const body = await req.json().catch(() => null);
|
||||
|
||||
if (!Array.isArray(body)) {
|
||||
return NextResponse.json({ message: "Request body must be an array." }, { status: 400 });
|
||||
}
|
||||
|
||||
const result = await backApi.post<ArrayBuffer>(
|
||||
"/performance/excel/download",
|
||||
body,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
|
||||
return new NextResponse(result, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"Content-Disposition": `attachment; filename="performance.xlsx"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PATCH = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (!action) {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({ message: "Request body is required." }, { status: 400 });
|
||||
}
|
||||
|
||||
await backApi.patch<void>("/performance", body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const DELETE = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [performanceId] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (performanceId && slug.length === 1) {
|
||||
await backApi.del<void>(`/performance/${encodeURIComponent(performanceId)}`);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
130
src/app/api/review/[[...slug]]/route.ts
Normal file
130
src/app/api/review/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {cookies} from "next/headers";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createBackApi} from "@/lib/server-api";
|
||||
import {PerformanceReview} from "@/types/gwcf";
|
||||
import {serverEnv} from "@/lib/env.server";
|
||||
import {CookieKeys} from "@/store/cookie/cookie-keys";
|
||||
|
||||
const reviewFileName = (prefix: string, performanceId: string, reviewType: string) =>
|
||||
`${prefix}-${performanceId}-${reviewType}`;
|
||||
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, second, third, fourth] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (action === "template" && second === "download" && third && slug.length === 3) {
|
||||
const cookieStore = await cookies();
|
||||
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value;
|
||||
const response = await fetch(`${serverEnv.API_BACK_SERVER.replace(/\/+$/, "")}/review/template/download/${encodeURIComponent(third)}`, {
|
||||
headers: accessToken ? {authorization: `Bearer ${accessToken}`} : undefined,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return new NextResponse(await response.text().catch(() => ""), {status: response.status});
|
||||
}
|
||||
|
||||
const result = await response.arrayBuffer();
|
||||
const headers = new Headers();
|
||||
headers.set("Content-Type", response.headers.get("content-type") ?? "application/octet-stream");
|
||||
const disposition = response.headers.get("content-disposition");
|
||||
if (disposition) headers.set("Content-Disposition", disposition);
|
||||
|
||||
return new NextResponse(result, {
|
||||
status: 200,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
if (action === "download" && second && third && fourth && slug.length === 4) {
|
||||
const result = await backApi.get<ArrayBuffer>(
|
||||
`/review/download/${encodeURIComponent(second)}/${encodeURIComponent(third)}/${encodeURIComponent(fourth)}`,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
|
||||
return new NextResponse(result, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/octet-stream",
|
||||
"Content-Disposition": `attachment; filename="${reviewFileName("review-original", second, third)}"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (action === "pdf" && second && third && fourth && slug.length === 4) {
|
||||
const result = await backApi.get<ArrayBuffer>(
|
||||
`/review/pdf/${encodeURIComponent(second)}/${encodeURIComponent(third)}/${encodeURIComponent(fourth)}`,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
const disposition = req.nextUrl.searchParams.get("disposition") === "inline" ? "inline" : "attachment";
|
||||
return new NextResponse(result, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/pdf",
|
||||
"Content-Disposition": `${disposition}; filename="${reviewFileName("review-pdf", second, third)}.pdf"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (action && second && third && slug.length === 3) {
|
||||
const result = await backApi.get<PerformanceReview>(
|
||||
`/review/${encodeURIComponent(action)}/${encodeURIComponent(second)}/${encodeURIComponent(third)}`
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action, second, third] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (action === "start" && second && third && slug.length === 3) {
|
||||
await backApi.post<void>(`/review/start/${encodeURIComponent(second)}/${encodeURIComponent(third)}`);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
if (action === "end" && second && third && slug.length === 3) {
|
||||
await backApi.post<void>(`/review/end/${encodeURIComponent(second)}/${encodeURIComponent(third)}`);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
if (action && second && slug.length === 2) {
|
||||
const formData = await req.formData();
|
||||
const file = formData.get("file") as File | null;
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json({ message: "file field is required." }, { status: 400 });
|
||||
}
|
||||
|
||||
const backendForm = new FormData();
|
||||
backendForm.append("file", file, file.name);
|
||||
|
||||
const result = await backApi.postForm<PerformanceReview>(
|
||||
`/review/${encodeURIComponent(action)}/${encodeURIComponent(second)}`,
|
||||
backendForm
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
147
src/app/api/user/[[...slug]]/route.ts
Normal file
147
src/app/api/user/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createBackApi} from "@/lib/server-api";
|
||||
import {ExcelUploadResult} from "@/types/common";
|
||||
import {UserFull} from "@/types/gwcf";
|
||||
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (action === "list" && slug.length === 2) {
|
||||
const result = await backApi.get<UserFull[]>(`/user/list/${encodeURIComponent(slug[1])}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (slug.length === 1 && action) {
|
||||
const result = await backApi.get<UserFull>(`/user/${encodeURIComponent(action)}`);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const POST = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (action === "excel-upload" && slug.length === 2) {
|
||||
const formData = await req.formData();
|
||||
const file = formData.get("file") as File | null;
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json({ message: "file field is required." }, { status: 400 });
|
||||
}
|
||||
|
||||
const backendForm = new FormData();
|
||||
backendForm.append("file", file, file.name);
|
||||
|
||||
const result = await backApi.postForm<ExcelUploadResult>(
|
||||
`/user/excel/upload/${encodeURIComponent(slug[1])}`,
|
||||
backendForm
|
||||
);
|
||||
return NextResponse.json(result, { status: 200 });
|
||||
}
|
||||
|
||||
if (action === "excel-template" && slug.length === 2) {
|
||||
const result = await backApi.post<ArrayBuffer>(
|
||||
`/user/excel/template/${encodeURIComponent(slug[1])}`,
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
|
||||
return new NextResponse(result, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"Content-Disposition": `attachment; filename="user_${slug[1]}_template.xlsx"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (action === "excel-download" && slug.length === 2) {
|
||||
const body = await req.json().catch(() => null);
|
||||
|
||||
if (!Array.isArray(body)) {
|
||||
return NextResponse.json({ message: "Request body must be an array." }, { status: 400 });
|
||||
}
|
||||
|
||||
const result = await backApi.post<ArrayBuffer>(
|
||||
`/user/excel/download/${encodeURIComponent(slug[1])}`,
|
||||
body,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
|
||||
return new NextResponse(result, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"Content-Disposition": `attachment; filename="user_${slug[1]}.xlsx"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const PATCH = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [action] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (!action) {
|
||||
const body = await req.json().catch(() => null);
|
||||
if (!body) {
|
||||
return NextResponse.json({ message: "Request body is required." }, { status: 400 });
|
||||
}
|
||||
|
||||
await backApi.patch<void>("/user", body);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export const DELETE = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
const {slug = []} = await context.params;
|
||||
const [userId] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (userId && slug.length === 1) {
|
||||
await backApi.del<void>(`/user/${encodeURIComponent(userId)}`);
|
||||
return new NextResponse(null, { status: 204 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ message: "Not found" }, { status: 404 });
|
||||
} catch (error: unknown) {
|
||||
return errorToResponse(error);
|
||||
}
|
||||
};
|
||||
@@ -188,14 +188,18 @@
|
||||
--status-departed-bg: #ecedf7;
|
||||
--status-departed-fg: #272154;
|
||||
|
||||
--status-arrived: #35b6b4; /* 3 도착: CI Emerald Green (메인컬러) */
|
||||
--status-arrived-bg: #e6f8f8;
|
||||
--status-arrived-fg: #1e9896;
|
||||
--status-arrived: #0072a3; /* 3 도착: blue-cyan, 완료와 구분 */
|
||||
--status-arrived-bg: #e8f6fb;
|
||||
--status-arrived-fg: #005f86;
|
||||
|
||||
--status-done: #004844; /* 10 완료: CI Deep Green — 최종 완결 */
|
||||
--status-done-bg: #e0f0ef;
|
||||
--status-done-fg: #004844;
|
||||
|
||||
--status-danger: var(--destructive);
|
||||
--status-danger-bg: #fff0f0;
|
||||
--status-danger-fg: #b91c1c;
|
||||
|
||||
/* Excel */
|
||||
--excel: #1d6f42;
|
||||
--excel-foreground: #ffffff;
|
||||
@@ -309,14 +313,18 @@
|
||||
--status-departed-bg: #1a1b2e;
|
||||
--status-departed-fg: #9fa1d6;
|
||||
|
||||
--status-arrived: #5ec7c5;
|
||||
--status-arrived-bg: #0d2e2e;
|
||||
--status-arrived-fg: #92d9d8;
|
||||
--status-arrived: #00a0d4;
|
||||
--status-arrived-bg: #082838;
|
||||
--status-arrived-fg: #7ddcff;
|
||||
|
||||
--status-done: #28aaa8;
|
||||
--status-done-bg: #0a1f1f;
|
||||
--status-done-fg: #5ec7c5;
|
||||
|
||||
--status-danger: #e03333;
|
||||
--status-danger-bg: #2e1111;
|
||||
--status-danger-fg: #ff8a8a;
|
||||
|
||||
/* Excel */
|
||||
--excel: #28a852;
|
||||
--excel-foreground: #ffffff;
|
||||
@@ -479,18 +487,21 @@
|
||||
.bg-status-departed { background-color: var(--status-departed-bg) !important; }
|
||||
.bg-status-arrived { background-color: var(--status-arrived-bg) !important; }
|
||||
.bg-status-done { background-color: var(--status-done-bg) !important; }
|
||||
.bg-status-danger { background-color: var(--status-danger-bg) !important; }
|
||||
|
||||
.text-status-pending { color: var(--status-pending-fg) !important; }
|
||||
.text-status-inprogress { color: var(--status-inprogress-fg) !important; }
|
||||
.text-status-departed { color: var(--status-departed-fg) !important; }
|
||||
.text-status-arrived { color: var(--status-arrived-fg) !important; }
|
||||
.text-status-done { color: var(--status-done-fg) !important; }
|
||||
.text-status-danger { color: var(--status-danger-fg) !important; }
|
||||
|
||||
.border-status-pending { border-color: var(--status-pending) !important; }
|
||||
.border-status-inprogress { border-color: var(--status-inprogress) !important; }
|
||||
.border-status-departed { border-color: var(--status-departed) !important; }
|
||||
.border-status-arrived { border-color: var(--status-arrived) !important; }
|
||||
.border-status-done { border-color: var(--status-done) !important; }
|
||||
.border-status-danger { border-color: var(--status-danger) !important; }
|
||||
|
||||
/* =============================
|
||||
Content Text Size Utilities
|
||||
@@ -818,4 +829,10 @@
|
||||
color: var(--status-done-fg);
|
||||
border-color: var(--status-done);
|
||||
}
|
||||
|
||||
.gwcf-status-badge--danger {
|
||||
background-color: var(--status-danger-bg);
|
||||
color: var(--status-danger-fg);
|
||||
border-color: var(--status-danger);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,8 +11,8 @@ const notoSansKr = Noto_Sans_KR({
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "화재보험협회 대시보드",
|
||||
description: "화재보험협회 CX 대시보드",
|
||||
title: "강원문화재단 모니터링",
|
||||
description: "강원문화재단 모니터링 시스템",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
|
||||
66
src/components/common/DatePicker.tsx
Normal file
66
src/components/common/DatePicker.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import {format} from "date-fns";
|
||||
import {CalendarIcon, X} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Calendar} from "@/components/ui/calendar";
|
||||
import {Popover, PopoverContent, PopoverTrigger} from "@/components/ui/popover";
|
||||
import {cn} from "@/lib/utils";
|
||||
|
||||
const parseDate = (value: string) => {
|
||||
if (!value) return undefined;
|
||||
const [year, month, day] = value.split("-").map(Number);
|
||||
if (!year || !month || !day) return undefined;
|
||||
return new Date(year, month - 1, day);
|
||||
};
|
||||
|
||||
export function DatePicker({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = "날짜 선택",
|
||||
className,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
placeholder?: string;
|
||||
className?: string;
|
||||
}) {
|
||||
const selected = parseDate(value);
|
||||
|
||||
return (
|
||||
<div className={cn("relative", className)}>
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className={cn("h-9 w-full justify-start bg-white pr-8 text-left font-normal", !value && "text-muted-foreground")}
|
||||
>
|
||||
<CalendarIcon className="h-4 w-4" />
|
||||
{selected ? format(selected, "yyyy-MM-dd") : placeholder}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-0" align="start">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={selected}
|
||||
onSelect={(date) => onChange(date ? format(date, "yyyy-MM-dd") : "")}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{value && (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-2 top-1/2 inline-flex h-5 w-5 -translate-y-1/2 items-center justify-center rounded-full text-muted-foreground hover:bg-muted hover:text-foreground"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onChange("");
|
||||
}}
|
||||
aria-label="날짜 초기화"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
29
src/components/common/ExcelDownloadButton.tsx
Normal file
29
src/components/common/ExcelDownloadButton.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
"use client";
|
||||
|
||||
import Image from "next/image";
|
||||
|
||||
export type ExcelDownloadButtonProps = {
|
||||
requestExcelExport: () => void;
|
||||
}
|
||||
|
||||
const ExcelDownloadButton = ({
|
||||
requestExcelExport
|
||||
}: ExcelDownloadButtonProps) => {
|
||||
|
||||
return (
|
||||
<div className={"mr-3 mt-1.5 cursor-pointer"}>
|
||||
<Image
|
||||
src="/icon-excel.png"
|
||||
alt="excel export"
|
||||
width={27}
|
||||
height={27}
|
||||
className="object-contain"
|
||||
onClick={requestExcelExport}
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
|
||||
);
|
||||
};
|
||||
|
||||
export default ExcelDownloadButton;
|
||||
@@ -9,9 +9,9 @@ export function LoadingOverlay({ force = false }: { force?: boolean }) {
|
||||
if (!force && !isLoading) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[9999] bg-black-600/70 flex items-center justify-center">
|
||||
<div className="fixed inset-0 z-[9999] bg-black/60 flex items-center justify-center">
|
||||
{/* 심플 로딩 인디케이터 */}
|
||||
<div className="h-12 w-12 rounded-full border-4 border-gray-400 border-t-white animate-spin" />
|
||||
<div className="h-20 w-20 rounded-full border-10 !border-white/45 !border-t-white animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -47,6 +47,7 @@ export function DataTable<TData>({
|
||||
onRowSelectionChange,
|
||||
defaultPageSize = 10,
|
||||
pageSizeOptions = [5, 10, 25, 50],
|
||||
showPagination = true,
|
||||
paginationItemsToDisplay = 5
|
||||
}: Readonly<DataTableProps<TData>>) {
|
||||
// Pagination state
|
||||
@@ -240,7 +241,7 @@ export function DataTable<TData>({
|
||||
onClick={drag.wrapClick(() => handleRowClick(row))}
|
||||
className={cn(
|
||||
'content-text-base',
|
||||
'[&>td]:py-0 [&>td]:px-2',
|
||||
'[&>td]:py-3 [&>td]:px-3',
|
||||
selectMode !== 'none' && 'cursor-pointer',
|
||||
'data-[state=selected]:bg-slate-100 data-[state=selected]:font-semibold',
|
||||
shouldHighlight && 'bg-emerald-50',
|
||||
@@ -264,6 +265,7 @@ export function DataTable<TData>({
|
||||
</Table>
|
||||
</div>
|
||||
|
||||
{showPagination && (
|
||||
<div className='flex items-center justify-between gap-3 max-sm:flex-col p-2 pt-0'>
|
||||
<p className='text-muted-foreground flex-1 text-sm whitespace-nowrap' aria-live='polite'>
|
||||
Page <span className='text-foreground'>{table.getState().pagination.pageIndex + 1}</span> of{' '}
|
||||
@@ -380,6 +382,7 @@ export function DataTable<TData>({
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,47 +1,41 @@
|
||||
import { ColumnDef, PaginationState, SortingState } from '@tanstack/react-table'
|
||||
import {ColumnDef, PaginationState, SortingState} from "@tanstack/react-table";
|
||||
|
||||
export type SelectMode = 'none' | 'click-event' | 'single' | 'multi'
|
||||
export type SelectMode = "none" | "click-event" | "single" | "multi";
|
||||
|
||||
export type DataTableColumn<TData, TValue = unknown> = ColumnDef<TData, TValue> & {
|
||||
enableSorting?: boolean // 정렬 가능 여부 (기본값: false)
|
||||
}
|
||||
enableSorting?: boolean;
|
||||
};
|
||||
|
||||
export interface ServerPaginationParams {
|
||||
pageIndex: number
|
||||
pageSize: number
|
||||
sorting?: SortingState
|
||||
pageIndex: number;
|
||||
pageSize: number;
|
||||
sorting?: SortingState;
|
||||
}
|
||||
|
||||
export interface ServerPaginationResponse<TData> {
|
||||
data: TData[]
|
||||
totalCount: number
|
||||
pageCount: number
|
||||
data: TData[];
|
||||
totalCount: number;
|
||||
pageCount: number;
|
||||
}
|
||||
|
||||
export interface DataTableProps<TData> {
|
||||
// 필수 props
|
||||
columns: DataTableColumn<TData, any>[]
|
||||
data: TData[]
|
||||
getRowId?: (row: TData, index: number) => string //id 지정
|
||||
highlightRowIds?: string[]
|
||||
// 페이지네이션 모드
|
||||
isClient?: boolean // true: 클라이언트, false: 서버 (기본값: true)
|
||||
columns: DataTableColumn<TData, any>[];
|
||||
data: TData[];
|
||||
getRowId?: (row: TData, index: number) => string;
|
||||
highlightRowIds?: string[];
|
||||
|
||||
// 서버 페이지네이션 (isClient=false일 때 필요)
|
||||
pageCount?: number
|
||||
totalCount?: number
|
||||
onPaginationChange?: (pagination: PaginationState) => void
|
||||
onSortingChange?: (sorting: SortingState) => void
|
||||
isClient?: boolean;
|
||||
pageCount?: number;
|
||||
totalCount?: number;
|
||||
onPaginationChange?: (pagination: PaginationState) => void;
|
||||
onSortingChange?: (sorting: SortingState) => void;
|
||||
|
||||
// 선택 모드
|
||||
selectMode?: SelectMode // 'none' | 'click-event' | 'single' | 'multi' (기본값: 'none')
|
||||
onRowClick?: (selectedRows: TData) => void
|
||||
onRowSelectionChange?: (selectedRows: TData[]) => void
|
||||
selectMode?: SelectMode;
|
||||
onRowClick?: (selectedRows: TData) => void;
|
||||
onRowSelectionChange?: (selectedRows: TData[]) => void;
|
||||
|
||||
// 페이지네이션 설정
|
||||
defaultPageSize?: number
|
||||
pageSizeOptions?: number[]
|
||||
|
||||
// 기타 설정
|
||||
paginationItemsToDisplay?: number
|
||||
}
|
||||
defaultPageSize?: number;
|
||||
pageSizeOptions?: number[];
|
||||
showPagination?: boolean;
|
||||
paginationItemsToDisplay?: number;
|
||||
}
|
||||
|
||||
220
src/components/dialog/AssignMonitoringDialog.tsx
Normal file
220
src/components/dialog/AssignMonitoringDialog.tsx
Normal file
@@ -0,0 +1,220 @@
|
||||
"use client";
|
||||
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import {Save, Send} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Checkbox} from "@/components/ui/checkbox";
|
||||
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
|
||||
import {DataTable} from "@/components/data-table/DataTable";
|
||||
import {DataTableColumn} from "@/components/data-table/DataTable.type";
|
||||
import {StatusPill} from "@/components/gwcf/StatusPill";
|
||||
import {Code, MonitoringApplyUser, PerformanceFull} from "@/types/gwcf";
|
||||
import {CodeGroup} from "@/query/code";
|
||||
import {getCodeLabel, getDetailValue} from "@/lib/gwcf/view";
|
||||
import {getAssignStatusDisplay, MONITORING_ASSIGN_TYPE} from "@/lib/gwcf/performance-status";
|
||||
|
||||
type CodeMap = Partial<Record<CodeGroup, Code[]>>;
|
||||
|
||||
export function AssignMonitoringDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
selected,
|
||||
codes,
|
||||
applyUsers,
|
||||
isSavingAssign,
|
||||
onSaveAssign,
|
||||
onOpenSms,
|
||||
}: Readonly<{
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
selected: PerformanceFull | null;
|
||||
codes: CodeMap;
|
||||
applyUsers: MonitoringApplyUser[];
|
||||
isSavingAssign?: boolean;
|
||||
onSaveAssign: (performanceId: number, userIds: string[]) => void;
|
||||
onOpenSms: (assignUserIds: string[], smsUserIds: string[]) => void;
|
||||
}>) {
|
||||
const monitoringAssigns = useMemo(
|
||||
() => (selected?.performanceAssignList ?? []).filter((item) => item.assignType === MONITORING_ASSIGN_TYPE),
|
||||
[selected]
|
||||
);
|
||||
const [checkedIds, setCheckedIds] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setCheckedIds([]);
|
||||
return;
|
||||
}
|
||||
|
||||
setCheckedIds(monitoringAssigns.map((item) => item.assignUser));
|
||||
}, [monitoringAssigns, open, selected?.id]);
|
||||
|
||||
const confirmRequestCount = monitoringAssigns.length;
|
||||
const confirmedCount = monitoringAssigns.filter((item) => item.assignConfirm).length;
|
||||
const smsTargetIds = checkedIds.filter(
|
||||
(userId) => !monitoringAssigns.some((assign) => assign.assignUser === userId && assign.assignConfirm)
|
||||
);
|
||||
|
||||
const updateChecked = (applyUser: MonitoringApplyUser, checked: boolean) => {
|
||||
if (!selected || isSavingAssign) return;
|
||||
|
||||
const currentAssign = monitoringAssigns.find((assign) => assign.assignUser === applyUser.userId);
|
||||
|
||||
if (checked) {
|
||||
if (!checkedIds.includes(applyUser.userId) && checkedIds.length >= 2) {
|
||||
alert("모니터링 배정은 최대 2명까지 선택할 수 있습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
const next = Array.from(new Set([...checkedIds, applyUser.userId]));
|
||||
setCheckedIds(next);
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentAssign?.assignConfirm) {
|
||||
if (!confirm("이미 승인된 상태입니다. 정말로 취소 하시 겠습니까?")) return;
|
||||
} else if (currentAssign) {
|
||||
if (!confirm("이미 문자 발송된 상태입니다. 정말로 취소 하시 겠습니까?")) return;
|
||||
}
|
||||
|
||||
const next = checkedIds.filter((userId) => userId !== applyUser.userId);
|
||||
setCheckedIds(next);
|
||||
};
|
||||
|
||||
const toggleApplyUser = (applyUser: MonitoringApplyUser) => {
|
||||
updateChecked(applyUser, !checkedIds.includes(applyUser.userId));
|
||||
};
|
||||
|
||||
const columns = useMemo<DataTableColumn<MonitoringApplyUser>[]>(() => [
|
||||
{
|
||||
id: "select",
|
||||
header: "선택",
|
||||
cell: ({row}) => {
|
||||
const applyUser = row.original;
|
||||
const checked = checkedIds.includes(applyUser.userId);
|
||||
const disabled = (!checked && checkedIds.length >= 2) || isSavingAssign;
|
||||
|
||||
return (
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
tabIndex={-1}
|
||||
aria-label="배정 선택 상태"
|
||||
aria-disabled={disabled}
|
||||
className={disabled ? "pointer-events-none opacity-50" : "pointer-events-none"}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "user",
|
||||
header: "신청자",
|
||||
cell: ({row}) => (
|
||||
<div>
|
||||
<div className="font-semibold">{row.original.user?.userName || row.original.userId}</div>
|
||||
<div className="text-xs text-muted-foreground">{row.original.userId}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "area",
|
||||
header: "지역",
|
||||
cell: ({row}) =>
|
||||
getCodeLabel(codes, "area", getDetailValue(row.original.user?.userDetail, ["area", "userArea", "region"])) || "-",
|
||||
},
|
||||
{
|
||||
id: "tel",
|
||||
header: "연락처",
|
||||
cell: ({row}) => getDetailValue(row.original.user?.userDetail, ["tel", "phone", "userTel"], "-"),
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
header: "상태",
|
||||
cell: ({row}) => {
|
||||
const assigned = monitoringAssigns.find((item) => item.assignUser === row.original.userId);
|
||||
if (!assigned) return null;
|
||||
|
||||
const display = getAssignStatusDisplay(assigned.assignConfirm);
|
||||
return <StatusPill variant={display.variant}>{display.label}</StatusPill>;
|
||||
},
|
||||
},
|
||||
], [checkedIds, codes, isSavingAssign, monitoringAssigns]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-5xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>모니터링 요원 배정</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[1fr_1.2fr]">
|
||||
<section className="rounded-md border">
|
||||
<div className="border-b bg-muted px-3 py-2 font-semibold">공연 기본 정보</div>
|
||||
<table className="w-full border-collapse text-sm">
|
||||
<tbody>
|
||||
{[
|
||||
["연번", selected?.id],
|
||||
["사업유형", getCodeLabel(codes, "business_type", selected?.businessType)],
|
||||
["분야(장르)", getCodeLabel(codes, "genre", selected?.performanceGenre)],
|
||||
["지역", getCodeLabel(codes, "area", selected?.performanceArea)],
|
||||
["단체(팀)명", selected?.artistName],
|
||||
["사업명", selected?.performanceName],
|
||||
["사업 일정", selected?.performanceDtInfo],
|
||||
["운영 시간", selected?.performanceTimeInfo],
|
||||
["모니터링 일정", selected?.performanceMonitoringSchedule?.monitoringDate],
|
||||
["모니터링 시간", selected?.performanceMonitoringSchedule?.monitoringTimeInfo],
|
||||
["방문 장소", selected?.performanceMonitoringSchedule?.monitoringAddress],
|
||||
["예매 예약", getCodeLabel(codes, "ticket_reservation_status", selected?.ticketReservationStatus)],
|
||||
["예매 비고", selected?.ticketReservationMemo],
|
||||
].map(([label, value]) => (
|
||||
<tr key={String(label)}>
|
||||
<th className="w-32 border bg-muted p-2 text-left">{label}</th>
|
||||
<td className="border p-2">{value || "-"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section className="space-y-3 rounded-md border p-3">
|
||||
<div className="grid grid-cols-3 rounded-md border text-center text-sm">
|
||||
<div className="p-2">
|
||||
<div className="text-muted-foreground">신청자</div>
|
||||
<div className="font-semibold">{applyUsers.length}</div>
|
||||
</div>
|
||||
<div className="border-x p-2">
|
||||
<div className="text-muted-foreground">확정요청</div>
|
||||
<div className="font-semibold">{confirmRequestCount}</div>
|
||||
</div>
|
||||
<div className="p-2">
|
||||
<div className="text-muted-foreground">확정</div>
|
||||
<div className="font-semibold">{confirmedCount}</div>
|
||||
</div>
|
||||
</div>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={applyUsers}
|
||||
getRowId={(row) => row.userId}
|
||||
defaultPageSize={applyUsers.length || 10}
|
||||
pageSizeOptions={[applyUsers.length || 10]}
|
||||
showPagination={false}
|
||||
selectMode="click-event"
|
||||
onRowClick={toggleApplyUser}
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" disabled={!selected || isSavingAssign} onClick={() => selected && onSaveAssign(selected.id, checkedIds)}>
|
||||
<Save className="h-4 w-4" />
|
||||
저장
|
||||
</Button>
|
||||
<Button type="button" variant="outline" disabled={smsTargetIds.length === 0 || isSavingAssign} onClick={() => onOpenSms(checkedIds, smsTargetIds)}>
|
||||
<Send className="h-4 w-4" />
|
||||
확정 문자 발송
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>닫기</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
102
src/components/dialog/ExcelRegisterDialog.tsx
Normal file
102
src/components/dialog/ExcelRegisterDialog.tsx
Normal file
@@ -0,0 +1,102 @@
|
||||
"use client";
|
||||
|
||||
import {useEffect, useState} from "react";
|
||||
import {Download, FileUp} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {ExcelUploadResult} from "@/types/common";
|
||||
import {downloadBase64File} from "@/lib/utils";
|
||||
|
||||
export function ExcelRegisterDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
onDownloadTemplate,
|
||||
onUpload,
|
||||
isUploading,
|
||||
}: Readonly<{
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: string;
|
||||
onDownloadTemplate: () => void;
|
||||
onUpload: (file: File) => Promise<ExcelUploadResult>;
|
||||
isUploading?: boolean;
|
||||
}>) {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [uploadResult, setUploadResult] = useState<ExcelUploadResult | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setFile(null);
|
||||
setUploadResult(null);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const upload = async () => {
|
||||
if (!file) return;
|
||||
const result = await onUpload(file);
|
||||
setUploadResult(result);
|
||||
};
|
||||
|
||||
const downloadErrorFile = () => {
|
||||
if (!uploadResult?.errorFileBase64) return;
|
||||
downloadBase64File(uploadResult.errorFileBase64, uploadResult.errorFileName || "excel_upload_error.xlsx");
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-3">
|
||||
<Button type="button" variant="outline" className="w-full" onClick={onDownloadTemplate}>
|
||||
<Download className="h-4 w-4" />
|
||||
양식 다운로드
|
||||
</Button>
|
||||
<label className="flex h-11 cursor-pointer items-center justify-center gap-2 rounded-md border bg-muted text-sm font-medium">
|
||||
<FileUp className="h-4 w-4" />
|
||||
{file ? file.name : "파일 업로드"}
|
||||
<input
|
||||
type="file"
|
||||
accept=".xlsx,.xls"
|
||||
className="hidden"
|
||||
onChange={(event) => {
|
||||
setFile(event.target.files?.[0] ?? null);
|
||||
setUploadResult(null);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
{uploadResult && (
|
||||
<div className="rounded-md border bg-muted/40 p-3 text-sm">
|
||||
<div>전체: {uploadResult.totalCount}</div>
|
||||
<div>성공: {uploadResult.successCount}</div>
|
||||
<div>실패: {uploadResult.failCount}</div>
|
||||
{uploadResult.hasErrorFile && (
|
||||
<Button type="button" variant="outline" size="sm" className="mt-2 w-full" onClick={downloadErrorFile}>
|
||||
<Download className="h-4 w-4" />
|
||||
오류 파일 다운로드
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={!file || isUploading}
|
||||
onClick={upload}
|
||||
>
|
||||
등록
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
268
src/components/dialog/MonitoringPerformanceDetailDialog.tsx
Normal file
268
src/components/dialog/MonitoringPerformanceDetailDialog.tsx
Normal file
@@ -0,0 +1,268 @@
|
||||
"use client";
|
||||
|
||||
import {ReactNode, useMemo, useRef} from "react";
|
||||
import {Download, ImageIcon, ScanSearch, Upload} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
|
||||
import {StatusPill} from "@/components/gwcf/StatusPill";
|
||||
import {Code, PerformanceFull} from "@/types/gwcf";
|
||||
import {CodeGroup} from "@/query/code";
|
||||
import {getCodeLabel} from "@/lib/gwcf/view";
|
||||
import {
|
||||
getMonitoringDisplayRow,
|
||||
getMonitoringDisplayStatus,
|
||||
getMonitoringRecordedAt,
|
||||
} from "@/lib/gwcf/performance-status";
|
||||
import {
|
||||
useDownloadReviewOriginalMutation,
|
||||
useDownloadReviewPdfMutation,
|
||||
useUploadReviewFileMutation,
|
||||
} from "@/query/review";
|
||||
import {useDownloadEvidenceZipMutation, useMonitoringEvidenceQuery} from "@/query/monitoring";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import {
|
||||
buildEvidenceImageSrc,
|
||||
buildImagePreviewUrl,
|
||||
buildReviewPdfPreviewUrl,
|
||||
downloadBlob,
|
||||
downloadFromUrl,
|
||||
getEvidenceZipDownloadName,
|
||||
getReviewOriginalDownloadName,
|
||||
getReviewPdfDownloadName,
|
||||
openPreviewWindow,
|
||||
} from "@/lib/gwcf/file";
|
||||
|
||||
type CodeMap = Partial<Record<CodeGroup, Code[]>>;
|
||||
|
||||
function MobileDetailRow({label, children}: {label: string; children: ReactNode}) {
|
||||
return (
|
||||
<div className="space-y-1 border-b px-3 py-2 last:border-b-0">
|
||||
<div className="text-xs font-semibold text-muted-foreground">{label}</div>
|
||||
<div className="break-words text-sm">{children || "-"}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ActionButton({
|
||||
children,
|
||||
icon = "download",
|
||||
disabled = false,
|
||||
onClick,
|
||||
}: Readonly<{
|
||||
children: ReactNode;
|
||||
icon?: "download" | "upload" | "image" | "preview";
|
||||
disabled?: boolean;
|
||||
onClick?: () => void;
|
||||
}>) {
|
||||
const Icon = icon === "upload" ? Upload : icon === "image" ? ImageIcon : icon === "preview" ? ScanSearch : Download;
|
||||
return (
|
||||
<Button type="button" size="sm" variant="outline" disabled={disabled} onClick={onClick} className="min-h-10 flex-1">
|
||||
<Icon className="h-4 w-4" />
|
||||
{children}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function MonitoringReviewActions({
|
||||
performanceId,
|
||||
reviewType,
|
||||
userId,
|
||||
uploadFileName,
|
||||
pdfFileName,
|
||||
}: Readonly<{
|
||||
performanceId: number;
|
||||
reviewType: number;
|
||||
userId?: string;
|
||||
uploadFileName?: string;
|
||||
pdfFileName?: string;
|
||||
}>) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const uploadMutation = useUploadReviewFileMutation();
|
||||
const originalMutation = useDownloadReviewOriginalMutation();
|
||||
const pdfMutation = useDownloadReviewPdfMutation();
|
||||
const {withLoadingAsync} = useLoading();
|
||||
|
||||
const upload = async (file?: File) => {
|
||||
try {
|
||||
if (!file) return;
|
||||
await withLoadingAsync(() => uploadMutation.mutateAsync({performanceId, reviewType, file}));
|
||||
alert("파일 업로드가 완료되었습니다.");
|
||||
} finally {
|
||||
if (fileInputRef.current) fileInputRef.current.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
const downloadOriginal = async () => {
|
||||
if (!userId) return;
|
||||
const buffer = await originalMutation.mutateAsync({performanceId, reviewType, userId});
|
||||
downloadBlob(buffer, getReviewOriginalDownloadName(performanceId, reviewType, uploadFileName));
|
||||
};
|
||||
|
||||
const downloadPdf = async () => {
|
||||
if (!userId) return;
|
||||
const buffer = await pdfMutation.mutateAsync({performanceId, reviewType, userId});
|
||||
downloadBlob(buffer, getReviewPdfDownloadName(performanceId, reviewType, pdfFileName), "application/pdf");
|
||||
};
|
||||
|
||||
const previewPdf = () => {
|
||||
if (!pdfFileName || !userId) return;
|
||||
openPreviewWindow(buildReviewPdfPreviewUrl(performanceId, reviewType, userId, pdfFileName));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<input ref={fileInputRef} type="file" className="hidden" onChange={(event) => void upload(event.target.files?.[0])} />
|
||||
<ActionButton icon="upload" disabled={uploadMutation.isPending} onClick={() => fileInputRef.current?.click()}>파일 업로드</ActionButton>
|
||||
<ActionButton disabled={!userId || !uploadFileName || originalMutation.isPending} onClick={downloadOriginal}>원본</ActionButton>
|
||||
<ActionButton disabled={!userId || !pdfFileName || pdfMutation.isPending} onClick={downloadPdf}>PDF</ActionButton>
|
||||
<ActionButton icon="preview" disabled={!userId || !pdfFileName} onClick={previewPdf}>미리보기</ActionButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EvidenceActions({performanceId, userId}: {performanceId: number; userId?: string}) {
|
||||
const enabled = performanceId > 0 && Boolean(userId);
|
||||
const {data: evidenceList = []} = useMonitoringEvidenceQuery(performanceId, userId ?? "", enabled);
|
||||
const zipMutation = useDownloadEvidenceZipMutation();
|
||||
|
||||
const download = async () => {
|
||||
if (!userId) return;
|
||||
const buffer = await zipMutation.mutateAsync({performanceId, userId});
|
||||
downloadBlob(buffer, getEvidenceZipDownloadName(performanceId, userId), "application/zip");
|
||||
};
|
||||
|
||||
const preview = () => {
|
||||
if (!userId) return;
|
||||
const images = evidenceList
|
||||
.flatMap((item) =>
|
||||
(item.evidenceImg ?? "")
|
||||
.split("|")
|
||||
.map((fileName) => fileName.trim())
|
||||
.filter(Boolean)
|
||||
)
|
||||
.map((fileName) => buildEvidenceImageSrc(performanceId, userId, fileName));
|
||||
|
||||
if (images.length === 0) {
|
||||
alert("미리보기할 증빙사진이 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
openPreviewWindow(buildImagePreviewUrl("증빙사진", images));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<ActionButton icon="image" disabled={!userId || zipMutation.isPending} onClick={download}>증빙사진</ActionButton>
|
||||
<ActionButton icon="preview" disabled={!userId || evidenceList.length === 0} onClick={preview}>증빙 미리보기</ActionButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function MonitoringPerformanceDetailDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
performance,
|
||||
codes,
|
||||
userId,
|
||||
}: Readonly<{
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
performance: PerformanceFull | null;
|
||||
codes: CodeMap;
|
||||
userId?: string;
|
||||
}>) {
|
||||
const row = useMemo(() => {
|
||||
if (!performance || !userId) return undefined;
|
||||
return ([0, 1] as const)
|
||||
.map((index) => getMonitoringDisplayRow(performance, index))
|
||||
.find((item) => item.userId === userId);
|
||||
}, [performance, userId]);
|
||||
|
||||
const latestVisit = row?.slot.visit?.[0];
|
||||
const status = row
|
||||
? getMonitoringDisplayStatus(
|
||||
row,
|
||||
getCodeLabel(codes, "monitoring_visit_status", latestVisit?.monitoringVisitStatus),
|
||||
getCodeLabel(codes, "review_status", row.review?.reviewStatus)
|
||||
)
|
||||
: {label: "미배치", variant: "danger" as const};
|
||||
|
||||
const downloadTemplate = () => downloadFromUrl("/api/review/template/download/1");
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="flex max-h-[92vh] w-[calc(100vw-24px)] max-w-[430px] flex-col overflow-hidden p-0">
|
||||
<DialogHeader className="border-b px-4 py-3">
|
||||
<DialogTitle className="text-base">모니터링 상세</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="min-h-0 flex-1 space-y-3 overflow-y-auto p-3">
|
||||
{performance ? (
|
||||
<>
|
||||
<section className="overflow-hidden rounded-md border">
|
||||
<MobileDetailRow label="연번">{performance.id}</MobileDetailRow>
|
||||
<MobileDetailRow label="사업유형">{getCodeLabel(codes, "business_type", performance.businessType)}</MobileDetailRow>
|
||||
<MobileDetailRow label="분야(장르)">{getCodeLabel(codes, "genre", performance.performanceGenre)}</MobileDetailRow>
|
||||
<MobileDetailRow label="지역">{getCodeLabel(codes, "area", performance.performanceArea)}</MobileDetailRow>
|
||||
<MobileDetailRow label="단체(인)명">{performance.artistName}</MobileDetailRow>
|
||||
<MobileDetailRow label="사업명">{performance.performanceName}</MobileDetailRow>
|
||||
<MobileDetailRow label="사업 수행 월">{performance.performanceStartMonth}월</MobileDetailRow>
|
||||
<MobileDetailRow label="사업 일정">{performance.performanceDtInfo}</MobileDetailRow>
|
||||
<MobileDetailRow label="운영 시간">{performance.performanceTimeInfo}</MobileDetailRow>
|
||||
<MobileDetailRow label="예매 예약">{getCodeLabel(codes, "ticket_reservation_status", performance.ticketReservationStatus)}</MobileDetailRow>
|
||||
<MobileDetailRow label="예매 비고">{performance.ticketReservationMemo}</MobileDetailRow>
|
||||
<MobileDetailRow label="모니터링 일정">{performance.performanceMonitoringSchedule?.monitoringDate}</MobileDetailRow>
|
||||
<MobileDetailRow label="모니터링 시간">{performance.performanceMonitoringSchedule?.monitoringTimeInfo}</MobileDetailRow>
|
||||
<MobileDetailRow label="방문 장소">{performance.performanceMonitoringSchedule?.monitoringAddress}</MobileDetailRow>
|
||||
<MobileDetailRow label="메모">{performance.performanceMemo}</MobileDetailRow>
|
||||
</section>
|
||||
|
||||
<section className="space-y-3 rounded-md border p-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="font-semibold">나의 진행 상태</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" size="sm" variant="outline" onClick={downloadTemplate}>
|
||||
<Download className="h-4 w-4" />
|
||||
양식
|
||||
</Button>
|
||||
<StatusPill variant={status.variant}>{status.label}</StatusPill>
|
||||
</div>
|
||||
</div>
|
||||
{row ? (
|
||||
<MonitoringReviewActions
|
||||
performanceId={performance.id}
|
||||
reviewType={row.reviewType}
|
||||
userId={row.review?.regUser || row.userId}
|
||||
uploadFileName={row.review?.uploadFileName}
|
||||
pdfFileName={row.review?.pdfFileName}
|
||||
/>
|
||||
) : (
|
||||
<div className="rounded-md bg-muted p-3 text-sm text-muted-foreground">나의 모니터링 배정 정보를 찾을 수 없습니다.</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{row?.slot.visit?.length ? (
|
||||
<section className="space-y-3 rounded-md border p-3">
|
||||
<div className="font-semibold">모니터링 방문 기록</div>
|
||||
<div className="grid gap-1 text-sm text-muted-foreground">
|
||||
<div>출발: {getMonitoringRecordedAt(row.slot.timeline.departure)}</div>
|
||||
<div>도착: {getMonitoringRecordedAt(row.slot.timeline.arrival)}</div>
|
||||
</div>
|
||||
{row.slot.timeline.arrival && (
|
||||
<EvidenceActions performanceId={performance.id} userId={row.evidenceUserId} />
|
||||
)}
|
||||
</section>
|
||||
) : null}
|
||||
</>
|
||||
) : (
|
||||
<div className="rounded-md border p-4 text-sm text-muted-foreground">공연 정보를 불러오는 중입니다.</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="border-t px-4 py-3">
|
||||
<Button type="button" variant="outline" className="w-full" onClick={() => onOpenChange(false)}>닫기</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
81
src/components/dialog/MonitoringVisitDialog.tsx
Normal file
81
src/components/dialog/MonitoringVisitDialog.tsx
Normal file
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import {ReactNode, useEffect, useMemo, useState} from "react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {PerformanceCompact} from "@/types/gwcf";
|
||||
|
||||
function DetailRow({label, children}: {label: string; children: ReactNode}) {
|
||||
return (
|
||||
<div className="grid grid-cols-[130px_1fr] border-b last:border-b-0">
|
||||
<div className="bg-muted px-3 py-2 text-sm font-semibold">{label}</div>
|
||||
<div className="min-h-9 px-3 py-2 text-sm">{children || "-"}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function MonitoringVisitDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
performance,
|
||||
mode,
|
||||
onSubmit,
|
||||
isSubmitting,
|
||||
}: Readonly<{
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
performance: PerformanceCompact | null;
|
||||
mode: "departure" | "arrival";
|
||||
onSubmit?: (files?: File[]) => void | Promise<void>;
|
||||
isSubmitting?: boolean;
|
||||
}>) {
|
||||
const nowText = useMemo(() => new Date().toLocaleString("ko-KR"), [open]);
|
||||
const [files, setFiles] = useState<File[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) setFiles([]);
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>모니터링 {mode === "departure" ? "출발" : "도착"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="rounded-md border">
|
||||
<DetailRow label="현재 시간">{nowText}</DetailRow>
|
||||
<DetailRow label="모니터링 일정">
|
||||
{performance?.performanceMonitoringSchedule?.monitoringDate} {performance?.performanceMonitoringSchedule?.monitoringTimeInfo}
|
||||
</DetailRow>
|
||||
<DetailRow label="사업명">{performance?.performanceName}</DetailRow>
|
||||
<DetailRow label="장소">{performance?.performanceMonitoringSchedule?.monitoringAddress}</DetailRow>
|
||||
{mode === "arrival" && (
|
||||
<DetailRow label="증빙사진">
|
||||
<label className="flex min-h-11 cursor-pointer items-center justify-center rounded-md border bg-muted px-3 py-2 text-sm font-medium">
|
||||
{files.length > 0 ? `${files.length}개 파일 선택됨` : "증빙 사진 선택"}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={(event) => setFiles(Array.from(event.target.files ?? []))}
|
||||
/>
|
||||
</label>
|
||||
</DetailRow>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" disabled={!performance || isSubmitting} onClick={() => onSubmit?.(files)}>
|
||||
{mode === "departure" ? "출발 저장" : "도착 저장"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
552
src/components/dialog/PerformanceDetailDialog.tsx
Normal file
552
src/components/dialog/PerformanceDetailDialog.tsx
Normal file
@@ -0,0 +1,552 @@
|
||||
"use client";
|
||||
|
||||
import {ReactNode, useEffect, useMemo, useRef, useState} from "react";
|
||||
import {Download, ImageIcon, ScanSearch, Upload} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
|
||||
import {DatePicker} from "@/components/common/DatePicker";
|
||||
import {FilterSelect} from "@/components/gwcf/FilterSelect";
|
||||
import {StatusPill} from "@/components/gwcf/StatusPill";
|
||||
import {Code, PerformanceCompact, PerformanceFull, PerformanceMonitoringSchedule, PerformanceStaff, UserFull} from "@/types/gwcf";
|
||||
import {CodeGroup} from "@/query/code";
|
||||
import {getCodeLabel, getDetailValue, ROLE} from "@/lib/gwcf/view";
|
||||
import {
|
||||
getMonitoringDisplayRow,
|
||||
getMonitoringDisplayStatus,
|
||||
getMonitoringRecordedAt,
|
||||
getReviewByType,
|
||||
getReviewStatusDisplay,
|
||||
getWrittenReviewRows,
|
||||
isReviewComplete,
|
||||
LOCAL_GOVERNMENT_REVIEW_TYPE,
|
||||
} from "@/lib/gwcf/performance-status";
|
||||
import {
|
||||
useDownloadReviewOriginalMutation,
|
||||
useDownloadReviewPdfMutation,
|
||||
useReviewFileQuery,
|
||||
useUploadReviewFileMutation,
|
||||
} from "@/query/review";
|
||||
import {useDownloadEvidenceZipMutation, useMonitoringEvidenceQuery} from "@/query/monitoring";
|
||||
import {useUsersQuery} from "@/query/user";
|
||||
import {useLoading} from "@/hooks/useLoading";
|
||||
import {
|
||||
buildEvidenceImageSrc,
|
||||
buildImagePreviewUrl,
|
||||
buildReviewPdfPreviewUrl,
|
||||
downloadBlob,
|
||||
downloadFromUrl,
|
||||
getEvidenceZipDownloadName,
|
||||
getReviewOriginalDownloadName,
|
||||
getReviewPdfDownloadName,
|
||||
openPreviewWindow,
|
||||
openWrittenReviewWindow,
|
||||
} from "@/lib/gwcf/file";
|
||||
|
||||
type CodeMap = Partial<Record<CodeGroup, Code[]>>;
|
||||
|
||||
function DetailRow({label, children}: {label: string; children: ReactNode}) {
|
||||
return (
|
||||
<div className="grid grid-cols-[130px_1fr] border-b last:border-b-0">
|
||||
<div className="bg-muted px-3 py-2 text-sm font-semibold">{label}</div>
|
||||
<div className="min-h-9 px-3 py-2 text-sm">{children || "-"}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FileActionButton({
|
||||
children,
|
||||
icon = "download",
|
||||
disabled = false,
|
||||
onClick,
|
||||
}: Readonly<{
|
||||
children: ReactNode;
|
||||
icon?: "download" | "upload" | "image" | "preview";
|
||||
disabled?: boolean;
|
||||
onClick?: () => void;
|
||||
}>) {
|
||||
const Icon = icon === "upload" ? Upload : icon === "image" ? ImageIcon : icon === "preview" ? ScanSearch : Download;
|
||||
return (
|
||||
<Button type="button" size="xs" variant="outline" disabled={disabled} onClick={onClick}>
|
||||
<Icon className="h-3 w-3" />
|
||||
{children}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
function AssignedUserInfo({
|
||||
userId,
|
||||
user,
|
||||
codes,
|
||||
type,
|
||||
}: Readonly<{
|
||||
userId?: string;
|
||||
user?: UserFull;
|
||||
codes: CodeMap;
|
||||
type: "monitoring" | "written";
|
||||
}>) {
|
||||
const detail = user?.userDetail;
|
||||
const tel = getDetailValue(detail, ["tel", "phone", "userTel"], "-");
|
||||
const email = getDetailValue(detail, ["email", "userEmail"], "-");
|
||||
const metaValue = type === "monitoring"
|
||||
? getCodeLabel(codes, "area", getDetailValue(detail, ["area", "userArea", "region"]))
|
||||
: getCodeLabel(codes, "genre", getDetailValue(detail, ["userGenre", "genre", "reviewGenre"]));
|
||||
const metaLabel = type === "monitoring" ? "지역" : "장르";
|
||||
const hasCar = getCodeLabel(codes, "has_car", getDetailValue(detail, ["userHasCar", "has_car", "hasCar"])) || "-";
|
||||
|
||||
return (
|
||||
<div className="rounded-md border bg-muted/30 p-2 text-sm">
|
||||
<div className="grid gap-1 text-xs text-muted-foreground sm:grid-cols-2">
|
||||
<span>ID: {userId || "-"}</span>
|
||||
<span>{metaLabel}: {metaValue || "-"}</span>
|
||||
<span>연락처: {tel}</span>
|
||||
<span>이메일: {email}</span>
|
||||
{type === "monitoring" && <span>자차유무: {hasCar}</span>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ReviewFileActions({
|
||||
performanceId,
|
||||
reviewType,
|
||||
userId,
|
||||
uploadFileName,
|
||||
pdfFileName,
|
||||
canEdit,
|
||||
}: Readonly<{
|
||||
performanceId: number;
|
||||
reviewType: number;
|
||||
userId?: string;
|
||||
uploadFileName?: string;
|
||||
pdfFileName?: string;
|
||||
canEdit: boolean;
|
||||
}>) {
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const uploadMutation = useUploadReviewFileMutation();
|
||||
const originalMutation = useDownloadReviewOriginalMutation();
|
||||
const pdfMutation = useDownloadReviewPdfMutation();
|
||||
const {withLoadingAsync} = useLoading();
|
||||
const complete = Boolean(pdfFileName);
|
||||
|
||||
const upload = async (file?: File) => {
|
||||
try {
|
||||
if (!file) return;
|
||||
await withLoadingAsync(() => uploadMutation.mutateAsync({performanceId, reviewType, file}));
|
||||
alert("파일 업로드가 완료되었습니다.");
|
||||
} finally {
|
||||
if (fileInputRef.current) fileInputRef.current.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
const downloadOriginal = async () => {
|
||||
if (!userId) return;
|
||||
const buffer = await originalMutation.mutateAsync({ performanceId, reviewType, userId });
|
||||
downloadBlob(
|
||||
buffer,
|
||||
getReviewOriginalDownloadName(performanceId, reviewType, uploadFileName)
|
||||
);
|
||||
};
|
||||
|
||||
const downloadPdf = async () => {
|
||||
if (!userId) return;
|
||||
const buffer = await pdfMutation.mutateAsync({ performanceId, reviewType, userId });
|
||||
downloadBlob(
|
||||
buffer,
|
||||
getReviewPdfDownloadName(performanceId, reviewType, pdfFileName),
|
||||
"application/pdf"
|
||||
);
|
||||
};
|
||||
|
||||
const previewPdf = () => {
|
||||
if (!pdfFileName || !userId) return;
|
||||
openPreviewWindow(buildReviewPdfPreviewUrl(performanceId, reviewType, userId, pdfFileName));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{canEdit && (
|
||||
<>
|
||||
<input ref={fileInputRef} type="file" className="hidden" onChange={(event) => void upload(event.target.files?.[0])} />
|
||||
<FileActionButton icon="upload" disabled={uploadMutation.isPending || !complete} onClick={() => fileInputRef.current?.click()}>파일 업로드</FileActionButton>
|
||||
</>
|
||||
)}
|
||||
<FileActionButton icon="download" disabled={!userId || !uploadFileName || originalMutation.isPending} onClick={downloadOriginal}>원본</FileActionButton>
|
||||
<FileActionButton icon="download" disabled={!userId || !pdfFileName || pdfMutation.isPending} onClick={downloadPdf}>PDF</FileActionButton>
|
||||
<FileActionButton icon="preview" disabled={!userId || !pdfFileName} onClick={previewPdf}>미리보기</FileActionButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EvidenceZipButton({performanceId, userId}: {performanceId: number; userId: string}) {
|
||||
const {data: evidenceList = []} = useMonitoringEvidenceQuery(performanceId, userId, performanceId > 0 && Boolean(userId));
|
||||
const zipMutation = useDownloadEvidenceZipMutation();
|
||||
const download = async () => {
|
||||
const buffer = await zipMutation.mutateAsync({performanceId, userId});
|
||||
downloadBlob(buffer, getEvidenceZipDownloadName(performanceId, userId), "application/zip");
|
||||
};
|
||||
|
||||
const preview = () => {
|
||||
const images = evidenceList
|
||||
.flatMap((item) =>
|
||||
(item.evidenceImg ?? "")
|
||||
.split("|")
|
||||
.map((fileName) => fileName.trim())
|
||||
.filter(Boolean)
|
||||
)
|
||||
.map((fileName) => buildEvidenceImageSrc(performanceId, userId, fileName));
|
||||
|
||||
if (images.length === 0) {
|
||||
alert("미리보기할 증빙사진이 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
openPreviewWindow(buildImagePreviewUrl("증빙 미리보기", images));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<FileActionButton icon="image" disabled={zipMutation.isPending} onClick={download}>다운로드</FileActionButton>
|
||||
<FileActionButton icon="preview" disabled={evidenceList.length === 0} onClick={preview}>증빙 미리보기</FileActionButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LocalGovernmentReviewRow({
|
||||
performance,
|
||||
codes,
|
||||
}: {
|
||||
performance: PerformanceFull | PerformanceCompact;
|
||||
codes: CodeMap;
|
||||
}) {
|
||||
const reviewType = LOCAL_GOVERNMENT_REVIEW_TYPE;
|
||||
const fallbackReviewRow = getReviewByType(performance as PerformanceFull, reviewType);
|
||||
const userId = fallbackReviewRow?.review.regUser || fallbackReviewRow?.userId;
|
||||
const {data: fetchedReview} = useReviewFileQuery(performance.id, reviewType, userId, performance.id > 0 && Boolean(userId));
|
||||
const review = fetchedReview ?? fallbackReviewRow?.review;
|
||||
const label = getCodeLabel(codes, "review_status", review?.reviewStatus);
|
||||
const display = getReviewStatusDisplay(label, review, true);
|
||||
|
||||
return (
|
||||
<div className="space-y-2 border-b p-3">
|
||||
<div className="font-semibold">지자체</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<StatusPill variant={display.variant}>{display.label}</StatusPill>
|
||||
<ReviewFileActions performanceId={performance.id} reviewType={reviewType} userId={review?.regUser || userId} uploadFileName={review?.uploadFileName} pdfFileName={review?.pdfFileName} canEdit={true} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MonitoringStatusRow({
|
||||
performance,
|
||||
index,
|
||||
codes,
|
||||
userMap,
|
||||
canEdit,
|
||||
}: Readonly<{
|
||||
performance: PerformanceFull | PerformanceCompact;
|
||||
index: 0 | 1;
|
||||
codes: CodeMap;
|
||||
userMap: Map<string, UserFull>;
|
||||
canEdit: boolean;
|
||||
}>) {
|
||||
const row = getMonitoringDisplayRow(performance as PerformanceFull, index);
|
||||
const user = row.userId ? userMap.get(row.userId) : undefined;
|
||||
const latestVisit = row.slot.visit?.[0];
|
||||
const display = getMonitoringDisplayStatus(
|
||||
row,
|
||||
getCodeLabel(codes, "monitoring_visit_status", latestVisit?.monitoringVisitStatus),
|
||||
getCodeLabel(codes, "review_status", row.review?.reviewStatus)
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-2 border-b p-3">
|
||||
<div className="font-semibold">모니터링 {index + 1}</div>
|
||||
<div className="grid gap-1 text-sm">
|
||||
<AssignedUserInfo userId={row.userId} user={user} codes={codes} type="monitoring" />
|
||||
<div className="flex flex-wrap items-center gap-2 mb-2">
|
||||
<StatusPill variant={display.variant}>{display.label}</StatusPill>
|
||||
<ReviewFileActions performanceId={performance.id} reviewType={row.reviewType} userId={row.review?.regUser || row.userId} uploadFileName={row.review?.uploadFileName} pdfFileName={row.review?.pdfFileName} canEdit={canEdit} />
|
||||
</div>
|
||||
{row.slot.visit?.length ? (
|
||||
<>
|
||||
<div className="rounded-md border bg-muted/30 p-2 text-sm">
|
||||
<div className="grid gap-1 text-xs text-muted-foreground sm:grid-cols-1">
|
||||
<span>출발: {getMonitoringRecordedAt(row.slot.timeline.departure)}</span>
|
||||
<span>도착: {getMonitoringRecordedAt(row.slot.timeline.arrival)}</span>
|
||||
</div>
|
||||
</div>
|
||||
{row.slot.timeline.arrival && row.evidenceUserId && (
|
||||
<EvidenceZipButton
|
||||
performanceId={performance.id}
|
||||
userId={row.evidenceUserId}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WrittenReviewRows({
|
||||
performance,
|
||||
codes,
|
||||
userMap,
|
||||
canEdit,
|
||||
}: Readonly<{
|
||||
performance: PerformanceFull | PerformanceCompact;
|
||||
codes: CodeMap;
|
||||
userMap: Map<string, UserFull>;
|
||||
canEdit: boolean;
|
||||
}>) {
|
||||
const rows = getWrittenReviewRows(performance as PerformanceFull);
|
||||
|
||||
if(rows.length === 0){
|
||||
rows.push({userId: "", assign: undefined, review: undefined});
|
||||
}
|
||||
|
||||
const openWrittenReviewLink = (userId: string, complete: boolean) => {
|
||||
openWrittenReviewWindow(performance.id, userId, complete);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2 border-b p-3">
|
||||
<div className="font-semibold">서면평가</div>
|
||||
<div className="grid gap-1 text-sm">
|
||||
{rows.map(({userId, assign, review}) => {
|
||||
const user = userMap.get(userId);
|
||||
const complete = isReviewComplete(review);
|
||||
const reviewType = review?.reviewType ?? assign?.assignType ?? 2;
|
||||
const label = getCodeLabel(codes, "review_status", review?.reviewStatus);
|
||||
const display = getReviewStatusDisplay(label, review, Boolean(assign));
|
||||
return (
|
||||
<div key={`${userId}-${reviewType}`} className="space-y-2 border-b p-3 last:border-b-0">
|
||||
<AssignedUserInfo userId={userId} user={user} codes={codes} type="written" />
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<StatusPill variant={display.variant} onClick={complete ? () => openWrittenReviewLink(userId, true) : undefined}>
|
||||
{display.label}
|
||||
</StatusPill>
|
||||
{canEdit && (
|
||||
<Button type="button" size="xs" variant="outline" disabled={!complete} onClick={() => openWrittenReviewLink(userId, false)}>
|
||||
평가 수정
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PerformanceDetailDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
performance,
|
||||
codes,
|
||||
canEdit,
|
||||
onSave,
|
||||
}: Readonly<{
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
performance: PerformanceFull | PerformanceCompact | null;
|
||||
codes: CodeMap;
|
||||
canEdit: boolean;
|
||||
onSave?: (performance: PerformanceCompact) => void;
|
||||
}>) {
|
||||
const [draft, setDraft] = useState<PerformanceCompact | null>(null);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const {data: monitoringUsers = []} = useUsersQuery(ROLE.MONITORING, open);
|
||||
const {data: writtenUsers = []} = useUsersQuery(ROLE.WRITTEN_REVIEWER, open);
|
||||
const monitoringUserMap = useMemo(
|
||||
() => new Map(monitoringUsers.map((user) => [user.userId, user])),
|
||||
[monitoringUsers]
|
||||
);
|
||||
const writtenUserMap = useMemo(
|
||||
() => new Map(writtenUsers.map((user) => [user.userId, user])),
|
||||
[writtenUsers]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!performance) {
|
||||
setDraft(null);
|
||||
setIsEditing(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setDraft({
|
||||
id: performance.id,
|
||||
businessType: performance.businessType,
|
||||
performanceGenre: performance.performanceGenre,
|
||||
performanceArea: performance.performanceArea,
|
||||
artistName: performance.artistName,
|
||||
performanceName: performance.performanceName,
|
||||
performanceStartMonth: performance.performanceStartMonth,
|
||||
performanceDtInfo: performance.performanceDtInfo,
|
||||
performanceTimeInfo: performance.performanceTimeInfo,
|
||||
ticketReservationStatus: performance.ticketReservationStatus,
|
||||
ticketReservationMemo: performance.ticketReservationMemo,
|
||||
performanceMemo: performance.performanceMemo,
|
||||
performanceDetail: performance.performanceDetail,
|
||||
performanceStaff: performance.performanceStaff,
|
||||
performanceMonitoringSchedule: performance.performanceMonitoringSchedule,
|
||||
});
|
||||
setIsEditing(false);
|
||||
}, [performance]);
|
||||
|
||||
const updateDraft = <K extends keyof PerformanceCompact>(key: K, value: PerformanceCompact[K]) => {
|
||||
setDraft((prev) => prev ? {...prev, [key]: value} : prev);
|
||||
};
|
||||
|
||||
const updateSchedule = <K extends keyof PerformanceMonitoringSchedule>(key: K, value: PerformanceMonitoringSchedule[K]) => {
|
||||
setDraft((prev) => prev ? {
|
||||
...prev,
|
||||
performanceMonitoringSchedule: {
|
||||
...prev.performanceMonitoringSchedule,
|
||||
[key]: value,
|
||||
},
|
||||
} : prev);
|
||||
};
|
||||
|
||||
const updateStaff = (index: number, key: keyof PerformanceStaff, value: string | number) => {
|
||||
setDraft((prev) => {
|
||||
if (!prev) return prev;
|
||||
const next = [...(prev.performanceStaff ?? [])];
|
||||
next[index] = {...next[index], [key]: value};
|
||||
return {...prev, performanceStaff: next};
|
||||
});
|
||||
};
|
||||
|
||||
const resetDraft = () => {
|
||||
if (!performance) return;
|
||||
setDraft({
|
||||
id: performance.id,
|
||||
businessType: performance.businessType,
|
||||
performanceGenre: performance.performanceGenre,
|
||||
performanceArea: performance.performanceArea,
|
||||
artistName: performance.artistName,
|
||||
performanceName: performance.performanceName,
|
||||
performanceStartMonth: performance.performanceStartMonth,
|
||||
performanceDtInfo: performance.performanceDtInfo,
|
||||
performanceTimeInfo: performance.performanceTimeInfo,
|
||||
ticketReservationStatus: performance.ticketReservationStatus,
|
||||
ticketReservationMemo: performance.ticketReservationMemo,
|
||||
performanceMemo: performance.performanceMemo,
|
||||
performanceDetail: performance.performanceDetail,
|
||||
performanceStaff: performance.performanceStaff,
|
||||
performanceMonitoringSchedule: performance.performanceMonitoringSchedule,
|
||||
});
|
||||
};
|
||||
|
||||
const save = () => {
|
||||
if (!draft) return;
|
||||
onSave?.(draft);
|
||||
setIsEditing(false);
|
||||
};
|
||||
|
||||
const downloadTemplate = (reviewType: number) => {
|
||||
downloadFromUrl(`/api/review/template/download/${reviewType}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-6xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>사업 상세 정보</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto pr-1">
|
||||
{draft && (
|
||||
<div className="grid gap-4 lg:grid-cols-[1.1fr_0.9fr]">
|
||||
<div className="space-y-4">
|
||||
<section className="rounded-md border">
|
||||
<DetailRow label="연번">{draft.id}</DetailRow>
|
||||
<DetailRow label="사업유형">{getCodeLabel(codes, "business_type", draft.businessType)}</DetailRow>
|
||||
<DetailRow label="분야(장르)">{getCodeLabel(codes, "genre", draft.performanceGenre)}</DetailRow>
|
||||
<DetailRow label="지역">{getCodeLabel(codes, "area", draft.performanceArea)}</DetailRow>
|
||||
<DetailRow label="단체(인)명">{draft.artistName}</DetailRow>
|
||||
<DetailRow label="사업명">{isEditing ? <Input value={draft.performanceName} onChange={(event) => updateDraft("performanceName", event.target.value)} /> : draft.performanceName}</DetailRow>
|
||||
<DetailRow label="사업 수행 월">{isEditing ? <Input type="number" value={draft.performanceStartMonth} onChange={(event) => updateDraft("performanceStartMonth", Number(event.target.value))} /> : `${draft.performanceStartMonth}월`}</DetailRow>
|
||||
<DetailRow label="사업 일정">{isEditing ? <Input value={draft.performanceDtInfo} onChange={(event) => updateDraft("performanceDtInfo", event.target.value)} /> : draft.performanceDtInfo}</DetailRow>
|
||||
<DetailRow label="운영 시간">{isEditing ? <Input value={draft.performanceTimeInfo} onChange={(event) => updateDraft("performanceTimeInfo", event.target.value)} /> : draft.performanceTimeInfo}</DetailRow>
|
||||
<DetailRow label="예매 예약">
|
||||
{isEditing ? (
|
||||
<FilterSelect value={String(draft.ticketReservationStatus ?? "")} onChange={(value) => updateDraft("ticketReservationStatus", Number(value))} options={codes.ticket_reservation_status ?? []} placeholder="예매 예약" />
|
||||
) : getCodeLabel(codes, "ticket_reservation_status", draft.ticketReservationStatus)}
|
||||
</DetailRow>
|
||||
<DetailRow label="예매 비고">{isEditing ? <Input value={draft.ticketReservationMemo} onChange={(event) => updateDraft("ticketReservationMemo", event.target.value)} /> : draft.ticketReservationMemo}</DetailRow>
|
||||
<DetailRow label="모니터링 일정">{isEditing ? <DatePicker value={draft.performanceMonitoringSchedule?.monitoringDate ?? ""} onChange={(value) => updateSchedule("monitoringDate", value)} /> : draft.performanceMonitoringSchedule?.monitoringDate}</DetailRow>
|
||||
<DetailRow label="모니터링 시간">{isEditing ? <Input value={draft.performanceMonitoringSchedule?.monitoringTimeInfo ?? ""} onChange={(event) => updateSchedule("monitoringTimeInfo", event.target.value)} /> : draft.performanceMonitoringSchedule?.monitoringTimeInfo}</DetailRow>
|
||||
<DetailRow label="방문 장소">{isEditing ? <Input value={draft.performanceMonitoringSchedule?.monitoringAddress ?? ""} onChange={(event) => updateSchedule("monitoringAddress", event.target.value)} /> : draft.performanceMonitoringSchedule?.monitoringAddress}</DetailRow>
|
||||
<DetailRow label="메모">{isEditing ? <Input value={draft.performanceMemo} onChange={(event) => updateDraft("performanceMemo", event.target.value)} /> : draft.performanceMemo}</DetailRow>
|
||||
</section>
|
||||
|
||||
<section className="rounded-md border">
|
||||
<div className="border-b bg-muted px-3 py-2 font-semibold">관계자 정보</div>
|
||||
<div className="overflow-auto">
|
||||
<table className="w-full min-w-[620px] border-collapse text-sm">
|
||||
<thead>
|
||||
<tr className="bg-muted">
|
||||
<th className="border p-2">유형</th>
|
||||
<th className="border p-2">이름</th>
|
||||
<th className="border p-2">연락처1</th>
|
||||
<th className="border p-2">연락처2</th>
|
||||
<th className="border p-2">이메일</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{draft.performanceStaff?.map((staff, index) => (
|
||||
<tr key={staff.id}>
|
||||
<td className="border p-2">{getCodeLabel(codes, "staff_type", staff.staffType)}</td>
|
||||
<td className="border p-2">{isEditing ? <Input value={staff.staffName} onChange={(event) => updateStaff(index, "staffName", event.target.value)} /> : staff.staffName}</td>
|
||||
<td className="border p-2">{isEditing ? <Input value={staff.staffTel1} onChange={(event) => updateStaff(index, "staffTel1", event.target.value)} /> : staff.staffTel1}</td>
|
||||
<td className="border p-2">{isEditing ? <Input value={staff.staffTel2} onChange={(event) => updateStaff(index, "staffTel2", event.target.value)} /> : staff.staffTel2}</td>
|
||||
<td className="border p-2">{isEditing ? <Input value={staff.staffEmail} onChange={(event) => updateStaff(index, "staffEmail", event.target.value)} /> : staff.staffEmail}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section className="rounded-md border">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 border-b bg-muted px-3 py-2">
|
||||
<div className="font-semibold">평가 및 모니터링 현황</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="button" size="sm" variant="outline" onClick={() => downloadTemplate(1)}>
|
||||
<Download className="h-4 w-4" />
|
||||
모니터링 양식
|
||||
</Button>
|
||||
<Button type="button" size="sm" variant="outline" onClick={() => downloadTemplate(3)}>
|
||||
<Download className="h-4 w-4" />
|
||||
지자체 양식
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<LocalGovernmentReviewRow performance={performance ?? draft} codes={codes} />
|
||||
<MonitoringStatusRow performance={performance ?? draft} index={0} codes={codes} userMap={monitoringUserMap} canEdit={canEdit} />
|
||||
<MonitoringStatusRow performance={performance ?? draft} index={1} codes={codes} userMap={monitoringUserMap} canEdit={canEdit} />
|
||||
<WrittenReviewRows performance={performance ?? draft} codes={codes} userMap={writtenUserMap} canEdit={canEdit} />
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="shrink-0 border-t pt-4">
|
||||
{canEdit && draft && !isEditing && <Button type="button" onClick={() => setIsEditing(true)}>수정</Button>}
|
||||
{canEdit && draft && isEditing && (
|
||||
<>
|
||||
<Button type="button" onClick={save}>저장</Button>
|
||||
<Button type="button" variant="outline" onClick={() => { resetDraft(); setIsEditing(false); }}>취소</Button>
|
||||
</>
|
||||
)}
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>닫기</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
265
src/components/dialog/SmsSendDialog.tsx
Normal file
265
src/components/dialog/SmsSendDialog.tsx
Normal file
@@ -0,0 +1,265 @@
|
||||
"use client";
|
||||
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import {Edit, RotateCcw, Save, Send} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Input} from "@/components/ui/input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
NOTIFICATION_REQUEST_SERVICE,
|
||||
useNotificationTemplateQuery,
|
||||
useSaveNotificationTemplateMutation,
|
||||
useSendSmsBulkMutation,
|
||||
} from "@/query/notification";
|
||||
import {SaveTemplateRequest, Template} from "@/types/notification";
|
||||
import {UserCompact} from "@/types/gwcf";
|
||||
import {getDetailValue} from "@/lib/gwcf/view";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
import {buildUserMsgParam} from "@/lib/gwcf/notification";
|
||||
|
||||
type TemplateDraft = Pick<Template, "tmplatIdx" | "tmplatNm" | "tmplatTitle" | "tmplatBody" | "sendTel">;
|
||||
|
||||
const toText = (value: string | null | undefined) => value ?? "";
|
||||
|
||||
const toDraft = (template: Template, emptyBody = false): TemplateDraft => ({
|
||||
tmplatIdx: template.tmplatIdx,
|
||||
tmplatNm: toText(template.tmplatNm),
|
||||
tmplatTitle: toText(template.tmplatTitle),
|
||||
tmplatBody: emptyBody ? "" : toText(template.tmplatBody),
|
||||
sendTel: toText(template.sendTel),
|
||||
});
|
||||
|
||||
export function SmsSendDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title = "문자 발송",
|
||||
templateIdx,
|
||||
newMessageTemplateIdx,
|
||||
selectedUsers,
|
||||
addParams = {},
|
||||
onBeforeDefaultTemplateSend,
|
||||
isBeforeSendPending = false,
|
||||
onSent,
|
||||
}: Readonly<{
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title?: string;
|
||||
templateIdx: number;
|
||||
newMessageTemplateIdx?: number;
|
||||
selectedUsers: UserCompact[];
|
||||
addParams?: Record<string, string>;
|
||||
onBeforeDefaultTemplateSend?: () => Promise<void>;
|
||||
isBeforeSendPending?: boolean;
|
||||
onSent?: () => void;
|
||||
}>) {
|
||||
const {auth} = useAuth();
|
||||
const [activeTemplateIdx, setActiveTemplateIdx] = useState(templateIdx);
|
||||
const [isNewMessage, setIsNewMessage] = useState(false);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [draft, setDraft] = useState<TemplateDraft | null>(null);
|
||||
|
||||
const templateQuery = useNotificationTemplateQuery(activeTemplateIdx, open);
|
||||
const saveTemplateMutation = useSaveNotificationTemplateMutation();
|
||||
const sendSmsMutation = useSendSmsBulkMutation();
|
||||
|
||||
const isBusy = templateQuery.isLoading || saveTemplateMutation.isPending || sendSmsMutation.isPending || isBeforeSendPending;
|
||||
const canEdit = isNewMessage || isEditing;
|
||||
|
||||
const destinations = useMemo(() => {
|
||||
return selectedUsers
|
||||
.map((user) => ({
|
||||
sid: user.userId,
|
||||
destTel: getDetailValue(user.userDetail, ["userTel"]),
|
||||
destNm: user.userName || user.userId,
|
||||
msgParam: {
|
||||
...buildUserMsgParam(user),
|
||||
...addParams,
|
||||
},
|
||||
}))
|
||||
.filter((item) => item.destTel);
|
||||
}, [selectedUsers, addParams]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
setActiveTemplateIdx(templateIdx);
|
||||
setIsNewMessage(false);
|
||||
setIsEditing(false);
|
||||
setDraft(null);
|
||||
}, [open, templateIdx]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !templateQuery.data) return;
|
||||
|
||||
setDraft(toDraft(templateQuery.data, isNewMessage));
|
||||
setIsEditing(false);
|
||||
}, [isNewMessage, open, templateQuery.data]);
|
||||
|
||||
const updateDraft = <K extends keyof TemplateDraft>(key: K, value: TemplateDraft[K]) => {
|
||||
setDraft((prev) => prev ? {...prev, [key]: value} : prev);
|
||||
};
|
||||
|
||||
const saveTemplate = async () => {
|
||||
if (!draft) return null;
|
||||
|
||||
const payload: SaveTemplateRequest = {
|
||||
tmplatIdx: draft.tmplatIdx,
|
||||
tmplatNm: draft.tmplatNm,
|
||||
tmplatTitle: draft.tmplatTitle,
|
||||
tmplatBody: draft.tmplatBody,
|
||||
sendTel: draft.sendTel,
|
||||
};
|
||||
|
||||
const saved = await saveTemplateMutation.mutateAsync(payload);
|
||||
setDraft(toDraft(saved));
|
||||
setIsEditing(false);
|
||||
return saved;
|
||||
};
|
||||
|
||||
const switchToNewMessage = () => {
|
||||
if (!newMessageTemplateIdx) return;
|
||||
|
||||
setActiveTemplateIdx(newMessageTemplateIdx);
|
||||
setIsNewMessage(true);
|
||||
setIsEditing(false);
|
||||
setDraft(null);
|
||||
};
|
||||
|
||||
const restoreTemplate = () => {
|
||||
setActiveTemplateIdx(templateIdx);
|
||||
setIsNewMessage(false);
|
||||
setIsEditing(false);
|
||||
setDraft(null);
|
||||
};
|
||||
|
||||
const send = async () => {
|
||||
if (!draft) return;
|
||||
|
||||
if (!auth.user?.userCmpn || !auth.user?.userId) {
|
||||
alert("로그인 사용자 정보를 확인할 수 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedUsers.length === 0) {
|
||||
alert("문자를 발송할 사용자를 선택해 주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (destinations.length === 0) {
|
||||
alert("발송 가능한 연락처가 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (destinations.length !== selectedUsers.length) {
|
||||
if (!confirm("연락처가 없는 사용자는 제외하고 발송합니다. 계속하시겠습니까?")) return;
|
||||
}
|
||||
|
||||
if (isNewMessage) {
|
||||
await saveTemplate();
|
||||
} else {
|
||||
await onBeforeDefaultTemplateSend?.();
|
||||
}
|
||||
|
||||
const result = await sendSmsMutation.mutateAsync({
|
||||
templateIdx: draft.tmplatIdx,
|
||||
reqstCmpn: auth.user.userCmpn,
|
||||
reqstUser: auth.user.userId,
|
||||
reqstSvc: NOTIFICATION_REQUEST_SERVICE,
|
||||
destinations,
|
||||
});
|
||||
|
||||
alert(`문자 발송 요청이 ${result.requestCount}건 완료되었습니다.`);
|
||||
onSent?.();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto pr-1">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border bg-muted/30 p-3">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
선택 인원: <span className="font-semibold text-foreground">{selectedUsers.length}</span>명
|
||||
{destinations.length !== selectedUsers.length && (
|
||||
<span className="ml-2 text-destructive">발송 가능 {destinations.length}명</span>
|
||||
)}
|
||||
</div>
|
||||
{newMessageTemplateIdx && (
|
||||
isNewMessage ? (
|
||||
<Button type="button" size="sm" variant="outline" onClick={restoreTemplate} disabled={isBusy}>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
기본 템플릿
|
||||
</Button>
|
||||
) : (
|
||||
<Button type="button" size="sm" variant="outline" onClick={switchToNewMessage} disabled={isBusy}>
|
||||
새문자 보내기
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
|
||||
{templateQuery.isLoading && (
|
||||
<div className="rounded-md border p-4 text-sm text-muted-foreground">템플릿 정보를 불러오는 중입니다.</div>
|
||||
)}
|
||||
|
||||
{draft && (
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<label className="space-y-1 text-sm">
|
||||
<span className="font-medium">템플릿명</span>
|
||||
<Input value={draft.tmplatNm} disabled />
|
||||
</label>
|
||||
<label className="space-y-1 text-sm">
|
||||
<span className="font-medium">발신번호</span>
|
||||
<Input value={draft.sendTel ?? ""} disabled={!canEdit || isBusy} onChange={(event) => updateDraft("sendTel", event.target.value)} />
|
||||
</label>
|
||||
</div>
|
||||
<label className="space-y-1 text-sm">
|
||||
<span className="font-medium">제목</span>
|
||||
<Input value={draft.tmplatTitle} disabled={!canEdit || isBusy} onChange={(event) => updateDraft("tmplatTitle", event.target.value)} />
|
||||
</label>
|
||||
<label className="space-y-1 text-sm">
|
||||
<span className="font-medium">내용</span>
|
||||
<textarea
|
||||
value={draft.tmplatBody}
|
||||
disabled={!canEdit || isBusy}
|
||||
onChange={(event) => updateDraft("tmplatBody", event.target.value)}
|
||||
className="min-h-56 w-full rounded-md border border-input bg-background p-3 text-sm disabled:cursor-not-allowed disabled:opacity-70"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="shrink-0 border-t pt-4">
|
||||
{!isNewMessage && draft && !isEditing && (
|
||||
<Button type="button" variant="outline" onClick={() => setIsEditing(true)} disabled={isBusy}>
|
||||
<Edit className="h-4 w-4" />
|
||||
수정
|
||||
</Button>
|
||||
)}
|
||||
{!isNewMessage && draft && isEditing && (
|
||||
<Button type="button" variant="outline" onClick={saveTemplate} disabled={isBusy}>
|
||||
<Save className="h-4 w-4" />
|
||||
저장
|
||||
</Button>
|
||||
)}
|
||||
<Button type="button" disabled={!draft || isBusy || isEditing || selectedUsers.length === 0} onClick={send}>
|
||||
<Send className="h-4 w-4" />
|
||||
발송
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
11
src/components/gwcf/EmptyRow.tsx
Normal file
11
src/components/gwcf/EmptyRow.tsx
Normal file
@@ -0,0 +1,11 @@
|
||||
"use client";
|
||||
|
||||
export function EmptyRow({colSpan}: {colSpan: number}) {
|
||||
return (
|
||||
<tr>
|
||||
<td colSpan={colSpan} className="h-28 border p-4 text-center text-sm text-muted-foreground">
|
||||
조회된 데이터가 없습니다.
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
}
|
||||
25
src/components/gwcf/FilePendingButton.tsx
Normal file
25
src/components/gwcf/FilePendingButton.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
"use client";
|
||||
|
||||
import {ReactNode} from "react";
|
||||
import {Download, ImageIcon, Upload} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
|
||||
export function FilePendingButton({
|
||||
children,
|
||||
icon = "download",
|
||||
disabled = true,
|
||||
onClick,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
icon?: "download" | "upload" | "image";
|
||||
disabled?: boolean;
|
||||
onClick?: () => void;
|
||||
}) {
|
||||
const Icon = icon === "upload" ? Upload : icon === "image" ? ImageIcon : Download;
|
||||
return (
|
||||
<Button type="button" size="xs" variant="outline" disabled={disabled} onClick={onClick}>
|
||||
<Icon className="h-3 w-3" />
|
||||
{children}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
37
src/components/gwcf/FilterSelect.tsx
Normal file
37
src/components/gwcf/FilterSelect.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
"use client";
|
||||
|
||||
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
|
||||
import {Code} from "@/types/gwcf";
|
||||
|
||||
export function FilterSelect({
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
placeholder,
|
||||
className,
|
||||
useClear = true,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
options: Code[];
|
||||
placeholder: string;
|
||||
className?: string;
|
||||
useClear?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<KriSingleSelect
|
||||
items={options}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
placeholder={placeholder}
|
||||
getValue={(item) => String(item.codeValue)}
|
||||
getLabel={(item) => item.codeLabel}
|
||||
useClear={useClear}
|
||||
clearLabel="전체"
|
||||
widthClassName={className}
|
||||
spanClassName="text-sm"
|
||||
badgeClassName="text-sm"
|
||||
className="h-9"
|
||||
/>
|
||||
);
|
||||
}
|
||||
34
src/components/gwcf/MultiFilterSelect.tsx
Normal file
34
src/components/gwcf/MultiFilterSelect.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
"use client";
|
||||
|
||||
import {KriMultiSelect} from "@/components/common/KriAutoComplete";
|
||||
import {Code} from "@/types/gwcf";
|
||||
|
||||
export function MultiFilterSelect({
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
placeholder,
|
||||
className,
|
||||
}: {
|
||||
value: string[];
|
||||
onChange: (value: string[]) => void;
|
||||
options: Code[];
|
||||
placeholder: string;
|
||||
className?: string;
|
||||
}) {
|
||||
return (
|
||||
<KriMultiSelect
|
||||
items={options}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
placeholder={placeholder}
|
||||
getValue={(item) => String(item.codeValue)}
|
||||
getLabel={(item) => item.codeLabel}
|
||||
widthClassName={className}
|
||||
maxCount={1}
|
||||
spanClassName="text-sm"
|
||||
badgeClassName="text-sm"
|
||||
className="h-9"
|
||||
/>
|
||||
);
|
||||
}
|
||||
12
src/components/gwcf/PagePanel.tsx
Normal file
12
src/components/gwcf/PagePanel.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import {ReactNode} from "react";
|
||||
import {cn} from "@/lib/utils";
|
||||
|
||||
export function PagePanel({children, className}: {children: ReactNode; className?: string}) {
|
||||
return (
|
||||
<section className={cn("rounded-md border border-gray-300 bg-white p-4 shadow-sm", className)}>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
62
src/components/gwcf/StatusPill.tsx
Normal file
62
src/components/gwcf/StatusPill.tsx
Normal file
@@ -0,0 +1,62 @@
|
||||
"use client";
|
||||
|
||||
import {MouseEvent, ReactNode} from "react";
|
||||
import {Tooltip, TooltipContent, TooltipProvider, TooltipTrigger} from "@/components/ui/tooltip";
|
||||
import {cn} from "@/lib/utils";
|
||||
|
||||
export type StatusPillVariant = "default" | "danger" | "pending" | "inprogress" | "departed" | "arrived" | "done";
|
||||
|
||||
const variantClassName: Record<StatusPillVariant, string> = {
|
||||
default: "border-primary/30 bg-primary/10 text-primary",
|
||||
danger: "gwcf-status-badge--danger",
|
||||
pending: "gwcf-status-badge--pending",
|
||||
inprogress: "gwcf-status-badge--inprogress",
|
||||
departed: "gwcf-status-badge--departed",
|
||||
arrived: "gwcf-status-badge--arrived",
|
||||
done: "gwcf-status-badge--done",
|
||||
};
|
||||
|
||||
export function StatusPill({
|
||||
children,
|
||||
onClick,
|
||||
variant = "default",
|
||||
tooltip,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
onClick?: () => void;
|
||||
variant?: StatusPillVariant;
|
||||
tooltip?: ReactNode;
|
||||
}) {
|
||||
const className = cn(
|
||||
"inline-flex min-w-14 items-center justify-center rounded-full border px-2 py-1 text-xs font-semibold",
|
||||
variant !== "default" && "gwcf-status-badge",
|
||||
variantClassName[variant],
|
||||
onClick && "cursor-pointer hover:opacity-80"
|
||||
);
|
||||
|
||||
const handleClick = (event: MouseEvent<HTMLButtonElement>) => {
|
||||
event.stopPropagation();
|
||||
onClick?.();
|
||||
};
|
||||
|
||||
const pill = onClick ? (
|
||||
<button type="button" className={className} onClick={handleClick}>
|
||||
{children || "-"}
|
||||
</button>
|
||||
) : (
|
||||
<span className={className}>
|
||||
{children || "-"}
|
||||
</span>
|
||||
);
|
||||
|
||||
if (!tooltip) return pill;
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{pill}</TooltipTrigger>
|
||||
<TooltipContent sideOffset={6}>{tooltip}</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import Image from "next/image";
|
||||
import {TOP_MENUS} from "@/config/menu.data";
|
||||
import type {LoginUser} from "@/types/auth";
|
||||
import {SITE_TITLE} from "@/config/gwcf.config";
|
||||
import {useLogoutMutation} from "@/query/auth";
|
||||
import {isFoundationRole, isInternalRole} from "@/lib/gwcf/view";
|
||||
|
||||
interface HeaderProps {
|
||||
userInfo: LoginUser | undefined;
|
||||
@@ -20,6 +22,14 @@ export const Header = ({
|
||||
activeTopId,
|
||||
onNavigate,
|
||||
}: HeaderProps) => {
|
||||
const logoutMutation = useLogoutMutation();
|
||||
const menus = TOP_MENUS.filter((menu) => {
|
||||
if (!isInternalRole(userInfo?.userRole)) {
|
||||
return !["user-list", "assign"].includes(menu.id);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
return (
|
||||
<header className="bg-white border-b border-gray-200 sticky top-0 z-40">
|
||||
<div className="relative flex items-center justify-between px-4 h-16">
|
||||
@@ -52,7 +62,7 @@ export const Header = ({
|
||||
{
|
||||
!isMonitoring && (
|
||||
<nav className="flex items-center gap-1">
|
||||
{TOP_MENUS.map((m) => (
|
||||
{menus.map((m) => (
|
||||
<Button
|
||||
key={m.id}
|
||||
variant={activeTopId === m.id ? "default" : "ghost"}
|
||||
@@ -73,12 +83,13 @@ export const Header = ({
|
||||
<div className="relative z-10 flex items-center gap-4">
|
||||
<span
|
||||
className="content-text-base text-header-color font-bold">
|
||||
{userInfo?.userName || "박준성7957"}
|
||||
{userInfo?.userName || ""}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="gap-2 sm:bg-primary sm:text-primary-foreground sm:hover:bg-primary/90"
|
||||
onClick={() => onNavigate("/logout")}
|
||||
>
|
||||
<LogOut className="w-4 h-4"/>
|
||||
<span className="hidden sm:inline">로그아웃</span>
|
||||
|
||||
@@ -27,7 +27,7 @@ const MainLayout = ({ children }: MainLayoutProps) => {
|
||||
setUserInfo(auth.user);
|
||||
}
|
||||
else{
|
||||
//router.replace("/logout");
|
||||
router.replace("/logout");
|
||||
}
|
||||
}, [auth.user, mounted, router])
|
||||
|
||||
@@ -39,9 +39,9 @@ const MainLayout = ({ children }: MainLayoutProps) => {
|
||||
<div
|
||||
className="bg-gray-50 flex flex-col min-h-screen"
|
||||
>
|
||||
{/* 헤더 - 고정 폰트 크기 */}
|
||||
{/* 헤더 - 고정 높이 */}
|
||||
<Header
|
||||
isMonitoring={isMonitoring}
|
||||
isMonitoring={mounted ? isMonitoring : false}
|
||||
userInfo={userInfo}
|
||||
activeTopId={activeTop.id}
|
||||
onNavigate={movePage}
|
||||
@@ -49,7 +49,7 @@ const MainLayout = ({ children }: MainLayoutProps) => {
|
||||
|
||||
{/* 본문 */}
|
||||
<div className="flex flex-1 min-h-0">
|
||||
{/* 메인 콘텐츠만 가변 폰트 크기 적용 */}
|
||||
{/* 메인 콘텐츠만 가변 높이 적용 */}
|
||||
<main className="flex-1 p-4">
|
||||
{children}
|
||||
</main>
|
||||
@@ -59,3 +59,4 @@ const MainLayout = ({ children }: MainLayoutProps) => {
|
||||
};
|
||||
|
||||
export default MainLayout;
|
||||
|
||||
|
||||
220
src/components/ui/calendar.tsx
Normal file
220
src/components/ui/calendar.tsx
Normal file
@@ -0,0 +1,220 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
} from "lucide-react"
|
||||
import {
|
||||
DayPicker,
|
||||
getDefaultClassNames,
|
||||
type DayButton,
|
||||
} from "react-day-picker"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button, buttonVariants } from "@/components/ui/button"
|
||||
|
||||
function Calendar({
|
||||
className,
|
||||
classNames,
|
||||
showOutsideDays = true,
|
||||
captionLayout = "label",
|
||||
buttonVariant = "ghost",
|
||||
formatters,
|
||||
components,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayPicker> & {
|
||||
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
|
||||
}) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
return (
|
||||
<DayPicker
|
||||
showOutsideDays={showOutsideDays}
|
||||
className={cn(
|
||||
"group/calendar bg-background p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
|
||||
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||
className
|
||||
)}
|
||||
captionLayout={captionLayout}
|
||||
formatters={{
|
||||
formatMonthDropdown: (date) =>
|
||||
date.toLocaleString("default", { month: "short" }),
|
||||
...formatters,
|
||||
}}
|
||||
classNames={{
|
||||
root: cn("w-fit", defaultClassNames.root),
|
||||
months: cn(
|
||||
"relative flex flex-col gap-4 md:flex-row",
|
||||
defaultClassNames.months
|
||||
),
|
||||
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
|
||||
nav: cn(
|
||||
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
|
||||
defaultClassNames.nav
|
||||
),
|
||||
button_previous: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||
defaultClassNames.button_previous
|
||||
),
|
||||
button_next: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||
defaultClassNames.button_next
|
||||
),
|
||||
month_caption: cn(
|
||||
"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
|
||||
defaultClassNames.month_caption
|
||||
),
|
||||
dropdowns: cn(
|
||||
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
|
||||
defaultClassNames.dropdowns
|
||||
),
|
||||
dropdown_root: cn(
|
||||
"relative rounded-md border border-input shadow-xs has-focus:border-ring has-focus:ring-[3px] has-focus:ring-ring/50",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn(
|
||||
"absolute inset-0 bg-popover opacity-0",
|
||||
defaultClassNames.dropdown
|
||||
),
|
||||
caption_label: cn(
|
||||
"font-medium select-none",
|
||||
captionLayout === "label"
|
||||
? "text-sm"
|
||||
: "flex h-8 items-center gap-1 rounded-md pr-1 pl-2 text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
|
||||
defaultClassNames.caption_label
|
||||
),
|
||||
table: "w-full border-collapse",
|
||||
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||
weekday: cn(
|
||||
"flex-1 rounded-md text-[0.8rem] font-normal text-muted-foreground select-none",
|
||||
defaultClassNames.weekday
|
||||
),
|
||||
week: cn("mt-2 flex w-full", defaultClassNames.week),
|
||||
week_number_header: cn(
|
||||
"w-(--cell-size) select-none",
|
||||
defaultClassNames.week_number_header
|
||||
),
|
||||
week_number: cn(
|
||||
"text-[0.8rem] text-muted-foreground select-none",
|
||||
defaultClassNames.week_number
|
||||
),
|
||||
day: cn(
|
||||
"group/day relative aspect-square h-full w-full p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-r-md",
|
||||
props.showWeekNumber
|
||||
? "[&:nth-child(2)[data-selected=true]_button]:rounded-l-md"
|
||||
: "[&:first-child[data-selected=true]_button]:rounded-l-md",
|
||||
defaultClassNames.day
|
||||
),
|
||||
range_start: cn(
|
||||
"rounded-l-md bg-accent",
|
||||
defaultClassNames.range_start
|
||||
),
|
||||
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
|
||||
today: cn(
|
||||
"rounded-md bg-accent text-accent-foreground data-[selected=true]:rounded-none",
|
||||
defaultClassNames.today
|
||||
),
|
||||
outside: cn(
|
||||
"text-muted-foreground aria-selected:text-muted-foreground",
|
||||
defaultClassNames.outside
|
||||
),
|
||||
disabled: cn(
|
||||
"text-muted-foreground opacity-50",
|
||||
defaultClassNames.disabled
|
||||
),
|
||||
hidden: cn("invisible", defaultClassNames.hidden),
|
||||
...classNames,
|
||||
} as React.ComponentProps<typeof DayPicker>["classNames"]}
|
||||
components={{
|
||||
Root: ({ className, rootRef, ...props }) => {
|
||||
return (
|
||||
<div
|
||||
data-slot="calendar"
|
||||
ref={rootRef}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
},
|
||||
Chevron: ({ className, orientation, ...props }) => {
|
||||
if (orientation === "left") {
|
||||
return (
|
||||
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
if (orientation === "right") {
|
||||
return (
|
||||
<ChevronRightIcon
|
||||
className={cn("size-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ChevronDownIcon className={cn("size-4", className)} {...props} />
|
||||
)
|
||||
},
|
||||
DayButton: CalendarDayButton,
|
||||
WeekNumber: ({ children, ...props }) => {
|
||||
return (
|
||||
<td {...props}>
|
||||
<div className="flex size-(--cell-size) items-center justify-center text-center">
|
||||
{children}
|
||||
</div>
|
||||
</td>
|
||||
)
|
||||
},
|
||||
...components,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CalendarDayButton({
|
||||
className,
|
||||
day,
|
||||
modifiers,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DayButton>) {
|
||||
const defaultClassNames = getDefaultClassNames()
|
||||
|
||||
const ref = React.useRef<HTMLButtonElement>(null)
|
||||
React.useEffect(() => {
|
||||
if (modifiers.focused) ref.current?.focus()
|
||||
}, [modifiers.focused])
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
data-day={day.date.toLocaleDateString()}
|
||||
data-selected-single={
|
||||
modifiers.selected &&
|
||||
!modifiers.range_start &&
|
||||
!modifiers.range_end &&
|
||||
!modifiers.range_middle
|
||||
}
|
||||
data-range-start={modifiers.range_start}
|
||||
data-range-end={modifiers.range_end}
|
||||
data-range-middle={modifiers.range_middle}
|
||||
className={cn(
|
||||
"flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-none data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-accent-foreground [&>span]:text-xs [&>span]:opacity-70",
|
||||
defaultClassNames.day,
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Calendar, CalendarDayButton }
|
||||
@@ -70,7 +70,7 @@ function DialogContent({
|
||||
{showCloseButton && (
|
||||
<DialogPrimitive.Close
|
||||
data-slot="dialog-close"
|
||||
className="absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||
className="cursor-pointer absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
|
||||
>
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
|
||||
@@ -11,6 +11,7 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30",
|
||||
"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50",
|
||||
"aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",
|
||||
"bg-white",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -1136,171 +1136,150 @@ function MultiSelectInner(
|
||||
responsiveSettings.compactMode && "gap-0.5"
|
||||
)}
|
||||
>
|
||||
{selectedValues
|
||||
.slice(0, responsiveSettings.maxCount)
|
||||
.map((value) => {
|
||||
const option =
|
||||
getOptionByValue(value) ??
|
||||
({ value, label: value } as MultiSelectOption<any>);
|
||||
const IconComponent = option.icon;
|
||||
const customStyle = option.style;
|
||||
const badgeStyle: React.CSSProperties = {
|
||||
animationDuration: `${animation}s`,
|
||||
...(customStyle?.badgeColor && {
|
||||
backgroundColor: customStyle.badgeColor,
|
||||
}),
|
||||
...(customStyle?.gradient && {
|
||||
background: customStyle.gradient,
|
||||
color: "white",
|
||||
}),
|
||||
};
|
||||
return (
|
||||
<Badge
|
||||
key={value}
|
||||
className={cn(
|
||||
getBadgeAnimationClass(),
|
||||
multiSelectVariants({ variant }),
|
||||
customStyle?.gradient &&
|
||||
"text-white border-transparent",
|
||||
responsiveSettings.compactMode &&
|
||||
"px-1.5 py-0.5",
|
||||
screenSize === "mobile" &&
|
||||
"max-w-[120px] truncate",
|
||||
singleLine &&
|
||||
"flex-shrink-0 whitespace-nowrap",
|
||||
"[&>svg]:pointer-events-auto",
|
||||
badgeClassName
|
||||
)}
|
||||
style={{
|
||||
...badgeStyle,
|
||||
animationDuration: `${
|
||||
animationConfig?.duration || animation
|
||||
}s`,
|
||||
animationDelay: `${
|
||||
animationConfig?.delay || 0
|
||||
}s`,
|
||||
}}
|
||||
>
|
||||
{IconComponent &&
|
||||
!responsiveSettings.hideIcons && (
|
||||
<IconComponent
|
||||
className={cn(
|
||||
"h-4 w-4 mr-2",
|
||||
responsiveSettings.compactMode &&
|
||||
"h-3 w-3 mr-1",
|
||||
customStyle?.iconColor &&
|
||||
"text-current"
|
||||
)}
|
||||
{...(customStyle?.iconColor && {
|
||||
style: { color: customStyle.iconColor },
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
<span
|
||||
{
|
||||
selectedValues.length <= responsiveSettings.maxCount?
|
||||
selectedValues
|
||||
.slice(0, responsiveSettings.maxCount)
|
||||
.map((value) => {
|
||||
const option =
|
||||
getOptionByValue(value) ??
|
||||
({ value, label: value } as MultiSelectOption<any>);
|
||||
const IconComponent = option.icon;
|
||||
const customStyle = option.style;
|
||||
const badgeStyle: React.CSSProperties = {
|
||||
animationDuration: `${animation}s`,
|
||||
...(customStyle?.badgeColor && {
|
||||
backgroundColor: customStyle.badgeColor,
|
||||
}),
|
||||
...(customStyle?.gradient && {
|
||||
background: customStyle.gradient,
|
||||
color: "white",
|
||||
}),
|
||||
};
|
||||
return (
|
||||
<Badge
|
||||
key={value}
|
||||
className={cn(
|
||||
screenSize === "mobile" && "truncate"
|
||||
getBadgeAnimationClass(),
|
||||
multiSelectVariants({ variant }),
|
||||
customStyle?.gradient &&
|
||||
"text-white border-transparent",
|
||||
responsiveSettings.compactMode &&
|
||||
"px-1.5 py-0.5",
|
||||
screenSize === "mobile" &&
|
||||
"max-w-[120px] truncate",
|
||||
singleLine &&
|
||||
"flex-shrink-0 whitespace-nowrap",
|
||||
"[&>svg]:pointer-events-auto",
|
||||
badgeClassName
|
||||
)}
|
||||
style={{
|
||||
...badgeStyle,
|
||||
animationDuration: `${
|
||||
animationConfig?.duration || animation
|
||||
}s`,
|
||||
animationDelay: `${
|
||||
animationConfig?.delay || 0
|
||||
}s`,
|
||||
}}
|
||||
>
|
||||
{IconComponent &&
|
||||
!responsiveSettings.hideIcons && (
|
||||
<IconComponent
|
||||
className={cn(
|
||||
"h-4 w-4 mr-2",
|
||||
responsiveSettings.compactMode &&
|
||||
"h-3 w-3 mr-1",
|
||||
customStyle?.iconColor &&
|
||||
"text-current"
|
||||
)}
|
||||
{...(customStyle?.iconColor && {
|
||||
style: { color: customStyle.iconColor },
|
||||
})}
|
||||
/>
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
screenSize === "mobile" && "truncate"
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</span>
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
toggleOption(value);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (
|
||||
event.key === "Enter" ||
|
||||
event.key === " "
|
||||
) {
|
||||
event.preventDefault();
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
toggleOption(value);
|
||||
}
|
||||
}}
|
||||
aria-label={`Remove ${option.label} from selection`}
|
||||
className="ml-2 h-4.5 w-4.5 cursor-pointer hover:bg-white/20 rounded-sm p-0.5 -m-0.5 focus:outline-none focus:ring-1 focus:ring-white/50"
|
||||
>
|
||||
{!preventDeselect &&
|
||||
<XCircle
|
||||
className={cn(
|
||||
"h-3 w-3",
|
||||
responsiveSettings.compactMode &&
|
||||
"h-2.5 w-2.5"
|
||||
)}
|
||||
/>
|
||||
}
|
||||
</div>
|
||||
</Badge>
|
||||
);
|
||||
})
|
||||
.filter(Boolean)}
|
||||
{selectedValues.length >
|
||||
responsiveSettings.maxCount && (
|
||||
<Badge
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (
|
||||
event.key === "Enter" ||
|
||||
event.key === " "
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
toggleOption(value);
|
||||
}
|
||||
}}
|
||||
aria-label={`Remove ${option.label} from selection`}
|
||||
className="ml-2 h-4.5 w-4.5 cursor-pointer hover:bg-white/20 rounded-sm p-0.5 -m-0.5 focus:outline-none focus:ring-1 focus:ring-white/50"
|
||||
>
|
||||
{!preventDeselect &&
|
||||
<XCircle
|
||||
className={cn(
|
||||
"h-3 w-3",
|
||||
responsiveSettings.compactMode &&
|
||||
"h-2.5 w-2.5"
|
||||
)}
|
||||
/>
|
||||
}
|
||||
</div>
|
||||
</Badge>
|
||||
);
|
||||
})
|
||||
.filter(Boolean)
|
||||
:
|
||||
<Badge
|
||||
className={cn(
|
||||
"bg-transparent text-foreground border-foreground/1 hover:bg-transparent",
|
||||
getBadgeAnimationClass(),
|
||||
multiSelectVariants({ variant }),
|
||||
responsiveSettings.compactMode &&
|
||||
"px-1.5 py-0.5",
|
||||
singleLine &&
|
||||
"flex-shrink-0 whitespace-nowrap",
|
||||
"[&>svg]:pointer-events-auto",
|
||||
badgeClassName
|
||||
)}
|
||||
style={{
|
||||
animationDuration: `${
|
||||
animationConfig?.duration || animation
|
||||
}s`,
|
||||
animationDelay: `${
|
||||
animationConfig?.delay || 0
|
||||
}s`,
|
||||
}}
|
||||
>
|
||||
{`+ ${
|
||||
selectedValues.length
|
||||
}`}
|
||||
<XCircle
|
||||
className={cn(
|
||||
"bg-transparent text-foreground border-foreground/1 hover:bg-transparent",
|
||||
getBadgeAnimationClass(),
|
||||
multiSelectVariants({ variant }),
|
||||
"ml-2 h-4 w-4 mt-0.5 cursor-pointer",
|
||||
responsiveSettings.compactMode &&
|
||||
"px-1.5 py-0.5",
|
||||
singleLine &&
|
||||
"flex-shrink-0 whitespace-nowrap",
|
||||
"[&>svg]:pointer-events-auto",
|
||||
badgeClassName
|
||||
"ml-1 h-3 w-3"
|
||||
)}
|
||||
style={{
|
||||
animationDuration: `${
|
||||
animationConfig?.duration || animation
|
||||
}s`,
|
||||
animationDelay: `${
|
||||
animationConfig?.delay || 0
|
||||
}s`,
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
handleClear();
|
||||
}}
|
||||
>
|
||||
{`+${
|
||||
selectedValues.length -
|
||||
responsiveSettings.maxCount
|
||||
} more`}
|
||||
<XCircle
|
||||
className={cn(
|
||||
"ml-2 h-4 w-4 mt-0.5 cursor-pointer",
|
||||
responsiveSettings.compactMode &&
|
||||
"ml-1 h-3 w-3"
|
||||
)}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
clearExtraOptions();
|
||||
}}
|
||||
/>
|
||||
</Badge>
|
||||
)}
|
||||
/>
|
||||
</Badge>
|
||||
}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between">
|
||||
{!preventDeselect &&
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
handleClear();
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handleClear();
|
||||
}
|
||||
}}
|
||||
aria-label={`Clear all ${selectedValues.length} selected options`}
|
||||
className="flex items-center justify-center h-4 w-4 mx-2 cursor-pointer text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 rounded-sm"
|
||||
>
|
||||
<XIcon className="h-4 w-4" />
|
||||
</div>
|
||||
}
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="flex min-h-6 h-full"
|
||||
|
||||
57
src/components/ui/tooltip.tsx
Normal file
57
src/components/ui/tooltip.tsx
Normal file
@@ -0,0 +1,57 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Tooltip as TooltipPrimitive } from "radix-ui"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
|
||||
@@ -1,13 +1,41 @@
|
||||
export const SITE_TITLE = "강원 문화예술 지원 사업 모니터링 및 종합평가";
|
||||
export const SITE_TITLE = "강원문화재단 문화예술지원사업 모니터링 및 종합평가";
|
||||
|
||||
export const TOP_MENU_KEY_MAP: Record<string, string> = {
|
||||
"performance-list":"사업정보",
|
||||
"user-list":"계정관리",
|
||||
}
|
||||
"performance-list": "사업정보",
|
||||
"user-list": "계정관리",
|
||||
"assign": "모니터링 배정",
|
||||
};
|
||||
|
||||
export const TOP_MENU_PATH_MAP: Record<string, string> = {
|
||||
"performance-list":"/performance",
|
||||
"user-list":"/user",
|
||||
}
|
||||
"performance-list": "/performance",
|
||||
"user-list": "/user",
|
||||
"assign": "/assign",
|
||||
};
|
||||
|
||||
export const MONITORING_USER_ROLE = 9003;
|
||||
export const MONITORING_USER_ROLE = 9003;
|
||||
|
||||
export const WRITTEN_REVIEW_PKEY = "2605013_ZZ";
|
||||
|
||||
export const WRITTEN_REVIEW_LINK_URL = {
|
||||
incomplete: `https://kon.kric.com/project/${WRITTEN_REVIEW_PKEY}/INDEX.asp`,
|
||||
complete: `https://kon.kric.com/survey_to_pdf/survey_layout_total.asp?AD=FALSE&PRJCODE=${WRITTEN_REVIEW_PKEY}`,
|
||||
} as const;
|
||||
|
||||
export const buildWrittenReviewLink = ({
|
||||
performanceId,
|
||||
userId,
|
||||
complete,
|
||||
}: {
|
||||
performanceId: number;
|
||||
userId: string;
|
||||
complete: boolean;
|
||||
}) => {
|
||||
alert("준비 중입니다.");
|
||||
return "";
|
||||
|
||||
const baseUrl = complete ? WRITTEN_REVIEW_LINK_URL.complete : WRITTEN_REVIEW_LINK_URL.incomplete;
|
||||
const url = new URL(baseUrl, typeof window === "undefined" ? "http://localhost" : window.location.origin);
|
||||
url.searchParams.set("SID", String(performanceId));
|
||||
url.searchParams.set("UID", userId);
|
||||
return /^https?:\/\//i.test(baseUrl) ? url.toString() : url.pathname + url.search;
|
||||
};
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback } from "react";
|
||||
import { useAtom } from "jotai";
|
||||
import { layoutSelectedMenuAtom } from "@/store/jotai/layout";
|
||||
|
||||
export const useLayoutSelectedMenu = () => {
|
||||
const [selectedMenusByTopMenu, setSelectedMenusByTopMenu] = useAtom(layoutSelectedMenuAtom);
|
||||
|
||||
const selectMenu = useCallback(
|
||||
(topMenuId: string, menuId: string) => {
|
||||
setSelectedMenusByTopMenu((prev) => ({
|
||||
...prev,
|
||||
[topMenuId]: menuId,
|
||||
}));
|
||||
},
|
||||
[setSelectedMenusByTopMenu],
|
||||
);
|
||||
|
||||
return {
|
||||
selectedMenusByTopMenu,
|
||||
selectMenu,
|
||||
};
|
||||
};
|
||||
@@ -7,4 +7,5 @@ const required = (name: string) => {
|
||||
export const serverEnv = {
|
||||
ENV: required("ENV"),
|
||||
API_BACK_SERVER: required("API_BACK_SERVER"),
|
||||
NOTI_HUB_SERVER: required("NOTI_HUB_SERVER"),
|
||||
};
|
||||
4
src/lib/gwcf/date.ts
Normal file
4
src/lib/gwcf/date.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
export const toLocalDateString = (date = new Date()) => {
|
||||
const pad = (value: number) => String(value).padStart(2, "0");
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
||||
};
|
||||
79
src/lib/gwcf/file.ts
Normal file
79
src/lib/gwcf/file.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import {downloadFile} from "@/lib/utils";
|
||||
import {buildWrittenReviewLink} from "@/config/gwcf.config";
|
||||
|
||||
const REVIEW_TIMESTAMP_PREFIX = /^\d{4}-\d{2}-\d{2}_\d{6}_/;
|
||||
|
||||
export const removeTimestampPrefix = (fileName?: string) =>
|
||||
fileName?.replace(REVIEW_TIMESTAMP_PREFIX, "");
|
||||
|
||||
export const downloadBlob = (
|
||||
buffer: ArrayBuffer,
|
||||
fileName: string,
|
||||
type = "application/octet-stream"
|
||||
) => {
|
||||
downloadFile(new Blob([buffer], {type}), fileName);
|
||||
};
|
||||
|
||||
export const downloadExcelBuffer = (buffer: ArrayBuffer, fileName: string) => {
|
||||
downloadBlob(buffer, fileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
|
||||
};
|
||||
|
||||
export const downloadFromUrl = (url: string) => {
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = "";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
};
|
||||
|
||||
export const getReviewOriginalDownloadName = (
|
||||
performanceId: number,
|
||||
reviewType: number,
|
||||
uploadFileName?: string
|
||||
) => removeTimestampPrefix(uploadFileName) || `review-original-${performanceId}-${reviewType}`;
|
||||
|
||||
export const getReviewPdfDownloadName = (
|
||||
performanceId: number,
|
||||
reviewType: number,
|
||||
pdfFileName?: string
|
||||
) => removeTimestampPrefix(pdfFileName) || `review-pdf-${performanceId}-${reviewType}.pdf`;
|
||||
|
||||
export const getEvidenceZipDownloadName = (performanceId: number, userId: string) =>
|
||||
`도착 증빙_${performanceId}_${userId}.zip`;
|
||||
|
||||
export const buildReviewPdfPreviewUrl = (
|
||||
performanceId: number,
|
||||
reviewType: number,
|
||||
userId: string,
|
||||
title?: string
|
||||
) => {
|
||||
const src = `/api/review/pdf/${performanceId}/${reviewType}/${encodeURIComponent(userId)}?disposition=inline`;
|
||||
return `/file-preview?type=pdf&src=${encodeURIComponent(src)}&title=${encodeURIComponent(title || getReviewPdfDownloadName(performanceId, reviewType))}`;
|
||||
};
|
||||
|
||||
export const buildEvidenceImageSrc = (
|
||||
performanceId: number,
|
||||
userId: string,
|
||||
fileName: string
|
||||
) => `/api/file/visit/${performanceId}/${encodeURIComponent(userId)}/${encodeURIComponent(fileName)}`;
|
||||
|
||||
export const buildImagePreviewUrl = (title: string, images: string[]) =>
|
||||
`/file-preview?type=image&title=${encodeURIComponent(title)}&images=${encodeURIComponent(JSON.stringify(images))}`;
|
||||
|
||||
export const openPreviewWindow = (url: string) => {
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
};
|
||||
|
||||
export const openWrittenReviewWindow = (
|
||||
performanceId: number,
|
||||
userId: string | undefined,
|
||||
complete = false
|
||||
) => {
|
||||
if (!userId) return;
|
||||
const url = buildWrittenReviewLink({performanceId, userId, complete});
|
||||
|
||||
if(url){
|
||||
window.open(url, "_blank", "noopener,noreferrer");
|
||||
}
|
||||
};
|
||||
35
src/lib/gwcf/notification.ts
Normal file
35
src/lib/gwcf/notification.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import {PerformanceFull, UserCompact} from "@/types/gwcf";
|
||||
|
||||
export const toNotificationParamValue = (value: unknown) => value == null ? "" : String(value);
|
||||
|
||||
export const buildUserMsgParam = (user: UserCompact): Record<string, string> => ({
|
||||
...Object.fromEntries(
|
||||
Object.entries(user.userDetail ?? {}).map(([key, value]) => [key, toNotificationParamValue(value)])
|
||||
),
|
||||
userId: toNotificationParamValue(user.userId),
|
||||
userCmpn: toNotificationParamValue(user.userCmpn),
|
||||
userTeam: toNotificationParamValue(user.userTeam),
|
||||
userName: toNotificationParamValue(user.userName),
|
||||
userRole: toNotificationParamValue(user.userRole),
|
||||
});
|
||||
|
||||
export const buildPerformanceSmsParams = (performance: PerformanceFull): Record<string, string> => ({
|
||||
businessType: toNotificationParamValue(performance.businessType),
|
||||
performanceGenre: toNotificationParamValue(performance.performanceGenre),
|
||||
performanceArea: toNotificationParamValue(performance.performanceArea),
|
||||
artistName: toNotificationParamValue(performance.artistName),
|
||||
performanceName: toNotificationParamValue(performance.performanceName),
|
||||
performanceStartMonth: toNotificationParamValue(performance.performanceStartMonth),
|
||||
performanceDtInfo: toNotificationParamValue(performance.performanceDtInfo),
|
||||
performanceTimeInfo: toNotificationParamValue(performance.performanceTimeInfo),
|
||||
ticketReservationStatus: toNotificationParamValue(performance.ticketReservationStatus),
|
||||
ticketReservationMemo: toNotificationParamValue(performance.ticketReservationMemo),
|
||||
performanceMemo: toNotificationParamValue(performance.performanceMemo),
|
||||
...Object.fromEntries(
|
||||
Object.entries(performance.performanceDetail ?? {}).map(([key, value]) => [key, toNotificationParamValue(value)])
|
||||
),
|
||||
...Object.fromEntries(
|
||||
Object.entries(performance.performanceMonitoringSchedule ?? {}).map(([key, value]) => [key, toNotificationParamValue(value)])
|
||||
),
|
||||
performanceId: toNotificationParamValue(performance.id),
|
||||
});
|
||||
317
src/lib/gwcf/performance-status.ts
Normal file
317
src/lib/gwcf/performance-status.ts
Normal file
@@ -0,0 +1,317 @@
|
||||
import {Code, PerformanceAssign, PerformanceFull, PerformanceMonitoringVisit, PerformanceReview, UserCompact} from "@/types/gwcf";
|
||||
import type {StatusPillVariant} from "@/components/gwcf/StatusPill";
|
||||
|
||||
export const LOCAL_GOVERNMENT_REVIEW_TYPE = 3;
|
||||
export const MONITORING_ASSIGN_TYPE = 1;
|
||||
export const WRITTEN_REVIEW_ASSIGN_TYPE = 2;
|
||||
export const MONITORING_DEPARTURE_STATUS = 2;
|
||||
export const MONITORING_ARRIVAL_STATUS = 3;
|
||||
|
||||
export type MonitoringVisitTimeline = {
|
||||
departure?: PerformanceMonitoringVisit;
|
||||
arrival?: PerformanceMonitoringVisit;
|
||||
};
|
||||
|
||||
export type MonitoringSlot = {
|
||||
assign?: PerformanceAssign;
|
||||
user?: UserCompact;
|
||||
visit?: PerformanceMonitoringVisit[];
|
||||
timeline: MonitoringVisitTimeline;
|
||||
};
|
||||
|
||||
export type ReviewDisplayRow = {
|
||||
userId: string;
|
||||
assign?: PerformanceAssign;
|
||||
review?: PerformanceReview;
|
||||
};
|
||||
|
||||
export type MonitoringDisplayRow = {
|
||||
index: 0 | 1;
|
||||
reviewType: number;
|
||||
slot: MonitoringSlot;
|
||||
userId?: string;
|
||||
evidenceUserId?: string;
|
||||
review?: PerformanceReview;
|
||||
};
|
||||
|
||||
export type StatusDisplay = {
|
||||
label: string;
|
||||
variant: StatusPillVariant;
|
||||
};
|
||||
|
||||
export const STATUS_FILTER = {
|
||||
UNASSIGNED: "-1001",
|
||||
INCOMPLETE: "-1002",
|
||||
PENDING: "-1003",
|
||||
IN_PROGRESS: "-1004",
|
||||
DEPARTED: "-1005",
|
||||
ARRIVED: "-1006",
|
||||
DONE: "-1007",
|
||||
} as const;
|
||||
|
||||
export const makeStatusOption = (value: string, label: string): Code => ({
|
||||
codeGroup: "status_filter",
|
||||
codeValue: Number(value),
|
||||
codeGroupLabel: "상태",
|
||||
codeLabel: label,
|
||||
memo: "",
|
||||
});
|
||||
|
||||
export const statusFilterOptions = {
|
||||
incomplete: makeStatusOption(STATUS_FILTER.INCOMPLETE, "미완료"),
|
||||
pending: makeStatusOption(STATUS_FILTER.PENDING, "미진행"),
|
||||
inProgress: makeStatusOption(STATUS_FILTER.IN_PROGRESS, "진행중"),
|
||||
departed: makeStatusOption(STATUS_FILTER.DEPARTED, "출발"),
|
||||
arrived: makeStatusOption(STATUS_FILTER.ARRIVED, "도착"),
|
||||
done: makeStatusOption(STATUS_FILTER.DONE, "완료"),
|
||||
};
|
||||
|
||||
export const normalizeStatusLabel = (label?: string) => label?.replace(/\s/g, "") ?? "";
|
||||
export const labelHasInProgress = (label?: string) => normalizeStatusLabel(label).includes("진행");
|
||||
export const labelHasDeparted = (label?: string) => normalizeStatusLabel(label).includes("출발");
|
||||
export const labelHasArrived = (label?: string) => normalizeStatusLabel(label).includes("도착");
|
||||
export const labelHasComplete = (label?: string) => normalizeStatusLabel(label).includes("완료");
|
||||
|
||||
const sortMonitoringVisits = (visits: PerformanceMonitoringVisit[]) => {
|
||||
return [...visits].sort((a, b) => {
|
||||
if (b.monitoringVisitStatus !== a.monitoringVisitStatus) {
|
||||
return b.monitoringVisitStatus - a.monitoringVisitStatus;
|
||||
}
|
||||
return new Date(b.regDt ?? 0).getTime() - new Date(a.regDt ?? 0).getTime();
|
||||
});
|
||||
};
|
||||
|
||||
const getMonitoringVisits = (visits: PerformanceMonitoringVisit[], userId?: string) => {
|
||||
const matchedVisits = userId ? visits.filter((item) => item.regUser === userId) : visits;
|
||||
const candidates = matchedVisits.length > 0 ? matchedVisits : visits;
|
||||
return sortMonitoringVisits(candidates);
|
||||
};
|
||||
|
||||
const getMonitoringTimeline = (visits: PerformanceMonitoringVisit[]): MonitoringVisitTimeline => ({
|
||||
departure: visits.find((visit) => visit.monitoringVisitStatus === MONITORING_DEPARTURE_STATUS),
|
||||
arrival: visits.find((visit) => visit.monitoringVisitStatus === MONITORING_ARRIVAL_STATUS),
|
||||
});
|
||||
|
||||
export const getMonitoringSlots = (performance: Partial<PerformanceFull>): [MonitoringSlot, MonitoringSlot] => {
|
||||
const confirmedAssigns = (performance.performanceAssignList ?? [])
|
||||
.filter((assign) => assign.assignType === MONITORING_ASSIGN_TYPE && assign.assignConfirm)
|
||||
.sort((a, b) => a.assignOrder - b.assignOrder || a.id - b.id);
|
||||
|
||||
const visits = performance.performanceMonitoringVisitMap ?? {};
|
||||
|
||||
return [0, 1].map((index) => {
|
||||
const assign = confirmedAssigns[index];
|
||||
const userVisits = assign ? visits[assign.assignUser] ?? [] : [];
|
||||
const sortedVisits = assign ? getMonitoringVisits(userVisits, assign.assignUser) : [];
|
||||
|
||||
return {assign, visit: sortedVisits, timeline: getMonitoringTimeline(sortedVisits)};
|
||||
}) as [MonitoringSlot, MonitoringSlot];
|
||||
};
|
||||
|
||||
export const getReviewByType = (performance: Partial<PerformanceFull>, reviewType: number) => {
|
||||
const map = performance.performanceReviewMap ?? {};
|
||||
for (const [userId, reviews] of Object.entries(map)) {
|
||||
const review = reviews.find((item) => item.reviewType === reviewType);
|
||||
if (review) return {userId, review};
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const getReviewRows = (performance: Partial<PerformanceFull>) => {
|
||||
return Object.entries(performance.performanceReviewMap ?? {}).flatMap(([userId, reviews]) =>
|
||||
reviews.map((review) => ({userId, review}))
|
||||
);
|
||||
};
|
||||
|
||||
export const getMonitoringReviewByIndex = (
|
||||
performance: Partial<PerformanceFull>,
|
||||
index: 0 | 1,
|
||||
slot?: MonitoringSlot
|
||||
) => {
|
||||
const assignedUserId = slot?.assign?.assignUser;
|
||||
const assignedReview = assignedUserId
|
||||
? (performance.performanceReviewMap?.[assignedUserId] ?? []).find((review) => review.reviewType === MONITORING_ASSIGN_TYPE)
|
||||
: undefined;
|
||||
|
||||
return assignedReview && assignedUserId
|
||||
? {userId: assignedUserId, review: assignedReview}
|
||||
: undefined;
|
||||
};
|
||||
|
||||
export const getMonitoringDisplayRow = (
|
||||
performance: Partial<PerformanceFull>,
|
||||
index: 0 | 1
|
||||
): MonitoringDisplayRow => {
|
||||
const slot = getMonitoringSlots(performance)[index];
|
||||
const reviewRow = getMonitoringReviewByIndex(performance, index, slot);
|
||||
const visit = slot.visit?.[0];
|
||||
|
||||
return {
|
||||
index,
|
||||
reviewType: MONITORING_ASSIGN_TYPE,
|
||||
slot,
|
||||
userId: slot.assign?.assignUser,
|
||||
evidenceUserId: slot.timeline.arrival?.regUser || visit?.regUser || slot.assign?.assignUser,
|
||||
review: reviewRow?.review,
|
||||
};
|
||||
};
|
||||
|
||||
export const getWrittenReviewRows = (performance: Partial<PerformanceFull>): ReviewDisplayRow[] => {
|
||||
const writtenAssigns = (performance.performanceAssignList ?? [])
|
||||
.filter((assign) => assign.assignType === WRITTEN_REVIEW_ASSIGN_TYPE);
|
||||
const assignedUserIds = writtenAssigns.map((assign) => assign.assignUser);
|
||||
|
||||
const reviewRows = getReviewRows(performance).filter(({userId, review}) =>
|
||||
review.reviewType === WRITTEN_REVIEW_ASSIGN_TYPE &&
|
||||
assignedUserIds.includes(userId)
|
||||
);
|
||||
|
||||
const reviewByUser = new Map(reviewRows.map((row) => [row.userId, row.review]));
|
||||
const userIds = Array.from(new Set([...assignedUserIds, ...reviewRows.map((row) => row.userId)]));
|
||||
|
||||
return userIds.map((userId) => ({
|
||||
userId,
|
||||
assign: writtenAssigns.find((assign) => assign.assignUser === userId),
|
||||
review: reviewByUser.get(userId),
|
||||
}));
|
||||
};
|
||||
|
||||
export const formatDateTime = (date: Date) => {
|
||||
if (Number.isNaN(date.getTime())) return "-";
|
||||
const pad = (value: number) => String(value).padStart(2, "0");
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
||||
};
|
||||
|
||||
export const getMonitoringRecordedAt = (visit?: PerformanceMonitoringVisit) => {
|
||||
if (visit?.regDt) return formatDateTime(new Date(visit.regDt));
|
||||
|
||||
const timestamp = visit?.gpsRaw?.timestamp;
|
||||
if (typeof timestamp === "number") return formatDateTime(new Date(timestamp));
|
||||
if (typeof timestamp === "string") return formatDateTime(new Date(timestamp));
|
||||
return "-";
|
||||
};
|
||||
|
||||
export const getMonitoringRecordedUser = (visit?: PerformanceMonitoringVisit) => {
|
||||
return visit?.regUser || "-";
|
||||
};
|
||||
|
||||
export const isReviewComplete = (review?: PerformanceReview) => {
|
||||
return review?.reviewStatus === 10;
|
||||
};
|
||||
|
||||
export const getReviewFilterValue = (
|
||||
review: PerformanceReview | undefined,
|
||||
label: string | undefined,
|
||||
{
|
||||
isWrittenReviewer = false,
|
||||
allowInProgress = false,
|
||||
assigned = Boolean(review),
|
||||
alwaysAssigned = false,
|
||||
}: {
|
||||
isWrittenReviewer?: boolean;
|
||||
allowInProgress?: boolean;
|
||||
assigned?: boolean;
|
||||
alwaysAssigned?: boolean;
|
||||
} = {}
|
||||
) => {
|
||||
if (isWrittenReviewer) {
|
||||
return isReviewComplete(review)
|
||||
? STATUS_FILTER.DONE
|
||||
: STATUS_FILTER.INCOMPLETE;
|
||||
}
|
||||
|
||||
if (!alwaysAssigned && !assigned && !review) return STATUS_FILTER.UNASSIGNED;
|
||||
if (isReviewComplete(review)) return STATUS_FILTER.DONE;
|
||||
if (allowInProgress && labelHasInProgress(label)) return STATUS_FILTER.IN_PROGRESS;
|
||||
return STATUS_FILTER.PENDING;
|
||||
};
|
||||
|
||||
export const getReviewStatusDisplay = (
|
||||
label?: string,
|
||||
review?: PerformanceReview,
|
||||
assigned = Boolean(review)
|
||||
): StatusDisplay => {
|
||||
if (!assigned) return {label: "미배치", variant: "danger"};
|
||||
|
||||
const normalized = normalizeStatusLabel(label);
|
||||
if (normalized.includes("완료")) return {label: label || "완료", variant: "done"};
|
||||
if (normalized.includes("진행")) return {label: label || "진행중", variant: "inprogress"};
|
||||
|
||||
return {label: label || "미진행", variant: "pending"};
|
||||
};
|
||||
|
||||
export const getReviewRecordedAt = (review?: PerformanceReview) => {
|
||||
return review?.reviewDt ? formatDateTime(new Date(review.reviewDt)) : "-";
|
||||
}
|
||||
|
||||
export const getCompleteRecordedAt = (review?: PerformanceReview) => {
|
||||
return isReviewComplete(review) ? getReviewRecordedAt(review) : "-";
|
||||
}
|
||||
|
||||
export const getWrittenReviewerSimpleReviewStatusDisplay = (
|
||||
review?: PerformanceReview,
|
||||
allowInProgress = false,
|
||||
label?: string
|
||||
): StatusDisplay => {
|
||||
if (isReviewComplete(review)) return {label: "완료", variant: "done"};
|
||||
|
||||
if (allowInProgress && normalizeStatusLabel(label).includes("진행")) {
|
||||
return {label: "진행중", variant: "inprogress"};
|
||||
}
|
||||
|
||||
return {label: "미완료", variant: "pending"};
|
||||
};
|
||||
|
||||
export const getMonitoringFilterValue = (
|
||||
row: MonitoringDisplayRow,
|
||||
visitLabel: string | undefined,
|
||||
reviewLabel: string | undefined,
|
||||
isWrittenReviewer = false
|
||||
) => {
|
||||
if (isWrittenReviewer) {
|
||||
return isReviewComplete(row.review)
|
||||
? STATUS_FILTER.DONE
|
||||
: STATUS_FILTER.INCOMPLETE;
|
||||
}
|
||||
|
||||
if (isReviewComplete(row.review)) return STATUS_FILTER.DONE;
|
||||
if (!row.slot.assign && !row.slot.visit?.length) return STATUS_FILTER.UNASSIGNED;
|
||||
if (!row.slot.visit?.length) return STATUS_FILTER.PENDING;
|
||||
if (labelHasDeparted(visitLabel)) return STATUS_FILTER.DEPARTED;
|
||||
if (labelHasArrived(visitLabel)) return STATUS_FILTER.ARRIVED;
|
||||
return STATUS_FILTER.PENDING;
|
||||
};
|
||||
|
||||
export const getMonitoringStatusDisplay = (label?: string, slot?: MonitoringSlot): StatusDisplay => {
|
||||
if (!slot?.assign && !slot?.visit?.length) return {label: "미배치", variant: "danger"};
|
||||
if (!slot?.visit?.length) return {label: "미진행", variant: "pending"};
|
||||
|
||||
const normalized = normalizeStatusLabel(label);
|
||||
if (normalized.includes("완료")) return {label: label || "완료", variant: "done"};
|
||||
if (normalized.includes("도착")) return {label: label || "도착", variant: "arrived"};
|
||||
if (normalized.includes("출발")) return {label: label || "출발", variant: "departed"};
|
||||
|
||||
return {label: label || "미진행", variant: "pending"};
|
||||
};
|
||||
|
||||
export const getMonitoringDisplayStatus = (
|
||||
row: MonitoringDisplayRow,
|
||||
visitLabel?: string,
|
||||
reviewLabel?: string,
|
||||
isWrittenReviewer = false
|
||||
): StatusDisplay => {
|
||||
if (isWrittenReviewer) {
|
||||
return isReviewComplete(row.review)
|
||||
? {label: "완료", variant: "done"}
|
||||
: {label: "미완료", variant: "pending"};
|
||||
}
|
||||
|
||||
if (isReviewComplete(row.review)) return {label: reviewLabel || "완료", variant: "done"};
|
||||
return getMonitoringStatusDisplay(visitLabel, row.slot);
|
||||
};
|
||||
|
||||
export const getAssignStatusDisplay = (confirmed: boolean): StatusDisplay => {
|
||||
return confirmed
|
||||
? {label: "확정", variant: "done"}
|
||||
: {label: "요청", variant: "inprogress"};
|
||||
};
|
||||
119
src/lib/gwcf/view.ts
Normal file
119
src/lib/gwcf/view.ts
Normal file
@@ -0,0 +1,119 @@
|
||||
import {Code, PerformanceCompact, PerformanceFull, UserFull} from "@/types/gwcf";
|
||||
import {CodeGroup} from "@/query/code";
|
||||
|
||||
export const ROLE = {
|
||||
ADMIN: 1001,
|
||||
RESEARCHER: 1002,
|
||||
FIELD_INSPECTOR: 1003,
|
||||
CONTACT_AGENT: 1004,
|
||||
FOUNDATION: 2011,
|
||||
WRITTEN_REVIEWER: 2021,
|
||||
MONITORING: 9003,
|
||||
} as const;
|
||||
|
||||
export const getRoleGroup = (role?: number | null) => {
|
||||
if (!role) return 0;
|
||||
return Math.floor(role / 1000) * 1000;
|
||||
};
|
||||
|
||||
export const isInternalRole = (role?: number | null) => getRoleGroup(role) === 1000;
|
||||
export const isExternalRole = (role?: number | null) => getRoleGroup(role) === 2000;
|
||||
export const isMonitoringRole = (role?: number | null) => getRoleGroup(role) === 9000;
|
||||
export const isFoundationRole = (role?: number | null) => role === ROLE.FOUNDATION;
|
||||
export const isWrittenReviewerRole = (role?: number | null) => role === ROLE.WRITTEN_REVIEWER;
|
||||
|
||||
export const getCodeLabel = (
|
||||
codes: Partial<Record<CodeGroup, Code[]>>,
|
||||
group: CodeGroup,
|
||||
value: number | string | undefined | null
|
||||
) => {
|
||||
if (value === undefined || value === null || value === "") return "";
|
||||
const numericValue = Number(value);
|
||||
const found = codes[group]?.find((code) => code.codeValue === numericValue);
|
||||
return found?.codeLabel ?? String(value);
|
||||
};
|
||||
|
||||
export const getDetailValue = (
|
||||
detail: Record<string, string> | undefined,
|
||||
keys: string[],
|
||||
fallback = ""
|
||||
) => {
|
||||
if (!detail) return fallback;
|
||||
for (const key of keys) {
|
||||
const value = detail[key];
|
||||
if (value !== undefined && value !== "") return value;
|
||||
}
|
||||
return fallback;
|
||||
};
|
||||
|
||||
export const includesText = (value: unknown, keyword: string) => {
|
||||
if (!keyword) return true;
|
||||
return String(value ?? "").toLowerCase().includes(keyword.toLowerCase());
|
||||
};
|
||||
|
||||
export const filterPerformance = (
|
||||
item: PerformanceCompact | PerformanceFull,
|
||||
filters: {
|
||||
businessType?: string | string[];
|
||||
genre?: string | string[];
|
||||
area?: string | string[];
|
||||
monitoringDate?: string;
|
||||
keyword?: string;
|
||||
}
|
||||
) => {
|
||||
const keyword = filters.keyword?.trim() ?? "";
|
||||
const schedule = item.performanceMonitoringSchedule;
|
||||
const matches = (filter: string | string[] | undefined, value: number | string) => {
|
||||
if (!filter || filter.length === 0) return true;
|
||||
const values = Array.isArray(filter) ? filter : [filter];
|
||||
return values.includes(String(value));
|
||||
};
|
||||
|
||||
return (
|
||||
matches(filters.businessType, item.businessType) &&
|
||||
matches(filters.genre, item.performanceGenre) &&
|
||||
matches(filters.area, item.performanceArea) &&
|
||||
(!filters.monitoringDate || schedule?.monitoringDate === filters.monitoringDate) &&
|
||||
(
|
||||
includesText(item.id, keyword) ||
|
||||
includesText(item.performanceName, keyword) ||
|
||||
includesText(item.artistName, keyword)
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
export const filterUser = (
|
||||
user: UserFull,
|
||||
filters: {
|
||||
area?: string | string[];
|
||||
gender?: string | string[];
|
||||
genre?: string | string[];
|
||||
keyword?: string;
|
||||
}
|
||||
) => {
|
||||
const detail = user.userDetail ?? {};
|
||||
const area = getDetailValue(detail, ["area", "userArea", "region"]);
|
||||
const gender = getDetailValue(detail, ["gender", "userGender"]);
|
||||
const genre = getDetailValue(detail, ["genre", "performanceGenre", "reviewGenre"]);
|
||||
const keyword = filters.keyword?.trim() ?? "";
|
||||
const matches = (filter: string | string[] | undefined, value: string) => {
|
||||
if (!filter || filter.length === 0) return true;
|
||||
const values = Array.isArray(filter) ? filter : [filter];
|
||||
return values.includes(value);
|
||||
};
|
||||
|
||||
return (
|
||||
matches(filters.area, area) &&
|
||||
matches(filters.gender, gender) &&
|
||||
matches(filters.genre, genre) &&
|
||||
(
|
||||
includesText(user.userId, keyword) ||
|
||||
includesText(user.userName, keyword) ||
|
||||
includesText(user.userTeam, keyword) ||
|
||||
includesText(user.userCmpn, keyword) ||
|
||||
includesText(user.memo, keyword) ||
|
||||
includesText(getDetailValue(detail, ["tel", "phone", "userTel"]), keyword) ||
|
||||
includesText(getDetailValue(detail, ["email", "userEmail"]), keyword)
|
||||
)
|
||||
);
|
||||
};
|
||||
@@ -102,6 +102,20 @@ const isJsonContentType = (ctype: string) => {
|
||||
return ct.includes("application/json") || ct.includes("+json")
|
||||
}
|
||||
|
||||
const getErrorMessage = (data: unknown) => {
|
||||
if (typeof data === "object" && data !== null) {
|
||||
const error = data as { detail?: unknown; message?: unknown; errMessage?: unknown };
|
||||
return (
|
||||
(typeof error.detail === "string" && error.detail) ||
|
||||
(typeof error.message === "string" && error.message) ||
|
||||
(typeof error.errMessage === "string" && error.errMessage) ||
|
||||
undefined
|
||||
);
|
||||
}
|
||||
|
||||
return typeof data === "string" && data ? data : undefined;
|
||||
};
|
||||
|
||||
export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {}) => {
|
||||
const {
|
||||
getToken,
|
||||
@@ -179,7 +193,7 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
|
||||
}
|
||||
|
||||
const autoLogout = options.autoLogoutOnAuthError ?? true;
|
||||
const suppressAlert = options.suppressAlert ?? true;
|
||||
const suppressAlert = options.suppressAlert ?? options.method === "GET";
|
||||
|
||||
if (res.status === 401) options.onAuthError?.();
|
||||
|
||||
@@ -191,12 +205,7 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
|
||||
}
|
||||
|
||||
if (!suppressAlert && typeof window !== "undefined") {
|
||||
const serverMsg =
|
||||
typeof parsedError === "object" && parsedError !== null && "message" in parsedError
|
||||
? String((parsedError as { message?: unknown }).message ?? "")
|
||||
: typeof parsedError === "string"
|
||||
? parsedError
|
||||
: undefined;
|
||||
const serverMsg = getErrorMessage(parsedError);
|
||||
|
||||
const msg = setErrorMessage?.(res.status, serverMsg) ?? (serverMsg ?? `HTTP ${res.status}`);
|
||||
alert(`[${res.status}] ${msg}`);
|
||||
@@ -223,7 +232,7 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
|
||||
|
||||
if (!res.ok) {
|
||||
const autoLogout = options.autoLogoutOnAuthError ?? true;
|
||||
const suppressAlert = options.suppressAlert ?? true;
|
||||
const suppressAlert = options.suppressAlert ?? options.method === "GET";
|
||||
|
||||
if (res.status === 401) options.onAuthError?.();
|
||||
|
||||
@@ -235,12 +244,7 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
|
||||
}
|
||||
|
||||
if (!suppressAlert && typeof window !== "undefined") {
|
||||
const serverMsg =
|
||||
typeof parsed === "object" && parsed !== null && "message" in parsed
|
||||
? String((parsed as { message?: unknown }).message ?? "")
|
||||
: typeof parsed === "string"
|
||||
? parsed
|
||||
: undefined;
|
||||
const serverMsg = getErrorMessage(parsed);
|
||||
|
||||
const msg = setErrorMessage?.(res.status, serverMsg) ?? (serverMsg ?? `HTTP ${res.status}`);
|
||||
alert(`[${res.status}] ${msg}`);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { createHttpClient } from "@/lib/http-client";
|
||||
import { serverEnv } from "@/lib/env.server";
|
||||
import {CookieKeys} from "@/store/cookie/cookie-keys";
|
||||
|
||||
const createServerApi = async (rootUrl: string, defaultHeaders?: Record<string, string>) => {
|
||||
const cookieStore = await cookies();
|
||||
const accessToken = cookieStore.get("access_token")?.value ?? null;
|
||||
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value ?? null;
|
||||
|
||||
return createHttpClient(rootUrl, {
|
||||
getToken: () => accessToken, // 이미 위에서 읽은 값만 참조
|
||||
@@ -17,4 +18,8 @@ const createServerApi = async (rootUrl: string, defaultHeaders?: Record<string,
|
||||
|
||||
export const createBackApi = () => {
|
||||
return createServerApi(serverEnv.API_BACK_SERVER);
|
||||
}
|
||||
|
||||
export const createNotiHubApi = () => {
|
||||
return createServerApi(serverEnv.NOTI_HUB_SERVER);
|
||||
}
|
||||
127
src/lib/utils.ts
127
src/lib/utils.ts
@@ -60,3 +60,130 @@ export const roundNumber = (num: number|null, decimalPoint?: number) => {
|
||||
const factor = 10 ** decimalPoint;
|
||||
return Math.round(num * factor) / factor;
|
||||
};
|
||||
|
||||
export const downloadFile = (blob: Blob, filename: string) => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
export const downloadBase64File = (base64: string, filename: string) => {
|
||||
const byteString = atob(base64);
|
||||
const arrayBuffer = new ArrayBuffer(byteString.length);
|
||||
const uint8Array = new Uint8Array(arrayBuffer);
|
||||
|
||||
for (let i = 0; i < byteString.length; i++) {
|
||||
uint8Array[i] = byteString.charCodeAt(i);
|
||||
}
|
||||
|
||||
const blob = new Blob([arrayBuffer], {
|
||||
type:
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
});
|
||||
|
||||
downloadFile(blob, filename);
|
||||
};
|
||||
|
||||
export type CompressImageFileOptions = {
|
||||
maxWidth?: number;
|
||||
maxHeight?: number;
|
||||
quality?: number;
|
||||
mimeType?: "image/jpeg" | "image/webp" | "image/png";
|
||||
skipBelowBytes?: number;
|
||||
};
|
||||
|
||||
const getCompressedImageName = (fileName: string, mimeType: string) => {
|
||||
const extension = mimeType === "image/png" ? "png" : mimeType === "image/webp" ? "webp" : "jpg";
|
||||
const baseName = fileName.replace(/\.[^.]+$/, "");
|
||||
return `${baseName || "image"}.${extension}`;
|
||||
};
|
||||
|
||||
const loadImageElement = (file: File) => {
|
||||
return new Promise<HTMLImageElement>((resolve, reject) => {
|
||||
const url = URL.createObjectURL(file);
|
||||
const image = new Image();
|
||||
|
||||
image.onload = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
resolve(image);
|
||||
};
|
||||
image.onerror = () => {
|
||||
URL.revokeObjectURL(url);
|
||||
reject(new Error("Failed to load image."));
|
||||
};
|
||||
image.src = url;
|
||||
});
|
||||
};
|
||||
|
||||
const canvasToBlob = (canvas: HTMLCanvasElement, mimeType: string, quality: number) => {
|
||||
return new Promise<Blob>((resolve, reject) => {
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
if (blob) resolve(blob);
|
||||
else reject(new Error("Failed to compress image."));
|
||||
},
|
||||
mimeType,
|
||||
quality
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
export const compressImageFile = async (
|
||||
file: File,
|
||||
options: CompressImageFileOptions = {}
|
||||
) => {
|
||||
if (!file.type.startsWith("image/") || file.type === "image/svg+xml" || file.type === "image/gif") {
|
||||
return file;
|
||||
}
|
||||
|
||||
const {
|
||||
maxWidth = 1600,
|
||||
maxHeight = 1600,
|
||||
quality = 0.75,
|
||||
mimeType = "image/jpeg",
|
||||
skipBelowBytes = 500 * 1024,
|
||||
} = options;
|
||||
|
||||
if (file.size <= skipBelowBytes) return file;
|
||||
|
||||
try {
|
||||
const image = await loadImageElement(file);
|
||||
const ratio = Math.min(maxWidth / image.naturalWidth, maxHeight / image.naturalHeight, 1);
|
||||
const width = Math.max(1, Math.round(image.naturalWidth * ratio));
|
||||
const height = Math.max(1, Math.round(image.naturalHeight * ratio));
|
||||
const canvas = document.createElement("canvas");
|
||||
const ctx = canvas.getContext("2d");
|
||||
|
||||
if (!ctx) return file;
|
||||
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
|
||||
if (mimeType === "image/jpeg") {
|
||||
ctx.fillStyle = "#fff";
|
||||
ctx.fillRect(0, 0, width, height);
|
||||
}
|
||||
|
||||
ctx.drawImage(image, 0, 0, width, height);
|
||||
|
||||
const blob = await canvasToBlob(canvas, mimeType, quality);
|
||||
if (blob.size >= file.size) return file;
|
||||
|
||||
return new File([blob], getCompressedImageName(file.name, mimeType), {
|
||||
type: blob.type || mimeType,
|
||||
lastModified: Date.now(),
|
||||
});
|
||||
} catch {
|
||||
return file;
|
||||
}
|
||||
};
|
||||
|
||||
export const compressImageFiles = (
|
||||
files: File[],
|
||||
options?: CompressImageFileOptions
|
||||
) => Promise.all(files.map((file) => compressImageFile(file, options)));
|
||||
|
||||
122
src/query/assign.ts
Normal file
122
src/query/assign.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
"use client";
|
||||
|
||||
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {qk} from "@/query/key/keys";
|
||||
import {AssignUserCount, MonitoringApplyUser, PerformanceApplyCount, PerformanceAssign, PerformanceFull} from "@/types/gwcf";
|
||||
import {ExcelUploadResult} from "@/types/common";
|
||||
|
||||
const MONITORING_ASSIGN_TYPE = 1;
|
||||
|
||||
const mergeMonitoringAssigns = <T extends PerformanceFull>(performance: T, monitoringAssigns: PerformanceAssign[]): T => ({
|
||||
...performance,
|
||||
performanceAssignList: [
|
||||
...(performance.performanceAssignList ?? []).filter((assign) => assign.assignType !== MONITORING_ASSIGN_TYPE),
|
||||
...monitoringAssigns,
|
||||
],
|
||||
});
|
||||
|
||||
export function useMonitoringApplyUsersQuery(performanceId: number, enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.assignApplyUsers(performanceId),
|
||||
queryFn: () => nextApi.get<MonitoringApplyUser[]>(`/assign/monitoring/apply-users/${performanceId}`),
|
||||
enabled: enabled && performanceId > 0,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssignUserCountsQuery(enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.assignUserCounts(),
|
||||
queryFn: () => nextApi.get<AssignUserCount[]>("/assign/users/count"),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useMonitoringApplyUserCountsQuery(enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.assignApplyUserCounts(),
|
||||
queryFn: () => nextApi.get<PerformanceApplyCount[]>("/assign/monitoring/apply-users/count"),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useSaveMonitoringAssignMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({performanceId, userIds}: {performanceId: number; userIds: string[]}) =>
|
||||
nextApi.post<PerformanceAssign[]>("/assign/monitoring", {performanceId, userIds}),
|
||||
onSuccess: (res, {performanceId}) => {
|
||||
qc.setQueryData<PerformanceFull | undefined>(qk.performance(performanceId), (old) =>
|
||||
old ? mergeMonitoringAssigns(old, res) : old
|
||||
);
|
||||
qc.setQueryData<PerformanceFull[] | undefined>(qk.performanceList(), (old) =>
|
||||
old?.map((performance) => performance.id === performanceId ? mergeMonitoringAssigns(performance, res) : performance)
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssignConfirmMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({performanceId, userId}: {performanceId: number; userId: string}) =>
|
||||
nextApi.patch<void>(`/assign/confirm/${performanceId}/${encodeURIComponent(userId)}`),
|
||||
onSuccess: (_res, {performanceId, userId}) => {
|
||||
qc.invalidateQueries({ queryKey: qk.assignConfirm(performanceId, userId) });
|
||||
qc.invalidateQueries({ queryKey: qk.performance(performanceId) });
|
||||
qc.invalidateQueries({ queryKey: ["performance", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useAssignCancelMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({performanceId, userId}: {performanceId: number; userId: string}) =>
|
||||
nextApi.patch<void>(`/assign/cancel/${performanceId}/${encodeURIComponent(userId)}`),
|
||||
onSuccess: (_res, {performanceId, userId}) => {
|
||||
qc.invalidateQueries({ queryKey: qk.assignConfirm(performanceId, userId) });
|
||||
qc.invalidateQueries({ queryKey: qk.performance(performanceId) });
|
||||
qc.invalidateQueries({ queryKey: ["performance", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useKonAssignConfirmMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({performanceId, userId}: {performanceId: number; userId: string}) =>
|
||||
nextApi.post<string>(`/assign/confirm/${performanceId}/${encodeURIComponent(userId)}`),
|
||||
onSuccess: (_res, {performanceId, userId}) => {
|
||||
qc.invalidateQueries({ queryKey: qk.assignConfirm(performanceId, userId) });
|
||||
qc.invalidateQueries({ queryKey: ["performance", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUploadWrittenAssignExcelMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (file: File): Promise<ExcelUploadResult> => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return nextApi.postForm<ExcelUploadResult>("/assign/written/excel-upload", formData);
|
||||
},
|
||||
onSuccess: (res) => {
|
||||
if (!res.hasErrorFile) {
|
||||
qc.invalidateQueries({ queryKey: ["performance", "list"] });
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
54
src/query/code.ts
Normal file
54
src/query/code.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import {useQueries, useQuery} from "@tanstack/react-query";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {qk} from "@/query/key/keys";
|
||||
import {Code} from "@/types/gwcf";
|
||||
|
||||
export const CODE_GROUPS = [
|
||||
"area",
|
||||
"assign_type",
|
||||
"business_type",
|
||||
"gender",
|
||||
"genre",
|
||||
"has_car",
|
||||
"monitoring_visit_status",
|
||||
"review_status",
|
||||
"review_type",
|
||||
"staff_type",
|
||||
"ticket_reservation_status",
|
||||
"user_role",
|
||||
] as const;
|
||||
|
||||
export type CodeGroup = (typeof CODE_GROUPS)[number];
|
||||
|
||||
export function useCodeQuery(codeGroup: CodeGroup, enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.codes(codeGroup),
|
||||
queryFn: () => nextApi.get<Code[]>(`/code/${codeGroup}`),
|
||||
enabled,
|
||||
staleTime: 10 * 60_000,
|
||||
});
|
||||
}
|
||||
|
||||
export function useCodesQuery(groups: readonly CodeGroup[] = CODE_GROUPS) {
|
||||
return useQueries({
|
||||
queries: groups.map((codeGroup) => ({
|
||||
queryKey: qk.codes(codeGroup),
|
||||
queryFn: () => nextApi.get<Code[]>(`/code/${codeGroup}`),
|
||||
staleTime: 10 * 60_000,
|
||||
})),
|
||||
combine: (results) => {
|
||||
const data = groups.reduce<Record<CodeGroup, Code[]>>((acc, group, index) => {
|
||||
acc[group] = results[index].data ?? [];
|
||||
return acc;
|
||||
}, {} as Record<CodeGroup, Code[]>);
|
||||
|
||||
return {
|
||||
data,
|
||||
isLoading: results.some((result) => result.isLoading),
|
||||
isError: results.some((result) => result.isError),
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
19
src/query/key/keys.ts
Normal file
19
src/query/key/keys.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
export const qk = {
|
||||
codes: (codeGroup: string) => ["code", codeGroup] as const,
|
||||
|
||||
users: (userRole: number) => ["user", "list", userRole] as const,
|
||||
user: (userId: string) => ["user", "detail", userId] as const,
|
||||
|
||||
performanceList: () => ["performance", "list"] as const,
|
||||
performanceCompactList: () => ["performance", "list", "compact"] as const,
|
||||
performance: (performanceId: number) => ["performance", "detail", performanceId] as const,
|
||||
|
||||
assignApplyUsers: (performanceId: number) => ["assign", "monitoring", "apply-users", performanceId] as const,
|
||||
assignApplyUserCounts: () => ["assign", "monitoring", "apply-users", "count"] as const,
|
||||
assignUserCounts: () => ["assign", "users", "count"] as const,
|
||||
assignConfirm: (performanceId: number, userId: string) => ["assign", "confirm", performanceId, userId] as const,
|
||||
|
||||
monitoringEvidence: (performanceId: number, userId: string) => ["monitoring", "evidence", performanceId, userId] as const,
|
||||
|
||||
review: (performanceId: number, reviewType: number, userId?: string) => ["review", performanceId, reviewType, userId] as const,
|
||||
} as const;
|
||||
58
src/query/monitoring.ts
Normal file
58
src/query/monitoring.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
"use client";
|
||||
|
||||
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {qk} from "@/query/key/keys";
|
||||
import {MonitoringGpsRequest, PerformanceMonitoringVisit} from "@/types/gwcf";
|
||||
import {compressImageFiles} from "@/lib/utils";
|
||||
|
||||
export function useSaveDepartureMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({performanceId, gps}: {performanceId: number; gps: MonitoringGpsRequest}) =>
|
||||
nextApi.post<PerformanceMonitoringVisit>(`/monitoring/visit/departure/${performanceId}`, gps),
|
||||
onSuccess: (_res, {performanceId}) => {
|
||||
qc.invalidateQueries({ queryKey: qk.performance(performanceId) });
|
||||
qc.invalidateQueries({ queryKey: ["performance", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useSaveArrivalMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({performanceId, gps, files}: {performanceId: number; gps: MonitoringGpsRequest; files?: File[]}) => {
|
||||
const formData = new FormData();
|
||||
const compressedFiles = files ? await compressImageFiles(files) : [];
|
||||
formData.append("gps", new Blob([JSON.stringify(gps)], {type: "application/json"}));
|
||||
compressedFiles.forEach((file) => formData.append("files", file, file.name));
|
||||
return nextApi.postForm<PerformanceMonitoringVisit>(`/monitoring/visit/arrival/${performanceId}`, formData);
|
||||
},
|
||||
onSuccess: (_res, {performanceId}) => {
|
||||
qc.invalidateQueries({ queryKey: qk.performance(performanceId) });
|
||||
qc.invalidateQueries({ queryKey: ["performance", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useMonitoringEvidenceQuery(performanceId: number, userId: string, enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.monitoringEvidence(performanceId, userId),
|
||||
queryFn: () => nextApi.get<PerformanceMonitoringVisit[]>(`/monitoring/visit/evidence/${performanceId}/${encodeURIComponent(userId)}`),
|
||||
enabled: enabled && performanceId > 0 && Boolean(userId),
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadEvidenceZipMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({performanceId, userId}: {performanceId: number; userId: string}) =>
|
||||
nextApi.get<ArrayBuffer>(
|
||||
`/monitoring/visit/evidence/zip/${performanceId}/${encodeURIComponent(userId)}`,
|
||||
{expectBinary: true}
|
||||
),
|
||||
});
|
||||
}
|
||||
35
src/query/notification.ts
Normal file
35
src/query/notification.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import {useMutation, useQuery} from "@tanstack/react-query";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {BulkSendResponse, SaveTemplateRequest, SendSmsBulkRequest, Template} from "@/types/notification";
|
||||
|
||||
export const SMS_TEMPLATE_IDS = {
|
||||
ACCOUNT_MONITORING: 45,
|
||||
ASSIGN_CONFIRM: 46,
|
||||
CUSTOM: 47,
|
||||
} as const;
|
||||
|
||||
export const NOTIFICATION_REQUEST_SERVICE = "gwcf-review";
|
||||
|
||||
export function useNotificationTemplateQuery(templateIdx: number, enabled = true) {
|
||||
return useQuery({
|
||||
queryKey: ["notification", "template", templateIdx],
|
||||
queryFn: () => nextApi.get<Template>(`/notification/template/${templateIdx}`),
|
||||
enabled: enabled && templateIdx > 0,
|
||||
});
|
||||
}
|
||||
|
||||
export function useSaveNotificationTemplateMutation() {
|
||||
return useMutation({
|
||||
mutationFn: (data: SaveTemplateRequest) =>
|
||||
nextApi.patch<Template>("/notification/template", data),
|
||||
});
|
||||
}
|
||||
|
||||
export function useSendSmsBulkMutation() {
|
||||
return useMutation({
|
||||
mutationFn: (data: SendSmsBulkRequest) =>
|
||||
nextApi.post<BulkSendResponse>("/notification/sms-bulk", data),
|
||||
});
|
||||
}
|
||||
111
src/query/performance.ts
Normal file
111
src/query/performance.ts
Normal file
@@ -0,0 +1,111 @@
|
||||
"use client";
|
||||
|
||||
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {qk} from "@/query/key/keys";
|
||||
import {ExcelUploadResult} from "@/types/common";
|
||||
import {PerformanceCompact, PerformanceFull} from "@/types/gwcf";
|
||||
|
||||
export function usePerformanceListQuery(enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.performanceList(),
|
||||
queryFn: () => nextApi.get<PerformanceFull[]>("/performance/list"),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function usePerformanceCompactListQuery(enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.performanceCompactList(),
|
||||
queryFn: () => nextApi.get<PerformanceCompact[]>("/performance/list/compact"),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function usePerformanceDetailQuery(performanceId: number, enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.performance(performanceId),
|
||||
queryFn: () => nextApi.get<PerformanceFull>(`/performance/${performanceId}`),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdatePerformanceMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: PerformanceCompact) => nextApi.patch<void>("/performance", data),
|
||||
onSuccess: (_res, data) => {
|
||||
qc.invalidateQueries({ queryKey: qk.performance(data.id) });
|
||||
qc.invalidateQueries({ queryKey: ["performance", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeletePerformanceMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (performanceId: number) => nextApi.del<void>(`/performance/${performanceId}`),
|
||||
onSuccess: (_res, performanceId) => {
|
||||
qc.invalidateQueries({ queryKey: qk.performance(performanceId) });
|
||||
qc.invalidateQueries({ queryKey: ["performance", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUploadPerformanceExcelMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (file: File): Promise<ExcelUploadResult> => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return nextApi.postForm<ExcelUploadResult>("/performance/excel-upload", formData);
|
||||
},
|
||||
onSuccess: (res) => {
|
||||
if (!res.hasErrorFile) {
|
||||
qc.invalidateQueries({ queryKey: ["performance", "list"] });
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadPerformanceExcelTemplateMutation() {
|
||||
return useMutation({
|
||||
mutationFn: () =>
|
||||
nextApi.post<ArrayBuffer>(
|
||||
"/performance/excel-template",
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function useExportPerformanceMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({performanceIds}: {performanceIds: number[]}) =>
|
||||
nextApi.post<ArrayBuffer>(
|
||||
"/performance/excel-download",
|
||||
performanceIds.map(String),
|
||||
{ expectBinary: true }
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadAssignExcelTemplateMutation() {
|
||||
return useMutation({
|
||||
mutationFn: () =>
|
||||
nextApi.post<ArrayBuffer>(
|
||||
"/assign/written/excel-template",
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
),
|
||||
});
|
||||
}
|
||||
73
src/query/review.ts
Normal file
73
src/query/review.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {qk} from "@/query/key/keys";
|
||||
import {PerformanceReview} from "@/types/gwcf";
|
||||
|
||||
export function useReviewFileQuery(performanceId: number, reviewType: number, userId?: string, enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.review(performanceId, reviewType, userId),
|
||||
queryFn: () => nextApi.get<PerformanceReview>(`/review/${performanceId}/${reviewType}/${encodeURIComponent(userId ?? "")}`),
|
||||
enabled: enabled && performanceId > 0 && reviewType > 0 && Boolean(userId),
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useUploadReviewFileMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({performanceId, reviewType, file}: {performanceId: number; reviewType: number; file: File}) => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file, file.name);
|
||||
return nextApi.postForm<PerformanceReview>(`/review/${performanceId}/${reviewType}`, formData);
|
||||
},
|
||||
onSuccess: (_res, {performanceId, reviewType}) => {
|
||||
qc.invalidateQueries({ queryKey: ["review", performanceId, reviewType] });
|
||||
qc.invalidateQueries({ queryKey: qk.performance(performanceId) });
|
||||
qc.invalidateQueries({ queryKey: ["performance", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadReviewOriginalMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({performanceId, reviewType, userId}: {performanceId: number; reviewType: number; userId: string}) =>
|
||||
nextApi.get<ArrayBuffer>(`/review/download/${performanceId}/${reviewType}/${encodeURIComponent(userId)}`, {expectBinary: true}),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadReviewPdfMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({performanceId, reviewType, userId}: {performanceId: number; reviewType: number; userId: string}) =>
|
||||
nextApi.get<ArrayBuffer>(`/review/pdf/${performanceId}/${reviewType}/${encodeURIComponent(userId)}`, {expectBinary: true}),
|
||||
});
|
||||
}
|
||||
|
||||
export function useStartWrittenReviewMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({performanceId, userId}: {performanceId: number; userId: string}) =>
|
||||
nextApi.post<void>(`/review/start/${performanceId}/${encodeURIComponent(userId)}`),
|
||||
onSuccess: (_res, {performanceId}) => {
|
||||
qc.invalidateQueries({ queryKey: qk.performance(performanceId) });
|
||||
qc.invalidateQueries({ queryKey: ["performance", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useEndWrittenReviewMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: ({performanceId, userId}: {performanceId: number; userId: string}) =>
|
||||
nextApi.post<void>(`/review/end/${performanceId}/${encodeURIComponent(userId)}`),
|
||||
onSuccess: (_res, {performanceId}) => {
|
||||
qc.invalidateQueries({ queryKey: qk.performance(performanceId) });
|
||||
qc.invalidateQueries({ queryKey: ["performance", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
90
src/query/user.ts
Normal file
90
src/query/user.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
"use client";
|
||||
|
||||
import {useMutation, useQuery, useQueryClient} from "@tanstack/react-query";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {qk} from "@/query/key/keys";
|
||||
import {ExcelUploadResult} from "@/types/common";
|
||||
import {UserFull} from "@/types/gwcf";
|
||||
|
||||
export function useUsersQuery(userRole: number, enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.users(userRole),
|
||||
queryFn: () => nextApi.get<UserFull[]>(`/user/list/${userRole}`),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useUserDetailQuery(userId: string, enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.user(userId),
|
||||
queryFn: () => nextApi.get<UserFull>(`/user/${encodeURIComponent(userId)}`),
|
||||
enabled,
|
||||
staleTime: 0,
|
||||
refetchOnMount: "always",
|
||||
});
|
||||
}
|
||||
|
||||
export function useUpdateUserMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (data: UserFull) => nextApi.patch<void>("/user", data),
|
||||
onSuccess: (_res, data) => {
|
||||
qc.invalidateQueries({ queryKey: qk.user(data.userId) });
|
||||
qc.invalidateQueries({ queryKey: ["user", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useExportUserMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({userRole, userIds}: {userRole: number; userIds: string[]}) =>
|
||||
nextApi.post<ArrayBuffer>(
|
||||
`/user/excel-download/${userRole}`,
|
||||
userIds,
|
||||
{ expectBinary: true }
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDeleteUserMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (userId: string) => nextApi.del<void>(`/user/${encodeURIComponent(userId)}`),
|
||||
onSuccess: (_res, userId) => {
|
||||
qc.invalidateQueries({ queryKey: qk.user(userId) });
|
||||
qc.invalidateQueries({ queryKey: ["user", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useUploadUsersExcelMutation(userRole: number) {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (file: File): Promise<ExcelUploadResult> => {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
return nextApi.postForm<ExcelUploadResult>(`/user/excel-upload/${userRole}`, formData);
|
||||
},
|
||||
onSuccess: (res) => {
|
||||
if (!res.hasErrorFile) {
|
||||
qc.invalidateQueries({ queryKey: qk.users(userRole) });
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadUserExcelTemplateMutation(userRole: number) {
|
||||
return useMutation({
|
||||
mutationFn: () =>
|
||||
nextApi.post<ArrayBuffer>(
|
||||
`/user/excel-template/${userRole}`,
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -4,6 +4,15 @@ import { atom } from 'jotai'
|
||||
// Dialog추가 할 때만다 추가하기
|
||||
export type DialogId =
|
||||
| 'loginDialog'
|
||||
| 'performanceDetailDialog'
|
||||
| 'performanceExcelRegisterDialog'
|
||||
| 'assignWrittenExcelDialog'
|
||||
| 'userExcelRegisterDialog'
|
||||
| 'userSmsSendDialog'
|
||||
| 'monitoringVisitDialog'
|
||||
| 'monitoringDetailDialog'
|
||||
| 'assignMonitoringDialog'
|
||||
| 'assignSmsSendDialog'
|
||||
|
||||
// 현재 열려 있는 다이얼로그 ID 리스트
|
||||
export const openDialogIdsAtom = atom<DialogId[]>([])
|
||||
|
||||
@@ -4,6 +4,15 @@ export type DataVerification = {
|
||||
errMessage: string;
|
||||
}
|
||||
|
||||
export type ExcelUploadResult = {
|
||||
totalCount: number;
|
||||
successCount: number;
|
||||
failCount: number;
|
||||
hasErrorFile: boolean;
|
||||
errorFileName: string;
|
||||
errorFileBase64: string;
|
||||
}
|
||||
|
||||
export type RouteContext = { params: Promise<{ slug?: string[] }> };
|
||||
|
||||
export type PageRequest = {
|
||||
@@ -25,4 +34,4 @@ export type PageResponse<T> = {
|
||||
empty: boolean;
|
||||
}
|
||||
|
||||
export type SelectedMap = Record<string, string>;
|
||||
export type SelectedMap = Record<string, string>;
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
export type UserFull = {
|
||||
userId: string;
|
||||
userPw: string;
|
||||
userName: string;
|
||||
userCmpn: string;
|
||||
userTeam: string;
|
||||
userRole: number;
|
||||
memo: string;
|
||||
userDetail: Record<string, string>;
|
||||
};
|
||||
|
||||
export type UserCompact = {
|
||||
userId: string;
|
||||
userCmpn: string;
|
||||
userTeam: string;
|
||||
userName: string;
|
||||
userRole: number;
|
||||
userDetail: Record<string, string>;
|
||||
};
|
||||
|
||||
export type Code = {
|
||||
codeGroup: string;
|
||||
codeValue: number;
|
||||
codeGroupLabel: string;
|
||||
codeLabel: string;
|
||||
memo: string;
|
||||
};
|
||||
|
||||
export type PerformanceAssign = {
|
||||
id: number;
|
||||
performanceId: number;
|
||||
assignType: number;
|
||||
assignOrder: number;
|
||||
assignUser: string;
|
||||
assignConfirm: boolean;
|
||||
};
|
||||
|
||||
export type MonitoringApplyUser = {
|
||||
performanceId: number;
|
||||
userId: string;
|
||||
user: UserCompact;
|
||||
};
|
||||
|
||||
export type AssignUserCount = {
|
||||
assignUser: string;
|
||||
assignCount: number;
|
||||
};
|
||||
|
||||
export type PerformanceApplyCount = {
|
||||
performanceId: string;
|
||||
applyCnt: number;
|
||||
};
|
||||
|
||||
export type MonitoringGpsRequest = {
|
||||
gpsLatitude: number | null;
|
||||
gpsLongitude: number | null;
|
||||
gpsAccuracyM: number | null;
|
||||
gpsRaw: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type PerformanceBase = {
|
||||
id: number;
|
||||
businessType: number;
|
||||
performanceGenre: number;
|
||||
performanceArea: number;
|
||||
artistName: string;
|
||||
performanceName: string;
|
||||
performanceStartMonth: number;
|
||||
performanceDtInfo: string;
|
||||
performanceTimeInfo: string;
|
||||
ticketReservationStatus: number;
|
||||
ticketReservationMemo: string;
|
||||
performanceMemo: string;
|
||||
};
|
||||
|
||||
export type PerformanceCompact = PerformanceBase & {
|
||||
performanceDetail: Record<string, string>;
|
||||
performanceStaff: PerformanceStaff[];
|
||||
performanceMonitoringSchedule: PerformanceMonitoringSchedule;
|
||||
};
|
||||
|
||||
export type PerformanceFull = PerformanceBase & {
|
||||
performanceDetail: Record<string, string>;
|
||||
performanceStaff: PerformanceStaff[];
|
||||
performanceMonitoringSchedule: PerformanceMonitoringSchedule;
|
||||
performanceAssignList: PerformanceAssign[];
|
||||
performanceMonitoringVisitMap: Record<string, PerformanceMonitoringVisit[]>;
|
||||
performanceReviewMap: Record<string, PerformanceReview[]>;
|
||||
};
|
||||
|
||||
export type PerformanceMonitoringSchedule = {
|
||||
id: number;
|
||||
performanceId: number;
|
||||
monitoringDate: string;
|
||||
monitoringTimeInfo: string;
|
||||
monitoringAddress: string;
|
||||
};
|
||||
|
||||
export type PerformanceMonitoringVisit = {
|
||||
id: number;
|
||||
performanceId: number;
|
||||
regUser?: string;
|
||||
regDt?: string;
|
||||
monitoringVisitStatus: number;
|
||||
evidenceImg: string;
|
||||
gpsLatitude: number;
|
||||
gpsLongitude: number;
|
||||
gpsAccuracyM: number;
|
||||
gpsRaw: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type PerformanceReview = {
|
||||
performanceId: number;
|
||||
reviewType: number;
|
||||
regUser: string;
|
||||
reviewDt: string;
|
||||
reviewStatus: number;
|
||||
uploadFileName: string;
|
||||
pdfConvert: boolean;
|
||||
pdfFileName: string;
|
||||
};
|
||||
|
||||
export type PerformanceStaff = {
|
||||
id: number;
|
||||
performanceId: number;
|
||||
staffType: number;
|
||||
staffName: string;
|
||||
staffTel1: string;
|
||||
staffTel2: string;
|
||||
staffEmail: string;
|
||||
};
|
||||
|
||||
40
src/types/notification.ts
Normal file
40
src/types/notification.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
export type Template = {
|
||||
itrntPrjctCd: string;
|
||||
tmplatTy: number;
|
||||
tmplatNm: string;
|
||||
tmplatTitle: string;
|
||||
tmplatBody: string;
|
||||
senderKey?: string;
|
||||
kkoTmplatCd?: string;
|
||||
nationCd?: string;
|
||||
atchFl?: string;
|
||||
delayTime?: number;
|
||||
sendTel?: string;
|
||||
sendEml?: string;
|
||||
sendNm: string;
|
||||
tmplatIdx: number;
|
||||
};
|
||||
|
||||
export type SmsDestination = {
|
||||
sid?: string;
|
||||
destTel: string;
|
||||
destNm: string;
|
||||
msgParam?: Record<string, string>;
|
||||
};
|
||||
|
||||
export type SaveTemplateRequest = Pick<Template, "tmplatIdx" | "tmplatNm" | "tmplatTitle" | "tmplatBody" | "sendTel">;
|
||||
|
||||
export type SendSmsBulkRequest = {
|
||||
templateIdx: number;
|
||||
reqstCmpn: string;
|
||||
reqstUser: string;
|
||||
reqstSvc: string;
|
||||
destinations: SmsDestination[];
|
||||
};
|
||||
|
||||
export type BulkSendResponse = {
|
||||
bulkSendKey: string;
|
||||
requestCount: number;
|
||||
acceptCount: number;
|
||||
failCount: number;
|
||||
};
|
||||
Reference in New Issue
Block a user