develop #1
@@ -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"
|
||||
}
|
||||
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",
|
||||
|
||||
220
src/app/(pages)/(main)/assign/page.tsx
Normal file
220
src/app/(pages)/(main)/assign/page.tsx
Normal file
@@ -0,0 +1,220 @@
|
||||
"use client";
|
||||
|
||||
import {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";
|
||||
|
||||
const toParamValue = (value: unknown) => value == null ? "" : String(value);
|
||||
|
||||
const buildPerformanceSmsParams = (performance: PerformanceFull): Record<string, string> => ({
|
||||
businessType: toParamValue(performance.businessType),
|
||||
performanceGenre: toParamValue(performance.performanceGenre),
|
||||
performanceArea: toParamValue(performance.performanceArea),
|
||||
artistName: toParamValue(performance.artistName),
|
||||
performanceName: toParamValue(performance.performanceName),
|
||||
performanceStartMonth: toParamValue(performance.performanceStartMonth),
|
||||
performanceDtInfo: toParamValue(performance.performanceDtInfo),
|
||||
performanceTimeInfo: toParamValue(performance.performanceTimeInfo),
|
||||
ticketReservationStatus: toParamValue(performance.ticketReservationStatus),
|
||||
ticketReservationMemo: toParamValue(performance.ticketReservationMemo),
|
||||
performanceMemo: toParamValue(performance.performanceMemo),
|
||||
...Object.fromEntries(
|
||||
Object.entries(performance.performanceDetail ?? {}).map(([key, value]) => [key, toParamValue(value)])
|
||||
),
|
||||
...Object.fromEntries(
|
||||
Object.entries(performance.performanceMonitoringSchedule ?? {}).map(([key, value]) => [key, toParamValue(value)])
|
||||
),
|
||||
performanceId: toParamValue(performance.id),
|
||||
});
|
||||
|
||||
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 [smsTargetIds, setSmsTargetIds] = useState<string[]>([]);
|
||||
|
||||
const refreshAssignList = () => {
|
||||
void refetchPerformanceList();
|
||||
void refetchApplyCounts();
|
||||
};
|
||||
|
||||
const updateFilters = (updater: (prev: typeof filters) => typeof filters) => {
|
||||
setFilters(updater);
|
||||
refreshAssignList();
|
||||
};
|
||||
|
||||
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={(userIds) => {
|
||||
suppressAssignCloseRef.current = true;
|
||||
setSmsTargetIds(userIds);
|
||||
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}
|
||||
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,227 @@
|
||||
'use client'
|
||||
"use client";
|
||||
|
||||
import {useMemo, useState} from "react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {FilterSelect} from "@/components/gwcf/FilterSelect";
|
||||
import {MonitoringVisitDialog} from "@/components/dialog/MonitoringVisitDialog";
|
||||
import {PerformanceDetailDialog} from "@/components/dialog/PerformanceDetailDialog";
|
||||
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";
|
||||
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
|
||||
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));
|
||||
}, [data, userId]);
|
||||
|
||||
const todayItems = useMemo(() => {
|
||||
const matched = assignedItems
|
||||
.filter((item) => item.performanceMonitoringSchedule?.monitoringDate === today)
|
||||
.sort((a, b) => a.performanceName.localeCompare(b.performanceName, "ko"));
|
||||
|
||||
return matched.length > 0 ? matched : assignedItems;
|
||||
}, [assignedItems]);
|
||||
|
||||
const selected = useMemo(() => {
|
||||
return todayItems.find((item) => item.id === selectedId) ?? todayItems[0] ?? null;
|
||||
}, [selectedId, todayItems]);
|
||||
|
||||
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}
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const saveVisit = async (files?: File[]) => {
|
||||
if (!selected) return;
|
||||
|
||||
const gps = await getGps();
|
||||
if (visitMode === "departure") {
|
||||
await departureMutation.mutateAsync({performanceId: selected.id, gps});
|
||||
} else {
|
||||
await arrivalMutation.mutateAsync({performanceId: selected.id, gps, files});
|
||||
}
|
||||
hideDialog("monitoringVisitDialog");
|
||||
refreshMonitoringList();
|
||||
};
|
||||
|
||||
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={todayItems.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>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<Button type="button" disabled={!selected} onClick={() => openVisit("departure")}>출발</Button>
|
||||
<Button type="button" disabled={!selected} variant="outline" 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={todayItems}
|
||||
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}
|
||||
/>
|
||||
|
||||
<PerformanceDetailDialog
|
||||
open={detailOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (open) {
|
||||
showDialog("monitoringDetailDialog");
|
||||
return;
|
||||
}
|
||||
|
||||
hideDialog("monitoringDetailDialog");
|
||||
refreshMonitoringList();
|
||||
}}
|
||||
performance={detailData ?? selected}
|
||||
codes={codes}
|
||||
canEdit={false}
|
||||
/>
|
||||
</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,484 @@
|
||||
'use client'
|
||||
"use client";
|
||||
|
||||
import {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,
|
||||
usePerformanceDetailQuery,
|
||||
usePerformanceListQuery,
|
||||
useUpdatePerformanceMutation,
|
||||
useUploadPerformanceExcelMutation,
|
||||
} from "@/query/performance";
|
||||
import {useUploadWrittenAssignExcelMutation} from "@/query/assign";
|
||||
import {useDownloadReviewPdfMutation} from "@/query/review";
|
||||
import {useDownloadEvidenceZipMutation} from "@/query/monitoring";
|
||||
import {filterPerformance, getCodeLabel, isInternalRole, isWrittenReviewerRole} from "@/lib/gwcf/view";
|
||||
import {
|
||||
getMonitoringRecordedAt,
|
||||
getMonitoringRecordedUser,
|
||||
getMonitoringSlots,
|
||||
getMonitoringStatusDisplay,
|
||||
getReviewByType,
|
||||
getReviewStatusDisplay,
|
||||
getWrittenReviewRows,
|
||||
getWrittenReviewerSimpleMonitoringStatusDisplay,
|
||||
getWrittenReviewerSimpleReviewStatusDisplay,
|
||||
isReviewComplete,
|
||||
LOCAL_GOVERNMENT_REVIEW_TYPE,
|
||||
} from "@/lib/gwcf/performance-status";
|
||||
import {buildWrittenReviewLink} from "@/config/gwcf.config";
|
||||
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 {downloadFile} from "@/lib/utils";
|
||||
|
||||
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 STATUS_FILTER = {
|
||||
UNASSIGNED: "-1001",
|
||||
INCOMPLETE: "-1002",
|
||||
PENDING: "-1003",
|
||||
IN_PROGRESS: "-1004",
|
||||
DEPARTED: "-1005",
|
||||
ARRIVED: "-1006",
|
||||
DONE: "-1007",
|
||||
} as const;
|
||||
|
||||
const makeStatusOption = (value: string, label: string): Code => ({
|
||||
codeGroup: "status_filter",
|
||||
codeValue: Number(value),
|
||||
codeGroupLabel: "상태",
|
||||
codeLabel: label,
|
||||
memo: "",
|
||||
});
|
||||
|
||||
const normalizeStatusLabel = (label?: string) => label?.replace(/\s/g, "") ?? "";
|
||||
const labelHasComplete = (label?: string) => normalizeStatusLabel(label).includes("완료");
|
||||
const labelHasInProgress = (label?: string) => normalizeStatusLabel(label).includes("진행");
|
||||
const labelHasDeparted = (label?: string) => normalizeStatusLabel(label).includes("출발");
|
||||
const labelHasArrived = (label?: string) => normalizeStatusLabel(label).includes("도착");
|
||||
|
||||
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, "완료"),
|
||||
};
|
||||
|
||||
const PerformancePage = () => {
|
||||
return (
|
||||
<div>PerformancePage</div>
|
||||
);
|
||||
}
|
||||
const mounted = useMounted();
|
||||
const {auth} = useAuth();
|
||||
const userRole = auth.user?.userRole;
|
||||
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 reviewPdfMutation = useDownloadReviewPdfMutation();
|
||||
const evidenceZipMutation = useDownloadEvidenceZipMutation();
|
||||
|
||||
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 getReviewFilterValue = (review?: PerformanceReview, allowInProgress = false, alwaysAssigned = false) => {
|
||||
const label = getCodeLabel(codes, "review_status", review?.reviewStatus);
|
||||
|
||||
if (isWrittenReviewer) {
|
||||
if (isReviewComplete(review) || labelHasComplete(label)) return STATUS_FILTER.DONE;
|
||||
return STATUS_FILTER.INCOMPLETE;
|
||||
}
|
||||
|
||||
if (!alwaysAssigned && !review) return STATUS_FILTER.UNASSIGNED;
|
||||
if (isReviewComplete(review) || labelHasComplete(label)) return STATUS_FILTER.DONE;
|
||||
if (allowInProgress && labelHasInProgress(label)) return STATUS_FILTER.IN_PROGRESS;
|
||||
return STATUS_FILTER.PENDING;
|
||||
};
|
||||
|
||||
const getMonitoringFilterValue = (performance: PerformanceFull, index: 0 | 1) => {
|
||||
const slot = getMonitoringSlots(performance)[index];
|
||||
const label = getCodeLabel(codes, "monitoring_visit_status", slot.visit?.monitoringVisitStatus);
|
||||
|
||||
if (isWrittenReviewer) {
|
||||
return slot.visit ? STATUS_FILTER.DONE : STATUS_FILTER.INCOMPLETE;
|
||||
}
|
||||
|
||||
if (!slot.assign) return STATUS_FILTER.UNASSIGNED;
|
||||
if (!slot.visit) return STATUS_FILTER.PENDING;
|
||||
if (labelHasComplete(label)) return STATUS_FILTER.DONE;
|
||||
if (labelHasDeparted(label)) return STATUS_FILTER.DEPARTED;
|
||||
if (labelHasArrived(label)) return STATUS_FILTER.ARRIVED;
|
||||
return STATUS_FILTER.PENDING;
|
||||
};
|
||||
|
||||
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 filteredData = useMemo(() => {
|
||||
return data.filter((item) => {
|
||||
const localReview = getReviewByType(item, LOCAL_GOVERNMENT_REVIEW_TYPE)?.review;
|
||||
const writtenReviewRow = getWrittenReviewRows(item)[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, getReviewFilterValue(localReview, false, true)) &&
|
||||
matchesStatus(filters.monitoring1Status, getMonitoringFilterValue(item, 0)) &&
|
||||
matchesStatus(filters.monitoring2Status, getMonitoringFilterValue(item, 1)) &&
|
||||
matchesStatus(filters.writtenReviewStatus, getReviewFilterValue(writtenReviewRow?.review, true, Boolean(writtenReviewRow?.assign)))
|
||||
);
|
||||
});
|
||||
}, [codes, data, filters, isWrittenReviewer]);
|
||||
|
||||
const openDetail = (performance: PerformanceFull) => {
|
||||
if (isWrittenReviewer) return;
|
||||
lastSelectedRef.current = performance.id;
|
||||
setSelectedId(performance.id);
|
||||
showDialog("performanceDetailDialog");
|
||||
};
|
||||
|
||||
const downloadBlob = (buffer: ArrayBuffer, fileName: string, type = "application/octet-stream") => {
|
||||
downloadFile(new Blob([buffer], {type}), fileName);
|
||||
};
|
||||
|
||||
const downloadReviewPdf = async (performanceId: number, review?: PerformanceReview) => {
|
||||
if (!review || !isReviewComplete(review)) return;
|
||||
const buffer = await reviewPdfMutation.mutateAsync({performanceId, reviewType: review.reviewType});
|
||||
downloadBlob(buffer, review.pdfFileName || `review-${performanceId}-${review.reviewType}.pdf`, "application/pdf");
|
||||
};
|
||||
|
||||
const downloadEvidenceZip = async (performanceId: number, userId?: string) => {
|
||||
if (!userId) return;
|
||||
const buffer = await evidenceZipMutation.mutateAsync({performanceId, userId});
|
||||
downloadBlob(buffer, `monitoring-evidence-${performanceId}-${userId}.zip`, "application/zip");
|
||||
};
|
||||
|
||||
const openWrittenReviewLink = (performanceId: number, userId?: string, complete = false) => {
|
||||
if (!userId) return;
|
||||
window.open(buildWrittenReviewLink({performanceId, userId, complete}), "_blank", "noopener,noreferrer");
|
||||
};
|
||||
|
||||
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)
|
||||
? () => downloadReviewPdf(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>기록일시: -</div>
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
{display.label}
|
||||
</StatusPill>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const renderMonitoringStatus = (performance: PerformanceFull, index: 0 | 1) => {
|
||||
const slot = getMonitoringSlots(performance)[index];
|
||||
const label = getCodeLabel(codes, "monitoring_visit_status", slot.visit?.monitoringVisitStatus);
|
||||
const display = isWrittenReviewer
|
||||
? getWrittenReviewerSimpleMonitoringStatusDisplay(slot)
|
||||
: getMonitoringStatusDisplay(label, slot);
|
||||
|
||||
return (
|
||||
<div className="flex min-w-24 justify-center text-xs">
|
||||
<StatusPill
|
||||
variant={display.variant}
|
||||
onClick={!isWrittenReviewer && slot.visit ? () => downloadEvidenceZip(performance.id, slot.assign?.assignUser) : undefined}
|
||||
tooltip={isWrittenReviewer ? undefined : (
|
||||
<div className="space-y-1">
|
||||
<div>사용자: {getMonitoringRecordedUser(slot.visit)}</div>
|
||||
<div>기록일시: {getMonitoringRecordedAt(slot.visit)}</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 = getWrittenReviewRows(row.original)[0];
|
||||
return renderReviewStatus({
|
||||
performance: row.original,
|
||||
review: found?.review,
|
||||
userId: found?.userId,
|
||||
useWrittenLink: isWrittenReviewer,
|
||||
alwaysAssigned: Boolean(found?.assign),
|
||||
});
|
||||
},
|
||||
},
|
||||
], [codes, isWrittenReviewer]);
|
||||
|
||||
const downloadPerformanceTemplate = async () => {
|
||||
const buffer = await performanceTemplateMutation.mutateAsync();
|
||||
const blob = new Blob([buffer], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
|
||||
downloadFile(blob, "사업 등록 template.xlsx");
|
||||
};
|
||||
|
||||
const downloadWrittenAssignTemplate = async () => {
|
||||
const buffer = await writtenAssignTemplateMutation.mutateAsync();
|
||||
const blob = new Blob([buffer], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
|
||||
downloadFile(blob, "서면 평가 배정 template.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>
|
||||
{canEdit && (
|
||||
<div className="mb-3 flex justify-end gap-2">
|
||||
<Button type="button" onClick={() => showDialog("performanceExcelRegisterDialog")}>
|
||||
<Upload className="h-4 w-4" />
|
||||
사업 등록
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => showDialog("assignWrittenExcelDialog")}>
|
||||
서면 평가 배정
|
||||
</Button>
|
||||
</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}
|
||||
isWrittenReviewer={false}
|
||||
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,307 @@
|
||||
'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,
|
||||
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 {downloadFile} from "@/lib/utils";
|
||||
|
||||
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 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();
|
||||
const blob = new Blob([buffer], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
|
||||
downloadFile(blob, tab === "monitoring" ? "모니터링 요원 template.xlsx" : "서면 평가위원 template.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>
|
||||
</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;
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
@@ -66,8 +66,10 @@ export const POST = async (
|
||||
const [action] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if(action === "assign-confirm" && slug.length === 2) {
|
||||
const result = await backApi.post<boolean>(`/assign/confirm/${slug[1]}`)
|
||||
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 }));
|
||||
}
|
||||
|
||||
|
||||
@@ -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="monitoring-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);
|
||||
}
|
||||
};
|
||||
124
src/app/api/performance/[[...slug]]/route.ts
Normal file
124
src/app/api/performance/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
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 });
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
104
src/app/api/review/[[...slug]]/route.ts
Normal file
104
src/app/api/review/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {RouteContext} from "@/types/common";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
import {createBackApi} from "@/lib/server-api";
|
||||
import {PerformanceReview} from "@/types/gwcf";
|
||||
|
||||
const reviewFileName = (prefix: string, performanceId: string, reviewType: string) =>
|
||||
`${prefix}-${performanceId}-${reviewType}`;
|
||||
|
||||
export const GET = async (
|
||||
req: NextRequest,
|
||||
context: RouteContext
|
||||
) => {
|
||||
try {
|
||||
void req;
|
||||
const {slug = []} = await context.params;
|
||||
const [action, second, third] = slug;
|
||||
const backApi = await createBackApi();
|
||||
|
||||
if (action === "download" && second && third && slug.length === 3) {
|
||||
const result = await backApi.get<ArrayBuffer>(
|
||||
`/review/download/${encodeURIComponent(second)}/${encodeURIComponent(third)}`,
|
||||
{ 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 && slug.length === 3) {
|
||||
const result = await backApi.get<ArrayBuffer>(
|
||||
`/review/pdf/${encodeURIComponent(second)}/${encodeURIComponent(third)}`,
|
||||
{ expectBinary: true }
|
||||
);
|
||||
|
||||
return new NextResponse(result, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/pdf",
|
||||
"Content-Disposition": `attachment; filename="${reviewFileName("review-pdf", second, third)}.pdf"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (action && second && slug.length === 2) {
|
||||
const result = await backApi.get<PerformanceReview>(
|
||||
`/review/${encodeURIComponent(action)}/${encodeURIComponent(second)}`
|
||||
);
|
||||
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 && slug.length === 2) {
|
||||
await backApi.post<void>(`/review/start/${encodeURIComponent(second)}`);
|
||||
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);
|
||||
}
|
||||
};
|
||||
125
src/app/api/user/[[...slug]]/route.ts
Normal file
125
src/app/api/user/[[...slug]]/route.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
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"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -9,7 +9,7 @@ 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>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
218
src/components/dialog/AssignMonitoringDialog.tsx
Normal file
218
src/components/dialog/AssignMonitoringDialog.tsx
Normal file
@@ -0,0 +1,218 @@
|
||||
"use client";
|
||||
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import {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: (userIds: 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);
|
||||
onSaveAssign(selected.id, next);
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentAssign?.assignConfirm) {
|
||||
if (!confirm("이미 승인된 상태입니다. 정말로 취소 하시 겠습니까?")) return;
|
||||
} else if (currentAssign) {
|
||||
if (!confirm("이미 문자 발송된 상태입니다. 정말로 취소 하시 겠습니까?")) return;
|
||||
}
|
||||
|
||||
const next = checkedIds.filter((userId) => userId !== applyUser.userId);
|
||||
setCheckedIds(next);
|
||||
onSaveAssign(selected.id, 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={smsTargetIds.length === 0} onClick={() => onOpenSms(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>
|
||||
);
|
||||
}
|
||||
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,
|
||||
}: {
|
||||
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>
|
||||
);
|
||||
}
|
||||
471
src/components/dialog/PerformanceDetailDialog.tsx
Normal file
471
src/components/dialog/PerformanceDetailDialog.tsx
Normal file
@@ -0,0 +1,471 @@
|
||||
"use client";
|
||||
|
||||
import {ReactNode, useEffect, useMemo, useState} from "react";
|
||||
import {Download, ImageIcon, 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 {
|
||||
getMonitoringRecordedAt,
|
||||
getMonitoringRecordedUser,
|
||||
getMonitoringSlots,
|
||||
getMonitoringStatusDisplay,
|
||||
getReviewStatusDisplay,
|
||||
getWrittenReviewRows,
|
||||
isReviewComplete,
|
||||
LOCAL_GOVERNMENT_REVIEW_TYPE,
|
||||
} from "@/lib/gwcf/performance-status";
|
||||
import {buildWrittenReviewLink} from "@/config/gwcf.config";
|
||||
import {
|
||||
useDownloadReviewOriginalMutation,
|
||||
useDownloadReviewPdfMutation,
|
||||
useEndWrittenReviewMutation,
|
||||
useReviewFileQuery,
|
||||
useStartWrittenReviewMutation,
|
||||
useUploadReviewFileMutation,
|
||||
} from "@/query/review";
|
||||
import {useDownloadEvidenceZipMutation} from "@/query/monitoring";
|
||||
import {downloadFile} from "@/lib/utils";
|
||||
import {useUsersQuery} from "@/query/user";
|
||||
|
||||
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,
|
||||
}: {
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
function AssignedUserInfo({
|
||||
userId,
|
||||
user,
|
||||
codes,
|
||||
type,
|
||||
}: {
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
const downloadBlob = (buffer: ArrayBuffer, fileName: string, type = "application/octet-stream") => {
|
||||
const blob = new Blob([buffer], {type});
|
||||
downloadFile(blob, fileName);
|
||||
};
|
||||
|
||||
function ReviewFileActions({
|
||||
performanceId,
|
||||
reviewType,
|
||||
uploadFileName,
|
||||
pdfFileName,
|
||||
}: {
|
||||
performanceId: number;
|
||||
reviewType: number;
|
||||
uploadFileName?: string;
|
||||
pdfFileName?: string;
|
||||
}) {
|
||||
const uploadMutation = useUploadReviewFileMutation();
|
||||
const originalMutation = useDownloadReviewOriginalMutation();
|
||||
const pdfMutation = useDownloadReviewPdfMutation();
|
||||
|
||||
const upload = (file?: File) => {
|
||||
if (!file) return;
|
||||
uploadMutation.mutate({performanceId, reviewType, file});
|
||||
};
|
||||
|
||||
const downloadOriginal = async () => {
|
||||
const buffer = await originalMutation.mutateAsync({performanceId, reviewType});
|
||||
downloadBlob(buffer, uploadFileName || `review-original-${performanceId}-${reviewType}`);
|
||||
};
|
||||
|
||||
const downloadPdf = async () => {
|
||||
const buffer = await pdfMutation.mutateAsync({performanceId, reviewType});
|
||||
downloadBlob(buffer, pdfFileName || `review-pdf-${performanceId}-${reviewType}.pdf`, "application/pdf");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<label>
|
||||
<input type="file" className="hidden" onChange={(event) => upload(event.target.files?.[0])} />
|
||||
<FileActionButton icon="upload" disabled={uploadMutation.isPending}>파일 업로드</FileActionButton>
|
||||
</label>
|
||||
<FileActionButton icon="download" disabled={!uploadFileName || originalMutation.isPending} onClick={downloadOriginal}>원본</FileActionButton>
|
||||
<FileActionButton icon="download" disabled={!pdfFileName || pdfMutation.isPending} onClick={downloadPdf}>PDF</FileActionButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EvidenceZipButton({performanceId, userId}: {performanceId: number; userId: string}) {
|
||||
const zipMutation = useDownloadEvidenceZipMutation();
|
||||
const download = async () => {
|
||||
const buffer = await zipMutation.mutateAsync({performanceId, userId});
|
||||
downloadBlob(buffer, `monitoring-evidence-${performanceId}-${userId}.zip`, "application/zip");
|
||||
};
|
||||
|
||||
return <FileActionButton icon="image" disabled={zipMutation.isPending} onClick={download}>증빙사진</FileActionButton>;
|
||||
}
|
||||
|
||||
function LocalGovernmentReviewRow({performanceId, codes}: {performanceId: number; codes: CodeMap}) {
|
||||
const reviewType = LOCAL_GOVERNMENT_REVIEW_TYPE;
|
||||
const {data: review} = useReviewFileQuery(performanceId, reviewType, performanceId > 0);
|
||||
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={performanceId} reviewType={reviewType} uploadFileName={review?.uploadFileName} pdfFileName={review?.pdfFileName} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MonitoringStatusRow({
|
||||
performance,
|
||||
index,
|
||||
codes,
|
||||
userMap,
|
||||
}: {
|
||||
performance: PerformanceFull | PerformanceCompact;
|
||||
index: 0 | 1;
|
||||
codes: CodeMap;
|
||||
userMap: Map<string, UserFull>;
|
||||
}) {
|
||||
const slot = getMonitoringSlots(performance as PerformanceFull)[index];
|
||||
const user = slot.assign?.assignUser ? userMap.get(slot.assign.assignUser) : undefined;
|
||||
const reviewType = index + 1;
|
||||
const {data: review} = useReviewFileQuery(performance.id, reviewType, performance.id > 0);
|
||||
const label = getCodeLabel(codes, "monitoring_visit_status", slot.visit?.monitoringVisitStatus);
|
||||
const display = getMonitoringStatusDisplay(label, slot);
|
||||
|
||||
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={slot.assign?.assignUser} user={user} codes={codes} type="monitoring" />
|
||||
<div>기록 사용자: {getMonitoringRecordedUser(slot.visit)}</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<StatusPill variant={display.variant}>{display.label}</StatusPill>
|
||||
<ReviewFileActions performanceId={performance.id} reviewType={reviewType} uploadFileName={review?.uploadFileName} pdfFileName={review?.pdfFileName} />
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<span>모니터링 출발/도착 기록: {getMonitoringRecordedAt(slot.visit)}</span>
|
||||
{slot.assign?.assignUser ? (
|
||||
<EvidenceZipButton performanceId={performance.id} userId={slot.assign.assignUser} />
|
||||
) : (
|
||||
<FileActionButton icon="image" disabled>증빙사진</FileActionButton>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WrittenReviewRows({
|
||||
performance,
|
||||
codes,
|
||||
isWrittenReviewer,
|
||||
userMap,
|
||||
}: {
|
||||
performance: PerformanceFull | PerformanceCompact;
|
||||
codes: CodeMap;
|
||||
isWrittenReviewer: boolean;
|
||||
userMap: Map<string, UserFull>;
|
||||
}) {
|
||||
const startMutation = useStartWrittenReviewMutation();
|
||||
const endMutation = useEndWrittenReviewMutation();
|
||||
const rows = getWrittenReviewRows(performance as PerformanceFull);
|
||||
|
||||
if(rows.length === 0){
|
||||
rows.push({userId: "", assign: undefined, review: undefined});
|
||||
}
|
||||
|
||||
const openWrittenReviewLink = (userId: string, complete: boolean) => {
|
||||
window.open(buildWrittenReviewLink({performanceId: performance.id, userId, complete}), "_blank", "noopener,noreferrer");
|
||||
};
|
||||
|
||||
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={isWrittenReviewer ? () => openWrittenReviewLink(userId, complete) : undefined}>
|
||||
{display.label}
|
||||
</StatusPill>
|
||||
{isWrittenReviewer && (
|
||||
<Button type="button" size="xs" variant="outline" onClick={() => openWrittenReviewLink(userId, complete)}>
|
||||
평가 링크
|
||||
</Button>
|
||||
)}
|
||||
<Button type="button" size="xs" variant="outline" onClick={() => startMutation.mutate(performance.id)}>
|
||||
평가진행
|
||||
</Button>
|
||||
{complete && (
|
||||
<Button type="button" size="xs" variant="outline" onClick={() => endMutation.mutate({performanceId: performance.id, userId})}>
|
||||
평가완료
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PerformanceDetailDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
performance,
|
||||
codes,
|
||||
canEdit,
|
||||
isWrittenReviewer = false,
|
||||
onSave,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
performance: PerformanceFull | PerformanceCompact | null;
|
||||
codes: CodeMap;
|
||||
canEdit: boolean;
|
||||
isWrittenReviewer?: 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);
|
||||
};
|
||||
|
||||
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="border-b bg-muted px-3 py-2 font-semibold">평가 및 모니터링 현황</div>
|
||||
<LocalGovernmentReviewRow performanceId={draft.id} codes={codes} />
|
||||
<MonitoringStatusRow performance={performance ?? draft} index={0} codes={codes} userMap={monitoringUserMap} />
|
||||
<MonitoringStatusRow performance={performance ?? draft} index={1} codes={codes} userMap={monitoringUserMap} />
|
||||
<WrittenReviewRows performance={performance ?? draft} codes={codes} isWrittenReviewer={isWrittenReviewer} userMap={writtenUserMap} />
|
||||
</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>
|
||||
);
|
||||
}
|
||||
271
src/components/dialog/SmsSendDialog.tsx
Normal file
271
src/components/dialog/SmsSendDialog.tsx
Normal file
@@ -0,0 +1,271 @@
|
||||
"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";
|
||||
|
||||
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),
|
||||
});
|
||||
|
||||
const toParamValue = (value: unknown) => value == null ? "" : String(value);
|
||||
|
||||
const buildUserMsgParam = (user: UserCompact): Record<string, string> => ({
|
||||
...Object.fromEntries(
|
||||
Object.entries(user.userDetail ?? {}).map(([key, value]) => [key, toParamValue(value)])
|
||||
),
|
||||
userId: toParamValue(user.userId),
|
||||
userCmpn: toParamValue(user.userCmpn),
|
||||
userTeam: toParamValue(user.userTeam),
|
||||
userName: toParamValue(user.userName),
|
||||
userRole: toParamValue(user.userRole),
|
||||
});
|
||||
|
||||
export function SmsSendDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title = "문자 발송",
|
||||
templateIdx,
|
||||
newMessageTemplateIdx,
|
||||
selectedUsers,
|
||||
addParams = {},
|
||||
onSent,
|
||||
}: Readonly<{
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title?: string;
|
||||
templateIdx: number;
|
||||
newMessageTemplateIdx?: number;
|
||||
selectedUsers: UserCompact[];
|
||||
addParams?: Record<string, string>;
|
||||
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;
|
||||
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();
|
||||
}
|
||||
|
||||
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 }
|
||||
@@ -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,36 @@
|
||||
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_LINK_URL = {
|
||||
incomplete: "/written-review",
|
||||
complete: "/written-review/result",
|
||||
} as const;
|
||||
|
||||
export const buildWrittenReviewLink = ({
|
||||
performanceId,
|
||||
userId,
|
||||
complete,
|
||||
}: {
|
||||
performanceId: number;
|
||||
userId: string;
|
||||
complete: boolean;
|
||||
}) => {
|
||||
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("performanceId", String(performanceId));
|
||||
url.searchParams.set("userId", userId);
|
||||
return /^https?:\/\//i.test(baseUrl) ? url.toString() : url.pathname + url.search;
|
||||
};
|
||||
|
||||
@@ -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"),
|
||||
};
|
||||
146
src/lib/gwcf/performance-status.ts
Normal file
146
src/lib/gwcf/performance-status.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
import {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 type MonitoringSlot = {
|
||||
assign?: PerformanceAssign;
|
||||
user?: UserCompact;
|
||||
visit?: PerformanceMonitoringVisit;
|
||||
};
|
||||
|
||||
export type StatusDisplay = {
|
||||
label: string;
|
||||
variant: StatusPillVariant;
|
||||
};
|
||||
|
||||
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.id - b.id);
|
||||
|
||||
const visits = performance.performanceMonitoringVisitMap ?? {};
|
||||
|
||||
return [0, 1].map((index) => {
|
||||
const assign = confirmedAssigns[index];
|
||||
const userVisits = assign ? visits[assign.assignUser] ?? [] : [];
|
||||
const visit = assign
|
||||
? userVisits.find((item) => item.regUser === assign.assignUser) ?? userVisits[0]
|
||||
: undefined;
|
||||
|
||||
return {assign, visit};
|
||||
}) 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 getWrittenReviewRows = (performance: Partial<PerformanceFull>) => {
|
||||
const reviewRows = getReviewRows(performance).filter(({review}) => review.reviewType !== LOCAL_GOVERNMENT_REVIEW_TYPE);
|
||||
const reviewByUser = new Map(reviewRows.map((row) => [row.userId, row.review]));
|
||||
|
||||
const assignedUserIds = (performance.performanceAssignList ?? [])
|
||||
.filter((assign) => assign.assignType !== MONITORING_ASSIGN_TYPE)
|
||||
.map((assign) => assign.assignUser);
|
||||
|
||||
const userIds = Array.from(new Set([...assignedUserIds, ...reviewRows.map((row) => row.userId)]));
|
||||
|
||||
return userIds.map((userId) => ({
|
||||
userId,
|
||||
assign: (performance.performanceAssignList ?? []).find(
|
||||
(assign) => assign.assignType !== MONITORING_ASSIGN_TYPE && 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 Boolean(review?.pdfFileName || review?.pdfConvert);
|
||||
};
|
||||
|
||||
const normalizeStatusLabel = (label?: string) => label?.replace(/\s/g, "") ?? "";
|
||||
|
||||
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 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 getWrittenReviewerSimpleMonitoringStatusDisplay = (slot?: MonitoringSlot): StatusDisplay => {
|
||||
return slot?.visit
|
||||
? {label: "완료", variant: "done"}
|
||||
: {label: "미완료", variant: "pending"};
|
||||
};
|
||||
|
||||
export const getMonitoringStatusDisplay = (label?: string, slot?: MonitoringSlot): StatusDisplay => {
|
||||
if (!slot?.assign) return {label: "미배치", variant: "danger"};
|
||||
if (!slot.visit) 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 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)
|
||||
)
|
||||
);
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
@@ -60,3 +60,31 @@ 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);
|
||||
};
|
||||
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) => ["review", performanceId, reviewType] as const,
|
||||
} as const;
|
||||
56
src/query/monitoring.ts
Normal file
56
src/query/monitoring.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
"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";
|
||||
|
||||
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: ({performanceId, gps, files}: {performanceId: number; gps: MonitoringGpsRequest; files?: File[]}) => {
|
||||
const formData = new FormData();
|
||||
formData.append("gps", new Blob([JSON.stringify(gps)], {type: "application/json"}));
|
||||
files?.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),
|
||||
});
|
||||
}
|
||||
100
src/query/performance.ts
Normal file
100
src/query/performance.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
"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 useDownloadAssignExcelTemplateMutation() {
|
||||
return useMutation({
|
||||
mutationFn: () =>
|
||||
nextApi.post<ArrayBuffer>(
|
||||
"/assign/written/excel-template",
|
||||
undefined,
|
||||
{ expectBinary: true }
|
||||
),
|
||||
});
|
||||
}
|
||||
72
src/query/review.ts
Normal file
72
src/query/review.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
"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, enabled: boolean = true) {
|
||||
return useQuery({
|
||||
queryKey: qk.review(performanceId, reviewType),
|
||||
queryFn: () => nextApi.get<PerformanceReview>(`/review/${performanceId}/${reviewType}`),
|
||||
enabled: enabled && performanceId > 0 && reviewType > 0,
|
||||
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: qk.review(performanceId, reviewType) });
|
||||
qc.invalidateQueries({ queryKey: qk.performance(performanceId) });
|
||||
qc.invalidateQueries({ queryKey: ["performance", "list"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadReviewOriginalMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({performanceId, reviewType}: {performanceId: number; reviewType: number}) =>
|
||||
nextApi.get<ArrayBuffer>(`/review/download/${performanceId}/${reviewType}`, {expectBinary: true}),
|
||||
});
|
||||
}
|
||||
|
||||
export function useDownloadReviewPdfMutation() {
|
||||
return useMutation({
|
||||
mutationFn: ({performanceId, reviewType}: {performanceId: number; reviewType: number}) =>
|
||||
nextApi.get<ArrayBuffer>(`/review/pdf/${performanceId}/${reviewType}`, {expectBinary: true}),
|
||||
});
|
||||
}
|
||||
|
||||
export function useStartWrittenReviewMutation() {
|
||||
const qc = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (performanceId: number) => nextApi.post<void>(`/review/start/${performanceId}`),
|
||||
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"] });
|
||||
},
|
||||
});
|
||||
}
|
||||
79
src/query/user.ts
Normal file
79
src/query/user.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
"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 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>;
|
||||
|
||||
@@ -9,6 +9,23 @@ export type UserFull = {
|
||||
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;
|
||||
@@ -18,6 +35,29 @@ export type PerformanceAssign = {
|
||||
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;
|
||||
gpsLongitude: number;
|
||||
gpsAccuracyM: number;
|
||||
gpsRaw: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export type PerformanceBase = {
|
||||
id: number;
|
||||
businessType: number;
|
||||
@@ -59,6 +99,8 @@ export type PerformanceMonitoringSchedule = {
|
||||
export type PerformanceMonitoringVisit = {
|
||||
id: number;
|
||||
performanceId: number;
|
||||
regUser?: string;
|
||||
regDt?: string;
|
||||
monitoringVisitStatus: number;
|
||||
evidenceImg: string;
|
||||
gpsLatitude: number;
|
||||
@@ -70,6 +112,7 @@ export type PerformanceMonitoringVisit = {
|
||||
export type PerformanceReview = {
|
||||
performanceId: number;
|
||||
reviewType: number;
|
||||
regUser?: string;
|
||||
reviewStatus: number;
|
||||
uploadFileName: string;
|
||||
pdfConvert: boolean;
|
||||
|
||||
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