260914_01_ENH: 1차 완성

This commit is contained in:
2026-09-14 15:07:40 +09:00
parent a6642c9a00
commit f1d21d3711
67 changed files with 5595 additions and 148 deletions

8
package-lock.json generated
View File

@@ -8,7 +8,7 @@
"name": "k-musical-manage-front",
"version": "0.1.0",
"dependencies": {
"@kri/common": "0.18.3",
"@kri/common": "0.18.4",
"@tanstack/react-query": "latest",
"@tanstack/react-table": "^8.21.3",
"@tiptap/extension-color": "^3.31.2",
@@ -1149,9 +1149,9 @@
}
},
"node_modules/@kri/common": {
"version": "0.18.3",
"resolved": "https://gitea.kric.com/api/packages/KRi/npm/%40kri%2Fcommon/-/0.18.3/common-0.18.3.tgz",
"integrity": "sha512-OfDW00bD32YftUdxEtC16EHVz6b1Y35yg4JQ4hzyDYp+CTbgPvKeG8IXUE8Lks6n/m4cE8Ds76wrc0QNtK53hg==",
"version": "0.18.4",
"resolved": "https://gitea.kric.com/api/packages/KRi/npm/%40kri%2Fcommon/-/0.18.4/common-0.18.4.tgz",
"integrity": "sha512-AzLsgakDKN54qrV8BViy/AdwM0IOpP7i3fWQ1ostqq29m72zsTRIDcSroSxh2RHPN955H6djCzmdZCP4iprLYA==",
"license": "UNLICENSED",
"dependencies": {
"clsx": "^2.1.1",

View File

@@ -10,7 +10,7 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@kri/common": "0.18.3",
"@kri/common": "0.18.4",
"@tanstack/react-query": "latest",
"@tanstack/react-table": "^8.21.3",
"@tiptap/extension-color": "^3.31.2",

BIN
public/icon-excel.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

View File

@@ -0,0 +1,281 @@
"use client";
import {useRef, useState} from "react";
import {CalendarDays} from "lucide-react";
import {Button} from "@/components/ui/button";
import {PagePanel} from "@/components/kmusical/PagePanel";
import {PerformanceFilterBar} from "@/components/kmusical/PerformanceFilterBar";
import {DataTable} from "@/components/data-table/DataTable";
import type {DataTableColumn} from "@/components/data-table/DataTable.type";
import {SmsSendDialog} from "@/components/dialog/SmsSendDialog";
import {AssignMonitoringDialog, type AssignmentSelection} from "@/components/dialog/AssignMonitoringDialog";
import {AssignCalendarDialog} from "@/components/dialog/AssignCalendarDialog";
import {useCodesQuery} from "@/query/code";
import {usePerformanceListQuery, usePerformanceQuery} from "@/query/performance";
import {
useCancelAssignMutation,
useConfirmAssignMutation,
useMonitoringApplyUsersCountQuery,
useMonitoringApplyUsersQuery,
} from "@/query/assign";
import {useReviewSlotsQuery} from "@/query/review";
import {filterPerformance, getCodeLabel, type PerformanceFilterState} from "@/lib/kmusical/view";
import {buildPerformanceSmsParams} from "@/lib/kmusical/notification";
import {PERFORMANCE_FIELD_LABELS} from "@/lib/kmusical/field-labels";
import {REVIEW_TYPE, type PerformanceFull, type ReviewType} from "@/types/kmusical";
import {SMS_TEMPLATE_IDS} from "@/query/notification";
import {useDialog} from "@/hooks/useDialog";
import {useUserListQuery} from "@/query/user";
import {MONITORING_USER_ROLE} from "@/config/kmusical.config";
const AssignPage = () => {
const {data: codes} = useCodesQuery();
const {data = [], isLoading, refetch: refetchList} = usePerformanceListQuery();
const {data: applyCounts = [], refetch: refetchCounts} = useMonitoringApplyUsersCountQuery();
const {data: reviewSlots = []} = useReviewSlotsQuery();
const {isDialogOpen, showDialog, hideDialog} = useDialog();
const [selectedId, setSelectedId] = useState("");
const [reviewSlotNumbersToSave, setReviewSlotNumbersToSave] = useState<number[]>([]);
const [assignmentsToSave, setAssignmentsToSave] = useState<AssignmentSelection[]>([]);
const [smsTargetIds, setSmsTargetIds] = useState<string[]>([]);
const [smsMode, setSmsMode] = useState<"assignConfirm" | "normal">("assignConfirm");
const [smsTemplateIdx, setSmsTemplateIdx] = useState<number[]>([SMS_TEMPLATE_IDS.ASSIGN_CONFIRM]);
const [smsDialogTitle, setSmsDialogTitle] = useState("확정 문자 발송");
const [newSmsTemplateIdx, setNewSmsTemplateIdx] = useState<number | undefined>();
const [filters, setFilters] = useState<PerformanceFilterState>({
businessType: [],
area: [],
month: "",
monitoringDate: "",
slotStatus: {},
keyword: "",
});
const assignOpen = isDialogOpen("assignMonitoringDialog");
const smsOpen = isDialogOpen("assignSmsSendDialog");
const calendarOpen = isDialogOpen("assignCalendarDialog");
const {data: detail, refetch: refetchDetail} = usePerformanceQuery(assignOpen ? selectedId : "");
const {data: applyUsers = []} = useMonitoringApplyUsersQuery(selectedId);
const {data: users = []} = useUserListQuery(MONITORING_USER_ROLE);
const suppressAssignCloseRef = useRef(false);
const confirmMutation = useConfirmAssignMutation();
const cancelMutation = useCancelAssignMutation();
const applyCountMap = new Map(applyCounts.map((item) => [item.performanceId, item.applyCnt]));
const reviewSlotTypeMap = new Map(reviewSlots.map((slot) => [slot.reviewSlot, slot.reviewType]));
const countConfirmedAssigns = (row: PerformanceFull, reviewType: ReviewType) =>
row.performanceAssignList.filter((assign) => reviewSlotTypeMap.get(assign.reviewSlot) === reviewType).length;
const filteredData = data
.filter((item) => filterPerformance(item, filters))
.sort((a, b) => (b.performanceMonitoringSchedule?.monitoringDate ?? "").localeCompare(a.performanceMonitoringSchedule?.monitoringDate ?? ""));
const selected = detail ?? data.find((item) => item.performanceId === selectedId) ?? null;
const availableUsers = Array.from(new Map([
...users.map((user) => [user.userId, user] as const),
...applyUsers.map((item) => [item.userId, item.user] as const),
]).values());
const smsTargetUsers = availableUsers.filter((user) => smsTargetIds.includes(user.userId));
const columns: DataTableColumn<PerformanceFull>[] = [
{accessorKey: "performanceId", header: PERFORMANCE_FIELD_LABELS.performanceId, size: 90},
{
accessorKey: "performanceName",
header: PERFORMANCE_FIELD_LABELS.performanceName,
size: 260,
cell: ({row}) => (
<div className="line-clamp-2" title={row.original.performanceName}>
{row.original.performanceName}
</div>
),
},
{id: "area", header: PERFORMANCE_FIELD_LABELS.performanceArea, size: 80, cell: ({row}) => getCodeLabel(codes, "area", row.original.performanceArea)},
{
accessorKey: "performanceDtInfo",
header: PERFORMANCE_FIELD_LABELS.performanceDtInfo,
size: 200,
cell: ({row}) => (
<div className="line-clamp-2" title={row.original.performanceDtInfo}>
{row.original.performanceDtInfo}
</div>
),
enableSorting: false
},
{
accessorKey: "performanceTimeInfo",
header: PERFORMANCE_FIELD_LABELS.performanceTimeInfo,
size: 220,
cell: ({row}) => (
<div className="line-clamp-2" title={row.original.performanceTimeInfo}>
{row.original.performanceTimeInfo}
</div>
),
enableSorting: false
},
{id: "applyCount", header: "신청자 수", size: 100, accessorFn: (row) => applyCountMap.get(row.performanceId) ?? 0},
{id: "monitoringAssignCount", header: "모니터링 확정자 수", size: 140, accessorFn: (row) => countConfirmedAssigns(row, REVIEW_TYPE.MONITORING)},
{id: "consultingAssignCount", header: "컨설팅 확정자 수", size: 140, accessorFn: (row) => countConfirmedAssigns(row, REVIEW_TYPE.CONSULTING)},
];
const openAssign = (performance: PerformanceFull) => {
suppressAssignCloseRef.current = false;
setSelectedId(performance.performanceId);
showDialog("assignMonitoringDialog");
};
const refresh = () => {
void refetchList();
void refetchCounts();
if (selectedId) void refetchDetail();
};
const saveAssignments = async (reviewSlotNumbers: number[], nextAssignments: AssignmentSelection[]) => {
if (!selectedId || !selected) throw new Error("배정할 공연 정보가 없습니다.");
const targetSlotNumberSet = new Set(reviewSlotNumbers);
const currentBySlot = new Map(
selected.performanceAssignList
.filter((assign) => targetSlotNumberSet.has(assign.reviewSlot))
.map((assign) => [assign.reviewSlot, assign.assignUser])
);
const nextBySlot = new Map(nextAssignments.map((assign) => [assign.reviewSlot, assign.userId]));
const slotsToCancel = Array.from(currentBySlot.entries())
.filter(([reviewSlot, userId]) => nextBySlot.get(reviewSlot) !== userId)
.map(([reviewSlot]) => reviewSlot)
.sort((a, b) => a - b);
const assignmentsToConfirm = nextAssignments
.filter(({reviewSlot, userId}) => currentBySlot.get(reviewSlot) !== userId)
.sort((a, b) => a.reviewSlot - b.reviewSlot);
for (const reviewSlot of slotsToCancel) {
await cancelMutation.mutateAsync({performanceId: selectedId, reviewSlot});
}
for (const {reviewSlot, userId} of assignmentsToConfirm) {
await confirmMutation.mutateAsync({performanceId: selectedId, reviewSlot, userId});
}
await refetchDetail();
void refetchList();
void refetchCounts();
};
return (
<div className="space-y-4">
<PagePanel>
<PerformanceFilterBar
codes={codes}
reviewSlots={reviewSlots}
filters={filters}
onFiltersChange={setFilters}
onSearch={refresh}
showMonth={false}
/>
</PagePanel>
<PagePanel className="overflow-x-auto">
<div className="mb-3 flex flex-wrap justify-end gap-2">
<Button type="button" variant="outline" onClick={() => showDialog("assignCalendarDialog")}>
<CalendarDays className="h-4 w-4" />배정 캘린더
</Button>
</div>
<DataTable
columns={columns}
data={filteredData}
getRowId={(row) => row.performanceId}
selectMode="click-event"
onRowClick={(performance) => openAssign(performance)}
defaultPageSize={10}
emptyText={isLoading ? "조회 중입니다." : "조회된 공연이 없습니다."}
bodyRowClassName="[&>td]:py-2"
/>
</PagePanel>
<AssignMonitoringDialog
open={assignOpen}
onOpenChange={(open) => {
if (open) {
showDialog("assignMonitoringDialog");
return;
}
if (suppressAssignCloseRef.current) return;
hideDialog("assignMonitoringDialog");
refresh();
}}
selected={selected}
codes={codes}
reviewSlots={reviewSlots}
applyUsers={applyUsers}
users={availableUsers}
isSaving={confirmMutation.isPending || cancelMutation.isPending}
onSaveAssign={async (reviewSlotNumbers, assignments) => {
await saveAssignments(reviewSlotNumbers, assignments);
alert("배정 정보가 저장되었습니다.");
}}
onOpenAssignSms={(reviewSlotNumbers, assignments, smsUserIds) => {
suppressAssignCloseRef.current = true;
setReviewSlotNumbersToSave(reviewSlotNumbers);
setAssignmentsToSave(assignments);
setSmsTargetIds(smsUserIds);
setSmsMode("assignConfirm");
setSmsTemplateIdx([SMS_TEMPLATE_IDS.ASSIGN_CONFIRM]);
setSmsDialogTitle("확정 문자 발송");
setNewSmsTemplateIdx(undefined);
showDialog("assignSmsSendDialog", false);
}}
onOpenNormalSms={(smsUserIds) => {
suppressAssignCloseRef.current = true;
setSmsTargetIds(smsUserIds);
setSmsMode("normal");
setSmsTemplateIdx([SMS_TEMPLATE_IDS.INFORM_ASSIGN, SMS_TEMPLATE_IDS.REMIND_ASSIGN]);
setSmsDialogTitle("문자 발송");
setNewSmsTemplateIdx(SMS_TEMPLATE_IDS.CUSTOM);
showDialog("assignSmsSendDialog", false);
}}
/>
<SmsSendDialog
open={smsOpen}
onOpenChange={(open) => {
if (open) {
suppressAssignCloseRef.current = true;
showDialog("assignSmsSendDialog", false);
return;
}
hideDialog("assignSmsSendDialog");
refresh();
window.setTimeout(() => {
suppressAssignCloseRef.current = false;
}, 0);
}}
title={smsDialogTitle}
templateIdx={smsTemplateIdx}
newMessageTemplateIdx={newSmsTemplateIdx}
selectedUsers={smsTargetUsers}
addParams={selected ? buildPerformanceSmsParams(selected) : {}}
denyParamKeys={["userCmpn", "userTeam", "userRole", "performanceId"]}
isBeforeSendPending={confirmMutation.isPending || cancelMutation.isPending}
onBeforeDefaultTemplateSend={smsMode === "assignConfirm"
? () => saveAssignments(reviewSlotNumbersToSave, assignmentsToSave)
: undefined}
onSent={refresh}
/>
<AssignCalendarDialog
open={calendarOpen}
onOpenChange={(open) => open ? showDialog("assignCalendarDialog") : hideDialog("assignCalendarDialog")}
performances={data}
applyCountMap={applyCountMap}
reviewSlots={reviewSlots}
reviewers={users}
/>
</div>
);
};
export default AssignPage;

View File

@@ -1,13 +1,27 @@
import { AppPageTitle } from "@/components/app-shell/AppPageTitle";
'use client'
import {useMounted} from "@kri/common/hooks";
import {useAuth} from "@/hooks/useAuth";
import {useEffect} from "react";
import {useRouter} from "next/navigation";
import {Route} from "next";
function LoadingOverlay(props: { force: boolean }) {
return null;
}
export default function MainPage() {
return (
<div className="space-y-6">
<AppPageTitle title="K-Musical 모니터링 시스템" description="프로젝트 기본 구성이 완료되었습니다." />
<div className="rounded-lg border bg-card p-6 text-card-foreground shadow-sm">
<p className="font-medium">다음 작업</p>
<p className="mt-2 text-sm text-muted-foreground">메뉴와 API 경로를 프로젝트 업무에 맞게 확장하세요.</p>
</div>
</div>
);
const router = useRouter();
const mounted = useMounted();
const { auth } = useAuth();
useEffect(() => {
if(auth && auth.user){
router.push("/performance" as Route);
}
}, [auth.user])
if (!mounted) return <LoadingOverlay force />;
return null;
}

View File

@@ -0,0 +1,207 @@
"use client";
import {useState} from "react";
import {Download, Upload} from "lucide-react";
import {Button} from "@/components/ui/button";
import {PagePanel} from "@/components/kmusical/PagePanel";
import {PerformanceFilterBar} from "@/components/kmusical/PerformanceFilterBar";
import {StatusPill} from "@/components/kmusical/StatusPill";
import {ExcelRegisterDialog} from "@/components/dialog/ExcelRegisterDialog";
import {PerformanceDetailDialog} from "@/components/dialog/PerformanceDetailDialog";
import {DataTable} from "@/components/data-table/DataTable";
import type {DataTableColumn} from "@/components/data-table/DataTable.type";
import {useCodesQuery} from "@/query/code";
import {
useDeletePerformanceMutation,
useExportPerformanceMutation,
useExportPerformanceTemplateMutation,
usePerformanceListQuery,
usePerformanceQuery,
useUpdatePerformanceMutation,
useUploadPerformanceExcelMutation,
} from "@/query/performance";
import {useDownloadReviewOriginalMutation, useReviewSlotsQuery} from "@/query/review";
import {filterPerformance, getCodeLabel, isInternalRole, isResearcherRole, type PerformanceFilterState} from "@/lib/kmusical/view";
import {getMonitoringStatusDisplay, isReviewComplete} from "@/lib/kmusical/performance-status";
import {downloadBlob, downloadExcelBuffer} from "@/lib/kmusical/file";
import {PERFORMANCE_FIELD_LABELS} from "@/lib/kmusical/field-labels";
import type {PerformanceFull} from "@/types/kmusical";
import {useAuth} from "@/hooks/useAuth";
import {useDialog} from "@/hooks/useDialog";
import ExcelDownloadButton from "@/components/kmusical/ExcelDownloadButton";
const PerformancePage = () => {
const {auth, isMonitoring} = useAuth();
const {data: codes} = useCodesQuery();
const {data = [], isLoading, refetch: refetchList} = usePerformanceListQuery();
const {data: reviewSlots = []} = useReviewSlotsQuery();
const {isDialogOpen, showDialog, hideDialog} = useDialog();
const [selectedId, setSelectedId] = useState("");
const [filters, setFilters] = useState<PerformanceFilterState>({
businessType: [],
area: [],
month: "",
monitoringDate: "",
slotStatus: {},
keyword: "",
});
const updateMutation = useUpdatePerformanceMutation();
const deleteMutation = useDeletePerformanceMutation();
const uploadMutation = useUploadPerformanceExcelMutation();
const templateMutation = useExportPerformanceTemplateMutation();
const exportMutation = useExportPerformanceMutation();
const originalMutation = useDownloadReviewOriginalMutation();
const detailOpen = isDialogOpen("performanceDetailDialog");
const registerOpen = isDialogOpen("performanceExcelRegisterDialog");
const {data: detail, refetch: refetchDetail} = usePerformanceQuery(detailOpen ? selectedId : "");
const canEdit = isInternalRole(auth.user?.userRole);
const canDelete = isResearcherRole(auth.user?.userRole);
const visibleData = isMonitoring
? data.filter((item) => Boolean(auth.user?.userId && item.performanceAssignList.some((assign) => assign.assignUser === auth.user?.userId)))
: data;
const filteredData = visibleData.filter((item) => filterPerformance(item, filters));
const downloadReview = async (performance: PerformanceFull, reviewSlot: number) => {
const review = Object.values(performance.performanceReviewMap ?? {}).find((item) => item.reviewSlot === reviewSlot);
if (!review?.uploadFileName) return;
const buffer = await originalMutation.mutateAsync({performanceId: performance.performanceId, reviewSlot});
downloadBlob(buffer, review.uploadFileName);
};
const columns: DataTableColumn<PerformanceFull>[] = [
{accessorKey: "performanceNo", header: PERFORMANCE_FIELD_LABELS.performanceNo, size: 60},
{accessorKey: "performanceId", header: PERFORMANCE_FIELD_LABELS.performanceId, size: 90},
{id: "businessType", header: PERFORMANCE_FIELD_LABELS.businessType, size: 100, cell: ({row}) => getCodeLabel(codes, "business_type", row.original.businessType)},
{id: "area", header: PERFORMANCE_FIELD_LABELS.performanceArea, size: 80, cell: ({row}) => getCodeLabel(codes, "area", row.original.performanceArea)},
{accessorKey: "artistName", header: PERFORMANCE_FIELD_LABELS.artistName, size: 160},
{accessorKey: "performanceName", header: PERFORMANCE_FIELD_LABELS.performanceName, size: 260},
{id: "performanceStartMonth", header: PERFORMANCE_FIELD_LABELS.performanceStartMonth,
size: 90,
accessorFn: (row) => row.performanceStartMonth ?? 0,
cell: ({row}) => row.original.performanceStartMonth === 0? "미정":`${row.original.performanceStartMonth}월`
},
{
accessorKey: "performanceDtInfo",
header: PERFORMANCE_FIELD_LABELS.performanceDtInfo,
size: 170,
enableSorting: false
},
{
accessorKey: "performanceTimeInfo",
header: PERFORMANCE_FIELD_LABELS.performanceTimeInfo,
size: 140,
enableSorting: false
},
...reviewSlots.map<DataTableColumn<PerformanceFull>>((slot) => ({
id: `review-${slot.reviewSlot}`,
header: slot.reviewLabel,
size: 110,
enableSorting: false,
cell: ({row}) => {
const assign = row.original.performanceAssignList.find((item) => item.reviewSlot === slot.reviewSlot);
const review = Object.values(row.original.performanceReviewMap ?? {}).find((item) => item.reviewSlot === slot.reviewSlot);
const display = getMonitoringStatusDisplay(getCodeLabel(codes, "review_status", review?.reviewStatus), {
reviewSlot: slot.reviewSlot,
reviewType: slot.reviewType,
assign,
review,
});
return (
<StatusPill
variant={display.variant}
onClick={isReviewComplete(review) ? () => downloadReview(row.original, slot.reviewSlot) : undefined}
tooltip={<span>담당자: {assign?.assignUser || "-"}</span>}
>
{display.label}
</StatusPill>
);
},
})),
];
const downloadTemplate = async () => {
downloadExcelBuffer(await templateMutation.mutateAsync(), "공연 등록 양식.xlsx");
};
const downloadPerformances = async () => {
if (filteredData.length === 0) {
alert("다운로드할 공연 정보가 없습니다.");
return;
}
downloadExcelBuffer(
await exportMutation.mutateAsync(filteredData.map((performance) => performance.performanceId)),
"공연 정보.xlsx"
);
};
return (
<div className="space-y-4">
<PagePanel>
<PerformanceFilterBar
codes={codes}
reviewSlots={reviewSlots}
filters={filters}
onFiltersChange={setFilters}
onSearch={() => refetchList()}
/>
</PagePanel>
<PagePanel className="overflow-x-auto">
<div className="mb-3 flex flex-wrap justify-end gap-2">
{canEdit && <Button type="button" onClick={() => showDialog("performanceExcelRegisterDialog")}><Upload className="h-4 w-4" />공연 등록</Button>}
<ExcelDownloadButton requestExcelExport={downloadPerformances} />
</div>
<DataTable
columns={columns}
data={filteredData}
getRowId={(row) => row.performanceId}
selectMode="click-event"
onRowClick={(performance) => {
setSelectedId(performance.performanceId);
showDialog("performanceDetailDialog");
}}
defaultPageSize={10}
emptyText={isLoading ? "조회 중입니다." : "조회된 공연이 없습니다."}
bodyRowClassName="[&>td]:py-2"
/>
</PagePanel>
<PerformanceDetailDialog
open={detailOpen}
onOpenChange={(open) => open ? showDialog("performanceDetailDialog") : hideDialog("performanceDetailDialog")}
performance={detail ?? data.find((item) => item.performanceId === selectedId) ?? null}
codes={codes}
reviewSlots={reviewSlots}
canEdit={canEdit}
canDelete={canDelete}
onSave={async (performance) => {
await updateMutation.mutateAsync(performance);
await Promise.all([refetchList(), refetchDetail()]);
}}
onDelete={async (performanceId) => {
await deleteMutation.mutateAsync(performanceId);
hideDialog("performanceDetailDialog");
setSelectedId("");
await refetchList();
}}
onRefresh={() => { void refetchList(); void refetchDetail(); }}
/>
<ExcelRegisterDialog
open={registerOpen}
onOpenChange={(open) => open ? showDialog("performanceExcelRegisterDialog") : hideDialog("performanceExcelRegisterDialog")}
title="공연 등록"
onDownloadTemplate={downloadTemplate}
onUpload={async (file) => {
const formData = new FormData();
formData.append("file", file, file.name);
return uploadMutation.mutateAsync(formData);
}}
isUploading={uploadMutation.isPending}
/>
</div>
);
};
export default PerformancePage;

View File

@@ -0,0 +1,231 @@
"use client";
import {MouseEvent, ReactNode, useCallback, useRef, useState} from "react";
import {Download, Search, Send, Upload} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {PagePanel} from "@/components/kmusical/PagePanel";
import {ExcelRegisterDialog} from "@/components/dialog/ExcelRegisterDialog";
import {SmsSendDialog} from "@/components/dialog/SmsSendDialog";
import {EmailSendDialog} from "@/components/dialog/EmailSendDialog";
import {DataTable} from "@/components/data-table/DataTable";
import type {DataTableColumn} from "@/components/data-table/DataTable.type";
import {useAssignUserCountsQuery} from "@/query/assign";
import {
useDeleteUserMutation,
useExportUserMutation,
useExportUserTemplateMutation,
useUpdateUserMutation,
useUploadUserExcelMutation,
useUserListQuery,
} from "@/query/user";
import {filterUser, getDetailValue} from "@/lib/kmusical/view";
import {downloadExcelBuffer} from "@/lib/kmusical/file";
import {USER_FIELD_LABELS} from "@/lib/kmusical/field-labels";
import {MONITORING_USER_ROLE} from "@/config/kmusical.config";
import type {UserFull} from "@/types/kmusical";
import {EML_TEMPLATE_IDS, SMS_TEMPLATE_IDS} from "@/query/notification";
import {useDialog} from "@/hooks/useDialog";
import ExcelDownloadButton from "@/components/kmusical/ExcelDownloadButton";
type UserFilters = {keyword: string};
function StopCell({children}: {children: ReactNode}) {
const stop = (event: MouseEvent<HTMLDivElement>) => event.stopPropagation();
return <div onClick={stop}>{children}</div>;
}
const UserPage = () => {
const {data = [], isLoading, refetch: refetchUsers} = useUserListQuery(MONITORING_USER_ROLE);
const {data: assignCounts = [], refetch: refetchCounts} = useAssignUserCountsQuery();
const {isDialogOpen, showDialog, hideDialog} = useDialog();
const [selectedIds, setSelectedIds] = useState<string[]>([]);
const [editingId, setEditingId] = useState<string | null>(null);
const [filters, setFilters] = useState<UserFilters>({keyword: ""});
const [, renderDraft] = useState(0);
const draftRef = useRef<UserFull | null>(null);
const updateMutation = useUpdateUserMutation();
const deleteMutation = useDeleteUserMutation();
const uploadMutation = useUploadUserExcelMutation();
const templateMutation = useExportUserTemplateMutation();
const exportMutation = useExportUserMutation();
const assignCountMap = new Map(assignCounts.map((item) => [item.assignUser, item.assignCount]));
const filteredData = data.filter((user) => filterUser(user, filters));
const smsTargetUsers = data.filter((user) => selectedIds.includes(user.userId));
const refresh = () => {
void refetchUsers();
void refetchCounts();
};
const handleSelectionChange = useCallback((rows: UserFull[]) => {
setSelectedIds(rows.map((row) => row.userId));
}, []);
const updateDraft = (updater: (current: UserFull) => UserFull) => {
if (!draftRef.current) return;
draftRef.current = updater(draftRef.current);
renderDraft((value) => value + 1);
};
const renderDetailCell = (user: UserFull, key: string) => {
const draft = editingId === user.userId ? draftRef.current : null;
const value = getDetailValue(draft?.userDetail ?? user.userDetail, key);
if (!draft) return value || "-";
return (
<StopCell>
<Input value={value} onChange={(event) => updateDraft((current) => ({...current, userDetail: {...current.userDetail, [key]: event.target.value}}))} />
</StopCell>
);
};
const saveUser = async () => {
if (!draftRef.current) return;
await updateMutation.mutateAsync(draftRef.current);
setEditingId(null);
draftRef.current = null;
renderDraft((value) => value + 1);
alert("사용자 정보가 수정되었습니다.");
};
const columns: DataTableColumn<UserFull>[] = [
{accessorKey: "userId", header: USER_FIELD_LABELS.userId},
{accessorKey: "userName", header: USER_FIELD_LABELS.userName},
{id: "assignCount", header: "배정 횟수", accessorFn: (row) => assignCountMap.get(row.userId) ?? 0},
{
id: "cmpn",
header: USER_FIELD_LABELS.userCmpn,
cell: ({row}) => {
const draft = editingId === row.original.userId ? draftRef.current : null;
if (!draft) return row.original.userCmpn || "-";
return (
<StopCell>
<Input value={draft.userCmpn} onChange={(event) => updateDraft((current) => ({...current, userCmpn: event.target.value}))} />
</StopCell>
);
},
},
{id: "grade", header: USER_FIELD_LABELS.userGrade, cell: ({row}) => renderDetailCell(row.original, "userGrade")},
{id: "tel", header: USER_FIELD_LABELS.userTel, cell: ({row}) => renderDetailCell(row.original, "userTel")},
{id: "email", header: USER_FIELD_LABELS.userEmail, cell: ({row}) => renderDetailCell(row.original, "userEmail")},
{
id: "memo",
header: USER_FIELD_LABELS.memo,
cell: ({row}) => editingId === row.original.userId && draftRef.current ? (
<StopCell><Input value={draftRef.current.memo} onChange={(event) => updateDraft((current) => ({...current, memo: event.target.value}))} /></StopCell>
) : row.original.memo,
},
{
id: "actions",
header: "관리",
enableSorting: false,
cell: ({row}) => (
<StopCell>
<div className="flex justify-center gap-1">
{editingId === row.original.userId ? (
<Button type="button" size="sm" onClick={saveUser}>저장</Button>
) : (
<Button type="button" size="sm" variant="outline" onClick={() => { setEditingId(row.original.userId); draftRef.current = {...row.original, userDetail: {...row.original.userDetail}}; renderDraft((value) => value + 1); }}>수정</Button>
)}
<Button
type="button"
size="sm"
variant="destructive"
onClick={async () => {
if (!confirm("사용자를 삭제하시겠습니까?")) return;
await deleteMutation.mutateAsync(row.original.userId);
refresh();
}}
>
삭제
</Button>
</div>
</StopCell>
),
},
];
const downloadTemplate = async () => {
downloadExcelBuffer(await templateMutation.mutateAsync(MONITORING_USER_ROLE), "평가위원 등록 양식.xlsx");
};
const downloadUsers = async () => {
if (filteredData.length === 0) {
alert("다운로드할 사용자가 없습니다.");
return;
}
downloadExcelBuffer(
await exportMutation.mutateAsync({userRole: MONITORING_USER_ROLE, userIds: filteredData.map((user) => user.userId)}),
"평가위원.xlsx"
);
};
return (
<div className="space-y-4">
<PagePanel>
<div className="flex gap-2">
<Input value={filters.keyword} onChange={(event) => setFilters((current) => ({...current, keyword: event.target.value}))} placeholder="ID, 이름, 연락처 또는 이메일" />
<Button type="button" variant="outline" onClick={refresh}><Search className="h-4 w-4" />검색</Button>
</div>
</PagePanel>
<PagePanel className="overflow-x-auto">
<div className="mb-3 flex flex-wrap justify-end gap-2">
<Button type="button" variant="outline" onClick={() => showDialog("userEmailSendDialog")} disabled={selectedIds.length === 0}><Send className="h-4 w-4" />이메일 발송</Button>
<Button type="button" variant="outline" onClick={() => showDialog("userSmsSendDialog")} disabled={selectedIds.length === 0}><Send className="h-4 w-4" />문자 발송</Button>
<Button type="button" onClick={() => showDialog("userExcelRegisterDialog")}><Upload className="h-4 w-4" />평가위원 등록</Button>
<ExcelDownloadButton requestExcelExport={downloadUsers} />
</div>
<DataTable
columns={columns}
data={filteredData}
getRowId={(row) => row.userId}
selectMode="multi"
onRowSelectionChange={handleSelectionChange}
defaultPageSize={50}
disablePagination
maxBodyHeight="65vh"
emptyText={isLoading ? "조회 중입니다." : "조회된 평가위원이 없습니다."}
headerCellClassName="text-base"
bodyCellClassName="text-base"
bodyRowClassName="[&>td]:py-3"
/>
</PagePanel>
<ExcelRegisterDialog
open={isDialogOpen("userExcelRegisterDialog")}
onOpenChange={(open) => open ? showDialog("userExcelRegisterDialog") : hideDialog("userExcelRegisterDialog")}
title="평가위원 등록"
onDownloadTemplate={downloadTemplate}
onUpload={async (file) => {
const formData = new FormData();
formData.append("file", file, file.name);
return uploadMutation.mutateAsync({userRole: MONITORING_USER_ROLE, formData});
}}
isUploading={uploadMutation.isPending}
/>
<EmailSendDialog
open={isDialogOpen("userEmailSendDialog")}
onOpenChange={(open) => open ? showDialog("userEmailSendDialog") : hideDialog("userEmailSendDialog")}
templateIdx={[EML_TEMPLATE_IDS.CUSTOM]}
selectedUsers={smsTargetUsers}
onSent={refresh}
denyParamKeys={["userCmpn", "userTeam", "userRole"]}
/>
<SmsSendDialog
open={isDialogOpen("userSmsSendDialog")}
onOpenChange={(open) => open ? showDialog("userSmsSendDialog") : hideDialog("userSmsSendDialog")}
templateIdx={[SMS_TEMPLATE_IDS.ACCOUNT_MONITORING]}
newMessageTemplateIdx={SMS_TEMPLATE_IDS.CUSTOM}
selectedUsers={smsTargetUsers}
onSent={refresh}
denyParamKeys={["userCmpn", "userTeam", "userRole"]}
/>
</div>
);
};
export default UserPage;

View File

@@ -0,0 +1,112 @@
import {headers} from "next/headers";
import {getFileNameFromContentDisposition} from "@/lib/kmusical/file";
type FilePreviewPageProps = {
searchParams: Promise<{
src?: string;
title?: string;
type?: "pdf" | "image";
images?: string;
}>;
};
const parseImages = (images?: string) => {
if (!images) return [];
try {
const parsed = JSON.parse(images);
return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === "string") : [];
} catch {
return [];
}
};
const isAllowedSrc = (src: string) =>
src.startsWith("/api/review/pdf/") ||
src.startsWith("/api/review/template/pdf/") ||
src.startsWith("/api/file/");
const getAbsoluteSrc = async (src: string) => {
const headersList = await headers();
const host = headersList.get("x-forwarded-host") ?? headersList.get("host");
if (!host) return undefined;
const protocol = headersList.get("x-forwarded-proto") ?? "http";
return new URL(src, `${protocol}://${host}`).toString();
};
const getPdfTitleFromSrc = async (src: string) => {
if (!isAllowedSrc(src)) return undefined;
try {
const headersList = await headers();
const absoluteSrc = await getAbsoluteSrc(src);
if (!absoluteSrc) return undefined;
const response = await fetch(absoluteSrc, {
headers: {
cookie: headersList.get("cookie") ?? "",
},
cache: "no-store",
});
const fileName = getFileNameFromContentDisposition(response.headers.get("content-disposition"));
await response.body?.cancel().catch(() => undefined);
return fileName;
} catch {
return undefined;
}
};
const getTitle = async (paramTitle: string, src: string, type: "image" | "pdf") => {
const defaultTitle = "파일 미리보기";
if(paramTitle) return paramTitle;
if(type === "pdf") return await getPdfTitleFromSrc(src) ?? defaultTitle;
return defaultTitle;
}
export default async function FilePreviewPage({ searchParams }: FilePreviewPageProps) {
const params = await searchParams;
const images = parseImages(params.images);
const type = params.type ?? (images.length > 0 ? "image" : "pdf");
const src = params.src ?? "";
const title = await getTitle(params.title ?? "", src, type) ;
return (
<main className="flex min-h-screen flex-col bg-background text-foreground">
<header className="flex h-14 shrink-0 items-center justify-between border-b border-border bg-card px-4">
<h1 className="truncate text-base font-medium text-foreground">{title}</h1>
</header>
{type === "image" ? (
<div className="grid flex-1 gap-4 overflow-auto p-4 md:grid-cols-2">
{images.filter(isAllowedSrc).map((imageSrc, index) => (
<figure
key={`${imageSrc}-${index}`}
className="rounded-lg border border-border bg-card p-3 shadow-sm"
>
<img
src={imageSrc}
alt={`${title} ${index + 1}`}
className="mx-auto max-h-[80vh] rounded border border-border bg-white object-contain"
/>
<figcaption className="mt-2 truncate text-xs text-muted-foreground">
{decodeURIComponent(imageSrc.split("/").pop() ?? "")}
</figcaption>
</figure>
))}
{images.length === 0 && (
<div className="col-span-full flex min-h-80 items-center justify-center text-sm text-muted-foreground">
미리보기할 이미지가 없습니다.
</div>
)}
</div>
) : isAllowedSrc(src) ? (
<iframe src={src} title={title} className="min-h-0 flex-1 bg-white" />
) : (
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">
미리보기 경로가 올바르지 않습니다.
</div>
)}
</main>
);
}

View File

@@ -0,0 +1,39 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createBackApi } from "@/lib/http-server";
import type { RouteContext } from "@/types/common";
const apiPath = (slug: string[]) => `/assign${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
const toResponse = (result: unknown) => (result === undefined ? new NextResponse(null, { status: 204 }) : NextResponse.json(result));
export async function GET(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const query = Object.fromEntries(request.nextUrl.searchParams.entries());
const serverApi = await createBackApi();
return toResponse(await serverApi.get<unknown>(apiPath(slug), { query }));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function POST(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createBackApi();
const body = await request.json().catch(() => undefined);
return toResponse(await serverApi.post<unknown>(apiPath(slug), body));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function DELETE(_request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createBackApi();
return toResponse(await serverApi.del<unknown>(apiPath(slug)));
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -0,0 +1,16 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createBackApi } from "@/lib/http-server";
import type { RouteContext } from "@/types/common";
const apiPath = (slug: string[]) => `/code${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
export async function GET(_request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createBackApi();
return NextResponse.json(await serverApi.get<unknown>(apiPath(slug)));
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -1,73 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createServerApi } from "@/lib/http-server";
import type { RouteContext } from "@/types/common";
const apiPath = (slug: string[]) => `/example${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
const toResponse = (result: unknown) => result === undefined ? new NextResponse(null, { status: 204 }) : NextResponse.json(result);
export async function GET(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const query = Object.fromEntries(request.nextUrl.searchParams.entries());
const serverApi = await createServerApi();
return toResponse(await serverApi.get<unknown>(apiPath(slug), { query }));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function POST(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
const contentType = request.headers.get("content-type") ?? "";
if (contentType.includes("multipart/form-data")) {
return toResponse(await serverApi.postForm<unknown>(apiPath(slug), await request.formData()));
}
const body = await request.json().catch(() => undefined);
return toResponse(await serverApi.post<unknown>(apiPath(slug), body));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function PUT(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
const contentType = request.headers.get("content-type") ?? "";
if (contentType.includes("multipart/form-data")) {
return toResponse(await serverApi.putForm<unknown>(apiPath(slug), await request.formData()));
}
const body = await request.json().catch(() => undefined);
return toResponse(await serverApi.put<unknown>(apiPath(slug), body));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function PATCH(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
const body = await request.json().catch(() => undefined);
return toResponse(await serverApi.patch<unknown>(apiPath(slug), body));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function DELETE(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
const body = await request.json().catch(() => undefined);
return toResponse(await serverApi.del<unknown>(apiPath(slug), body === undefined ? undefined : { json: body }));
} catch (error: unknown) {
return errorToResponse(error);
}
}
// createHttpClient의 FormData 전용 메서드는 postForm과 putForm입니다.
// PATCH/DELETE multipart가 필요하면 공용 HTTP Client 정책을 확인한 뒤 별도 구현하세요.

View File

@@ -0,0 +1,114 @@
import {NextRequest, NextResponse} from "next/server";
import { errorToResponse } from "@kri/common/http";
import {RouteContext} from "@/types/common";
import {createBackApi} from "@/lib/http-server";
import {Code, PerformanceFull} from "@/types/kmusical";
const ALLOWED_ORIGIN = "https://kon.kric.com";
const corsHeaders = {
"Access-Control-Allow-Origin": ALLOWED_ORIGIN,
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Vary": "Origin",
};
const getRequestOrigin = (req: NextRequest) => {
const origin = req.headers.get("origin");
if (origin) {
return origin;
}
const referer = req.headers.get("referer");
if (!referer) {
return null;
}
try {
return new URL(referer).origin;
} catch {
return null;
}
};
const isAllowedOrigin = (req: NextRequest) => {
return getRequestOrigin(req) === ALLOWED_ORIGIN;
};
const withCors = (response: NextResponse) => {
Object.entries(corsHeaders).forEach(([key, value]) => {
response.headers.set(key, value);
});
return response;
};
export const OPTIONS = async (req: NextRequest) => {
if (!isAllowedOrigin(req)) {
return withCors(NextResponse.json({ message: "Forbidden" }, { status: 403 }));
}
return new NextResponse(null, {
status: 204,
headers: corsHeaders,
});
};
export const POST = async (
req: NextRequest,
context: RouteContext
) => {
try {
if (!isAllowedOrigin(req)) {
return withCors(NextResponse.json({ message: "Forbidden" }, { status: 403 }));
}
const {slug = []} = await context.params;
const [action] = slug;
const backApi = await createBackApi();
if(action === "code" && slug.length === 2) {
const result = await backApi.get<Code[]>(`/code/${encodeURIComponent(slug[1])}`)
return withCors(NextResponse.json(result, { status: 200 }));
}
if(action === "assign-confirm" && slug.length === 3) {
const result = await backApi.post<string>(
`/assign/confirm/${encodeURIComponent(slug[1])}/${encodeURIComponent(slug[2])}`
);
return withCors(NextResponse.json(result, { status: 200 }));
}
if(action === "assign-reject" && slug.length === 3) {
const result = await backApi.post<string>(
`/assign/reject/${encodeURIComponent(slug[1])}/${encodeURIComponent(slug[2])}`
);
return withCors(NextResponse.json(result, { status: 200 }));
}
if(action === "performance" && slug.length === 2) {
const result = await backApi.get<PerformanceFull>(`/performance/${encodeURIComponent(slug[1])}`)
return withCors(NextResponse.json(result, { status: 200 }));
}
if(action === "performance-list") {
const result = await backApi.get<PerformanceFull[]>(`/performance/list`)
return withCors(NextResponse.json(result, { status: 200 }));
}
if (action === "written-review-start" && slug.length === 3) {
await backApi.post<void>(`/review/start/${encodeURIComponent(slug[1])}/${encodeURIComponent(slug[3])}`);
return new NextResponse(null, { status: 204 });
}
if (action === "written-reviewend" && slug.length === 3) {
await backApi.post<void>(`/review/end/${encodeURIComponent(slug[1])}/${encodeURIComponent(slug[2])}`);
return new NextResponse(null, { status: 204 });
}
return withCors(NextResponse.json({ message: "Not found" }, { status: 404 }));
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -3,7 +3,7 @@ import type { LoginRequest, LoginUser } from "@kri/common";
import { errorToResponse } from "@kri/common/http";
import { AUTH_COOKIE_MAX_AGE } from "@/const/common.const";
import { serverEnv } from "@/lib/env.server";
import { createServerApi } from "@/lib/http-server";
import {createBackApi} from "@/lib/http-server";
import { CookieKeys } from "@/store/cookie/cookie-keys";
import type { RouteContext } from "@/types/common";
@@ -12,7 +12,7 @@ type LoginResponse = { accessToken: string; user: LoginUser };
export async function POST(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
const serverApi = await createBackApi();
const body = (await request.json()) as LoginRequest;
const suffix = slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : "";
const result = await serverApi.post<LoginResponse>(`/auth/login${suffix}`, body);

View File

@@ -1,14 +1,14 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { serverEnv } from "@/lib/env.server";
import { createServerApi } from "@/lib/http-server";
import {createBackApi} from "@/lib/http-server";
import { CookieKeys } from "@/store/cookie/cookie-keys";
import type { RouteContext } from "@/types/common";
export async function POST(_request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createServerApi();
const serverApi = await createBackApi();
const suffix = slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : "";
await serverApi.post<boolean>(`/auth/logout${suffix}`);

View File

@@ -0,0 +1,158 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createNotiHubApi } from "@/lib/http-server";
import type { RouteContext } from "@/types/common";
import type {
BulkSendResponse,
EmailDestInfo,
SendEmailBulkRequest,
SendSmsBulkRequest,
SmsDestInfo,
Template,
} from "@/types/notification";
const apiPath = (slug: string[]) => `${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
const toResponse = (result: unknown) =>
result === undefined ? new NextResponse(null, { status: 204 }) : NextResponse.json(result);
type BulkChannel = "sms" | "email";
type BulkRequest = SendSmsBulkRequest | SendEmailBulkRequest;
type Destination = SmsDestInfo | EmailDestInfo;
function containsBlankString(value: unknown): boolean {
if (typeof value === "string") return value.trim().length === 0;
if (Array.isArray(value)) return value.some(containsBlankString);
if (value && typeof value === "object") return Object.values(value).some(containsBlankString);
return false;
}
function isValidDestination(destination: unknown, channel: BulkChannel): destination is Destination {
if (!destination || typeof destination !== "object" || Array.isArray(destination) || containsBlankString(destination)) {
return false;
}
const address = channel === "sms" ? "destTel" : "destEml";
return typeof (destination as Record<string, unknown>)[address] === "string";
}
function isValidBulkRequest(body: unknown, channel: BulkChannel): body is BulkRequest {
if (!body || typeof body !== "object" || Array.isArray(body)) return false;
const request = body as Record<string, unknown>;
return (
typeof request.templateIdx === "number" &&
Number.isInteger(request.templateIdx) &&
request.templateIdx > 0 &&
typeof request.reqstCmpn === "string" &&
request.reqstCmpn.trim().length > 0 &&
typeof request.reqstUser === "string" &&
request.reqstUser.trim().length > 0 &&
typeof request.reqstSvc === "string" &&
request.reqstSvc.trim().length > 0 &&
Array.isArray(request.destinations) &&
request.destinations.length > 0 &&
request.destinations.every((destination) => isValidDestination(destination, channel))
);
}
async function sendBulk(body: BulkRequest, channel: BulkChannel) {
const notiHubApi = await createNotiHubApi();
const template = await notiHubApi.get<Template>(`/template/${body.templateIdx}`);
const bulkSendKey = await notiHubApi.put<string>(`/send-${channel}/create/bulk`, {
reqstCmpn: body.reqstCmpn,
reqstUser: body.reqstUser,
reqstSvc: body.reqstSvc,
prjctCd: template.itrntPrjctCd,
tmplatIdx: template.tmplatIdx,
resve: false,
trgtCnt: body.destinations.length,
});
return notiHubApi.post<BulkSendResponse>(`/send-${channel}/bulk`, {
...(channel === "sms" ? { sendTel: template.sendTel } : { sendEml: template.sendEml }),
sendNm: template.sendNm,
bulkSendKey,
destInfoList: body.destinations,
});
}
export async function GET(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const query = Object.fromEntries(request.nextUrl.searchParams.entries());
const notiHubApi = await createNotiHubApi();
if (slug.length === 3 && slug[0] === "template" && slug[2] === "attachment") {
const buffer = await notiHubApi.get<ArrayBuffer>(apiPath(slug), {query, expectBinary: true});
return new NextResponse(buffer, {headers: {"Content-Type": "application/octet-stream"}});
}
return toResponse(await notiHubApi.get<unknown>(apiPath(slug), { query }));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function POST(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const channel: BulkChannel | undefined =
slug.length === 1 && slug[0] === "sms-bulk"
? "sms"
: slug.length === 1 && slug[0] === "email-bulk"
? "email"
: undefined;
if (channel) {
const body: unknown = await request.json().catch(() => undefined);
if (!isValidBulkRequest(body, channel)) {
const label = channel === "sms" ? "SMS" : "Email";
return NextResponse.json({ message: `${label} request body is invalid.` }, { status: 400 });
}
return toResponse(await sendBulk(body, channel));
}
const notiHubApi = await createNotiHubApi();
const body = await request.json().catch(() => undefined);
return toResponse(await notiHubApi.post<unknown>(apiPath(slug), body));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function PUT(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const notiHubApi = await createNotiHubApi();
const contentType = request.headers.get("content-type") ?? "";
if (contentType.includes("multipart/form-data")) {
return toResponse(await notiHubApi.putForm<unknown>(apiPath(slug), await request.formData()));
}
const body = await request.json().catch(() => undefined);
return toResponse(await notiHubApi.put<unknown>(apiPath(slug), body));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function PATCH(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const notiHubApi = await createNotiHubApi();
const contentType = request.headers.get("content-type") ?? "";
if (contentType.includes("multipart/form-data")) {
const query = new URLSearchParams();
request.nextUrl.searchParams.getAll("deleteFileNames").forEach((name) => query.append("deleteFileNames", name));
const path = query.size ? `${apiPath(slug)}?${query}` : apiPath(slug);
return toResponse(await notiHubApi.patchForm<unknown>(path, await request.formData()));
}
const body = await request.json().catch(() => undefined);
return toResponse(await notiHubApi.patch<unknown>(apiPath(slug), body));
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -0,0 +1,65 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createBackApi, fetchBackBinary } from "@/lib/http-server";
import type { RouteContext } from "@/types/common";
const apiPath = (slug: string[]) => `/performance${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
const toResponse = (result: unknown) => (result === undefined ? new NextResponse(null, { status: 204 }) : NextResponse.json(result));
/*
* excel/download, excel/template은 xlsx 바이너리를 그대로 반환한다.
* excel/upload는 결과를 ExcelUploadResultDto(JSON)로 반환하므로 일반 경로를 탄다.
*/
const isBinaryExcelPath = (slug: string[]) => slug[0] === "excel" && (slug[1] === "download" || slug[1] === "template");
export async function GET(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const query = Object.fromEntries(request.nextUrl.searchParams.entries());
const serverApi = await createBackApi();
return toResponse(await serverApi.get<unknown>(apiPath(slug), { query }));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function POST(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
if (isBinaryExcelPath(slug)) {
const body = await request.json().catch(() => undefined);
return await fetchBackBinary(apiPath(slug), {
method: "POST",
headers: body !== undefined ? { "content-type": "application/json" } : undefined,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
}
const serverApi = await createBackApi();
return toResponse(await serverApi.postForm<unknown>(apiPath(slug), await request.formData()));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function PATCH(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createBackApi();
const body = await request.json().catch(() => undefined);
return toResponse(await serverApi.patch<unknown>(apiPath(slug), body));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function DELETE(_request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createBackApi();
return toResponse(await serverApi.del<unknown>(apiPath(slug)));
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createBackApi, fetchBackBinary } from "@/lib/http-server";
import type { RouteContext } from "@/types/common";
const apiPath = (slug: string[]) => `/review${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
const toResponse = (result: unknown) => (result === undefined ? new NextResponse(null, { status: 204 }) : NextResponse.json(result));
/*
* download/{id}/{slot}, pdf/{id}/{slot}, template/download/{type}, template/pdf/{type}는
* 파일 바이너리를 그대로 반환한다.
*/
const BINARY_GET_PREFIXES = ["download", "pdf", "template"];
const isBinaryGetPath = (slug: string[]) => BINARY_GET_PREFIXES.includes(slug[0]);
export async function GET(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
if (isBinaryGetPath(slug)) {
const response = await fetchBackBinary(apiPath(slug));
if (slug[0] === "pdf" && request.nextUrl.searchParams.get("inline") === "true") {
const disposition = response.headers.get("content-disposition");
response.headers.set("content-type", "application/pdf");
response.headers.set("content-disposition", disposition ? disposition.replace(/^[^;]+/, "inline") : "inline");
}
return response;
}
const query = Object.fromEntries(request.nextUrl.searchParams.entries());
const serverApi = await createBackApi();
return toResponse(await serverApi.get<unknown>(apiPath(slug), { query }));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function POST(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const query = Object.fromEntries(request.nextUrl.searchParams.entries());
const serverApi = await createBackApi();
return toResponse(await serverApi.postForm<unknown>(apiPath(slug), await request.formData(), { query }));
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -0,0 +1,65 @@
import { NextRequest, NextResponse } from "next/server";
import { errorToResponse } from "@kri/common/http";
import { createBackApi, fetchBackBinary } from "@/lib/http-server";
import type { RouteContext } from "@/types/common";
const apiPath = (slug: string[]) => `/user${slug.length ? `/${slug.map(encodeURIComponent).join("/")}` : ""}`;
const toResponse = (result: unknown) => (result === undefined ? new NextResponse(null, { status: 204 }) : NextResponse.json(result));
/*
* excel/download, excel/template은 xlsx 바이너리를 그대로 반환한다.
* excel/upload는 결과를 ExcelUploadResultDto(JSON)로 반환하므로 일반 경로를 탄다.
*/
const isBinaryExcelPath = (slug: string[]) => slug[0] === "excel" && (slug[1] === "download" || slug[1] === "template");
export async function GET(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const query = Object.fromEntries(request.nextUrl.searchParams.entries());
const serverApi = await createBackApi();
return toResponse(await serverApi.get<unknown>(apiPath(slug), { query }));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function POST(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
if (isBinaryExcelPath(slug)) {
const body = await request.json().catch(() => undefined);
return await fetchBackBinary(apiPath(slug), {
method: "POST",
headers: body !== undefined ? { "content-type": "application/json" } : undefined,
body: body !== undefined ? JSON.stringify(body) : undefined,
});
}
const serverApi = await createBackApi();
return toResponse(await serverApi.postForm<unknown>(apiPath(slug), await request.formData()));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function PATCH(request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createBackApi();
const body = await request.json().catch(() => undefined);
return toResponse(await serverApi.patch<unknown>(apiPath(slug), body));
} catch (error: unknown) {
return errorToResponse(error);
}
}
export async function DELETE(_request: NextRequest, context: RouteContext) {
try {
const { slug = [] } = await context.params;
const serverApi = await createBackApi();
return toResponse(await serverApi.del<unknown>(apiPath(slug)));
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -48,6 +48,53 @@
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: #8ca529;
--kmf-gray: #e7e6e6;
--kmf-black: #1a1a1a;
--status-pending: #d1d5db;
--status-pending-bg: #f3f4f6;
--status-pending-fg: #4b5563;
--status-inprogress: #93c5fd;
--status-inprogress-bg: #eff6ff;
--status-inprogress-fg: #1d4ed8;
--status-departed: #fdba74;
--status-departed-bg: #fff7ed;
--status-departed-fg: #c2410c;
--status-arrived: #a5b4fc;
--status-arrived-bg: #eef2ff;
--status-arrived-fg: #4338ca;
--status-done: var(--primary);
--status-done-bg: var(--accent);
--status-done-fg: var(--accent-foreground);
--status-danger: #fca5a5;
--status-danger-bg: #fef2f2;
--status-danger-fg: #b91c1c;
--series-1: #2a78d6;
--series-1-bg: #eff6ff;
--series-1-fg: #1d4ed8;
--series-2: #1baf7a;
--series-2-bg: #ecfdf5;
--series-2-fg: #047857;
--series-3: #eda100;
--series-3-bg: #fffbeb;
--series-3-fg: #92400e;
--series-4: #008300;
--series-4-bg: #f0fdf4;
--series-4-fg: #15803d;
--series-5: #4a3aa7;
--series-5-bg: #f5f3ff;
--series-5-fg: #5b21b6;
--series-6: #e34948;
--series-6-bg: #fef2f2;
--series-6-fg: #b91c1c;
--series-7: #e87ba4;
--series-7-bg: #fdf2f8;
--series-7-fg: #9d174d;
--series-8: #eb6834;
--series-8-bg: #fff7ed;
--series-8-fg: #9a3412;
}
.dark {
@@ -58,7 +105,7 @@
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: #9db63b;
--primary-foreground: #1a2408;
--primary-foreground: #fdfbf3;
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
@@ -69,6 +116,50 @@
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: #9db63b;
--status-pending: oklch(1 0 0 / 25%);
--status-pending-bg: oklch(1 0 0 / 10%);
--status-pending-fg: oklch(0.85 0 0);
--status-inprogress: #1e40af;
--status-inprogress-bg: oklch(0.28 0.06 255);
--status-inprogress-fg: #93c5fd;
--status-departed: #9a3412;
--status-departed-bg: oklch(0.28 0.06 55);
--status-departed-fg: #fdba74;
--status-arrived: #3730a3;
--status-arrived-bg: oklch(0.28 0.06 285);
--status-arrived-fg: #a5b4fc;
--status-done: var(--primary);
--status-done-bg: var(--accent);
--status-done-fg: var(--accent-foreground);
--status-danger: #7f1d1d;
--status-danger-bg: oklch(0.28 0.06 25);
--status-danger-fg: #fca5a5;
--series-1: #3987e5;
--series-1-bg: oklch(0.28 0.06 255);
--series-1-fg: #93c5fd;
--series-2: #199e70;
--series-2-bg: oklch(0.28 0.06 195);
--series-2-fg: #5eead4;
--series-3: #c98500;
--series-3-bg: oklch(0.28 0.06 85);
--series-3-fg: #fcd34d;
--series-4: #008300;
--series-4-bg: oklch(0.28 0.06 160);
--series-4-fg: #6ee7b7;
--series-5: #9085e9;
--series-5-bg: oklch(0.28 0.06 300);
--series-5-fg: #c4b5fd;
--series-6: #e66767;
--series-6-bg: oklch(0.28 0.06 25);
--series-6-fg: #fca5a5;
--series-7: #d55181;
--series-7-bg: oklch(0.28 0.06 350);
--series-7-fg: #f9a8d4;
--series-8: #d95926;
--series-8-bg: oklch(0.28 0.06 55);
--series-8-fg: #fdba74;
}
@layer base {
@@ -85,3 +176,175 @@
.ProseMirror [data-resize-handle="bottom-left"] { left: -5px; bottom: -5px; cursor: sw-resize !important; }
.ProseMirror [data-resize-handle="top-right"] { right: -5px; top: -5px; cursor: ne-resize !important; }
.ProseMirror [data-resize-handle="top-left"] { left: -5px; top: -5px; cursor: nw-resize !important; }
/* =============================
KMF Components
(Table / Category Card / Status Badge)
============================= */
@layer components {
.kmf-table {
width: 100%;
min-width: 980px;
border-collapse: collapse;
table-layout: fixed;
background-color: #fff;
}
.kmf-table tbody,
.kmf-table tr {
background-color: #fff;
}
.kmf-table th,
.kmf-table td {
background-color: inherit;
padding: 6px 12px;
font-size: 13px;
line-height: 1.15;
text-align: center;
word-wrap: break-word;
word-break: auto-phrase;
}
.kmf-table tbody th,
.kmf-table tbody td {
padding: 6px 12px;
}
.kmf-table thead th.kmf-table-border-none,
.kmf-table thead td.kmf-table-border-none {
background: transparent !important;
}
.kmf-table thead th.kmf-table-blank-head,
.kmf-table thead td.kmf-table-blank-head {
background: var(--background) !important;
}
.kmf-table thead tr.kmf-table__group th,
.kmf-table thead tr.kmf-table__group th {
background-color: var(--kmf-gray);
color: var(--kmf-black);
font-weight: 700;
}
.kmf-table thead tr.kmf-table__subhead th,
.kmf-table thead tr.kmf-table__subhead th {
background-color: var(--primary);
color: var(--kmf-black);
font-weight: 700;
}
.kmf-table tbody th.kmf-table__rowhead {
text-align: left;
font-weight: 700;
color: var(--foreground);
background-color: inherit;
word-wrap: break-word;
word-break: auto-phrase;
}
.kmf-table tbody td.kmf-table__section-row {
padding: 7px 12px;
color: var(--kmf-black);
}
.kmf-detail-table {
--kmf-detail-table-head-height: 56px;
}
.kmf-detail-rank-table {
--kmf-detail-table-row-height: 56px;
min-width: 285px !important;
}
.kmf-detail-table thead tr,
.kmf-detail-table thead th {
height: var(--kmf-detail-table-head-height);
}
.kmf-detail-table tbody th,
.kmf-detail-table tbody td {
vertical-align: middle;
height: var(--kmf-detail-table-row-height);
}
.kmf-category-card {
position: relative;
background-color: var(--card);
border: 1px solid var(--border);
border-radius: var(--radius-md);
padding: 16px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
.kmf-category-card__label {
position: absolute;
top: -14px;
left: 16px;
background: var(--primary);
color: var(--primary-foreground);
padding: 4px 14px;
border-radius: 9999px;
font-weight: 700;
font-size: 12px;
letter-spacing: -0.02em;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
}
/* Status Badge - usage: <span class="kmf-status-badge kmf-status-badge--done">완료</span> */
.kmf-status-badge {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 2px 10px;
border-radius: 9999px;
font-size: 12px;
font-weight: 700;
letter-spacing: -0.01em;
border: 1px solid transparent;
white-space: nowrap;
}
/* 미진행 */
.kmf-status-badge--pending {
background-color: var(--status-pending-bg);
color: var(--status-pending-fg);
border-color: var(--status-pending);
}
/* 진행중 */
.kmf-status-badge--inprogress {
background-color: var(--status-inprogress-bg);
color: var(--status-inprogress-fg);
border-color: var(--status-inprogress);
}
/* 출발 */
.kmf-status-badge--departed {
background-color: var(--status-departed-bg);
color: var(--status-departed-fg);
border-color: var(--status-departed);
}
/* 도착 */
.kmf-status-badge--arrived {
background-color: var(--status-arrived-bg);
color: var(--status-arrived-fg);
border-color: var(--status-arrived);
}
/* 완료 */
.kmf-status-badge--done {
background-color: var(--status-done-bg);
color: var(--status-done-fg);
border-color: var(--status-done);
}
/* 미배치 등 위험/경고 */
.kmf-status-badge--danger {
background-color: var(--status-danger-bg);
color: var(--status-danger-fg);
border-color: var(--status-danger);
}
}

View File

@@ -4,28 +4,38 @@ import Image from "next/image";
import { LogOut } from "lucide-react";
import { Button } from "@/components/ui/button";
import { KriHeader } from "@/components/layout/KriHeader";
import { topMenus } from "@/config/menu.data";
import type { LoginUser } from "@kri/common";
import {TOP_MENUS} from "@/config/menu.data";
import {SITE_TITLE} from "@/config/common.config";
interface AppHeaderProps {
menuOpen: boolean;
showMenuButton: boolean;
activeMenuId?: string;
user?: LoginUser | null;
isMonitoring?: boolean;
onToggleMenu: () => void;
onNavigate: (path: string) => void;
}
export function AppHeader({ menuOpen, showMenuButton, activeMenuId, user, onToggleMenu, onNavigate }: AppHeaderProps) {
export function AppHeader({ menuOpen, showMenuButton, activeMenuId, user, isMonitoring, onToggleMenu, onNavigate }: AppHeaderProps) {
const siteTitle = (
<div
className="pointer-events-none absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 hidden sm:inline">
<h1 className="font-bold text-2xl text-header-color text-center whitespace-nowrap">{SITE_TITLE}</h1>
</div>
)
return (
<KriHeader
logo={<Image src="/logo.svg" alt="로고" width={120} height={40} className="h-10 w-auto object-contain" priority />}
menus={topMenus}
menus={isMonitoring? undefined : TOP_MENUS}
activeMenuId={activeMenuId}
menuOpen={menuOpen}
showMenuButton={showMenuButton}
onToggleMenu={onToggleMenu}
onNavigate={onNavigate}
center={siteTitle}
right={
<>
<span className="hidden text-sm text-muted-foreground sm:inline">{user?.userName ?? ""}</span>

View File

@@ -5,39 +5,38 @@ import { useMemo, useState, type ReactNode } from "react";
import { usePathname, useRouter } from "next/navigation";
import { KriMainLayout } from "@/components/layout/KriMainLayout";
import { AppHeader } from "./AppHeader";
import { AppSidebar } from "./AppSidebar";
import { sideMenus, topMenus } from "@/config/menu.data";
import { TOP_MENUS } from "@/config/menu.data";
import { useAuth } from "@/hooks/useAuth";
export function AppMainLayout({ children }: { children: ReactNode }) {
const pathname = usePathname();
const router = useRouter();
const { auth } = useAuth();
const { auth, isMonitoring } = useAuth();
const [menuOpen, setMenuOpen] = useState(true);
const activeMenuId = useMemo(
() => topMenus.find((item) => item.path && (pathname === item.path || pathname.startsWith(`${item.path}/`)))?.id,
() => TOP_MENUS.find((item) => item.path && (pathname === item.path || pathname.startsWith(`${item.path}/`)))?.id,
[pathname],
);
const navigate = (path: string) => router.push(path as Route);
const hasSidebar = sideMenus.length > 0;
return (
<KriMainLayout
sidebarOpen={hasSidebar && menuOpen}
sidebarOpen={false}
onSidebarOpenChange={setMenuOpen}
header={
<AppHeader
menuOpen={menuOpen}
showMenuButton={hasSidebar}
showMenuButton={false}
activeMenuId={activeMenuId}
user={auth.user}
isMonitoring={isMonitoring}
onToggleMenu={() => setMenuOpen((current) => !current)}
onNavigate={navigate}
/>
}
sidebar={hasSidebar ? <AppSidebar items={sideMenus} isOpen={menuOpen} pathname={pathname} onNavigate={navigate} /> : undefined}
>
{children}
</KriMainLayout>

View File

@@ -33,6 +33,9 @@ export function DataTable<TData, TValue = unknown>({
paginationItemsToDisplay = 5,
emptyText = '데이터가 없습니다.',
className,
headerCellClassName,
bodyCellClassName,
bodyRowClassName,
maxBodyHeight,
disablePagination = false,
topPinnedRows = EMPTY_PINNED_ROWS,
@@ -203,7 +206,7 @@ export function DataTable<TData, TValue = unknown>({
className={cn('relative w-full overflow-x-auto', maxBodyHeight && 'overflow-y-auto')}
style={maxBodyHeight ? { maxHeight: maxBodyHeight } : undefined}
>
<table className="w-full caption-bottom text-sm">
<table className="kmf-table w-full caption-bottom text-sm">
<TableHeader className={cn(maxBodyHeight && 'sticky top-0 z-20 bg-background')}>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="hover:bg-transparent">
@@ -215,11 +218,11 @@ export function DataTable<TData, TValue = unknown>({
return (
<TableHead
key={header.id}
className={cn('text-base font-semibold text-foreground', column.id === 'actions' && 'w-[140px] text-center')}
className={cn('font-semibold !text-center text-foreground', column.id === 'actions' && 'w-[140px]', headerCellClassName)}
style={{ width: header.getSize() !== 150 ? header.getSize() : undefined }}
>
{!header.isPlaceholder && column.getCanSort() ? (
<Button type="button" variant="ghost" className="flex gap-1 px-0 text-base font-semibold" onClick={column.getToggleSortingHandler()}>
<Button type="button" variant="ghost" className="flex gap-1 px-0 font-semibold" onClick={column.getToggleSortingHandler()}>
<span>{content}</span>
{sorted === 'asc' ? <ArrowUp className="size-3" /> : sorted === 'desc' ? <ArrowDown className="size-3" /> : <ArrowUpDown className="text-muted-foreground size-3" />}
</Button>
@@ -240,7 +243,7 @@ export function DataTable<TData, TValue = unknown>({
)}
style={maxBodyHeight ? { top: topOffsets[index] ?? 0 } : undefined}
>
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
{row.getVisibleCells().map((cell) => <TableCell key={cell.id} className={cn('text-center whitespace-normal break-words', bodyCellClassName)}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
</TableRow>
))}
{centerRows.length ? centerRows.map((row) => (
@@ -257,9 +260,10 @@ export function DataTable<TData, TValue = unknown>({
selectMode !== 'none' && 'cursor-pointer',
'data-[state=selected]:bg-muted data-[state=selected]:font-semibold',
highlightRowIds?.includes(row.id) && 'bg-emerald-50',
bodyRowClassName,
)}
>
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
{row.getVisibleCells().map((cell) => <TableCell key={cell.id} className={cn('text-center whitespace-normal break-words', bodyCellClassName)}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
</TableRow>
)) : (
<TableRow><TableCell colSpan={enhancedColumns.length} className="h-24 text-center">{emptyText}</TableCell></TableRow>
@@ -273,7 +277,7 @@ export function DataTable<TData, TValue = unknown>({
)}
style={maxBodyHeight ? { bottom: bottomOffsets[index] ?? 0 } : undefined}
>
{row.getVisibleCells().map((cell) => <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
{row.getVisibleCells().map((cell) => <TableCell key={cell.id} className={cn('text-center whitespace-normal break-words', bodyCellClassName)}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>)}
</TableRow>
))}
</TableBody>

View File

@@ -34,6 +34,9 @@ export interface DataTableProps<TData, TValue = unknown> {
paginationItemsToDisplay?: number
emptyText?: string
className?: string
headerCellClassName?: string
bodyCellClassName?: string
bodyRowClassName?: string
maxBodyHeight?: string
disablePagination?: boolean
topPinnedRows?: TData[]

View File

@@ -0,0 +1,508 @@
"use client";
import {useEffect, useState} from "react";
import {Check, ChevronLeft, ChevronRight} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {Checkbox} from "@/components/ui/checkbox";
import {Dialog, DialogContent, DialogHeader, DialogTitle} from "@/components/ui/dialog";
import {Popover, PopoverContent, PopoverTrigger} from "@/components/ui/popover";
import {Tooltip, TooltipContent, TooltipProvider, TooltipTrigger} from "@/components/ui/tooltip";
import {KriMultiSelect} from "@/components/common/KriAutoComplete";
import {StatusPill} from "@/components/kmusical/StatusPill";
import {useAllMonitoringApplyUsersQuery} from "@/query/assign";
import {getDetailValue, includesText} from "@/lib/kmusical/view";
import {
buildMonthGrid,
chunkIntoWeeks,
getPerformanceBadgeInfo,
getPerformanceColorSlot,
getVisiblePerformances,
groupPerformancesByDate,
WEEKDAY_LABELS,
type PerformanceBadgeInfo,
} from "@/lib/kmusical/assignment-calendar";
import {
REVIEW_TYPE,
type MonitoringApplyUser,
type PerformanceFull,
type PerformanceReviewSlot,
type ReviewType,
type UserCompact,
type UserFull,
} from "@/types/kmusical";
type DetailTab = "application" | "monitoring" | "consulting";
const DETAIL_TABS: ReadonlyArray<{id: DetailTab; label: string}> = [
{id: "application", label: "신청"},
{id: "monitoring", label: "현장 모니터링"},
{id: "consulting", label: "컨설팅"},
];
const MAX_BADGES_PER_DAY = 3;
const PERFORMANCE_BADGE_COLOR_CLASSES = [
"border-[var(--series-1)] bg-[var(--series-1-bg)] text-[var(--series-1-fg)]",
"border-[var(--series-2)] bg-[var(--series-2-bg)] text-[var(--series-2-fg)]",
"border-[var(--series-3)] bg-[var(--series-3-bg)] text-[var(--series-3-fg)]",
"border-[var(--series-4)] bg-[var(--series-4-bg)] text-[var(--series-4-fg)]",
"border-[var(--series-5)] bg-[var(--series-5-bg)] text-[var(--series-5-fg)]",
"border-[var(--series-6)] bg-[var(--series-6-bg)] text-[var(--series-6-fg)]",
"border-[var(--series-7)] bg-[var(--series-7-bg)] text-[var(--series-7-fg)]",
"border-[var(--series-8)] bg-[var(--series-8-bg)] text-[var(--series-8-fg)]",
] as const;
const PERFORMANCE_DOT_COLOR_CLASSES = [
"bg-[var(--series-1)]",
"bg-[var(--series-2)]",
"bg-[var(--series-3)]",
"bg-[var(--series-4)]",
"bg-[var(--series-5)]",
"bg-[var(--series-6)]",
"bg-[var(--series-7)]",
"bg-[var(--series-8)]",
] as const;
const getWeekdayTextClassName = (dayOfWeek: number) => {
if (dayOfWeek === 0) return "text-[#e34948] dark:text-[#e66767]";
if (dayOfWeek === 6) return "text-[#2a78d6] dark:text-[#3987e5]";
return "";
};
const getAssignedUserNames = (
performance: PerformanceFull,
reviewSlots: PerformanceReviewSlot[],
reviewType: ReviewType,
userById: Map<string, UserFull | UserCompact>
): string[] => {
const slotNumbers = new Set(reviewSlots.filter((slot) => slot.reviewType === reviewType).map((slot) => slot.reviewSlot));
return performance.performanceAssignList
.filter((assign) => slotNumbers.has(assign.reviewSlot))
.map((assign) => userById.get(assign.assignUser)?.userName || assign.assignUser);
};
export function AssignCalendarDialog({
open,
onOpenChange,
performances,
applyCountMap,
reviewSlots,
reviewers,
}: Readonly<{
open: boolean;
onOpenChange: (open: boolean) => void;
performances: PerformanceFull[];
applyCountMap: Map<string, number>;
reviewSlots: PerformanceReviewSlot[];
reviewers: UserFull[];
}>) {
const [visibleMonth, setVisibleMonth] = useState(() => new Date());
const [performanceSearch, setPerformanceSearch] = useState("");
const [selectedPerformanceIds, setSelectedPerformanceIds] = useState<Set<string>>(new Set());
const [selectedReviewerIds, setSelectedReviewerIds] = useState<string[]>([]);
const [selectedDetailPerformanceId, setSelectedDetailPerformanceId] = useState<string | null>(null);
const [activeDetailTab, setActiveDetailTab] = useState<DetailTab>("application");
const [expandedDayKey, setExpandedDayKey] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
setPerformanceSearch("");
setSelectedReviewerIds([]);
setSelectedDetailPerformanceId(null);
setActiveDetailTab("application");
setVisibleMonth(new Date());
setSelectedPerformanceIds(new Set(performances.map((performance) => performance.performanceId)));
// 다이얼로그를 다시 열 때마다 필터를 초기화한다. open 시점의 공연 목록만 반영하면 되므로 performances는 의도적으로 의존성에서 제외한다.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
useEffect(() => {
if (!open) return;
setSelectedPerformanceIds((current) => {
const validIds = new Set(performances.map((performance) => performance.performanceId));
const next = new Set(Array.from(current).filter((id) => validIds.has(id)));
return next.size === current.size ? current : next;
});
}, [open, performances]);
const visiblePerformances = getVisiblePerformances(performances, selectedPerformanceIds, selectedReviewerIds);
useEffect(() => {
if (selectedDetailPerformanceId == null) return;
const stillVisible = visiblePerformances.some((performance) => performance.performanceId === selectedDetailPerformanceId);
if (!stillVisible) setSelectedDetailPerformanceId(null);
}, [visiblePerformances, selectedDetailPerformanceId]);
const performancesByDate = groupPerformancesByDate(visiblePerformances);
const monthDays = buildMonthGrid(visibleMonth);
const detailPerformance = performances.find((performance) => performance.performanceId === selectedDetailPerformanceId) ?? null;
const {
data: allApplyUsers = [],
isLoading: isAllApplyLoading,
isError: isAllApplyError,
refetch: refetchAllApplyUsers,
} = useAllMonitoringApplyUsersQuery(open);
const applyUsersByPerformanceId = new Map<string, MonitoringApplyUser[]>();
for (const applyUser of allApplyUsers) {
const list = applyUsersByPerformanceId.get(applyUser.performanceId) ?? [];
list.push(applyUser);
applyUsersByPerformanceId.set(applyUser.performanceId, list);
}
const detailApplyUsers = detailPerformance ? applyUsersByPerformanceId.get(detailPerformance.performanceId) ?? [] : [];
const orderedPerformanceIds = performances.map((performance) => performance.performanceId);
const searchedPerformances = performances.filter((performance) => includesText(performance.performanceName, performanceSearch));
const allSelected = performances.length > 0 && selectedPerformanceIds.size === performances.length;
const togglePerformance = (performanceId: string) => {
setSelectedPerformanceIds((current) => {
const next = new Set(current);
if (next.has(performanceId)) next.delete(performanceId); else next.add(performanceId);
return next;
});
};
const toggleSelectAll = () => {
setSelectedPerformanceIds(allSelected ? new Set() : new Set(performances.map((performance) => performance.performanceId)));
};
const changeMonth = (offset: number) => {
setVisibleMonth((current) => new Date(current.getFullYear(), current.getMonth() + offset, 1));
};
const closeDetail = () => setSelectedDetailPerformanceId(null);
const userById = new Map<string, UserFull | UserCompact>([
...reviewers.map((user) => [user.userId, user] as const),
...detailApplyUsers.map((item) => [item.userId, item.user] as const),
]);
const assignedUserIds = new Set((detailPerformance?.performanceAssignList ?? []).map((assign) => assign.assignUser));
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex h-[min(760px,85vh)] max-h-[85vh] flex-col overflow-hidden sm:max-w-[min(112rem,95vw)]">
<DialogHeader className="shrink-0">
<DialogTitle>배정 현황 캘린더</DialogTitle>
</DialogHeader>
<div className={`grid min-h-0 flex-1 gap-4 overflow-hidden ${detailPerformance ? "lg:grid-cols-[300px_1fr_340px]" : "lg:grid-cols-[300px_1fr]"}`}>
<section className="flex min-h-0 flex-col gap-2 overflow-hidden rounded-md border p-3">
<Input
value={performanceSearch}
onChange={(event) => setPerformanceSearch(event.target.value)}
placeholder="작품명 검색"
/>
<label className="flex items-center gap-2 border-b pb-2 text-sm font-medium">
<Checkbox checked={allSelected} onCheckedChange={toggleSelectAll} />
전체 선택
</label>
<div className="min-h-0 flex-1 space-y-1 overflow-y-auto">
{searchedPerformances.length === 0 ? (
<div className="py-4 text-center text-sm text-muted-foreground">검색 결과가 없습니다.</div>
) : searchedPerformances.map((performance) => (
<label key={performance.performanceId} className="flex items-start gap-2 rounded px-1 py-1 text-sm hover:bg-muted">
<Checkbox
checked={selectedPerformanceIds.has(performance.performanceId)}
onCheckedChange={() => togglePerformance(performance.performanceId)}
/>
<span
className={`mt-1 size-2.5 shrink-0 rounded-full ${PERFORMANCE_DOT_COLOR_CLASSES[getPerformanceColorSlot(performance.performanceId, orderedPerformanceIds)]}`}
aria-hidden="true"
/>
<span className="min-w-0">
<span className="block truncate" title={performance.performanceName}>{performance.performanceName}</span>
<span className="block truncate text-xs text-muted-foreground">{performance.performanceId}</span>
</span>
</label>
))}
</div>
</section>
<section className="flex min-h-0 flex-col overflow-hidden rounded-md border">
<div className="flex shrink-0 items-center justify-between gap-2 border-b p-3">
<div className="flex items-center gap-1">
<Button type="button" variant="outline" size="icon-sm" aria-label="이전 달" onClick={() => changeMonth(-1)}>
<ChevronLeft className="h-4 w-4" />
</Button>
<div className="w-28 text-center font-semibold">{visibleMonth.getFullYear()}년 {visibleMonth.getMonth() + 1}월</div>
<Button type="button" variant="outline" size="icon-sm" aria-label="다음 달" onClick={() => changeMonth(1)}>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
<KriMultiSelect<UserFull>
items={reviewers}
value={selectedReviewerIds}
onChange={setSelectedReviewerIds}
getValue={(user) => user.userId}
getLabel={(user) => user.userName || user.userId}
placeholder="전체 평가위원"
widthClassName="w-64"
/>
</div>
{selectedPerformanceIds.size === 0 ? (
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">선택된 작품이 없습니다.</div>
) : visiblePerformances.length === 0 ? (
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">조건에 맞는 배정 일정이 없습니다.</div>
) : (
<TooltipProvider delayDuration={200}>
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto">
<div className="flex shrink-0">
{WEEKDAY_LABELS.map((label, index) => (
<div key={label} className={`flex-1 border-b bg-muted px-2 py-1 text-center text-xs font-medium ${getWeekdayTextClassName(index) || "text-muted-foreground"}`}>{label}</div>
))}
</div>
{chunkIntoWeeks(monthDays).map((week) => (
<div key={week[0].dateKey} className="flex">
{week.map((day) => {
const dayPerformances = performancesByDate.get(day.dateKey) ?? [];
const visibleBadges = dayPerformances.slice(0, MAX_BADGES_PER_DAY);
const overflowCount = dayPerformances.length - visibleBadges.length;
const weekdayClassName = getWeekdayTextClassName(day.date.getDay());
return (
<div
key={day.dateKey}
className={`min-h-24 flex-1 border-b border-r p-1 ${day.isCurrentMonth ? "" : "bg-muted/30 text-muted-foreground"}`}
>
<div className={`mb-1 text-xs ${day.isToday ? "font-bold text-primary" : weekdayClassName}`}>{day.date.getDate()}</div>
<div className="space-y-1">
{visibleBadges.map((performance) => (
<PerformanceBadge
key={performance.performanceId}
performance={performance}
badgeInfo={getPerformanceBadgeInfo(performance, applyCountMap, reviewSlots)}
colorClassName={PERFORMANCE_BADGE_COLOR_CLASSES[getPerformanceColorSlot(performance.performanceId, orderedPerformanceIds)]}
reviewSlots={reviewSlots}
userById={userById}
applyUsers={applyUsersByPerformanceId.get(performance.performanceId) ?? []}
onClick={() => setSelectedDetailPerformanceId(performance.performanceId)}
/>
))}
{overflowCount > 0 && (
<Popover
open={expandedDayKey === day.dateKey}
onOpenChange={(next) => setExpandedDayKey(next ? day.dateKey : null)}
>
<PopoverTrigger asChild>
<button type="button" className="w-full rounded px-1 py-0.5 text-left text-xs text-primary hover:underline">
외 {overflowCount}건
</button>
</PopoverTrigger>
<PopoverContent className="w-64 space-y-1">
{dayPerformances.map((performance) => (
<PerformanceBadge
key={performance.performanceId}
performance={performance}
badgeInfo={getPerformanceBadgeInfo(performance, applyCountMap, reviewSlots)}
colorClassName={PERFORMANCE_BADGE_COLOR_CLASSES[getPerformanceColorSlot(performance.performanceId, orderedPerformanceIds)]}
reviewSlots={reviewSlots}
userById={userById}
applyUsers={applyUsersByPerformanceId.get(performance.performanceId) ?? []}
onClick={() => {
setExpandedDayKey(null);
setSelectedDetailPerformanceId(performance.performanceId);
}}
/>
))}
</PopoverContent>
</Popover>
)}
</div>
</div>
);
})}
</div>
))}
</div>
</TooltipProvider>
)}
</section>
{detailPerformance && (
<section className="flex min-h-0 flex-col overflow-hidden rounded-md border">
<div className="flex shrink-0 items-start justify-between gap-2 border-b p-3">
<div className="min-w-0">
<div className="truncate font-semibold" title={detailPerformance.performanceName}>{detailPerformance.performanceName}</div>
<div className="text-xs text-muted-foreground">
{detailPerformance.performanceMonitoringSchedule?.monitoringDate || "-"}
</div>
</div>
<Button type="button" variant="ghost" size="sm" onClick={closeDetail}>닫기</Button>
</div>
<div role="tablist" aria-label="배정 상세" className="flex shrink-0 gap-1 border-b px-2">
{DETAIL_TABS.map((tab) => (
<button
key={tab.id}
type="button"
role="tab"
aria-selected={activeDetailTab === tab.id}
className={`cursor-pointer border-b-2 px-3 py-2 text-sm font-medium ${activeDetailTab === tab.id ? "border-primary text-foreground" : "border-transparent text-muted-foreground"}`}
onClick={() => setActiveDetailTab(tab.id)}
>
{tab.label}
</button>
))}
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-3">
{activeDetailTab === "application" && (
isAllApplyLoading ? (
<div className="py-6 text-center text-sm text-muted-foreground">조회 중입니다.</div>
) : isAllApplyError ? (
<div className="space-y-2 py-6 text-center text-sm text-muted-foreground">
<div>신청자 정보를 불러오지 못했습니다.</div>
<Button type="button" variant="outline" size="sm" onClick={() => refetchAllApplyUsers()}>다시 시도</Button>
</div>
) : detailApplyUsers.length === 0 ? (
<div className="py-6 text-center text-sm text-muted-foreground">신청자가 없습니다.</div>
) : (
<div className="space-y-2">
{detailApplyUsers.map((applyUser) => (
<div key={applyUser.userId} className="flex items-center justify-between gap-2 rounded border p-2 text-sm">
<div className="min-w-0">
<div className="truncate font-medium">{applyUser.user.userName || applyUser.userId}</div>
<div className="truncate text-xs text-muted-foreground">{applyUser.userId}</div>
<div className="truncate text-xs text-muted-foreground">
{getDetailValue(applyUser.user.userDetail, "userArea", "-")} · {getDetailValue(applyUser.user.userDetail, "userTel", "-")}
</div>
</div>
{assignedUserIds.has(applyUser.userId) ? (
<StatusPill variant="done">확정</StatusPill>
) : (
<StatusPill variant="pending">신청</StatusPill>
)}
</div>
))}
</div>
)
)}
{(activeDetailTab === "monitoring" || activeDetailTab === "consulting") && (
<ReviewSlotList
reviewType={activeDetailTab === "monitoring" ? REVIEW_TYPE.MONITORING : REVIEW_TYPE.CONSULTING}
reviewSlots={reviewSlots}
performance={detailPerformance}
userById={userById}
/>
)}
</div>
</section>
)}
</div>
</DialogContent>
</Dialog>
);
}
function PerformanceBadge({
performance,
badgeInfo,
colorClassName,
reviewSlots,
userById,
applyUsers,
onClick,
}: Readonly<{
performance: PerformanceFull;
badgeInfo: PerformanceBadgeInfo;
colorClassName: string;
reviewSlots: PerformanceReviewSlot[];
userById: Map<string, UserFull | UserCompact>;
applyUsers: MonitoringApplyUser[];
onClick: () => void;
}>) {
const accessibleLabel = badgeInfo.isMatchingComplete
? `${performance.performanceName}, 매칭 완료, 상세 보기`
: `${performance.performanceName}, ${badgeInfo.applyCount}명 신청, ${badgeInfo.assignCount}명 배정, 상세 보기`;
const monitoringNames = getAssignedUserNames(performance, reviewSlots, REVIEW_TYPE.MONITORING, userById);
const consultingNames = getAssignedUserNames(performance, reviewSlots, REVIEW_TYPE.CONSULTING, userById);
const applicantNames = applyUsers.map((applyUser) => applyUser.user.userName || applyUser.userId);
return (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={onClick}
aria-label={accessibleLabel}
className={`w-full rounded border px-1.5 py-1 text-left text-xs leading-tight transition-opacity hover:opacity-80 ${colorClassName}`}
>
<div className="line-clamp-2 font-medium">{performance.performanceName}</div>
<div>
{badgeInfo.isMatchingComplete ? (
<span className="inline-flex items-center gap-1"><Check className="h-3 w-3" />매칭 완료</span>
) : (
`${badgeInfo.applyCount}명 신청 / ${badgeInfo.assignCount}명 배정`
)}
</div>
</button>
</TooltipTrigger>
<TooltipContent side="right" className="w-64 space-y-1.5 text-left">
<div className="font-semibold">{performance.performanceName}</div>
<div>
<div className="font-medium text-muted-foreground">신청자</div>
<div>{applicantNames.length > 0 ? applicantNames.join(", ") : "없음"}</div>
</div>
<div>
<div className="font-medium text-muted-foreground">현장 모니터링 배정</div>
<div>{monitoringNames.length > 0 ? monitoringNames.join(", ") : "없음"}</div>
</div>
<div>
<div className="font-medium text-muted-foreground">컨설팅 배정</div>
<div>{consultingNames.length > 0 ? consultingNames.join(", ") : "없음"}</div>
</div>
</TooltipContent>
</Tooltip>
);
}
function ReviewSlotList({
reviewType,
reviewSlots,
performance,
userById,
}: Readonly<{
reviewType: ReviewType;
reviewSlots: PerformanceReviewSlot[];
performance: PerformanceFull;
userById: Map<string, UserFull | UserCompact>;
}>) {
const slots = reviewSlots.filter((slot) => slot.reviewType === reviewType).sort((a, b) => a.reviewSlot - b.reviewSlot);
if (slots.length === 0) {
return <div className="py-6 text-center text-sm text-muted-foreground">등록된 평가 슬롯이 없습니다.</div>;
}
return (
<div className="space-y-2">
{slots.map((slot) => {
const assign = performance.performanceAssignList.find((item) => item.reviewSlot === slot.reviewSlot);
const user = assign ? userById.get(assign.assignUser) : undefined;
return (
<div key={slot.reviewSlot} className="space-y-1 rounded border p-2 text-sm">
<div className="flex items-center justify-between gap-2">
<span className="font-medium">{slot.reviewLabel}</span>
{assign ? <StatusPill variant="done">배정</StatusPill> : <StatusPill variant="danger">미배정</StatusPill>}
</div>
{assign && (
<div className="text-xs text-muted-foreground">
<div>{user?.userName || assign.assignUser} ({assign.assignUser})</div>
<div>{getDetailValue(user?.userDetail, "userTel", "-")}</div>
</div>
)}
<div className="text-xs text-muted-foreground">
{performance.performanceMonitoringSchedule?.monitoringDate || "-"} {performance.performanceMonitoringSchedule?.monitoringTimeInfo || ""}
</div>
<div className="text-xs text-muted-foreground">{performance.performanceMonitoringSchedule?.monitoringAddress || "-"}</div>
</div>
);
})}
</div>
);
}

View File

@@ -0,0 +1,311 @@
"use client";
import {useEffect, useMemo, useState} from "react";
import {Save, Send} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Checkbox} from "@/components/ui/checkbox";
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
import {DataTable} from "@/components/data-table/DataTable";
import type {DataTableColumn} from "@/components/data-table/DataTable.type";
import {StatusPill} from "@/components/kmusical/StatusPill";
import type {Code, MonitoringApplyUser, PerformanceFull, PerformanceReviewSlot, ReviewType, UserCompact} from "@/types/kmusical";
import type {CodeGroup} from "@/query/code";
import {getCodeLabel, getDetailValue} from "@/lib/kmusical/view";
import {getReviewTypeLabel} from "@/lib/kmusical/performance-status";
import {PERFORMANCE_FIELD_LABELS, USER_FIELD_LABELS} from "@/lib/kmusical/field-labels";
type CodeMap = Partial<Record<CodeGroup, Code[]>>;
type AssignmentUserRow = Pick<MonitoringApplyUser, "userId" | "user">;
export type AssignmentSelection = {
reviewSlot: number;
userId: string;
};
export function AssignMonitoringDialog({
open,
onOpenChange,
selected,
codes,
reviewSlots,
applyUsers,
users,
isSaving = false,
onSaveAssign,
onOpenAssignSms,
onOpenNormalSms,
}: Readonly<{
open: boolean;
onOpenChange: (open: boolean) => void;
selected: PerformanceFull | null;
codes: CodeMap;
reviewSlots: PerformanceReviewSlot[];
applyUsers: MonitoringApplyUser[];
users: UserCompact[];
isSaving?: boolean;
onSaveAssign: (reviewSlotNumbers: number[], assignments: AssignmentSelection[]) => Promise<void>;
onOpenAssignSms: (reviewSlotNumbers: number[], assignments: AssignmentSelection[], smsUserIds: string[]) => void;
onOpenNormalSms: (smsUserIds: string[]) => void;
}>) {
const reviewTypes = useMemo(
() => Array.from(new Set(reviewSlots.map((slot) => slot.reviewType))),
[reviewSlots]
);
const [activeReviewType, setActiveReviewType] = useState<ReviewType | null>(reviewTypes[0] ?? null);
const [slotUsers, setSlotUsers] = useState<Record<number, string>>({});
useEffect(() => {
if (!open) return;
setActiveReviewType(reviewTypes[0] ?? null);
setSlotUsers(Object.fromEntries(
(selected?.performanceAssignList ?? []).map((assign) => [assign.reviewSlot, assign.assignUser])
));
}, [open, reviewTypes, selected]);
const activeSlots = reviewSlots
.filter((slot) => slot.reviewType === activeReviewType)
.sort((a, b) => a.reviewSlot - b.reviewSlot);
const activeSlotNumbers = activeSlots.map((slot) => slot.reviewSlot);
const activeSlotNumberSet = new Set(activeSlotNumbers);
const reviewBySlot = new Map(
Object.values(selected?.performanceReviewMap ?? {}).map((review) => [review.reviewSlot, review])
);
const slotByUserId = new Map(
Object.entries(slotUsers).map(([reviewSlot, userId]) => [userId, Number(reviewSlot)])
);
const checkedUserIds = activeSlots.flatMap((slot) => slotUsers[slot.reviewSlot] ? [slotUsers[slot.reviewSlot]] : []);
const savedUserIds = new Set(
(selected?.performanceAssignList ?? [])
.filter((assign) => activeSlotNumberSet.has(assign.reviewSlot))
.map((assign) => assign.assignUser)
);
const activeAssignments = activeSlots.flatMap((slot) => {
const userId = slotUsers[slot.reviewSlot];
return userId ? [{reviewSlot: slot.reviewSlot, userId}] : [];
});
const applicantIds = new Set(applyUsers.map((item) => item.userId));
const getUserGroup = (userId: string) => savedUserIds.has(userId) ? 0 : applicantIds.has(userId) ? 1 : 2;
const renderUserStatus = (userId: string) => {
if (savedUserIds.has(userId)) return <StatusPill variant="done">확정</StatusPill>;
const assignedSlot = slotByUserId.get(userId);
if (assignedSlot != null && !activeSlotNumberSet.has(assignedSlot)) {
return <StatusPill tooltip="다른 직무에 배정된 사용자입니다.">타직무</StatusPill>;
}
if (applicantIds.has(userId)) return <StatusPill variant="pending">신청</StatusPill>;
return null;
};
const sortedUsers: AssignmentUserRow[] = users
.map((user) => ({userId: user.userId, user}))
.sort((a, b) => getUserGroup(a.userId) - getUserGroup(b.userId)
|| (a.user.userName || a.userId).localeCompare(b.user.userName || b.userId, "ko")
|| a.userId.localeCompare(b.userId, "ko"));
const toggleAssignUser = (applyUser: AssignmentUserRow) => {
if (isSaving || activeReviewType == null) return;
const assignedSlot = slotByUserId.get(applyUser.userId);
if (assignedSlot != null) {
if (!activeSlotNumberSet.has(assignedSlot)) {
alert("동일한 공연에서는 한 신청자를 한 번만 배정할 수 있습니다.");
return;
}
if (reviewBySlot.has(assignedSlot)) {
alert("평가가 등록된 슬롯의 담당자는 해제할 수 없습니다.");
return;
}
setSlotUsers((current) => {
const next = {...current};
delete next[assignedSlot];
return next;
});
return;
}
const emptySlot = activeSlots.find((slot) => !slotUsers[slot.reviewSlot]);
if (!emptySlot) {
alert("선택한 리뷰 타입에 배정 가능한 슬롯이 없습니다.");
return;
}
setSlotUsers((current) => ({...current, [emptySlot.reviewSlot]: applyUser.userId}));
};
const columns = useMemo<DataTableColumn<AssignmentUserRow>[]>(() => [
{
id: "assign",
header: "선택",
size: 50,
enableSorting: false,
cell: ({row}) => {
const userId = row.original.userId;
const assignedSlot = slotByUserId.get(userId);
const checked = assignedSlot != null && activeSlotNumberSet.has(assignedSlot);
const locked = assignedSlot != null && reviewBySlot.has(assignedSlot);
const noEmptySlot = !checked && activeSlots.every((slot) => Boolean(slotUsers[slot.reviewSlot]));
const assignedToAnotherType = assignedSlot != null && !activeSlotNumberSet.has(assignedSlot);
return (
<Checkbox
checked={checked}
disabled={isSaving || locked || noEmptySlot || assignedToAnotherType}
aria-label={`${row.original.user.userName || userId} 선택`}
onCheckedChange={() => toggleAssignUser(row.original)}
onClick={(event) => event.stopPropagation()}
/>
);
},
},
{
id: "user",
header: USER_FIELD_LABELS.userName,
size: 140,
cell: ({row}) => (
<div className="min-w-0 text-center">
<div className="truncate font-semibold">{row.original.user.userName || row.original.userId}</div>
<div className="truncate text-xs text-muted-foreground">{row.original.userId}</div>
</div>
),
},
{
id: "area",
header: USER_FIELD_LABELS.userArea,
size: 80,
cell: ({row}) => (
<div className="truncate">
{getCodeLabel(codes, "area", getDetailValue(row.original.user.userDetail, "userArea")) || "-"}
</div>
),
},
{
id: "tel",
header: USER_FIELD_LABELS.userTel,
size: 130,
cell: ({row}) => <div className="truncate">{getDetailValue(row.original.user.userDetail, "userTel", "-")}</div>,
},
{
id: "status",
header: "상태",
size: 75,
cell: ({row}) => renderUserStatus(row.original.userId),
},
], [
activeSlotNumberSet,
activeSlots,
applicantIds,
codes,
isSaving,
reviewBySlot,
savedUserIds,
slotByUserId,
slotUsers,
]);
const changeReviewType = (reviewType: ReviewType) => {
setActiveReviewType(reviewType);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex h-[min(680px,85vh)] max-h-[85vh] flex-col overflow-hidden sm:max-w-6xl">
<DialogHeader className="shrink-0">
<DialogTitle>평가 담당자 배정</DialogTitle>
</DialogHeader>
<div className="grid min-h-0 flex-1 gap-4 lg:grid-cols-[0.85fr_1.15fr]">
<section className="min-h-0 overflow-y-auto rounded-md border">
<div className="border-b bg-muted px-3 py-2 font-semibold">공연 기본 정보</div>
<table className="w-full table-fixed border-collapse text-sm">
<tbody>
{[
[PERFORMANCE_FIELD_LABELS.performanceId, selected?.performanceId],
[PERFORMANCE_FIELD_LABELS.businessType, getCodeLabel(codes, "business_type", selected?.businessType)],
[PERFORMANCE_FIELD_LABELS.performanceArea, getCodeLabel(codes, "area", selected?.performanceArea)],
[PERFORMANCE_FIELD_LABELS.artistName, selected?.artistName],
[PERFORMANCE_FIELD_LABELS.performanceName, selected?.performanceName],
[PERFORMANCE_FIELD_LABELS.performanceDtInfo, selected?.performanceDtInfo],
[PERFORMANCE_FIELD_LABELS.monitoringDate, selected?.performanceMonitoringSchedule?.monitoringDate],
[PERFORMANCE_FIELD_LABELS.monitoringTimeInfo, selected?.performanceMonitoringSchedule?.monitoringTimeInfo],
[PERFORMANCE_FIELD_LABELS.monitoringAddress, selected?.performanceMonitoringSchedule?.monitoringAddress],
[PERFORMANCE_FIELD_LABELS.ticketReservationStatus, getCodeLabel(codes, "ticket_reservation_status", selected?.ticketReservationStatus)],
[PERFORMANCE_FIELD_LABELS.ticketReservationMemo, selected?.ticketReservationMemo],
].map(([label, value]) => (
<tr key={String(label)}>
<th className="w-32 border-b bg-muted/60 px-3 py-2 text-left align-top font-medium">{label}</th>
<td className="break-words border-b px-3 py-2">{value || "-"}</td>
</tr>
))}
</tbody>
</table>
</section>
<section className="flex min-h-0 min-w-0 flex-col rounded-md border p-3">
<div role="tablist" aria-label="평가 타입" className="flex shrink-0 gap-1 border-b">
{reviewTypes.map((reviewType) => (
<button
key={reviewType}
type="button"
role="tab"
aria-selected={activeReviewType === reviewType}
className={`cursor-pointer border-b-2 px-5 py-2 text-sm font-medium ${activeReviewType === reviewType ? "border-primary text-foreground" : "border-transparent text-muted-foreground"}`}
onClick={() => changeReviewType(reviewType)}
>
{getReviewTypeLabel(reviewType)}
</button>
))}
</div>
{activeSlots.length > 0 ? (
<>
<div className="my-3 grid shrink-0 grid-cols-2 overflow-hidden rounded-xl border text-center text-sm">
<div className="p-2.5">
<div className="text-muted-foreground">신청</div>
<div className="font-semibold">{applyUsers.length}</div>
</div>
<div className="border-l p-2.5">
<div className="text-muted-foreground">확정</div>
<div className="font-semibold">{savedUserIds.size}</div>
</div>
</div>
<div className="min-h-0 flex-1 overflow-hidden">
<DataTable
columns={columns}
data={sortedUsers}
getRowId={(row) => row.userId}
selectMode="click-event"
onRowClick={toggleAssignUser}
className="[&_table]:min-w-0 [&_table]:table-fixed"
headerCellClassName="text-center"
bodyCellClassName="text-center"
bodyRowClassName="[&>td]:py-2"
defaultPageSize={Math.max(sortedUsers.length, 1)}
pageSizeOptions={[Math.max(sortedUsers.length, 1)]}
disablePagination
maxBodyHeight="calc(min(680px,85vh) - 255px)"
emptyText="조회된 사용자가 없습니다."
/>
</div>
</>
) : (
<div className="flex flex-1 items-center justify-center text-sm text-muted-foreground">등록된 평가 슬롯이 없습니다.</div>
)}
</section>
</div>
<DialogFooter className="shrink-0">
<Button type="button" variant="outline" disabled={!selected || isSaving} onClick={() => onSaveAssign(activeSlotNumbers, activeAssignments)}>
<Save className="h-4 w-4" /> 저장
</Button>
<Button type="button" variant="outline" disabled={checkedUserIds.length === 0 || isSaving} onClick={() => onOpenAssignSms(activeSlotNumbers, activeAssignments, checkedUserIds)}>
<Send className="h-4 w-4" /> 확정 문자 발송
</Button>
<Button type="button" variant="outline" disabled={checkedUserIds.length === 0 || isSaving} onClick={() => onOpenNormalSms(checkedUserIds)}>
<Send className="h-4 w-4" /> 문자 발송
</Button>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>닫기</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,334 @@
"use client";
import {useEffect, useRef, useState} from "react";
import {Edit, Paperclip, RotateCcw, Save, Send, X} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from "@/components/ui/select";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle
} from "@/components/ui/dialog";
import {KriEditor, type KriEditorCommand} from "@/components/kri-editor";
import {useAuth} from "@/hooks/useAuth";
import {buildUserMsgParam} from "@/lib/kmusical/notification";
import {getDetailValue} from "@/lib/kmusical/view";
import {getSendParamLabel} from "@/lib/kmusical/field-labels";
import {downloadBlob} from "@/lib/kmusical/file";
import {SEND_TYPE, type Template} from "@/types/notification";
import type {UserCompact} from "@/types/kmusical";
import {
NOTIFICATION_REQUEST_SERVICE,
useDownloadEmailAttachmentMutation,
useNotificationTemplatesQuery,
useSaveEmailTemplateMutation,
useSendEmailBulkMutation,
useUploadEmailImageMutation,
} from "@/query/notification";
import {cn} from "@/lib/utils";
import {applyLinkPreviewClass} from "@/components/kri-editor/utils/linkPreview";
import {sanitizeEmailHtml} from "@/lib/kmusical/emailHtmlPolicy";
export function EmailSendDialog({
open,
onOpenChange,
title = "이메일 발송",
templateIdx,
newMessageTemplateIdx,
selectedUsers,
addParams = {},
denyParamKeys = [],
onSent,
}: Readonly<{
open: boolean;
onOpenChange: (open: boolean) => void;
title?: string;
templateIdx: number[];
newMessageTemplateIdx?: number;
selectedUsers: UserCompact[];
addParams?: Record<string, string>;
denyParamKeys?: string[];
onSent?: () => void;
}>) {
const {auth} = useAuth();
const templateKey = [...templateIdx, newMessageTemplateIdx ?? 0].join(",");
const ids = Array.from(new Set(templateKey.split(",").map(Number).filter((id) => id > 0)));
const templates = useNotificationTemplatesQuery(ids, open);
const saveMutation = useSaveEmailTemplateMutation();
const sendMutation = useSendEmailBulkMutation();
const imageMutation = useUploadEmailImageMutation();
const downloadMutation = useDownloadEmailAttachmentMutation();
const [activeId, setActiveId] = useState(templateIdx[0] ?? 0);
const [draft, setDraft] = useState<Template | null>(null);
const [editing, setEditing] = useState(false);
const [newMessage, setNewMessage] = useState(false);
const [files, setFiles] = useState<File[]>([]);
const [deletedNames, setDeletedNames] = useState<string[]>([]);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const lock = useRef(false);
const command = useRef<KriEditorCommand | null>(null);
const fileInput = useRef<HTMLInputElement | null>(null);
const active = templates.data.find((template) => template.tmplatIdx === activeId);
const isBusy = busy || saveMutation.isPending || sendMutation.isPending || imageMutation.isPending;
const canEdit = editing || newMessage;
useEffect(() => {
if (!open) return;
setActiveId(Number(templateKey.split(",")[0]) || 0);
setDraft(null);
setEditing(false);
setNewMessage(false);
setFiles([]);
setDeletedNames([]);
setError("");
}, [open, templateKey]);
useEffect(() => {
if (!open || !active) return;
// 작성 중인 내용은 백그라운드 조회로 덮어쓰지 않는다.
setDraft((current) => current ?? {...active});
}, [open, active]);
const destinations = selectedUsers.flatMap((user) => {
const destEml = getDetailValue(user.userDetail, "userEmail").trim();
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(destEml)) return [];
const msgParam = Object.fromEntries(Object.entries({...buildUserMsgParam(user), ...addParams})
.filter(([key, value]) => !denyParamKeys.includes(key) && value.trim()));
return [{sid: user.userId, destNm: user.userName.trim() || user.userId, destEml, msgParam}];
});
const paramKeys = Array.from(new Set(destinations.flatMap((item) => Object.keys(item.msgParam))));
const attachmentNames = draft?.atchFl?.split("|").filter(Boolean) ?? [];
const switchTemplate = (id: number, clear = false) => {
const template = templates.data.find((item) => item.tmplatIdx === id);
setActiveId(id);
setDraft(template ? {...template, ...(clear ? {tmplatTitle: "", tmplatBody: ""} : {})} : null);
setNewMessage(clear);
setEditing(false);
setFiles([]);
setDeletedNames(clear ? template?.atchFl?.split("|").filter(Boolean) ?? [] : []);
setError("");
};
const save = async () => {
if (!draft || draft.tmplatTy !== SEND_TYPE.EMAIL) throw new Error("이메일 템플릿을 확인해 주세요.");
if (!draft.tmplatNm.trim() || !draft.tmplatTitle?.trim() || !draft.tmplatBody.trim()) {
throw new Error("템플릿 이름, 제목과 내용을 입력해 주세요.");
}
const saved = await saveMutation.mutateAsync({
template: draft,
files,
deleteFileNames: deletedNames
});
setDraft(saved);
setFiles([]);
setDeletedNames([]);
setEditing(false);
return saved;
};
const run = async (action: () => Promise<void>) => {
if (lock.current) return;
lock.current = true;
setBusy(true);
setError("");
try {
await action();
} catch (cause) {
setError(cause instanceof Error ? cause.message : "요청을 처리하지 못했습니다. 다시 시도해 주세요.");
} finally {
lock.current = false;
setBusy(false);
}
};
const send = () => run(async () => {
if (!draft || draft.tmplatTy !== SEND_TYPE.EMAIL) throw new Error("이메일 템플릿을 확인해 주세요.");
if (!auth.user?.userCmpn || !auth.user.userId) throw new Error("로그인 사용자 정보를 확인할 수 없습니다.");
if (!destinations.length) throw new Error("발송 가능한 이메일 주소가 없습니다.");
if (destinations.length !== selectedUsers.length && !confirm("이메일 주소가 없거나 형식이 잘못된 사용자를 제외하고 발송하시겠습니까?")) return;
const template = newMessage ? await save() : draft;
const result = await sendMutation.mutateAsync({
templateIdx: template.tmplatIdx,
reqstCmpn: auth.user.userCmpn, reqstUser: auth.user.userId,
reqstSvc: NOTIFICATION_REQUEST_SERVICE, destinations
});
if (result.failCount > 0) {
setError(`이메일 요청 ${result.requestCount}건 중 외부 발송 실패 ${result.failCount}건입니다. 발송 결과를 확인해 주세요.`);
onSent?.();
return;
}
alert(`이메일 발송 요청 ${result.requestCount}건이 접수되었습니다.`);
onSent?.();
onOpenChange(false);
});
return (
<Dialog open={open} onOpenChange={(value) => {
if (!isBusy) onOpenChange(value);
}}>
<DialogContent showCloseButton={false}
className="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-5xl">
<DialogHeader className="flex-row flex-wrap items-center justify-between gap-3 space-y-0">
<DialogTitle>{title}</DialogTitle>
<div className="flex items-center gap-2">
<span
className="text-sm text-muted-foreground">선택 인원: {selectedUsers.length}명 · 발송 가능 {destinations.length}명</span>
{newMessageTemplateIdx && <Button variant="outline" size="sm"
disabled={isBusy || templates.isLoading || !active}
onClick={() => switchTemplate(newMessage ? templateIdx[0] : newMessageTemplateIdx, !newMessage)}>
{newMessage ? "기본 템플릿" : "새 메일 보내기"}
</Button>}
<Button variant="ghost" size="icon" disabled={isBusy}
onClick={() => onOpenChange(false)} aria-label="닫기"><X
className="size-4"/></Button>
</div>
</DialogHeader>
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto pr-1">
{templates.isLoading && !draft &&
<p className="text-sm text-muted-foreground">템플릿 정보를 불러오는 중입니다.</p>}
{templates.isError &&
<p role="alert" className="text-sm text-destructive">템플릿 정보를 불러오지 못했습니다. 창을 닫고 다시
시도해 주세요.</p>}
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
{draft && draft.tmplatTy !== SEND_TYPE.EMAIL &&
<p role="alert" className="text-destructive">이메일용 템플릿이 아닙니다.</p>}
{draft?.tmplatTy === SEND_TYPE.EMAIL && <>
<div className="grid gap-3 sm:grid-cols-2">
<label className="space-y-1 text-sm"><span>템플릿명</span>
<Select value={String(activeId)}
disabled={isBusy || canEdit || templateIdx.length <= 1}
onValueChange={(id) => switchTemplate(Number(id))}>
<SelectTrigger className="w-full"><SelectValue/></SelectTrigger>
<SelectContent>{templates.data.filter((item) => item.tmplatTy === SEND_TYPE.EMAIL && (templateIdx.includes(item.tmplatIdx) || item.tmplatIdx === activeId)).map((item) =>
<SelectItem key={item.tmplatIdx}
value={String(item.tmplatIdx)}>{item.tmplatNm}</SelectItem>)}</SelectContent>
</Select>
</label>
<label className="space-y-1 text-sm"><span>발신 이메일</span><Input
value={draft.sendEml ?? ""} disabled/></label>
</div>
<label className="block space-y-1 text-sm"><span>발신자명</span><Input
value={draft.sendNm} disabled/></label>
<label className="block space-y-1 text-sm"><span>제목</span><Input maxLength={128}
value={draft.tmplatTitle ?? ""}
disabled={!canEdit || isBusy}
onChange={(event) => setDraft({
...draft,
tmplatTitle: event.target.value
})}/></label>
{paramKeys.length > 0 && <div className="space-y-1 text-sm">
<div>사용 가능 변수값</div>
<div
className="flex max-h-32 flex-wrap gap-1.5 overflow-y-auto rounded-md border p-2">
{paramKeys.map((key) => <Button key={key} variant="secondary" size="sm"
disabled={!canEdit || isBusy}
onMouseDown={(event) => event.preventDefault()}
onClick={() => command.current?.insertText(`#{${key}}`)}>{getSendParamLabel(key)}
<code>{`#{${key}}`}</code></Button>)}
</div>
</div>}
<div className="space-y-1 text-sm"><span>내용</span>
{canEdit ? <div inert={isBusy}>
<KriEditor mode="both" showPreview value={draft.tmplatBody} debounceMs={0}
allowBase64={false}
onChange={(html) => setDraft((current) => current ? {
...current,
tmplatBody: html
} : current)}
onCommandReady={(value) => {
command.current = value;
}}
onImageUpload={async (file) => {
if (!draft.itrntPrjctCd) throw new Error("템플릿 프로젝트 정보가 없습니다.");
return imageMutation.mutateAsync({
projectCode: draft.itrntPrjctCd,
file
});
}}
/>
</div> : <div
className={cn('kri-editor-preview rounded-md border bg-muted/30 p-3')}
dangerouslySetInnerHTML={{
__html: applyLinkPreviewClass(
sanitizeEmailHtml(
draft.tmplatBody,
),
),
}}
/>
}
</div>
<div className="space-y-2 text-sm">
<div className="flex items-center justify-between">
<span>첨부파일 ({attachmentNames.filter((name) => !deletedNames.includes(name)).length + files.length})</span>
<Button size="sm" variant="outline" disabled={!canEdit || isBusy}
onClick={() => fileInput.current?.click()}><Paperclip
className="size-4"/> 파일 추가</Button>
</div>
<input ref={fileInput} type="file" multiple hidden onChange={(event) => {
const additions = Array.from(event.target.files ?? []);
event.target.value = "";
const names = new Set([...attachmentNames.filter((name) => !deletedNames.includes(name)), ...files.map((file) => file.name)]);
const accepted = additions.filter((file) => {
if (names.has(file.name) || file.name.includes("|")) {
setError("중복 파일명 또는 | 문자를 포함한 파일명은 사용할 수 없습니다.");
return false;
}
names.add(file.name);
return true;
});
setFiles((current) => [...current, ...accepted]);
}}/>
<ul className="space-y-1">
{attachmentNames.map((name) => <li key={name}
className="flex items-center justify-between gap-2 rounded border p-2">
<Button variant="link"
className={`h-auto min-w-0 truncate p-0 ${deletedNames.includes(name) ? "line-through" : ""}`}
disabled={isBusy || downloadMutation.isPending}
onClick={() => run(async () => downloadBlob(await downloadMutation.mutateAsync({
templateIdx: draft.tmplatIdx,
fileName: name
}), name))}>{name}</Button>
{canEdit && <Button size="sm" variant="ghost" disabled={isBusy}
onClick={() => setDeletedNames((current) => current.includes(name) ? current.filter((item) => item !== name) : [...current, name])}>{deletedNames.includes(name) ? "복원" : "삭제"}</Button>}
</li>)}
{files.map((file) => <li key={file.name}
className="flex items-center justify-between gap-2 rounded border p-2">
<span className="min-w-0 truncate">{file.name} (신규)</span><Button size="sm"
variant="ghost"
disabled={isBusy}
onClick={() => setFiles((current) => current.filter((item) => item !== file))}>제거</Button>
</li>)}
</ul>
</div>
</>}
</div>
<DialogFooter className="shrink-0 border-t pt-4">
{draft?.tmplatTy === SEND_TYPE.EMAIL && !newMessage && (!editing
? <Button variant="outline" disabled={isBusy} onClick={() => setEditing(true)}><Edit
className="size-4"/> 수정</Button>
: <><Button variant="outline" disabled={isBusy} onClick={() => run(async () => {
await save();
})}><Save className="size-4"/> 저장</Button><Button variant="outline"
disabled={isBusy}
onClick={() => switchTemplate(activeId)}><RotateCcw
className="size-4"/> 취소</Button></>)}
<Button
disabled={!draft || draft.tmplatTy !== SEND_TYPE.EMAIL || isBusy || editing || !destinations.length}
onClick={send}><Send className="size-4"/> 발송</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,103 @@
"use client";
import {useEffect, useState} from "react";
import type {ExcelUploadResult} from "@kri/common";
import {downloadFile} from "@kri/common/browser";
import {Download, FileUp} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
const base64ToBlob = (value: string) => {
const bytes = Uint8Array.from(atob(value), (character) => character.charCodeAt(0));
return new Blob([bytes], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
};
export function ExcelRegisterDialog({
open,
onOpenChange,
title,
onDownloadTemplate,
onUpload,
isUploading = false,
}: 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;
setUploadResult(await onUpload(file));
};
const downloadErrorFile = () => {
if (!uploadResult?.errorFileBase64) return;
downloadFile(
base64ToBlob(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"
disabled={isUploading}
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}>
{isUploading ? "등록 중" : "등록"}
</Button>
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
닫기
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,352 @@
"use client";
import {ReactNode, useEffect, useRef, useState} from "react";
import {Download, ScanSearch, Upload} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
import {FilterSelect} from "@/components/kmusical/FilterSelect";
import {StatusPill} from "@/components/kmusical/StatusPill";
import type {
Code,
PerformanceCompact,
PerformanceFull,
PerformanceMonitoringSchedule,
PerformanceReview,
PerformanceReviewSlot,
PerformanceStaff,
} from "@/types/kmusical";
import {PDF_CONVERT_STATUS} from "@/types/kmusical";
import type {CodeGroup} from "@/query/code";
import {
useDownloadReviewOriginalMutation,
useDownloadReviewPdfMutation,
useDownloadReviewTemplateMutation,
useUploadReviewFileMutation,
} from "@/query/review";
import {useUserQuery} from "@/query/user";
import {downloadBlob, downloadFromUrl} from "@/lib/kmusical/file";
import {toLocalDateString} from "@/lib/kmusical/date";
import {getCodeLabel, getDetailValue} from "@/lib/kmusical/view";
import {isReviewComplete} from "@/lib/kmusical/performance-status";
import {REVIEW_TYPE} from "@/types/kmusical";
import {PERFORMANCE_FIELD_LABELS} from "@/lib/kmusical/field-labels";
import {useAuth} from "@/hooks/useAuth";
type CodeMap = Partial<Record<CodeGroup, Code[]>>;
function DetailRow({label, children}: {label: string; children: ReactNode}) {
return (
<div className="grid grid-cols-[140px_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 ReviewSlotCard({
performanceId,
slot,
assignUser,
review,
onChanged,
}: Readonly<{
performanceId: string;
slot: PerformanceReviewSlot;
assignUser?: string;
review?: PerformanceReview;
onChanged?: () => void;
}>) {
const {auth, isMonitoring} = useAuth();
const {data: assignedUser} = useUserQuery(assignUser ?? "");
const fileInputRef = useRef<HTMLInputElement | null>(null);
const uploadMutation = useUploadReviewFileMutation(performanceId, slot.reviewSlot);
const originalMutation = useDownloadReviewOriginalMutation();
const pdfMutation = useDownloadReviewPdfMutation();
const canUpload = !isMonitoring || Boolean(assignUser && auth.user?.userId === assignUser);
const canPreviewPdf = Boolean(review?.pdfFileName && review.pdfConvert === PDF_CONVERT_STATUS.COMPLETED);
const upload = async (file?: File) => {
try {
if (!file || !canUpload) return;
const formData = new FormData();
formData.append("file", file, file.name);
await uploadMutation.mutateAsync({formData, paramUserId: !isMonitoring ? assignUser : undefined});
alert("평가 파일이 등록되었습니다.");
onChanged?.();
} finally {
if (fileInputRef.current) fileInputRef.current.value = "";
}
};
const downloadOriginal = async () => {
const buffer = await originalMutation.mutateAsync({performanceId, reviewSlot: slot.reviewSlot});
downloadBlob(buffer, review?.uploadFileName || `review-${performanceId}-${slot.reviewSlot}`);
};
const downloadPdf = async () => {
const buffer = await pdfMutation.mutateAsync({performanceId, reviewSlot: slot.reviewSlot});
downloadBlob(buffer, review?.pdfFileName || `review-${performanceId}-${slot.reviewSlot}.pdf`, "application/pdf");
};
const previewPdf = () => {
if (!canPreviewPdf) return;
const params = new URLSearchParams({
src: `/api/review/pdf/${encodeURIComponent(performanceId)}/${slot.reviewSlot}?inline=true`,
title: review?.pdfFileName || `${slot.reviewLabel} 미리보기`,
type: "pdf",
});
window.open(`/file-preview?${params.toString()}`, "_blank", "noopener,noreferrer");
};
const reviewerLabel = slot.reviewType === REVIEW_TYPE.CONSULTING ? "컨설팅 위원" : "평가 위원";
const reviewDateLabel = slot.reviewType === REVIEW_TYPE.CONSULTING ? "컨설팅일" : "평가일";
return (
<div className="space-y-2 border-b p-3 last:border-b-0">
<div className="font-semibold">{slot.reviewLabel}</div>
<div className="grid grid-cols-1 gap-x-4 gap-y-1 rounded-xl border bg-muted/30 p-2 text-xs text-muted-foreground sm:grid-cols-2">
<div className="min-w-0 break-words">{reviewerLabel}: {assignedUser?.userName || assignUser || "-"}</div>
<div className="min-w-0 break-words">
{reviewDateLabel}: {review?.reviewDt ? toLocalDateString(new Date(review.reviewDt)) : "-"}
</div>
<div className="min-w-0 break-words">연락처: {getDetailValue(assignedUser?.userDetail, "userTel", "-")}</div>
<div className="min-w-0 break-words">이메일: {getDetailValue(assignedUser?.userDetail, "userEmail", "-")}</div>
</div>
<div className="flex">
<StatusPill variant={isReviewComplete(review) ? "done" : assignUser ? "pending" : "danger"}>
{isReviewComplete(review) ? "완료" : assignUser ? "미진행" : "미배정"}
</StatusPill>
</div>
<div className="flex flex-wrap gap-1">
{canUpload && (
<>
<input ref={fileInputRef} type="file" className="hidden" onChange={(event) => void upload(event.target.files?.[0])} />
<Button type="button" size="xs" variant="outline" className="rounded-full" onClick={() => fileInputRef.current?.click()} disabled={uploadMutation.isPending}>
<Upload className="size-3" /> 평가 등록
</Button>
</>
)}
<Button type="button" size="xs" variant="outline" className="rounded-full" onClick={downloadOriginal} disabled={!review?.uploadFileName || originalMutation.isPending}>
<Download className="size-3" /> 원본
</Button>
<Button
type="button"
size="xs"
variant="outline"
className="rounded-full"
onClick={downloadPdf}
disabled={!canPreviewPdf || pdfMutation.isPending}
>
<Download className="size-3" /> PDF
</Button>
<Button type="button" size="xs" variant="outline" className="rounded-full" onClick={previewPdf} disabled={!canPreviewPdf}>
<ScanSearch className="size-3" /> 미리보기
</Button>
</div>
<p className="text-xs text-red-500">* 파일 크기 및 형식에 따라 PDF 변환이 최대 5분까지 소요됩니다.</p>
</div>
);
}
const clonePerformance = (performance: PerformanceCompact): PerformanceCompact => ({
...performance,
performanceDetail: {...performance.performanceDetail},
performanceMonitoringSchedule: {...performance.performanceMonitoringSchedule},
performanceStaff: performance.performanceStaff.map((staff) => ({...staff})),
});
export function PerformanceDetailDialog({
open,
onOpenChange,
performance,
codes,
reviewSlots,
canEdit,
canDelete,
onSave,
onDelete,
onRefresh,
}: Readonly<{
open: boolean;
onOpenChange: (open: boolean) => void;
performance: PerformanceFull | PerformanceCompact | null;
codes: CodeMap;
reviewSlots: PerformanceReviewSlot[];
canEdit: boolean;
canDelete: boolean;
onSave?: (performance: PerformanceCompact) => Promise<void> | void;
onDelete?: (performanceId: string) => Promise<void> | void;
onRefresh?: () => void;
}>) {
const {auth, isMonitoring} = useAuth();
const [draft, setDraft] = useState<PerformanceCompact | null>(null);
const [isEditing, setIsEditing] = useState(false);
useEffect(() => {
setDraft(performance ? clonePerformance(performance) : null);
setIsEditing(false);
}, [performance, open]);
const updateDraft = <K extends keyof PerformanceCompact>(key: K, value: PerformanceCompact[K]) => {
setDraft((current) => current ? {...current, [key]: value} : current);
};
const updateDetail = (key: string, value: string) => {
setDraft((current) => current ? {
...current,
performanceDetail: {...current.performanceDetail, [key]: value},
} : current);
};
const updateSchedule = <K extends keyof PerformanceMonitoringSchedule>(key: K, value: PerformanceMonitoringSchedule[K]) => {
setDraft((current) => current ? {
...current,
performanceMonitoringSchedule: {...current.performanceMonitoringSchedule, [key]: value},
} : current);
};
const updateStaff = (index: number, key: keyof PerformanceStaff, value: string) => {
setDraft((current) => {
if (!current) return current;
const performanceStaff = current.performanceStaff.map((staff, staffIndex) =>
staffIndex === index ? {...staff, [key]: value} : staff
);
return {...current, performanceStaff};
});
};
const save = async () => {
if (!draft) return;
await onSave?.(draft);
setIsEditing(false);
};
const deletePerformance = async () => {
if (!draft || !confirm("삭제된 공연은 복구할 수 없습니다. 삭제하시겠습니까?")) return;
await onDelete?.(draft.performanceId);
};
const fullPerformance = performance && "performanceAssignList" in performance ? performance : undefined;
const visibleReviewSlots = isMonitoring
? reviewSlots.filter((slot) => Boolean(
auth.user?.userId && fullPerformance?.performanceAssignList.some(
(assign) => assign.reviewSlot === slot.reviewSlot && assign.assignUser === auth.user?.userId,
),
))
: reviewSlots;
const visibleReviewTypes = [...new Set(visibleReviewSlots.map((slot) => slot.reviewType))];
const reviewTemplateMutation = useDownloadReviewTemplateMutation();
const downloadReviewTemplate = (reviewType: number) => {
reviewTemplateMutation.mutate(reviewType, {
onSuccess: () => downloadFromUrl(`/api/review/template/download/${reviewType}`),
});
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-6xl">
<DialogHeader><DialogTitle>공연 상세 정보</DialogTitle></DialogHeader>
<div className="min-h-0 flex-1 overflow-y-auto pr-1">
{draft && (
<div className="grid gap-4 lg:grid-cols-[1.05fr_0.95fr]">
<div className="space-y-4">
<section className="rounded-md border">
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceId}>{draft.performanceId}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.businessType}>{getCodeLabel(codes, "business_type", draft.businessType)}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceArea}>
{isEditing ? (
<FilterSelect value={String(draft.performanceArea)} onChange={(value) => updateDraft("performanceArea", Number(value))} options={codes.area ?? []} placeholder="지역" />
) : getCodeLabel(codes, "area", draft.performanceArea)}
</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceAreaDetail}>
{isEditing ? <Input value={draft.performanceDetail.performanceAreaDetail ?? ""} onChange={(event) => updateDetail("performanceAreaDetail", event.target.value)} /> : draft.performanceDetail.performanceAreaDetail}
</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.artistName}>{isEditing ? <Input value={draft.artistName} onChange={(event) => updateDraft("artistName", event.target.value)} /> : draft.artistName}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceName}>{isEditing ? <Input value={draft.performanceName} onChange={(event) => updateDraft("performanceName", event.target.value)} /> : draft.performanceName}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceStartMonth}>{isEditing ? <Input type="number" min={0} max={12} value={draft.performanceStartMonth} onChange={(event) => updateDraft("performanceStartMonth", Number(event.target.value))} /> : `${draft.performanceStartMonth}월`}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceDtInfo}>{isEditing ? <Input value={draft.performanceDtInfo} onChange={(event) => updateDraft("performanceDtInfo", event.target.value)} /> : draft.performanceDtInfo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceTimeInfo}>{isEditing ? <Input value={draft.performanceTimeInfo} onChange={(event) => updateDraft("performanceTimeInfo", event.target.value)} /> : draft.performanceTimeInfo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.ticketReservationStatus}>
{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={PERFORMANCE_FIELD_LABELS.ticketReservationMemo}>{isEditing ? <Input value={draft.ticketReservationMemo} onChange={(event) => updateDraft("ticketReservationMemo", event.target.value)} /> : draft.ticketReservationMemo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.monitoringDate}>{isEditing ? <Input type="date" value={draft.performanceMonitoringSchedule.monitoringDate ?? ""} onChange={(event) => updateSchedule("monitoringDate", event.target.value)} /> : draft.performanceMonitoringSchedule.monitoringDate}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.monitoringTimeInfo}>{isEditing ? <Input value={draft.performanceMonitoringSchedule.monitoringTimeInfo ?? ""} onChange={(event) => updateSchedule("monitoringTimeInfo", event.target.value)} /> : draft.performanceMonitoringSchedule.monitoringTimeInfo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.monitoringAddress}>{isEditing ? <Input value={draft.performanceMonitoringSchedule.monitoringAddress ?? ""} onChange={(event) => updateSchedule("monitoringAddress", event.target.value)} /> : draft.performanceMonitoringSchedule.monitoringAddress}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceMemo}>{isEditing ? <Input value={draft.performanceMemo} onChange={(event) => updateDraft("performanceMemo", event.target.value)} /> : draft.performanceMemo}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.consultingStatus}>{isEditing ? <Input value={draft.performanceDetail.consultingStatus ?? ""} onChange={(event) => updateDetail("consultingStatus", event.target.value)} /> : draft.performanceDetail.consultingStatus}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.clientManagerName}>{isEditing ? <Input value={draft.performanceDetail.clientManagerName ?? ""} onChange={(event) => updateDetail("clientManagerName", event.target.value)} /> : draft.performanceDetail.clientManagerName}</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="kmf-table min-w-[620px]">
<thead><tr><th>유형</th><th>이름</th><th>연락처1</th><th>연락처2</th><th>이메일</th></tr></thead>
<tbody>
{draft.performanceStaff.map((staff, index) => (
<tr key={staff.id}>
<td>{getCodeLabel(codes, "staff_type", staff.staffType)}</td>
<td>{isEditing ? <Input value={staff.staffName} onChange={(event) => updateStaff(index, "staffName", event.target.value)} /> : staff.staffName}</td>
<td>{isEditing ? <Input value={staff.staffTel1} onChange={(event) => updateStaff(index, "staffTel1", event.target.value)} /> : staff.staffTel1}</td>
<td>{isEditing ? <Input value={staff.staffTel2} onChange={(event) => updateStaff(index, "staffTel2", event.target.value)} /> : staff.staffTel2}</td>
<td>{isEditing ? <Input value={staff.staffEmail} onChange={(event) => updateStaff(index, "staffEmail", event.target.value)} /> : staff.staffEmail}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
</div>
<section className="rounded-md border">
<div className="flex flex-wrap items-center justify-between gap-2 border-b bg-muted px-3 py-2">
<div className="font-semibold">현장모니터링 및 컨설팅</div>
<div className="flex flex-wrap gap-1">
{visibleReviewTypes.map((reviewType) => (
<Button
key={reviewType}
type="button"
size="xs"
variant="outline"
className="rounded-full"
disabled={reviewTemplateMutation.isPending}
onClick={() => downloadReviewTemplate(reviewType)}
>
<Download className="size-3" /> {reviewType === REVIEW_TYPE.CONSULTING ? "컨설팅" : "모니터링"} 양식
</Button>
))}
</div>
</div>
{visibleReviewSlots.map((slot) => (
<ReviewSlotCard
key={slot.reviewSlot}
performanceId={draft.performanceId}
slot={slot}
assignUser={fullPerformance?.performanceAssignList.find((assign) => assign.reviewSlot === slot.reviewSlot)?.assignUser}
review={Object.values(fullPerformance?.performanceReviewMap ?? {}).find((item) => item.reviewSlot === slot.reviewSlot)}
onChanged={onRefresh}
/>
))}
{visibleReviewSlots.length === 0 && <div className="p-8 text-center text-sm text-muted-foreground">등록된 평가 슬롯이 없습니다.</div>}
</section>
</div>
)}
</div>
<DialogFooter className="shrink-0 border-t pt-4">
{canDelete && draft && <Button type="button" variant="destructive" onClick={deletePerformance}>삭제</Button>}
{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={() => { if (performance) setDraft(clonePerformance(performance)); setIsEditing(false); }}>취소</Button>
</>
)}
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>닫기</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,349 @@
"use client";
import {useEffect, useMemo, useRef, useState} from "react";
import {Edit, RotateCcw, Save, Send, X} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {Select, SelectContent, SelectItem, SelectTrigger, SelectValue} from "@/components/ui/select";
import {Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
import {
NOTIFICATION_REQUEST_SERVICE,
useNotificationTemplateQuery,
useNotificationTemplatesQuery,
useSaveNotificationTemplateMutation,
useSendSmsBulkMutation,
} from "@/query/notification";
import type {SaveTemplateRequest, Template} from "@/types/notification";
import {TMPLAT_PURPOSE} from "@/types/notification";
import type {UserCompact} from "@/types/kmusical";
import {getDetailValue} from "@/lib/kmusical/view";
import {
buildTemplatePreviewBody,
buildUserMsgParam,
getSmsByteLength,
isPhoneVerificationSupported,
} from "@/lib/kmusical/notification";
import {getSendParamLabel} from "@/lib/kmusical/field-labels";
import {useAuth} from "@/hooks/useAuth";
type TemplateDraft = Pick<
Template,
"tmplatIdx" | "tmplatTy" | "tmplatPurpose" | "tmplatNm" | "tmplatTitle" | "tmplatBody" | "sendTel"
>;
const toText = (value: string | null | undefined) => value ?? "";
const toDraft = (template: Template, clearContent = false): TemplateDraft => ({
tmplatIdx: template.tmplatIdx,
tmplatTy: template.tmplatTy,
tmplatPurpose: template.tmplatPurpose,
tmplatNm: template.tmplatNm ?? "",
tmplatTitle: clearContent ? "" : template.tmplatTitle ?? "",
tmplatBody: clearContent ? "" : template.tmplatBody ?? "",
sendTel: template.sendTel ?? "",
});
export function SmsSendDialog({
open,
onOpenChange,
title = "문자 발송",
templateIdx,
newMessageTemplateIdx,
selectedUsers,
addParams = {},
denyParamKeys = [],
onBeforeDefaultTemplateSend,
isBeforeSendPending = false,
onSent,
}: Readonly<{
open: boolean;
onOpenChange: (open: boolean) => void;
title?: string;
templateIdx: number[];
newMessageTemplateIdx?: number;
selectedUsers: UserCompact[];
addParams?: Record<string, string>;
denyParamKeys?: string[];
onBeforeDefaultTemplateSend?: () => Promise<void>;
isBeforeSendPending?: boolean;
onSent?: () => void;
}>) {
const {auth} = useAuth();
const templateIdxKey = templateIdx.join(",");
const templateIdxList = useMemo(
() => Array.from(new Set(templateIdx.filter((idx) => idx > 0))),
[templateIdxKey]
);
const defaultTemplateIdx = templateIdxList[0] ?? 0;
const [activeTemplateIdx, setActiveTemplateIdx] = useState(defaultTemplateIdx);
const [draft, setDraft] = useState<TemplateDraft | null>(null);
const [isEditing, setIsEditing] = useState(false);
const [isNewMessage, setIsNewMessage] = useState(false);
const bodyTextareaRef = useRef<HTMLTextAreaElement | null>(null);
const templatesQuery = useNotificationTemplatesQuery(templateIdxList, open);
const newMessageTemplateQuery = useNotificationTemplateQuery(
newMessageTemplateIdx ?? 0,
Boolean(open && isNewMessage && newMessageTemplateIdx)
);
const saveMutation = useSaveNotificationTemplateMutation();
const sendMutation = useSendSmsBulkMutation();
const activeTemplate = isNewMessage
? newMessageTemplateQuery.data
: templatesQuery.data.find((template) => template.tmplatIdx === activeTemplateIdx);
const isBusy = templatesQuery.isLoading
|| newMessageTemplateQuery.isLoading
|| saveMutation.isPending
|| sendMutation.isPending
|| isBeforeSendPending;
const canEdit = isNewMessage || isEditing;
const destinations = useMemo(() => {
const denied = new Set(denyParamKeys);
return selectedUsers.flatMap((user) => {
const destTel = getDetailValue(user.userDetail, "userTel").trim();
const destNm = (user.userName || user.userId).trim();
if (!destTel || !destNm) return [];
const msgParam = Object.fromEntries(
Object.entries({...buildUserMsgParam(user), ...addParams})
.filter(([key, value]) => !denied.has(key) && value.trim().length > 0)
);
return [{sid: user.userId, destTel, destNm, msgParam}];
});
}, [addParams, denyParamKeys, selectedUsers]);
const msgParamKeys = useMemo(
() => Array.from(new Set(destinations.flatMap((destination) => Object.keys(destination.msgParam)))),
[destinations]
);
useEffect(() => {
if (!open) return;
setActiveTemplateIdx(defaultTemplateIdx);
setDraft(null);
setIsEditing(false);
setIsNewMessage(false);
}, [defaultTemplateIdx, open, templateIdxKey]);
useEffect(() => {
if (!open || !activeTemplate) return;
setDraft(toDraft(activeTemplate, isNewMessage));
}, [activeTemplate, isNewMessage, open]);
const updateDraft = <K extends keyof TemplateDraft>(key: K, value: TemplateDraft[K]) => {
setDraft((current) => current ? {...current, [key]: value} : current);
};
const insertMsgParam = (key: string) => {
if (!draft || !canEdit || isBusy) return;
const token = `#{${key}}`;
const start = bodyTextareaRef.current?.selectionStart ?? draft.tmplatBody.length;
const end = bodyTextareaRef.current?.selectionEnd ?? start;
updateDraft("tmplatBody", `${draft.tmplatBody.slice(0, start)}${token}${draft.tmplatBody.slice(end)}`);
window.setTimeout(() => {
bodyTextareaRef.current?.focus();
bodyTextareaRef.current?.setSelectionRange(start + token.length, start + token.length);
}, 0);
};
const saveTemplate = async () => {
if (!draft || !draft.tmplatNm.trim() || !draft.tmplatBody.trim()) {
alert("템플릿 이름과 내용을 입력해 주세요.");
return null;
}
const payload: SaveTemplateRequest = {
tmplatIdx: draft.tmplatIdx,
tmplatNm: draft.tmplatNm.trim(),
tmplatTitle: draft.tmplatTitle?.trim(),
tmplatBody: draft.tmplatBody,
};
const saved = await saveMutation.mutateAsync(payload);
setDraft(toDraft(saved));
setIsEditing(false);
return saved;
};
const cancelEdit = () => {
if (activeTemplate) setDraft(toDraft(activeTemplate, isNewMessage));
setIsEditing(false);
};
const changeTemplate = (value: string) => {
setActiveTemplateIdx(Number(value));
setIsNewMessage(false);
setIsEditing(false);
setDraft(null);
};
const switchToNewMessage = () => {
if (!newMessageTemplateIdx) return;
setActiveTemplateIdx(newMessageTemplateIdx);
setIsNewMessage(true);
setIsEditing(false);
setDraft(null);
};
const restoreTemplate = () => {
setActiveTemplateIdx(defaultTemplateIdx);
setIsNewMessage(false);
setIsEditing(false);
setDraft(null);
};
const previewBody = draft ? buildTemplatePreviewBody(draft) : "";
const isSmsOrLms = draft ? isPhoneVerificationSupported(draft) : false;
const send = async () => {
if (!draft || !auth.user?.userCmpn || !auth.user.userId) {
alert("로그인 사용자 또는 템플릿 정보를 확인할 수 없습니다.");
return;
}
if (destinations.length === 0) {
alert("발송 가능한 연락처가 없습니다.");
return;
}
if (destinations.length !== selectedUsers.length && !confirm("연락처가 없는 사용자를 제외하고 발송하시겠습니까?")) {
return;
}
if (isEditing || isNewMessage) {
const saved = await saveTemplate();
if (!saved) return;
}
if (!isNewMessage) await onBeforeDefaultTemplateSend?.();
const result = await sendMutation.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 showCloseButton={false} className="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-2xl">
<DialogHeader className="flex-row flex-wrap items-center justify-between gap-3 space-y-0">
<DialogTitle>{title}</DialogTitle>
<div className="flex flex-wrap items-center gap-2">
<div className="text-sm whitespace-nowrap 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>
)
)}
<DialogClose asChild>
<Button type="button" size="icon" variant="ghost" className="h-8 w-8 shrink-0">
<X className="h-4 w-4" />
<span className="sr-only">닫기</span>
</Button>
</DialogClose>
</div>
</DialogHeader>
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto pr-1">
{isBusy && !draft && (
<div className="rounded-md border p-4 text-sm text-muted-foreground">템플릿 정보를 불러오는 중입니다.</div>
)}
{(templatesQuery.isError || newMessageTemplateQuery.isError) && !draft && (
<div className="rounded-md border border-destructive p-4 text-sm text-destructive">템플릿 정보를 불러오지 못했습니다.</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>
<Select value={String(activeTemplateIdx)} onValueChange={changeTemplate} disabled={isBusy || isEditing || isNewMessage || templateIdxList.length <= 1}>
<SelectTrigger className="w-full"><SelectValue placeholder="템플릿 선택" /></SelectTrigger>
<SelectContent>
{isNewMessage && <SelectItem value={String(draft.tmplatIdx)}>{toText(draft.tmplatNm) || String(draft.tmplatIdx)}</SelectItem>}
{templatesQuery.data.map((template) => (
<SelectItem key={template.tmplatIdx} value={String(template.tmplatIdx)}>
{toText(template.tmplatNm) || String(template.tmplatIdx)}
{template.tmplatPurpose === TMPLAT_PURPOSE.PHONE_VERIFICATION && " (인증)"}
</SelectItem>
))}
</SelectContent>
</Select>
</label>
<label className="space-y-1 text-sm">
<span className="font-medium">발신번호</span>
<Input value={draft.sendTel ?? ""} disabled />
</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>
{isSmsOrLms && (
<label className="space-y-1 text-sm">
<span className="font-medium">템플릿 용도</span>
<Select value={String(draft.tmplatPurpose)} disabled>
<SelectTrigger className="w-full"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value={String(TMPLAT_PURPOSE.NORMAL)}>일반</SelectItem>
<SelectItem value={String(TMPLAT_PURPOSE.PHONE_VERIFICATION)}>휴대전화번호 인증</SelectItem>
</SelectContent>
</Select>
</label>
)}
<label className="space-y-1 text-sm">
<span className="font-medium">내용</span>
<textarea ref={bodyTextareaRef} value={draft.tmplatBody} disabled={!canEdit || isBusy} onChange={(event) => updateDraft("tmplatBody", event.target.value)} className="min-h-52 w-full rounded-md border border-input bg-background p-3 text-sm disabled:cursor-not-allowed disabled:opacity-70" />
</label>
{msgParamKeys.length > 0 && (
<div className="space-y-1 text-sm">
<div className="font-medium text-muted-foreground">사용 가능 변수값</div>
<div className="max-h-36 overflow-y-auto rounded-md border bg-muted/20 p-2">
<div className="flex flex-wrap gap-1.5">
{msgParamKeys.map((key) => (
<Button key={key} type="button" className="h-auto flex-col items-start gap-0 rounded bg-muted px-2 py-1 text-center text-xs text-foreground hover:bg-muted/80 disabled:cursor-not-allowed disabled:opacity-50" disabled={!canEdit || isBusy} onClick={() => insertMsgParam(key)}>
<span className="text-center">{getSendParamLabel(key)}</span>
<code className="font-mono text-muted-foreground">{`#{${key}}`}</code>
</Button>
))}
</div>
</div>
</div>
)}
</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" variant="outline" onClick={cancelEdit} disabled={isBusy}><RotateCcw 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>
);
}

View 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>
);
}

View File

@@ -0,0 +1,29 @@
"use client";
import Image from "next/image";
export type ExcelDownloadButtonProps = {
requestExcelExport: () => void;
}
const ExcelDownloadButton = ({
requestExcelExport
}: ExcelDownloadButtonProps) => {
return (
<div className={"mr-3 mt-1.5 cursor-pointer"}>
<Image
src="/icon-excel.png"
alt="excel export"
width={27}
height={27}
className="object-contain"
onClick={requestExcelExport}
priority
/>
</div>
);
};
export default ExcelDownloadButton;

View 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>
);
}

View File

@@ -0,0 +1,37 @@
"use client";
import {KriSingleSelect} from "@/components/common/KriAutoComplete";
import {Code} from "@/types/kmusical";
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 ?? "w-full"}
spanClassName="text-sm"
badgeClassName="text-sm"
className="h-9"
/>
);
}

View File

@@ -0,0 +1,34 @@
"use client";
import {KriMultiSelect} from "@/components/common/KriAutoComplete";
import {Code} from "@/types/kmusical";
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 ?? "w-full"}
maxCount={1}
spanClassName="text-sm"
badgeClassName="text-sm"
className="h-9"
/>
);
}

View 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("kmf-category-card", className)}>
{children}
</section>
);
}

View File

@@ -0,0 +1,67 @@
"use client";
import {Search} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Input} from "@/components/ui/input";
import {FilterSelect} from "@/components/kmusical/FilterSelect";
import {MultiFilterSelect} from "@/components/kmusical/MultiFilterSelect";
import {STATUS_FILTER_OPTIONS} from "@/lib/kmusical/performance-status";
import {PERFORMANCE_FIELD_LABELS} from "@/lib/kmusical/field-labels";
import type {PerformanceFilterState} from "@/lib/kmusical/view";
import type {Code, PerformanceReviewSlot} from "@/types/kmusical";
import type {CodeGroup} from "@/query/code";
const MONTH_OPTIONS: Code[] = Array.from({length: 12}, (_, index) => ({
codeGroup: "month",
codeGroupLabel: "월",
codeValue: index + 1,
codeLabel: `${index + 1}월`,
memo: "",
}));
export function PerformanceFilterBar({
codes,
reviewSlots = [],
filters,
onFiltersChange,
onSearch,
keywordPlaceholder = "연번, 작품명 또는 단체명",
showMonth = true,
}: {
codes: Partial<Record<CodeGroup, Code[]>>;
reviewSlots?: PerformanceReviewSlot[];
filters: PerformanceFilterState;
onFiltersChange: (updater: (current: PerformanceFilterState) => PerformanceFilterState) => void;
onSearch: () => void;
keywordPlaceholder?: string;
showMonth?: boolean;
}) {
return (
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-2">
<div className="w-[180px]"><MultiFilterSelect value={filters.businessType} onChange={(value) => onFiltersChange((current) => ({...current, businessType: value}))} options={codes.business_type ?? []} placeholder={PERFORMANCE_FIELD_LABELS.businessType} /></div>
<div className="w-[180px]"><MultiFilterSelect value={filters.area} onChange={(value) => onFiltersChange((current) => ({...current, area: value}))} options={codes.area ?? []} placeholder={PERFORMANCE_FIELD_LABELS.performanceArea} /></div>
{showMonth && (
<div className="w-[140px]"><FilterSelect value={filters.month} onChange={(value) => onFiltersChange((current) => ({...current, month: value}))} options={MONTH_OPTIONS} placeholder={PERFORMANCE_FIELD_LABELS.performanceStartMonth} /></div>
)}
<Input type="date" className="w-[170px]" value={filters.monitoringDate} onChange={(event) => onFiltersChange((current) => ({...current, monitoringDate: event.target.value}))} />
<Input className="min-w-[200px] flex-1" value={filters.keyword} onChange={(event) => onFiltersChange((current) => ({...current, keyword: event.target.value}))} placeholder={keywordPlaceholder} />
<Button type="button" variant="outline" onClick={onSearch}><Search className="h-4 w-4" />조회</Button>
</div>
{reviewSlots.length > 0 && (
<div className="flex flex-wrap items-center gap-2">
{reviewSlots.map((slot) => (
<div className="w-[180px]" key={slot.reviewSlot}>
<FilterSelect
value={filters.slotStatus[slot.reviewSlot] ?? ""}
onChange={(value) => onFiltersChange((current) => ({...current, slotStatus: {...current.slotStatus, [slot.reviewSlot]: value}}))}
options={STATUS_FILTER_OPTIONS}
placeholder={`${slot.reviewLabel} 상태`}
/>
</div>
))}
</div>
)}
</div>
);
}

View 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: "kmf-status-badge--danger",
pending: "kmf-status-badge--pending",
inprogress: "kmf-status-badge--inprogress",
departed: "kmf-status-badge--departed",
arrived: "kmf-status-badge--arrived",
done: "kmf-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" && "kmf-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>
);
}

View File

@@ -8,6 +8,7 @@ export type {
KriEditorAllowedHtml,
KriEditorCommand,
KriEditorFontFamilyOption,
KriEditorWysiwygCompatibility,
KriEditorMode,
KriEditorProps,
KriEditorToolbarConfig,

View File

@@ -45,6 +45,11 @@ export type KriEditorFontFamilyOption = {
value: string
}
export type KriEditorWysiwygCompatibility = {
compatible: boolean
reason?: string
}
export type KriEditorProps = {
onEditorReady?: (editor: Editor | HTMLTextAreaElement | null) => void
onCommandReady?: (command: KriEditorCommand | null) => void

View File

@@ -14,7 +14,7 @@ function Checkbox({
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary",
"cursor-pointer peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary",
className
)}
{...props}

View File

@@ -8,7 +8,7 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
type={type}
data-slot="input"
className={cn(
"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",
"h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-left 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",
className

View File

@@ -0,0 +1,56 @@
"use client"
import * as React from "react"
import { cn } from "cn"
import { Tooltip as TooltipPrimitive } from "radix-ui"
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 }

View File

@@ -1,7 +1,13 @@
export const commonConfig = {
appName: "K-Musical 모니터링 시스템",
description: "K-Musical 모니터링 시스템",
homePath: "/",
loginPath: "/login",
logoutPath: "/logout",
} as const;
export const SITE_TITLE = "K 뮤지컬 지원사업 모니터링";
export const TOP_MENU_KEY_MAP: Record<string, string> = {
"performance-list": "사업정보",
"user-list": "계정관리",
"assign": "평가위원 배정",
};
export const TOP_MENU_PATH_MAP: Record<string, string> = {
"performance-list": "/performance",
"user-list": "/user",
"assign": "/assign",
};

View File

@@ -0,0 +1 @@
export const MONITORING_USER_ROLE = 9003;

View File

@@ -1,7 +1,15 @@
import type { SideMenuItem, TopMenuItem } from "./menu.type";
import {TopMenuItem} from "@/config/menu.type";
import {TOP_MENU_KEY_MAP, TOP_MENU_PATH_MAP} from "@/config/common.config";
export const topMenus: TopMenuItem[] = [
{ id: "home", label: "홈", path: "/" },
];
export const TOP_MENUS: TopMenuItem[] = Object.entries(TOP_MENU_KEY_MAP).map(
([key, value]) => {
const path = `/${TOP_MENU_PATH_MAP[key].replace(/^\/+/, "")}`;
export const sideMenus: SideMenuItem[] = [];
return {
id: key,
label: value,
path,
match: (pathname: string) => pathname === path,
};
}
);

View File

@@ -1,38 +1,55 @@
"use client";
import { useCallback } from "react";
import { useAtom } from "jotai";
import type { LoginUser } from "@kri/common";
import { createAuthHook, type AuthState as CommonAuthState } from "@kri/common/hooks";
import type { AuthState as CommonAuthState } from "@kri/common/hooks";
import { createPersistentAtom } from "@kri/common/jotai";
import { getLocalStorage, removeLocalStorage, setLocalStorage } from "@/store/storage/secure-storage";
import { StorageKeys } from "@/store/storage/storage-keys";
import {MONITORING_USER_ROLE} from "@/config/kmusical.config";
export type AuthState = CommonAuthState<LoginUser>;
const initialAuthState: AuthState = { user: null };
const loadInitialAuthState = (): AuthState => {
const stored = getLocalStorage(StorageKeys.AuthState);
return stored && typeof stored === "object" && "user" in stored
? { ...initialAuthState, ...(stored as Partial<AuthState>) }
: initialAuthState;
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const isLoginUser = (value: unknown): value is LoginUser => {
if (!isRecord(value)) return false;
return (
typeof value.userId === "string" &&
typeof value.userName === "string" &&
typeof value.userCmpn === "string" &&
typeof value.userTeam === "string" &&
typeof value.userRole === "number"
);
};
const { authAtom, useAuth: useCommonAuth } = createAuthHook<LoginUser>({ initialState: loadInitialAuthState() });
export const authStateAtom = authAtom;
const isPersistedAuthState = (value: unknown): value is AuthState =>
isRecord(value) && isLoginUser(value.user);
/*
* atom은 서버·클라이언트 최초 렌더 모두 initialAuthState로 시작한다.
* 저장소 값은 onMount(마운트 이후 시점)에만 반영되므로
* 서버 HTML과 클라이언트 최초 렌더가 항상 일치해 하이드레이션 오류가 발생하지 않는다.
*/
export const authStateAtom = createPersistentAtom<AuthState>(StorageKeys.AuthState, initialAuthState, {
storage: { get: getLocalStorage, set: setLocalStorage, remove: removeLocalStorage },
validate: isPersistedAuthState,
shouldRemove: (value) => value.user === null,
debugLabel: "authState",
});
export function useAuth() {
const { auth, setAuth: setCommonAuth } = useCommonAuth();
const [auth, setAuth] = useAtom(authStateAtom);
const setAuth = useCallback((next: AuthState | ((previous: AuthState) => AuthState)) => {
setCommonAuth((previous) => {
const resolved = typeof next === "function" ? next(previous) : next;
if (resolved.user === null) removeLocalStorage(StorageKeys.AuthState);
else setLocalStorage(StorageKeys.AuthState, resolved);
return resolved;
});
}, [setCommonAuth]);
const isMonitoring = auth.user?.userRole === MONITORING_USER_ROLE;
const setFromLoginResponse = useCallback((user: LoginUser) => setAuth({ user }), [setAuth]);
const logout = useCallback(() => setAuth(initialAuthState), [setAuth]);
return { auth, setAuth, setFromLoginResponse, logout } as const;
return { auth, isMonitoring, setAuth, setFromLoginResponse, logout } as const;
}

View File

@@ -1,13 +1,54 @@
import { cookies } from "next/headers";
import { createHttpClient } from "@kri/common/http";
import { NextResponse } from "next/server";
import { createHttpClient, HttpError } from "@kri/common/http";
import { serverEnv } from "@/lib/env.server";
import { CookieKeys } from "@/store/cookie/cookie-keys";
export async function createServerApi() {
async function createServerApi(rootUrl: string, defaultHeaders?: Record<string, string>) {
const cookieStore = await cookies();
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value ?? null;
return createHttpClient(serverEnv.API_SERVER, {
return createHttpClient(rootUrl, {
getToken: () => accessToken,
defaultHeaders: { "content-type": "application/json" },
defaultHeaders: {
"content-type": "application/json",
...(defaultHeaders ?? {}),
},
});
}
export const createBackApi = () => {
return createServerApi(serverEnv.API_SERVER);
}
export const createNotiHubApi = () => {
return createServerApi(serverEnv.NOTI_HUB_SERVER);
}
/*
* 엑셀/원본파일/PDF 다운로드처럼 바이너리를 그대로 내려줘야 하는 엔드포인트용.
* createHttpClient의 expectBinary는 응답 헤더(Content-Type/Content-Disposition)를 버리므로
* 여기서는 fetch 응답을 그대로 릴레이한다.
*/
export async function fetchBackBinary(path: string, init?: RequestInit) {
const cookieStore = await cookies();
const accessToken = cookieStore.get(CookieKeys.AuthToken)?.value ?? null;
const headers = new Headers(init?.headers);
if (accessToken) headers.set("authorization", `Bearer ${accessToken}`);
const response = await fetch(`${serverEnv.API_SERVER}${path}`, { ...init, headers, cache: "no-store" });
if (!response.ok) {
const data = await response.json().catch(() => null);
throw new HttpError(response.status, data, response.url, response.headers);
}
return new NextResponse(await response.arrayBuffer(), {
status: response.status,
headers: {
"content-type": response.headers.get("content-type") ?? "application/octet-stream",
...(response.headers.get("content-disposition")
? { "content-disposition": response.headers.get("content-disposition")! }
: {}),
},
});
}

View File

@@ -0,0 +1,108 @@
import {parseLocalDateString, toLocalDateString} from "@/lib/kmusical/date";
import type {PerformanceFull, PerformanceReviewSlot} from "@/types/kmusical";
export const WEEKDAY_LABELS = ["일", "월", "화", "수", "목", "금", "토"] as const;
export const MONTH_GRID_CELL_COUNT = 42;
export type CalendarDay = {
date: Date;
dateKey: string;
isCurrentMonth: boolean;
isToday: boolean;
};
export const buildMonthGrid = (visibleMonth: Date): CalendarDay[] => {
const year = visibleMonth.getFullYear();
const month = visibleMonth.getMonth();
const firstDayOfMonth = new Date(year, month, 1);
const startDate = new Date(year, month, 1 - firstDayOfMonth.getDay());
const today = toLocalDateString();
return Array.from({length: MONTH_GRID_CELL_COUNT}, (_, index) => {
const date = new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate() + index);
const dateKey = toLocalDateString(date);
return {
date,
dateKey,
isCurrentMonth: date.getMonth() === month,
isToday: dateKey === today,
};
});
};
export const chunkIntoWeeks = (days: CalendarDay[]): CalendarDay[][] => {
const weeks: CalendarDay[][] = [];
for (let index = 0; index < days.length; index += 7) {
weeks.push(days.slice(index, index + 7));
}
return weeks;
};
export const getVisiblePerformances = (
performances: PerformanceFull[],
selectedPerformanceIds: Set<string>,
selectedReviewerIds: string[]
): PerformanceFull[] => {
const reviewerIdSet = new Set(selectedReviewerIds);
return performances.filter((performance) => {
const selectedByPerformance = selectedPerformanceIds.has(performance.performanceId);
const selectedByReviewer = reviewerIdSet.size === 0
|| performance.performanceAssignList.some((assign) => reviewerIdSet.has(assign.assignUser));
return selectedByPerformance && selectedByReviewer;
});
};
const comparePerformancesInDay = (a: PerformanceFull, b: PerformanceFull) =>
(a.performanceMonitoringSchedule?.monitoringTimeInfo ?? "").localeCompare(b.performanceMonitoringSchedule?.monitoringTimeInfo ?? "", "ko")
|| a.performanceName.localeCompare(b.performanceName, "ko")
|| a.performanceId.localeCompare(b.performanceId, "ko");
export const groupPerformancesByDate = (performances: PerformanceFull[]): Map<string, PerformanceFull[]> => {
const grouped = new Map<string, PerformanceFull[]>();
for (const performance of performances) {
const date = parseLocalDateString(performance.performanceMonitoringSchedule?.monitoringDate);
if (!date) continue;
const dateKey = toLocalDateString(date);
const list = grouped.get(dateKey) ?? [];
list.push(performance);
grouped.set(dateKey, list);
}
for (const list of grouped.values()) {
list.sort(comparePerformancesInDay);
}
return grouped;
};
export const PERFORMANCE_COLOR_SLOT_COUNT = 8;
export const getPerformanceColorSlot = (performanceId: string, orderedPerformanceIds: string[]): number => {
const index = orderedPerformanceIds.indexOf(performanceId);
return index < 0 ? 0 : index % PERFORMANCE_COLOR_SLOT_COUNT;
};
export type PerformanceBadgeInfo = {
applyCount: number;
assignCount: number;
requiredAssignCount: number;
isMatchingComplete: boolean;
};
export const getPerformanceBadgeInfo = (
performance: PerformanceFull,
applyCountMap: Map<string, number>,
reviewSlots: PerformanceReviewSlot[]
): PerformanceBadgeInfo => {
const applyCount = applyCountMap.get(performance.performanceId) ?? 0;
const assignCount = performance.performanceAssignList.length;
const requiredAssignCount = reviewSlots.length;
const isMatchingComplete = requiredAssignCount > 0 && assignCount >= requiredAssignCount;
return {applyCount, assignCount, requiredAssignCount, isMatchingComplete};
};

13
src/lib/kmusical/date.ts Normal file
View File

@@ -0,0 +1,13 @@
export const toLocalDateString = (date = new Date()) => {
const pad = (value: number) => String(value).padStart(2, "0");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
};
export const parseLocalDateString = (value: string | undefined | null): Date | null => {
const match = value ? /^(\d{4})-(\d{2})-(\d{2})/.exec(value) : null;
if (!match) return null;
const [, year, month, day] = match;
const date = new Date(Number(year), Number(month) - 1, Number(day));
return Number.isNaN(date.getTime()) ? null : date;
};

View File

@@ -0,0 +1,225 @@
"use client";
import DOMPurify, { type DOMPurify as DOMPurifyInstance } from "dompurify";
import type { KriEditorWysiwygCompatibility } from "@/components/kri-editor";
const EMAIL_ALLOWED_ATTRIBUTES = {
a: ["href", "title", "style", "target", "rel"],
area: ["shape", "coords", "href", "alt", "title", "target"],
b: ["style"],
blockquote: ["cite"],
col: ["span", "width"],
colgroup: ["span", "width"],
div: ["style", "align"],
img: ["src", "width", "height", "alt", "title", "align", "style", "loading", "usemap"],
map: ["name", "id"],
mark: ["style", "data-color"],
ol: ["start", "type"],
p: ["style"],
q: ["cite"],
qrcode: ["src", "width", "height", "alt"],
span: ["style"],
table: ["summary", "width", "height", "style", "cellpadding", "cellspacing", "border", "align", "bgcolor", "role"],
tbody: ["style", "align", "valign"],
td: ["abbr", "axis", "colspan", "rowspan", "width", "height", "style", "align", "valign", "bgcolor"],
th: ["abbr", "axis", "colspan", "rowspan", "scope", "width", "height", "style", "align", "valign", "bgcolor"],
tr: ["style", "align", "valign", "bgcolor", "height"],
ul: ["type"],
} as const;
export const EMAIL_ALLOWED_TAGS = [
"a", "area", "b", "blockquote", "br", "caption", "cite", "code", "col", "colgroup", "dd", "div", "dl", "dt",
"em", "h1", "h2", "h3", "h4", "h5", "h6", "i", "img", "li", "map", "mark", "ol", "p", "pre", "q", "qrcode",
"small", "span", "strike", "strong", "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u", "ul",
] as const;
const TAGS_WITHOUT_ATTRIBUTES = new Set(
EMAIL_ALLOWED_TAGS.filter((tag) => !(tag in EMAIL_ALLOWED_ATTRIBUTES)),
);
const ALLOWED_TAG_SET = new Set<string>(EMAIL_ALLOWED_TAGS);
const ALLOWED_ATTRIBUTE_SET = new Set<string>(Object.values(EMAIL_ALLOWED_ATTRIBUTES).flat());
const ALLOWED_PROTOCOLS: Record<string, ReadonlySet<string>> = {
"a.href": new Set(["http", "https", "mailto", "tel", "ftp"]),
"area.href": new Set(["http", "https", "mailto", "tel"]),
"img.src": new Set(["http", "https"]),
"blockquote.cite": new Set(["http", "https"]),
"q.cite": new Set(["http", "https"]),
};
const WYSIWYG_ATTRIBUTES: Record<string, ReadonlySet<string>> = {
a: new Set(["href", "target", "rel", "class"]),
area: new Set(EMAIL_ALLOWED_ATTRIBUTES.area),
div: new Set(["style", "class"]),
img: new Set([...EMAIL_ALLOWED_ATTRIBUTES.img, "class", "data-kri-image"]),
map: new Set(EMAIL_ALLOWED_ATTRIBUTES.map),
mark: new Set(EMAIL_ALLOWED_ATTRIBUTES.mark),
ol: new Set(["start"]),
p: new Set(["style"]),
qrcode: new Set(EMAIL_ALLOWED_ATTRIBUTES.qrcode),
span: new Set(["style"]),
td: new Set(["colspan", "rowspan"]),
th: new Set(["colspan", "rowspan"]),
};
const WYSIWYG_TAGS = new Set([
"a", "area", "b", "br", "div", "em", "i", "img", "li", "map", "mark", "ol", "p", "qrcode", "span", "strong",
"table", "tbody", "td", "th", "tr", "u", "ul",
]);
const WYSIWYG_SPAN_STYLE_PROPERTIES = new Set(["color", "font-family", "font-size"]);
const WYSIWYG_PARAGRAPH_STYLE_PROPERTIES = new Set(["text-align"]);
function resolvePurifier(): DOMPurifyInstance | null {
if (typeof window === "undefined") return null;
if (typeof DOMPurify.sanitize === "function") return DOMPurify;
return DOMPurify(window);
}
function parseHtml(html: string): HTMLTemplateElement | null {
if (typeof document === "undefined") return null;
const template = document.createElement("template");
template.innerHTML = html;
return template;
}
function allowedAttributesFor(tagName: string): ReadonlySet<string> {
if (TAGS_WITHOUT_ATTRIBUTES.has(tagName as typeof EMAIL_ALLOWED_TAGS[number])) return new Set();
return new Set((EMAIL_ALLOWED_ATTRIBUTES as Record<string, readonly string[]>)[tagName] ?? []);
}
function hasAllowedProtocol(tagName: string, attributeName: string, value: string): boolean {
const protocols = ALLOWED_PROTOCOLS[`${tagName}.${attributeName}`];
if (!protocols) return true;
const match = /^([a-z][a-z\d+.-]*):/i.exec(value.trim());
return Boolean(match && protocols.has(match[1].toLowerCase()));
}
function styleProperties(value: string): Set<string> {
return new Set(
value.split(";")
.map((declaration) => declaration.split(":", 1)[0]?.trim().toLowerCase())
.filter((property): property is string => Boolean(property)),
);
}
function isWysiwygStyleCompatible(tagName: string, value: string): boolean {
if (tagName === "div" || tagName === "img" || tagName === "mark") return true;
const supported = tagName === "span"
? WYSIWYG_SPAN_STYLE_PROPERTIES
: tagName === "p" ? WYSIWYG_PARAGRAPH_STYLE_PROPERTIES : null;
return Boolean(supported && [...styleProperties(value)].every((property) => supported.has(property)));
}
function summarizeIssues(issues: readonly string[]): string {
const unique = [...new Set(issues)];
const visible = unique.slice(0, 3).join(", ");
const suffix = unique.length > 3 ? ` 외 ${unique.length - 3}개` : "";
return `${visible}${suffix} 항목은 WYSIWYG에서 손실될 수 있어 HTML 모드로 유지됩니다.`;
}
export function getEmailWysiwygCompatibility(html: string): KriEditorWysiwygCompatibility {
const template = parseHtml(html);
const issues: string[] = [];
if (!template) {
const tags = [...html.matchAll(/<\/?\s*([a-z][\w-]*)\b/gi)].map((match) => match[1].toLowerCase());
for (const tagName of tags) {
if (!WYSIWYG_TAGS.has(tagName)) issues.push(`<${tagName}>`);
}
} else {
for (const element of Array.from(template.content.querySelectorAll("*"))) {
const tagName = element.tagName.toLowerCase();
if (!WYSIWYG_TAGS.has(tagName)) {
issues.push(`<${tagName}>`);
continue;
}
const supportedAttributes = WYSIWYG_ATTRIBUTES[tagName] ?? new Set<string>();
for (const attribute of Array.from(element.attributes)) {
const attributeName = attribute.name.toLowerCase();
if (!supportedAttributes.has(attributeName)) {
issues.push(`<${tagName}>의 ${attributeName}`);
} else if (attributeName === "style" && !isWysiwygStyleCompatible(tagName, attribute.value)) {
issues.push(`<${tagName}>의 일부 style`);
}
}
if (tagName === "area" && element.parentElement?.tagName.toLowerCase() !== "map") {
issues.push("<map> 밖의 <area>");
}
}
}
return issues.length > 0
? { compatible: false, reason: summarizeIssues(issues) }
: { compatible: true };
}
function isEditorDecoration(tagName: string, attributeName: string, value: string): boolean {
if (tagName === "a" && attributeName === "class" && value === "kri-editor-link") return true;
if (tagName !== "img") return false;
return (attributeName === "class" && value === "max-w-full h-auto")
|| (attributeName === "data-kri-image" && value === "true");
}
export function getEmailHtmlPolicyIssues(html: string): string[] {
const template = parseHtml(html);
if (!template) return [];
const issues: string[] = [];
for (const element of Array.from(template.content.querySelectorAll("*"))) {
const tagName = element.tagName.toLowerCase();
if (!ALLOWED_TAG_SET.has(tagName)) {
issues.push(`<${tagName}> 태그`);
continue;
}
const allowedAttributes = allowedAttributesFor(tagName);
for (const attribute of Array.from(element.attributes)) {
const attributeName = attribute.name.toLowerCase();
if (isEditorDecoration(tagName, attributeName, attribute.value)) continue;
if (!allowedAttributes.has(attributeName)) {
issues.push(`<${tagName}>의 ${attributeName} 속성`);
} else if (!hasAllowedProtocol(tagName, attributeName, attribute.value)) {
issues.push(`<${tagName}>의 ${attributeName} URL`);
}
}
}
return [...new Set(issues)];
}
export function hasImageMapMarkup(html: string): boolean {
if (!html) return false;
const template = parseHtml(html);
if (!template) return /<\s*(map|area)\b/i.test(html);
return template.content.querySelector("map, area") !== null;
}
export function sanitizeEmailHtml(html: string): string {
if (!html) return "";
const purifier = resolvePurifier();
if (!purifier) return html.replace(/<[^>]*>/g, "");
const sanitized = purifier.sanitize(html, {
ALLOWED_TAGS: [...EMAIL_ALLOWED_TAGS],
ALLOWED_ATTR: [...ALLOWED_ATTRIBUTE_SET],
ALLOW_DATA_ATTR: false,
});
const template = parseHtml(sanitized);
if (!template) return "";
for (const element of Array.from(template.content.querySelectorAll("*"))) {
const tagName = element.tagName.toLowerCase();
const allowedAttributes = allowedAttributesFor(tagName);
for (const attribute of Array.from(element.attributes)) {
const attributeName = attribute.name.toLowerCase();
if (!allowedAttributes.has(attributeName) || !hasAllowedProtocol(tagName, attributeName, attribute.value)) {
element.removeAttribute(attribute.name);
}
}
}
return template.innerHTML.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "").trim();
}

View File

@@ -0,0 +1,61 @@
export const USER_FIELD_LABELS = {
userId: "ID",
userName: "이름",
userCmpn: "소속",
userTeam: "팀",
userGrade: "직급",
userRole: "권한",
userArea: "지역",
userGender: "성별",
userAge: "연령",
userGenre: "분야",
userHasCar: "차량 보유",
userTel: "연락처",
userEmail: "이메일",
memo: "메모",
} as const;
export const PERFORMANCE_FIELD_LABELS = {
performanceNo: "NO",
performanceId: "연번",
businessType: "사업유형",
performanceArea: "지역",
performanceAreaDetail: "지역 세부",
artistName: "단체명",
performanceName: "작품명",
performanceStartMonth: "사업 수행 월",
performanceDtInfo: "사업 일정",
performanceTimeInfo: "운영 시간",
ticketReservationStatus: "티켓 예약",
ticketReservationMemo: "티켓 비고",
performanceMemo: "메모",
monitoringDate: "모니터링 일정",
monitoringTimeInfo: "모니터링 시간",
monitoringAddress: "모니터링 방문장소",
monitoringPaymentDate: "요원 비용지급일",
consultingStatus: "컨설팅 진행여부",
checkDeliver: "교부여부",
checkReport: "보고서 확인여부",
ownStaffName: "대표자 명",
ownStaffTel1: "대표자 연락처1",
ownStaffTel2: "대표자 연락처2",
ownStaffEmail: "대표자 이메일",
contactStaffName: "실무자 명",
contactStaffTel1: "실무자 연락처1",
contactStaffTel2: "실무자 연락처2",
contactStaffEmail: "실무자 이메일",
clientManagerName: "예경 담당자 명",
} as const;
export const SEND_PARAM_LABELS = {
...USER_FIELD_LABELS,
...PERFORMANCE_FIELD_LABELS,
} as const;
export const getSendParamLabel = (key: string) =>
SEND_PARAM_LABELS[key as keyof typeof SEND_PARAM_LABELS] ?? key;

51
src/lib/kmusical/file.ts Normal file
View File

@@ -0,0 +1,51 @@
import {downloadFile} from "@kri/common/browser";
const trimDispositionValue = (value: string) => value.trim().replace(/^"|"$/g, "");
const decodeDispositionValue = (value: string) => {
const trimmed = trimDispositionValue(value);
const encodedValue = trimmed.includes("''") ? trimmed.split("''").slice(1).join("''") : trimmed;
try {
return decodeURIComponent(encodedValue);
} catch {
return encodedValue;
}
};
const getDispositionParams = (contentDisposition: string) =>
contentDisposition
.split(";")
.slice(1)
.map((part) => part.trim())
.reduce<Record<string, string>>((params, part) => {
const separatorIndex = part.indexOf("=");
if (separatorIndex < 0) return params;
const key = part.slice(0, separatorIndex).trim().toLowerCase();
const value = part.slice(separatorIndex + 1).trim();
if (key && value) params[key] = value;
return params;
}, {});
export const getFileNameFromContentDisposition = (contentDisposition?: string | null) => {
if (!contentDisposition) return undefined;
const params = getDispositionParams(contentDisposition);
const fileName = params["filename*"] || params.filename;
return fileName ? decodeDispositionValue(fileName) : undefined;
};
export const downloadBlob = (buffer: ArrayBuffer, fileName: string, type = "application/octet-stream") => {
downloadFile(new Blob([buffer], {type}), fileName);
};
export const downloadExcelBuffer = (buffer: ArrayBuffer, fileName: string) => {
downloadBlob(buffer, fileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
};
export const downloadFromUrl = (url: string) => {
const link = document.createElement("a");
link.href = url;
link.download = "";
document.body.appendChild(link);
link.click();
link.remove();
};

View File

@@ -0,0 +1,48 @@
import {PerformanceFull, UserCompact} from "@/types/kmusical";
import {SEND_TYPE, TMPLAT_PURPOSE, Template} from "@/types/notification";
export const PHONE_VERIFICATION_PREVIEW = "인증번호는 [######] 입니다.";
export const isPhoneVerificationSupported = (template: Pick<Template, "tmplatTy">) =>
template.tmplatTy === SEND_TYPE.EMAIL || template.tmplatTy === SEND_TYPE.SMS;
export const buildTemplatePreviewBody = (template: Pick<Template, "tmplatBody" | "tmplatPurpose">) =>
template.tmplatPurpose === TMPLAT_PURPOSE.PHONE_VERIFICATION
? `${template.tmplatBody}\n${PHONE_VERIFICATION_PREVIEW}`
: template.tmplatBody;
export const getSmsByteLength = (value: string) =>
Array.from(value).reduce((total, character) => total + (character.charCodeAt(0) > 0x7f ? 2 : 1), 0);
export const toNotificationParamValue = (value: unknown) => value == null ? "" : String(value);
export const buildUserMsgParam = (user: UserCompact): Record<string, string> => ({
...Object.fromEntries(
Object.entries(user.userDetail ?? {}).map(([key, value]) => [key, toNotificationParamValue(value)])
),
userId: toNotificationParamValue(user.userId),
userCmpn: toNotificationParamValue(user.userCmpn),
userTeam: toNotificationParamValue(user.userTeam),
userName: toNotificationParamValue(user.userName),
userRole: toNotificationParamValue(user.userRole),
});
export const buildPerformanceSmsParams = (performance: PerformanceFull): Record<string, string> => ({
businessType: toNotificationParamValue(performance.businessType),
performanceArea: toNotificationParamValue(performance.performanceArea),
artistName: toNotificationParamValue(performance.artistName),
performanceName: toNotificationParamValue(performance.performanceName),
performanceStartMonth: toNotificationParamValue(performance.performanceStartMonth),
performanceDtInfo: toNotificationParamValue(performance.performanceDtInfo),
performanceTimeInfo: toNotificationParamValue(performance.performanceTimeInfo),
ticketReservationStatus: toNotificationParamValue(performance.ticketReservationStatus),
ticketReservationMemo: toNotificationParamValue(performance.ticketReservationMemo),
performanceMemo: toNotificationParamValue(performance.performanceMemo),
...Object.fromEntries(
Object.entries(performance.performanceDetail ?? {}).map(([key, value]) => [key, toNotificationParamValue(value)])
),
...Object.fromEntries(
Object.entries(performance.performanceMonitoringSchedule ?? {}).map(([key, value]) => [key, toNotificationParamValue(value)])
),
performanceId: toNotificationParamValue(performance.performanceId),
});

View File

@@ -0,0 +1,186 @@
import {Code, PerformanceAssign, PerformanceFull, PerformanceReview, PerformanceReviewSlot, REVIEW_STATUS, REVIEW_TYPE, ReviewType, UserCompact} from "@/types/kmusical";
import type {StatusPillVariant} from "@/components/kmusical/StatusPill";
export type ReviewSlot = number;
export const getReviewTypeLabel = (reviewType: ReviewType) =>
reviewType === REVIEW_TYPE.CONSULTING ? "컨설팅" : "현장 모니터링";
export type MonitoringSlot = {
reviewSlot: ReviewSlot;
reviewType?: ReviewType;
assign?: PerformanceAssign;
user?: UserCompact;
review?: PerformanceReview;
};
export type MonitoringDisplayRow = {
index: ReviewSlot;
slot: MonitoringSlot;
userId?: string;
review?: PerformanceReview;
};
export type StatusDisplay = {
label: string;
variant: StatusPillVariant;
};
export const STATUS_FILTER = {
UNASSIGNED: "-1001",
PENDING: "-1003",
DONE: "-1007",
} as const;
export const makeStatusOption = (value: string, label: string): Code => ({
codeGroup: "status_filter",
codeValue: Number(value),
codeGroupLabel: "상태",
codeLabel: label,
memo: "",
});
export const statusFilterOptions = {
unassigned: makeStatusOption(STATUS_FILTER.UNASSIGNED, "미배치"),
pending: makeStatusOption(STATUS_FILTER.PENDING, "미진행"),
done: makeStatusOption(STATUS_FILTER.DONE, "완료"),
};
export const STATUS_FILTER_OPTIONS: Code[] = [
statusFilterOptions.unassigned,
statusFilterOptions.pending,
statusFilterOptions.done,
];
export const normalizeStatusLabel = (label?: string) => label?.replace(/\s/g, "") ?? "";
export const labelHasComplete = (label?: string) => normalizeStatusLabel(label).includes("완료");
const getSlotAssign = (performance: Partial<PerformanceFull>, slot: ReviewSlot) =>
(performance.performanceAssignList ?? []).find((assign) => assign.reviewSlot === slot);
const getSlotReview = (performance: Partial<PerformanceFull>, slot: ReviewSlot) => {
const map = performance.performanceReviewMap ?? {};
for (const [userId, review] of Object.entries(map)) {
if (review.reviewSlot === slot) return {userId, review};
}
return undefined;
};
/*
* reviewSlot은 평가위원 슬롯 번호로, 사업마다 몇 개가 쓰일지(1~5 이상) 고정돼 있지 않다.
* 담당자는 관리자가 강제로 배정/취소하므로 performanceAssignList에는 배정된 건만 남는다.
*/
export const getReviewSlots = (performance: Partial<PerformanceFull>): ReviewSlot[] => {
const assignSlots = (performance.performanceAssignList ?? []).map((assign) => assign.reviewSlot);
const reviewSlots = Object.values(performance.performanceReviewMap ?? {}).map((review) => review.reviewSlot);
return Array.from(new Set([...assignSlots, ...reviewSlots])).sort((a, b) => a - b);
};
export const getMonitoringSlot = (
performance: Partial<PerformanceFull>,
reviewSlot: ReviewSlot,
reviewType?: ReviewType
): MonitoringSlot => ({
reviewSlot,
reviewType,
assign: getSlotAssign(performance, reviewSlot),
review: getSlotReview(performance, reviewSlot)?.review,
});
/*
* reviewSlots(GET /review/slots)를 전달하면 슬롯별 reviewType(모니터링/컨설팅)까지 채워서 반환한다.
* 전달하지 않으면 해당 공연의 배정/평가 데이터에 등장한 슬롯 번호만으로 구성한다(reviewType 없음).
*/
export const getMonitoringSlots = (
performance: Partial<PerformanceFull>,
reviewSlots?: PerformanceReviewSlot[]
): MonitoringSlot[] => {
if (reviewSlots) {
return reviewSlots.map(({reviewSlot, reviewType}) => getMonitoringSlot(performance, reviewSlot, reviewType));
}
return getReviewSlots(performance).map((reviewSlot) => getMonitoringSlot(performance, reviewSlot));
};
export const getMonitoringDisplayRow = (
performance: Partial<PerformanceFull>,
reviewSlot: ReviewSlot,
reviewType?: ReviewType
): MonitoringDisplayRow => {
const slot = getMonitoringSlot(performance, reviewSlot, reviewType);
return {
index: reviewSlot,
slot,
userId: slot.assign?.assignUser,
review: slot.review,
};
};
export const getReviewRows = (performance: Partial<PerformanceFull>) =>
Object.entries(performance.performanceReviewMap ?? {}).map(([userId, review]) => ({userId, review}));
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 isReviewComplete = (review?: PerformanceReview) => {
return review?.reviewStatus === REVIEW_STATUS.DONE;
};
export const getReviewFilterValue = (
review: PerformanceReview | undefined,
{
assigned = Boolean(review),
alwaysAssigned = false,
}: {
assigned?: boolean;
alwaysAssigned?: boolean;
} = {}
) => {
if (!alwaysAssigned && !assigned && !review) return STATUS_FILTER.UNASSIGNED;
if (isReviewComplete(review)) return STATUS_FILTER.DONE;
return STATUS_FILTER.PENDING;
};
export const getReviewStatusDisplay = (
label?: string,
review?: PerformanceReview,
assigned = Boolean(review)
): StatusDisplay => {
if (!assigned) return {label: "미배치", variant: "danger"};
if (isReviewComplete(review)) return {label: label || "완료", variant: "done"};
return {label: label || "미진행", variant: "pending"};
};
export const getReviewRecordedAt = (review?: PerformanceReview) => {
return review?.reviewDt ? formatDateTime(new Date(review.reviewDt)) : "-";
}
export const getCompleteRecordedAt = (review?: PerformanceReview) => {
return isReviewComplete(review) ? getReviewRecordedAt(review) : "-";
}
export const getMonitoringFilterValue = (row: MonitoringDisplayRow) => {
if (isReviewComplete(row.review)) return STATUS_FILTER.DONE;
if (!row.slot.assign) return STATUS_FILTER.UNASSIGNED;
return STATUS_FILTER.PENDING;
};
export const getMonitoringStatusDisplay = (label: string | undefined, slot?: MonitoringSlot): StatusDisplay => {
if (!slot?.assign) return {label: "미배치", variant: "danger"};
if (isReviewComplete(slot.review)) return {label: label || "완료", variant: "done"};
return {label: label || "미진행", variant: "pending"};
};
export const getMonitoringDisplayStatus = (
row: MonitoringDisplayRow,
label?: string,
reviewLabel?: string
): StatusDisplay => {
if (isReviewComplete(row.review)) return {label: reviewLabel || "완료", variant: "done"};
return getMonitoringStatusDisplay(label, row.slot);
};

View File

@@ -0,0 +1,53 @@
"use client";
import DOMPurify, { type DOMPurify as DOMPurifyInstance } from "dompurify";
export type SanitizeHtmlOptions = {
tags?: string[];
attributes?: string[];
};
// Next.js SSR(Node) 환경에서는 dompurify가 window에 바인딩된 인스턴스가 아니라
// (window: Window) => DOMPurify 형태의 factory만 노출한다. window가 없으면
// factory를 호출할 방법이 없으므로, 여기서 안전하게 null로 폴백한다.
function resolvePurifier(): DOMPurifyInstance | null {
if (typeof window === "undefined") return null;
if (typeof DOMPurify.sanitize === "function") return DOMPurify;
return DOMPurify(window);
}
export function sanitizeHtml(
input: string,
options?: SanitizeHtmlOptions,
): string {
if (!input) {
return "";
}
const purifier = resolvePurifier();
if (!purifier) {
// DOM이 없어 실제 sanitize를 수행할 수 없는 환경(SSR 등)에서는
// 검증되지 않은 HTML을 그대로 노출하지 않도록 태그를 모두 제거한 텍스트만 반환한다.
// 브라우저에서 하이드레이션된 이후 재계산될 때 실제 sanitize 결과로 대체된다.
return input.replace(/<[^>]*>/g, "");
}
return purifier.sanitize(
input,
{
USE_PROFILES: {
html: true,
},
ADD_TAGS: options?.tags ?? [],
ADD_ATTR: options?.attributes ?? [],
},
);
}
export function sanitizeHtmlForPreview(
input: string,
options?: SanitizeHtmlOptions,
): string {
return sanitizeHtml(input, options);
}

124
src/lib/kmusical/view.ts Normal file
View File

@@ -0,0 +1,124 @@
import {Code, PerformanceCompact, PerformanceFull, UserFull} from "@/types/kmusical";
import {CodeGroup} from "@/query/code";
import {getMonitoringDisplayRow, getMonitoringFilterValue} from "@/lib/kmusical/performance-status";
export const ROLE = {
ADMIN: 1001,
RESEARCHER: 1002,
FIELD_INSPECTOR: 1003,
CONTACT_AGENT: 1004,
FOUNDATION: 2011,
MONITORING: 9003,
} as const;
export const getRoleGroup = (role?: number | null) => {
if (!role) return 0;
return Math.floor(role / 1000) * 1000;
};
export const isResearcherRole = (role?: number | null) => !role ? false : role <= ROLE.RESEARCHER;
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 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,
key: string,
fallback = ""
) => {
if (!detail) return fallback;
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 type PerformanceFilterState = {
businessType: string[];
area: string[];
month: string;
monitoringDate: string;
slotStatus: Record<number, string>;
keyword: string;
};
export const filterPerformance = (
item: PerformanceCompact | PerformanceFull,
filters: Partial<PerformanceFilterState>
) => {
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));
};
const matchesSlotStatus = Object.entries(filters.slotStatus ?? {}).every(
([reviewSlot, status]) => !status || getMonitoringFilterValue(getMonitoringDisplayRow(item, Number(reviewSlot))) === status
);
return (
matches(filters.businessType, item.businessType) &&
matches(filters.area, item.performanceArea) &&
matches(filters.month, item.performanceStartMonth) &&
(!filters.monitoringDate || schedule?.monitoringDate === filters.monitoringDate) &&
matchesSlotStatus &&
(
includesText(item.performanceId, 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, "userArea");
const gender = getDetailValue(detail, "userGender");
const genre = getDetailValue(detail, "userGenre");
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, "userTel"), keyword) ||
includesText(getDetailValue(detail, "userEmail"), keyword)
)
);
};

58
src/query/assign.ts Normal file
View File

@@ -0,0 +1,58 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { nextApi } from "@/lib/http-client";
import { queryKeys } from "@/query/key/keys";
import type {
AssignUserCount,
MonitoringApplyUser,
PerformanceApplyCount,
PerformanceAssign,
PerformanceAssignRequest,
} from "@/types/kmusical";
export const useMonitoringApplyUsersCountQuery = () => useQuery({
queryKey: queryKeys.assign.monitoringApplyUsersCount,
queryFn: () => nextApi.get<PerformanceApplyCount[]>("/assign/monitoring/apply-users/count"),
});
export const useMonitoringApplyUsersQuery = (performanceId: string, options?: {ignoreGlobalLoading?: boolean}) => useQuery({
queryKey: queryKeys.assign.monitoringApplyUsers(performanceId),
queryFn: () => nextApi.get<MonitoringApplyUser[]>(`/assign/monitoring/apply-users/${encodeURIComponent(performanceId)}`),
enabled: Boolean(performanceId),
meta: {ignoreGlobalLoading: options?.ignoreGlobalLoading ?? false},
});
export const useAllMonitoringApplyUsersQuery = (enabled = true) => useQuery({
queryKey: queryKeys.assign.allMonitoringApplyUsers,
queryFn: () => nextApi.get<MonitoringApplyUser[]>("/assign/monitoring/apply-users"),
enabled,
});
export const useAssignUserCountsQuery = () => useQuery({
queryKey: queryKeys.assign.userCounts,
queryFn: () => nextApi.get<AssignUserCount[]>("/assign/users/count"),
});
export function useConfirmAssignMutation() {
const client = useQueryClient();
return useMutation({
mutationFn: (request: PerformanceAssignRequest) => nextApi.post<PerformanceAssign>("/assign", request),
onSuccess: () => {
client.invalidateQueries({ queryKey: queryKeys.assign.all });
client.invalidateQueries({ queryKey: queryKeys.performance.all });
},
});
}
export function useCancelAssignMutation() {
const client = useQueryClient();
return useMutation({
mutationFn: ({ performanceId, reviewSlot }: { performanceId: string; reviewSlot: number }) =>
nextApi.del<void>(`/assign/${encodeURIComponent(performanceId)}/${reviewSlot}`),
onSuccess: () => {
client.invalidateQueries({ queryKey: queryKeys.assign.all });
client.invalidateQueries({ queryKey: queryKeys.performance.all });
},
});
}

44
src/query/code.ts Normal file
View File

@@ -0,0 +1,44 @@
"use client";
import { useQueries, useQuery } from "@tanstack/react-query";
import { nextApi } from "@/lib/http-client";
import { queryKeys } from "@/query/key/keys";
import type { Code } from "@/types/kmusical";
export type CodeGroup = string;
export const CODE_GROUPS = [
"area",
"business_type",
"gender",
"genre",
"has_car",
"review_status",
"review_type",
"staff_type",
"ticket_reservation_status",
"user_role",
] as const;
export const useCodeListQuery = (codeGroup: CodeGroup) => useQuery({
queryKey: queryKeys.code.group(codeGroup),
queryFn: () => nextApi.get<Code[]>(`/code/${encodeURIComponent(codeGroup)}`),
enabled: Boolean(codeGroup),
});
export function useCodesQuery(groups: readonly CodeGroup[] = CODE_GROUPS) {
return useQueries({
queries: groups.map((codeGroup) => ({
queryKey: queryKeys.code.group(codeGroup),
queryFn: () => nextApi.get<Code[]>(`/code/${encodeURIComponent(codeGroup)}`),
staleTime: 10 * 60_000,
})),
combine: (results) => ({
data: Object.fromEntries(
groups.map((group, index) => [group, results[index].data ?? []])
) as Record<CodeGroup, Code[]>,
isLoading: results.some((result) => result.isLoading),
isError: results.some((result) => result.isError),
}),
});
}

View File

@@ -3,4 +3,34 @@ export const queryKeys = {
all: ["example"] as const,
detail: (id: string) => ["example", id] as const,
},
assign: {
all: ["assign"] as const,
monitoringApplyUsersCount: ["assign", "monitoring-apply-users-count"] as const,
monitoringApplyUsers: (performanceId: string) => ["assign", "monitoring-apply-users", performanceId] as const,
allMonitoringApplyUsers: ["assign", "monitoring-apply-users", "all"] as const,
userCounts: ["assign", "user-counts"] as const,
},
code: {
all: ["code"] as const,
group: (codeGroup: string) => ["code", codeGroup] as const,
},
performance: {
all: ["performance"] as const,
list: ["performance", "list"] as const,
listCompact: ["performance", "list", "compact"] as const,
detail: (performanceId: string) => ["performance", performanceId] as const,
},
review: {
all: ["review"] as const,
slots: ["review", "slots"] as const,
detail: (performanceId: string, reviewSlot: number) => ["review", performanceId, reviewSlot] as const,
},
user: {
all: ["user"] as const,
list: (userRole: number) => ["user", "list", userRole] as const,
detail: (userId: string) => ["user", userId] as const,
},
sms: {
cursor: ["sms", "cursor"] as const,
},
} as const;

109
src/query/notification.ts Normal file
View File

@@ -0,0 +1,109 @@
"use client";
import {useMutation, useQueries, useQuery, useQueryClient} from "@tanstack/react-query";
import {nextApi} from "@/lib/http-client";
import {
BulkSendResponse,
SaveTemplateRequest,
SendEmailBulkRequest, SendSmsBulkRequest,
Template
} from "@/types/notification";
export const SMS_TEMPLATE_IDS = {
ACCOUNT_MONITORING: 94,
ASSIGN_CONFIRM: 93,
CUSTOM: 92,
INFORM_ASSIGN: 91,
REMIND_ASSIGN: 90,
} as const;
export const EML_TEMPLATE_IDS = {
CUSTOM: 89,
} as const;
export const NOTIFICATION_REQUEST_SERVICE = "k-musical-manage";
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 useNotificationTemplatesQuery(templateIdxList: number[], enabled = true) {
return useQueries({
queries: templateIdxList.map((templateIdx) => ({
queryKey: ["notification", "template", templateIdx],
queryFn: () => nextApi.get<Template>(`/notification/template/${templateIdx}`),
enabled: enabled && templateIdx > 0,
})),
combine: (results) => ({
data: results.flatMap((result) => result.data ? [result.data] : []),
isLoading: results.some((result) => result.isLoading),
isError: results.some((result) => result.isError),
}),
});
}
export function useSaveNotificationTemplateMutation() {
return useMutation({
mutationFn: (data: SaveTemplateRequest) => {
const formData = new FormData();
formData.append(
"template",
new Blob([JSON.stringify(data)], {type: "application/json"})
);
return nextApi.patchForm<Template>("/notification/template", formData);
},
});
}
export function useSendSmsBulkMutation() {
return useMutation({
mutationFn: (data: SendSmsBulkRequest) =>
nextApi.post<BulkSendResponse>("/notification/sms-bulk", data),
});
}
export function useSendEmailBulkMutation() {
return useMutation({
mutationFn: (data: SendEmailBulkRequest) =>
nextApi.post<BulkSendResponse>("/notification/email-bulk", data),
});
}
export function useSaveEmailTemplateMutation() {
const client = useQueryClient();
return useMutation({
mutationFn: ({template, files, deleteFileNames}: {template: Template; files: File[]; deleteFileNames: string[]}) => {
const formData = new FormData();
formData.append("template", new Blob([JSON.stringify(template)], {type: "application/json"}));
files.forEach((file) => formData.append("files", file, file.name));
const query = new URLSearchParams();
deleteFileNames.forEach((name) => query.append("deleteFileNames", name));
return nextApi.patchForm<Template>(`/notification/template?${query}`, formData);
},
onSuccess: (template) => client.setQueryData(["notification", "template", template.tmplatIdx], template),
});
}
export function useUploadEmailImageMutation() {
return useMutation({
mutationFn: ({projectCode, file}: {projectCode: string; file: File}) => {
const formData = new FormData();
formData.append("file", file, file.name);
return nextApi.putForm<string>(`/notification/template/body-image/${encodeURIComponent(projectCode)}`, formData);
},
});
}
export function useDownloadEmailAttachmentMutation() {
return useMutation({
mutationFn: ({templateIdx, fileName}: {templateIdx: number; fileName: string}) =>
nextApi.get<ArrayBuffer>(`/notification/template/${templateIdx}/attachment`, {
query: {fileName}, expectBinary: true,
}),
});
}

60
src/query/performance.ts Normal file
View File

@@ -0,0 +1,60 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { ExcelUploadResult } from "@kri/common";
import { nextApi } from "@/lib/http-client";
import { queryKeys } from "@/query/key/keys";
import type { PerformanceCompact, PerformanceFull } from "@/types/kmusical";
export const usePerformanceListQuery = () => useQuery({
queryKey: queryKeys.performance.list,
queryFn: () => nextApi.get<PerformanceFull[]>("/performance/list"),
});
export const usePerformanceCompactListQuery = () => useQuery({
queryKey: queryKeys.performance.listCompact,
queryFn: () => nextApi.get<PerformanceCompact[]>("/performance/list/compact"),
});
export const usePerformanceQuery = (performanceId: string) => useQuery({
queryKey: queryKeys.performance.detail(performanceId),
queryFn: () => nextApi.get<PerformanceFull>(`/performance/${encodeURIComponent(performanceId)}`),
enabled: Boolean(performanceId),
});
export function useUpdatePerformanceMutation() {
const client = useQueryClient();
return useMutation({
mutationFn: (request: PerformanceCompact) => nextApi.patch<void>("/performance", request),
onSuccess: () => client.invalidateQueries({ queryKey: queryKeys.performance.all }),
});
}
export function useDeletePerformanceMutation() {
const client = useQueryClient();
return useMutation({
mutationFn: (performanceId: string) => nextApi.del<void>(`/performance/${encodeURIComponent(performanceId)}`),
onSuccess: () => client.invalidateQueries({ queryKey: queryKeys.performance.all }),
});
}
export function useExportPerformanceMutation() {
return useMutation({
mutationFn: (performanceIds: string[]) =>
nextApi.post<ArrayBuffer>("/performance/excel/download", performanceIds, { expectBinary: true }),
});
}
export function useExportPerformanceTemplateMutation() {
return useMutation({
mutationFn: () => nextApi.post<ArrayBuffer>("/performance/excel/template", undefined, { expectBinary: true }),
});
}
export function useUploadPerformanceExcelMutation() {
const client = useQueryClient();
return useMutation({
mutationFn: (formData: FormData) => nextApi.postForm<ExcelUploadResult>("/performance/excel/upload", formData),
onSuccess: () => client.invalidateQueries({ queryKey: queryKeys.performance.all }),
});
}

65
src/query/review.ts Normal file
View File

@@ -0,0 +1,65 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { nextApi } from "@/lib/http-client";
import { queryKeys } from "@/query/key/keys";
import type { PerformanceReview, PerformanceReviewSlot } from "@/types/kmusical";
export const useReviewSlotsQuery = () => useQuery({
queryKey: queryKeys.review.slots,
queryFn: () => nextApi.get<PerformanceReviewSlot[]>("/review/slots"),
});
export const useReviewFileQuery = (performanceId: string, reviewSlot: number) => useQuery({
queryKey: queryKeys.review.detail(performanceId, reviewSlot),
queryFn: () => nextApi.get<PerformanceReview>(`/review/${encodeURIComponent(performanceId)}/${reviewSlot}`),
enabled: Boolean(performanceId),
});
export function useUploadReviewFileMutation(performanceId: string, reviewSlot: number) {
const client = useQueryClient();
return useMutation({
mutationFn: ({ formData, paramUserId }: { formData: FormData; paramUserId?: string }) =>
nextApi.postForm<PerformanceReview>(
`/review/${encodeURIComponent(performanceId)}/${reviewSlot}`,
formData,
paramUserId ? { query: { paramUserId } } : undefined
),
onSuccess: () => client.invalidateQueries({ queryKey: queryKeys.review.detail(performanceId, reviewSlot) }),
});
}
export function useDownloadReviewOriginalMutation() {
return useMutation({
mutationFn: ({ performanceId, reviewSlot }: { performanceId: string; reviewSlot: number }) =>
nextApi.get<ArrayBuffer>(`/review/download/${encodeURIComponent(performanceId)}/${reviewSlot}`, { expectBinary: true }),
});
}
export function useDownloadReviewPdfMutation() {
return useMutation({
mutationFn: ({ performanceId, reviewSlot }: { performanceId: string; reviewSlot: number }) =>
nextApi.get<ArrayBuffer>(`/review/pdf/${encodeURIComponent(performanceId)}/${reviewSlot}`, { expectBinary: true }),
});
}
export function useDownloadReviewTemplateMutation() {
return useMutation({
mutationFn: (reviewType: number) =>
nextApi.get<ArrayBuffer>(`/review/template/download/${reviewType}`, { expectBinary: true }),
});
}
export function useDownloadReviewPdfTemplateMutation() {
return useMutation({
mutationFn: (reviewType: number) =>
nextApi.get<ArrayBuffer>(`/review/template/pdf/${reviewType}`, { expectBinary: true }),
});
}
export function useUploadReviewTemplateMutation() {
return useMutation({
mutationFn: ({ reviewType, formData }: { reviewType: number; formData: FormData }) =>
nextApi.postForm<string>(`/review/template/upload/${reviewType}`, formData),
});
}

57
src/query/user.ts Normal file
View File

@@ -0,0 +1,57 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { ExcelUploadResult } from "@kri/common";
import { nextApi } from "@/lib/http-client";
import { queryKeys } from "@/query/key/keys";
import type { UserFull } from "@/types/kmusical";
export const useUserListQuery = (userRole: number) => useQuery({
queryKey: queryKeys.user.list(userRole),
queryFn: () => nextApi.get<UserFull[]>(`/user/list/${userRole}`),
});
export const useUserQuery = (userId: string) => useQuery({
queryKey: queryKeys.user.detail(userId),
queryFn: () => nextApi.get<UserFull>(`/user/${encodeURIComponent(userId)}`),
enabled: Boolean(userId),
});
export function useUpdateUserMutation() {
const client = useQueryClient();
return useMutation({
mutationFn: (request: UserFull) => nextApi.patch<void>("/user", request),
onSuccess: () => client.invalidateQueries({ queryKey: queryKeys.user.all }),
});
}
export function useDeleteUserMutation() {
const client = useQueryClient();
return useMutation({
mutationFn: (userId: string) => nextApi.del<void>(`/user/${encodeURIComponent(userId)}`),
onSuccess: () => client.invalidateQueries({ queryKey: queryKeys.user.all }),
});
}
export function useExportUserMutation() {
return useMutation({
mutationFn: ({ userRole, userIds }: { userRole: number; userIds: string[] }) =>
nextApi.post<ArrayBuffer>(`/user/excel/download/${userRole}`, userIds, { expectBinary: true }),
});
}
export function useExportUserTemplateMutation() {
return useMutation({
mutationFn: (userRole: number) =>
nextApi.post<ArrayBuffer>(`/user/excel/template/${userRole}`, undefined, { expectBinary: true }),
});
}
export function useUploadUserExcelMutation() {
const client = useQueryClient();
return useMutation({
mutationFn: ({ userRole, formData }: { userRole: number; formData: FormData }) =>
nextApi.postForm<ExcelUploadResult>(`/user/excel/upload/${userRole}`, formData),
onSuccess: () => client.invalidateQueries({ queryKey: queryKeys.user.all }),
});
}

View File

@@ -1 +1,10 @@
export type DialogId = "exampleDialog";
export type DialogId =
| "exampleDialog"
| "assignMonitoringDialog"
| "assignSmsSendDialog"
| "assignCalendarDialog"
| "performanceDetailDialog"
| "performanceExcelRegisterDialog"
| "userExcelRegisterDialog"
| "userSmsSendDialog"
| "userEmailSendDialog";

141
src/types/kmusical.ts Normal file
View File

@@ -0,0 +1,141 @@
export const PDF_CONVERT_STATUS = {
IN_PROGRESS: 0,
COMPLETED: 1,
NOT_TARGET: 8,
FAILED: 9,
} as const;
export type PdfConvertStatus = typeof PDF_CONVERT_STATUS[keyof typeof PDF_CONVERT_STATUS];
// Code
export type Code = {
codeGroup: string;
codeGroupLabel: string;
codeLabel: string;
codeValue: number;
memo: string;
};
// User
export type UserCompact = {
userCmpn: string;
userDetail: Record<string, string>;
userId: string;
userName: string;
userRole: number;
userTeam: string;
};
export type UserFull = {
memo: string;
userCmpn: string;
userDetail: Record<string, string>;
userId: string;
userName: string;
userPw: string;
userRole: number;
userTeam: string;
};
// Assign
export type PerformanceAssign = {
assignStatus: number;
assignUser: string;
performanceId: string;
reviewSlot: number;
};
export type PerformanceAssignRequest = {
performanceId: string;
reviewSlot: number;
userId: string;
};
export type PerformanceApplyCount = {
applyCnt: number;
performanceId: string;
};
export type MonitoringApplyUser = {
performanceId: string;
user: UserCompact;
userId: string;
};
export type AssignUserCount = {
assignCount: number;
assignUser: string;
};
// Performance
export type PerformanceStaff = {
id: number;
performanceId: string;
staffEmail: string;
staffName: string;
staffTel1: string;
staffTel2: string;
staffType: number;
};
export type PerformanceMonitoringSchedule = {
id: number;
monitoringAddress: string;
monitoringDate: string;
monitoringTimeInfo: string;
performanceId: string;
};
export const REVIEW_STATUS = {
PENDING: 0,
DONE: 10,
} as const;
export type ReviewStatus = typeof REVIEW_STATUS[keyof typeof REVIEW_STATUS];
export type PerformanceReview = {
pdfConvert: PdfConvertStatus;
pdfFileName: string;
performanceId: string;
regUser: string;
reviewDt: string;
reviewSlot: number;
reviewStatus: ReviewStatus;
uploadFileName: string;
};
export const REVIEW_TYPE = {
MONITORING: 1,
CONSULTING: 2,
} as const;
export type ReviewType = typeof REVIEW_TYPE[keyof typeof REVIEW_TYPE];
export type PerformanceReviewSlot = {
reviewSlot: number;
reviewType: ReviewType;
reviewLabel: string;
};
export type PerformanceCompact = {
performanceNo: number;
performanceId: string;
artistName: string;
businessType: number;
performanceArea: number;
performanceDetail: Record<string, string>;
performanceDtInfo: string;
performanceMemo: string;
performanceMonitoringSchedule: PerformanceMonitoringSchedule;
performanceName: string;
performanceStaff: PerformanceStaff[];
performanceStartMonth: number;
performanceTimeInfo: string;
ticketReservationMemo: string;
ticketReservationStatus: number;
};
export type PerformanceFull = PerformanceCompact & {
performanceAssignList: PerformanceAssign[];
performanceReviewMap: Record<string, PerformanceReview>;
};

81
src/types/notification.ts Normal file
View File

@@ -0,0 +1,81 @@
export const SEND_TYPE = {
EMAIL: 11,
SMS: 21,
LMS_MMS: 22,
KKO_AT: 31,
} as const;
export type SendType = (typeof SEND_TYPE)[keyof typeof SEND_TYPE];
export const CHANNEL_TYPE = {
EMAIL: 1,
SMS: 2,
KKO_AT: 3,
} as const;
export type ChannelType = (typeof CHANNEL_TYPE)[keyof typeof CHANNEL_TYPE];
export const TMPLAT_PURPOSE = {
NORMAL: 0,
PHONE_VERIFICATION: 1,
} as const;
export type TemplatePurpose = (typeof TMPLAT_PURPOSE)[keyof typeof TMPLAT_PURPOSE];
export type Template = {
atchFl?: string;
delayTime?: number;
itrntPrjctCd: string;
kkoTmplatCd?: string;
modDt?: string;
modUser?: string;
nationCd?: string;
regDt?: string;
regUser?: string;
sendEml?: string;
sendNm: string;
sendTel?: string;
senderKey?: string;
tmplatBody: string;
tmplatIdx: number;
tmplatNm: string;
tmplatPurpose: TemplatePurpose;
tmplatTitle?: string;
tmplatTy: SendType;
};
export type SaveTemplateRequest = Pick<Template, "tmplatIdx" | "tmplatNm" | "tmplatTitle" | "tmplatBody">;
type DestInfo = {
destEml: string;
destNm: string;
destTel: string;
msgParam: Record<string, string>;
sid: string;
};
export type SmsDestInfo = Pick<DestInfo, "sid" | "destNm" | "destTel" | "msgParam">;
export type EmailDestInfo = Pick<DestInfo, "sid" | "destNm" | "destEml" | "msgParam">;
export type SendSmsBulkRequest = {
templateIdx: number;
reqstCmpn: string;
reqstUser: string;
reqstSvc: string;
destinations: SmsDestInfo[];
};
export type SendEmailBulkRequest = {
templateIdx: number;
reqstCmpn: string;
reqstUser: string;
reqstSvc: string;
destinations: EmailDestInfo[];
};
export type BulkSendResponse = {
acceptCount: number;
bulkSendKey: string;
failCount: number;
requestCount: number;
};

View File

@@ -17,5 +17,5 @@
"paths": { "@/*": ["./src/*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts", "**/*.mts"],
"exclude": ["node_modules"]
"exclude": ["node_modules", "docs/*"]
}