From f1d21d371102701a95f1f19026208800998b046f Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Mon, 14 Sep 2026 15:07:40 +0900 Subject: [PATCH] =?UTF-8?q?260914=5F01=5FENH:=201=EC=B0=A8=20=EC=99=84?= =?UTF-8?q?=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package-lock.json | 8 +- package.json | 2 +- public/icon-excel.png | Bin 0 -> 8772 bytes src/app/(pages)/(main)/assign/page.tsx | 281 ++++++++++ src/app/(pages)/(main)/page.tsx | 34 +- src/app/(pages)/(main)/performance/page.tsx | 207 +++++++ src/app/(pages)/(main)/user/page.tsx | 231 ++++++++ src/app/(pages)/file-preview/page.tsx | 112 ++++ src/app/api/assign/[[...slug]]/route.ts | 39 ++ src/app/api/code/[[...slug]]/route.ts | 16 + src/app/api/example/[[...slug]]/route.ts | 73 --- src/app/api/kon/[[...slug]]/route.ts | 114 ++++ src/app/api/login/[[...slug]]/route.ts | 4 +- src/app/api/logout/[[...slug]]/route.ts | 4 +- src/app/api/notification/[[...slug]]/route.ts | 158 ++++++ src/app/api/performance/[[...slug]]/route.ts | 65 +++ src/app/api/review/[[...slug]]/route.ts | 47 ++ src/app/api/user/[[...slug]]/route.ts | 65 +++ src/app/globals.css | 265 ++++++++- src/components/app-shell/AppHeader.tsx | 16 +- src/components/app-shell/AppMainLayout.tsx | 15 +- src/components/data-table/DataTable.tsx | 16 +- src/components/data-table/DataTable.type.ts | 3 + .../dialog/AssignCalendarDialog.tsx | 508 ++++++++++++++++++ .../dialog/AssignMonitoringDialog.tsx | 311 +++++++++++ src/components/dialog/EmailSendDialog.tsx | 334 ++++++++++++ src/components/dialog/ExcelRegisterDialog.tsx | 103 ++++ .../dialog/PerformanceDetailDialog.tsx | 352 ++++++++++++ src/components/dialog/SmsSendDialog.tsx | 349 ++++++++++++ src/components/kmusical/EmptyRow.tsx | 11 + .../kmusical/ExcelDownloadButton.tsx | 29 + src/components/kmusical/FilePendingButton.tsx | 25 + src/components/kmusical/FilterSelect.tsx | 37 ++ src/components/kmusical/MultiFilterSelect.tsx | 34 ++ src/components/kmusical/PagePanel.tsx | 12 + .../kmusical/PerformanceFilterBar.tsx | 67 +++ src/components/kmusical/StatusPill.tsx | 62 +++ src/components/kri-editor/index.ts | 1 + src/components/kri-editor/types.ts | 5 + src/components/ui/checkbox.tsx | 2 +- src/components/ui/input.tsx | 2 +- src/components/ui/tooltip.tsx | 56 ++ src/config/common.config.ts | 20 +- src/config/kmusical.config.ts | 1 + src/config/menu.data.ts | 18 +- src/hooks/useAuth.ts | 53 +- src/lib/http-server.ts | 49 +- src/lib/kmusical/assignment-calendar.ts | 108 ++++ src/lib/kmusical/date.ts | 13 + src/lib/kmusical/emailHtmlPolicy.ts | 225 ++++++++ src/lib/kmusical/field-labels.ts | 61 +++ src/lib/kmusical/file.ts | 51 ++ src/lib/kmusical/notification.ts | 48 ++ src/lib/kmusical/performance-status.ts | 186 +++++++ src/lib/kmusical/sanitizeHtml.ts | 53 ++ src/lib/kmusical/view.ts | 124 +++++ src/query/assign.ts | 58 ++ src/query/code.ts | 44 ++ src/query/key/keys.ts | 30 ++ src/query/notification.ts | 109 ++++ src/query/performance.ts | 60 +++ src/query/review.ts | 65 +++ src/query/user.ts | 57 ++ src/store/jotai/dialog.ts | 11 +- src/types/kmusical.ts | 141 +++++ src/types/notification.ts | 81 +++ tsconfig.json | 2 +- 67 files changed, 5595 insertions(+), 148 deletions(-) create mode 100644 public/icon-excel.png create mode 100644 src/app/(pages)/(main)/assign/page.tsx create mode 100644 src/app/(pages)/(main)/performance/page.tsx create mode 100644 src/app/(pages)/(main)/user/page.tsx create mode 100644 src/app/(pages)/file-preview/page.tsx create mode 100644 src/app/api/assign/[[...slug]]/route.ts create mode 100644 src/app/api/code/[[...slug]]/route.ts delete mode 100644 src/app/api/example/[[...slug]]/route.ts create mode 100644 src/app/api/kon/[[...slug]]/route.ts create mode 100644 src/app/api/notification/[[...slug]]/route.ts create mode 100644 src/app/api/performance/[[...slug]]/route.ts create mode 100644 src/app/api/review/[[...slug]]/route.ts create mode 100644 src/app/api/user/[[...slug]]/route.ts create mode 100644 src/components/dialog/AssignCalendarDialog.tsx create mode 100644 src/components/dialog/AssignMonitoringDialog.tsx create mode 100644 src/components/dialog/EmailSendDialog.tsx create mode 100644 src/components/dialog/ExcelRegisterDialog.tsx create mode 100644 src/components/dialog/PerformanceDetailDialog.tsx create mode 100644 src/components/dialog/SmsSendDialog.tsx create mode 100644 src/components/kmusical/EmptyRow.tsx create mode 100644 src/components/kmusical/ExcelDownloadButton.tsx create mode 100644 src/components/kmusical/FilePendingButton.tsx create mode 100644 src/components/kmusical/FilterSelect.tsx create mode 100644 src/components/kmusical/MultiFilterSelect.tsx create mode 100644 src/components/kmusical/PagePanel.tsx create mode 100644 src/components/kmusical/PerformanceFilterBar.tsx create mode 100644 src/components/kmusical/StatusPill.tsx create mode 100644 src/components/ui/tooltip.tsx create mode 100644 src/config/kmusical.config.ts create mode 100644 src/lib/kmusical/assignment-calendar.ts create mode 100644 src/lib/kmusical/date.ts create mode 100644 src/lib/kmusical/emailHtmlPolicy.ts create mode 100644 src/lib/kmusical/field-labels.ts create mode 100644 src/lib/kmusical/file.ts create mode 100644 src/lib/kmusical/notification.ts create mode 100644 src/lib/kmusical/performance-status.ts create mode 100644 src/lib/kmusical/sanitizeHtml.ts create mode 100644 src/lib/kmusical/view.ts create mode 100644 src/query/assign.ts create mode 100644 src/query/code.ts create mode 100644 src/query/notification.ts create mode 100644 src/query/performance.ts create mode 100644 src/query/review.ts create mode 100644 src/query/user.ts create mode 100644 src/types/kmusical.ts create mode 100644 src/types/notification.ts diff --git a/package-lock.json b/package-lock.json index 1a8e0ac..439447e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 3070a6c..b5e4622 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/public/icon-excel.png b/public/icon-excel.png new file mode 100644 index 0000000000000000000000000000000000000000..36a0e076c40a18db9d9503d3af55c8b7a78652d7 GIT binary patch literal 8772 zcmeHscT|&EwC@*`B7>r%3`h&ksEiAE1StkcECZtgv4etu zV?hU{h(eGSjRcVr5S0>2FjADzC6u&#zT#c?{(IND>#ga=lu3}&OW!t z&3U=9rZNOU%Xhi#_!ENU04WD4DS-dJ#=Tnv|KXzkblwgXwrGC_KbD3#?skNr68d-I zgYw|_vPhSGQ4q9(1^>m>lO6;?(7LW&I~@1M`H%IQr5^C?OC~=z+Eh+cQhdClV#9{- zpXjf8d+hh$ep`RHw;}V#4LTb(3|_x_bzNb?r`qiHR=(V<@T6^E3q_t9W2)fwx@#E(Zx^YVmNkOEZg_F*OE|KnrqlixsCoD))h8y)S z%ub6e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R zh%=q6a4=T@`XL}QQ4A9! zg5b`&{|AWXSCVE%1Wn>S&Xsgtvjw{#0H})qj7T3q7{i1wOsoOK{%#94D{*PK7IALX zq$Oy=j;L}qX29(S8o_flN_}yl9S_#`2v?(Aq$C(&CxS^A>EWprrJ&1u|6F)#d_EwC zUc_keWAKh#c4y*JAYtkrMzo0nP2RkNTKpSu@4mdGn$GK*7EjyBaW&k318Ny2Wo9`S z!Q^598@#MRP(4ii42b-@z0Rg##Gdh=iqob_fE`*NAi(D{ zAWG7va4@kIWC*wl!UBnP2Xld2!xD$vP8mny# zCHQS1>+r1hwlXu_@t+ty?6|OEyR$H>#_|n1Rau?nDpU2Us;t{Liq)?BsCJnwdU|Of})R+#jZ+nIC}wwCh*59fjKiPyYwLR#plC literal 0 HcmV?d00001 diff --git a/src/app/(pages)/(main)/assign/page.tsx b/src/app/(pages)/(main)/assign/page.tsx new file mode 100644 index 0000000..baa19e8 --- /dev/null +++ b/src/app/(pages)/(main)/assign/page.tsx @@ -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([]); + const [assignmentsToSave, setAssignmentsToSave] = useState([]); + const [smsTargetIds, setSmsTargetIds] = useState([]); + const [smsMode, setSmsMode] = useState<"assignConfirm" | "normal">("assignConfirm"); + const [smsTemplateIdx, setSmsTemplateIdx] = useState([SMS_TEMPLATE_IDS.ASSIGN_CONFIRM]); + const [smsDialogTitle, setSmsDialogTitle] = useState("확정 문자 발송"); + const [newSmsTemplateIdx, setNewSmsTemplateIdx] = useState(); + const [filters, setFilters] = useState({ + 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[] = [ + {accessorKey: "performanceId", header: PERFORMANCE_FIELD_LABELS.performanceId, size: 90}, + { + accessorKey: "performanceName", + header: PERFORMANCE_FIELD_LABELS.performanceName, + size: 260, + cell: ({row}) => ( +
+ {row.original.performanceName} +
+ ), + }, + {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}) => ( +
+ {row.original.performanceDtInfo} +
+ ), + enableSorting: false + }, + { + accessorKey: "performanceTimeInfo", + header: PERFORMANCE_FIELD_LABELS.performanceTimeInfo, + size: 220, + cell: ({row}) => ( +
+ {row.original.performanceTimeInfo} +
+ ), + 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 ( +
+ + + + + +
+ +
+ row.performanceId} + selectMode="click-event" + onRowClick={(performance) => openAssign(performance)} + defaultPageSize={10} + emptyText={isLoading ? "조회 중입니다." : "조회된 공연이 없습니다."} + bodyRowClassName="[&>td]:py-2" + /> +
+ + { + 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); + }} + /> + + { + 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} + /> + + open ? showDialog("assignCalendarDialog") : hideDialog("assignCalendarDialog")} + performances={data} + applyCountMap={applyCountMap} + reviewSlots={reviewSlots} + reviewers={users} + /> +
+ ); +}; + +export default AssignPage; diff --git a/src/app/(pages)/(main)/page.tsx b/src/app/(pages)/(main)/page.tsx index ffdee1a..725ca2e 100644 --- a/src/app/(pages)/(main)/page.tsx +++ b/src/app/(pages)/(main)/page.tsx @@ -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 ( -
- -
-

다음 작업

-

메뉴와 API 경로를 프로젝트 업무에 맞게 확장하세요.

-
-
- ); + const router = useRouter(); + const mounted = useMounted(); + const { auth } = useAuth(); + + useEffect(() => { + if(auth && auth.user){ + router.push("/performance" as Route); + } + }, [auth.user]) + + if (!mounted) return ; + + return null; } diff --git a/src/app/(pages)/(main)/performance/page.tsx b/src/app/(pages)/(main)/performance/page.tsx new file mode 100644 index 0000000..b708086 --- /dev/null +++ b/src/app/(pages)/(main)/performance/page.tsx @@ -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({ + 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[] = [ + {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>((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 ( + downloadReview(row.original, slot.reviewSlot) : undefined} + tooltip={담당자: {assign?.assignUser || "-"}} + > + {display.label} + + ); + }, + })), + ]; + + 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 ( +
+ + refetchList()} + /> + + + +
+ {canEdit && } + +
+ row.performanceId} + selectMode="click-event" + onRowClick={(performance) => { + setSelectedId(performance.performanceId); + showDialog("performanceDetailDialog"); + }} + defaultPageSize={10} + emptyText={isLoading ? "조회 중입니다." : "조회된 공연이 없습니다."} + bodyRowClassName="[&>td]:py-2" + /> +
+ + 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(); }} + /> + + 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} + /> +
+ ); +}; + +export default PerformancePage; diff --git a/src/app/(pages)/(main)/user/page.tsx b/src/app/(pages)/(main)/user/page.tsx new file mode 100644 index 0000000..db044b8 --- /dev/null +++ b/src/app/(pages)/(main)/user/page.tsx @@ -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) => event.stopPropagation(); + return
{children}
; +} + +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([]); + const [editingId, setEditingId] = useState(null); + const [filters, setFilters] = useState({keyword: ""}); + const [, renderDraft] = useState(0); + const draftRef = useRef(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 ( + + updateDraft((current) => ({...current, userDetail: {...current.userDetail, [key]: event.target.value}}))} /> + + ); + }; + + 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[] = [ + {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 ( + + updateDraft((current) => ({...current, userCmpn: event.target.value}))} /> + + ); + }, + }, + {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 ? ( + updateDraft((current) => ({...current, memo: event.target.value}))} /> + ) : row.original.memo, + }, + { + id: "actions", + header: "관리", + enableSorting: false, + cell: ({row}) => ( + +
+ {editingId === row.original.userId ? ( + + ) : ( + + )} + +
+
+ ), + }, + ]; + + 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 ( +
+ +
+ setFilters((current) => ({...current, keyword: event.target.value}))} placeholder="ID, 이름, 연락처 또는 이메일" /> + +
+
+ + +
+ + + + +
+ row.userId} + selectMode="multi" + onRowSelectionChange={handleSelectionChange} + defaultPageSize={50} + disablePagination + maxBodyHeight="65vh" + emptyText={isLoading ? "조회 중입니다." : "조회된 평가위원이 없습니다."} + headerCellClassName="text-base" + bodyCellClassName="text-base" + bodyRowClassName="[&>td]:py-3" + /> +
+ + 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} + /> + + open ? showDialog("userEmailSendDialog") : hideDialog("userEmailSendDialog")} + templateIdx={[EML_TEMPLATE_IDS.CUSTOM]} + selectedUsers={smsTargetUsers} + onSent={refresh} + denyParamKeys={["userCmpn", "userTeam", "userRole"]} + /> + + open ? showDialog("userSmsSendDialog") : hideDialog("userSmsSendDialog")} + templateIdx={[SMS_TEMPLATE_IDS.ACCOUNT_MONITORING]} + newMessageTemplateIdx={SMS_TEMPLATE_IDS.CUSTOM} + selectedUsers={smsTargetUsers} + onSent={refresh} + denyParamKeys={["userCmpn", "userTeam", "userRole"]} + /> +
+ ); +}; + +export default UserPage; diff --git a/src/app/(pages)/file-preview/page.tsx b/src/app/(pages)/file-preview/page.tsx new file mode 100644 index 0000000..135d6d7 --- /dev/null +++ b/src/app/(pages)/file-preview/page.tsx @@ -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 ( +
+
+

{title}

+
+ + {type === "image" ? ( +
+ {images.filter(isAllowedSrc).map((imageSrc, index) => ( +
+ {`${title} +
+ {decodeURIComponent(imageSrc.split("/").pop() ?? "")} +
+
+ ))} + {images.length === 0 && ( +
+ 미리보기할 이미지가 없습니다. +
+ )} +
+ ) : isAllowedSrc(src) ? ( +