"use client"; import {ReactNode, useEffect, useMemo, useRef, useState} from "react"; import {Download, ImageIcon, ScanSearch, Upload, X} from "lucide-react"; import {Button} from "@/components/ui/button"; import {Input} from "@/components/ui/input"; import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog"; import {DatePicker} from "@/components/common/DatePicker"; import {FilterSelect} from "@/components/gwcf/FilterSelect"; import {StatusPill} from "@/components/gwcf/StatusPill"; import { Code, PdfConvertStatus, PerformanceCompact, PerformanceFull, PerformanceMonitoringSchedule, PerformanceStaff, UserFull } from "@/types/gwcf"; import {CodeGroup} from "@/query/code"; import {getCodeLabel, getDetailValue, ROLE} from "@/lib/gwcf/view"; import { getMonitoringDisplayRow, getMonitoringDisplayStatus, getMonitoringRecordedAt, getReviewByType, getReviewStatusDisplay, getWrittenReviewRows, isReviewComplete, LOCAL_GOVERNMENT_REVIEW_TYPE, } from "@/lib/gwcf/performance-status"; import { useDownloadReviewOriginalMutation, useDownloadReviewPdfMutation, useReviewFileQuery, useUploadReviewFileMutation, } from "@/query/review"; import {useDownloadEvidenceZipMutation, useMonitoringEvidenceQuery, useResetMonitoringVisitMutation} from "@/query/monitoring"; import {useUsersQuery} from "@/query/user"; import {useLoading} from "@/hooks/useLoading"; import { buildEvidenceImageSrc, buildImagePreviewUrl, buildReviewPdfPreviewUrl, downloadBlob, downloadFromUrl, getEvidenceZipDownloadName, getReviewOriginalDownloadName, getReviewPdfDisabled, getReviewPdfDownloadName, getReviewPdfStatusLabel, openPreviewWindow, openWrittenReviewWindow, } from "@/lib/gwcf/file"; import {PERFORMANCE_FIELD_LABELS, USER_FIELD_LABELS} from "@/lib/gwcf/field-labels"; import {useAuth} from "@/hooks/useAuth"; type CodeMap = Partial>; type PerformanceDetail = PerformanceCompact["performanceDetail"]; type MonitoringVisitResetStatus = "departure" | "arrival"; const DETAIL_TEXT_MAX_LENGTH = 2048; // UpdateNoticeDt는 한국시간 ISO 문자열이므로 시간대 변환 없이 표시만 정리한다. const formatUpdateNoticeDt = (value?: string) => (value ?? "").replace("T", " ").replace(/\.\d+/, ""); function DetailRow({label, children}: {label: string; children: ReactNode}) { return (
{label}
{children ?? "-"}
); } function FileActionButton({ children, icon = "download", disabled = false, onClick, }: Readonly<{ children: ReactNode; icon?: "download" | "upload" | "image" | "preview"; disabled?: boolean; onClick?: () => void; }>) { const Icon = icon === "upload" ? Upload : icon === "image" ? ImageIcon : icon === "preview" ? ScanSearch : Download; return ( ); } function AssignedUserInfo({ userId, user, codes, type, }: Readonly<{ userId?: string; user?: UserFull; codes: CodeMap; type: "monitoring" | "written"; }>) { const detail = user?.userDetail; const tel = getDetailValue(detail, "userTel", "-"); const email = getDetailValue(detail, "userEmail", "-"); const metaValue = type === "monitoring" ? getCodeLabel(codes, "area", getDetailValue(detail, "userArea")) : getCodeLabel(codes, "genre", getDetailValue(detail, "userGenre")); const metaLabel = type === "monitoring" ? USER_FIELD_LABELS.userArea : USER_FIELD_LABELS.userGenre; const hasCar = getCodeLabel(codes, "has_car", getDetailValue(detail, "userHasCar")) || "-"; return (
ID: {userId || "-"} {metaLabel}: {metaValue || "-"} {USER_FIELD_LABELS.userTel}: {tel} {USER_FIELD_LABELS.userEmail}: {email} {type === "monitoring" && {USER_FIELD_LABELS.userHasCar}: {hasCar}}
); } function ReviewFileActions({ performanceId, reviewType, userId, uploadFileName, pdfFileName, pdfConvert, canUpload, canEdit, }: Readonly<{ performanceId: number; reviewType: number; userId?: string; uploadFileName?: string; pdfFileName?: string; pdfConvert?: PdfConvertStatus canUpload: boolean; canEdit: boolean; }>) { const fileInputRef = useRef(null); const uploadMutation = useUploadReviewFileMutation(); const originalMutation = useDownloadReviewOriginalMutation(); const pdfMutation = useDownloadReviewPdfMutation(); const {withLoadingAsync} = useLoading(); const upload = async (file?: File) => { try { if (!file) return; await withLoadingAsync(() => uploadMutation.mutateAsync({performanceId, reviewType, file, paramUserId: userId}) ); alert("파일 업로드가 완료되었습니다."); } finally { if (fileInputRef.current) fileInputRef.current.value = ""; } }; const downloadOriginal = async () => { if (!userId) return; const buffer = await originalMutation.mutateAsync({ performanceId, reviewType, userId }); downloadBlob( buffer, getReviewOriginalDownloadName(performanceId, reviewType, uploadFileName) ); }; const downloadPdf = async () => { if (!userId) return; const buffer = await pdfMutation.mutateAsync({ performanceId, reviewType, userId }); downloadBlob( buffer, getReviewPdfDownloadName(performanceId, reviewType, pdfFileName), "application/pdf" ); }; const previewPdf = () => { if (!pdfFileName || !userId) return; openPreviewWindow(buildReviewPdfPreviewUrl(performanceId, reviewType, userId, pdfFileName)); }; return (
{canEdit && userId && ( <> void upload(event.target.files?.[0])} /> fileInputRef.current?.click()}>파일 업로드 )} 원본 {getReviewPdfStatusLabel(pdfConvert)} 미리보기 * 파일 크기 및 형식에 따라 PDF 변환이 최대 5분까지 소요됩니다.
); } function EvidenceZipButton({performanceId, userId}: {performanceId: number; userId: string}) { const {data: evidenceList = []} = useMonitoringEvidenceQuery(performanceId, userId, performanceId > 0 && Boolean(userId)); const zipMutation = useDownloadEvidenceZipMutation(); const download = async () => { const buffer = await zipMutation.mutateAsync({performanceId, userId}); downloadBlob(buffer, getEvidenceZipDownloadName(performanceId, userId), "application/zip"); }; const preview = () => { const images = evidenceList .flatMap((item) => (item.evidenceImg ?? "") .split("|") .map((fileName) => fileName.trim()) .filter(Boolean) ) .map((fileName) => buildEvidenceImageSrc(performanceId, userId, fileName)); if (images.length === 0) { alert("미리보기할 증빙사진이 없습니다."); return; } openPreviewWindow(buildImagePreviewUrl("증빙 미리보기", images)); }; return (
다운로드 증빙 미리보기
); } function LocalGovernmentReviewRow({ performance, codes, loginUserId, }: { performance: PerformanceFull | PerformanceCompact; codes: CodeMap; loginUserId: string | undefined; }) { const reviewType = LOCAL_GOVERNMENT_REVIEW_TYPE; const fallbackReviewRow = getReviewByType(performance as PerformanceFull, reviewType); const userId = fallbackReviewRow?.review.regUser || fallbackReviewRow?.userId; const {data: fetchedReview} = useReviewFileQuery(performance.id, reviewType, userId, performance.id > 0 && Boolean(userId)); if(performance.id % 100 !== 1){ return null; } const review = fetchedReview ?? fallbackReviewRow?.review; const label = getCodeLabel(codes, "review_status", review?.reviewStatus); const display = getReviewStatusDisplay(label, review, true); return (
자체 보고서
{display.label}
); } function MonitoringStatusRow({ performance, index, codes, userMap, canEdit, }: Readonly<{ performance: PerformanceFull | PerformanceCompact; index: 0 | 1; codes: CodeMap; userMap: Map; canEdit: boolean; }>) { const row = getMonitoringDisplayRow(performance as PerformanceFull, index); const user = row.userId ? userMap.get(row.userId) : undefined; const latestVisit = row.slot.visit?.[0]; const resetMutation = useResetMonitoringVisitMutation(); const display = getMonitoringDisplayStatus( row, getCodeLabel(codes, "monitoring_visit_status", latestVisit?.monitoringVisitStatus), getCodeLabel(codes, "review_status", row.review?.reviewStatus) ); const resetStatus: MonitoringVisitResetStatus | null = display.variant === "departed" ? "departure" : display.variant === "arrived" ? "arrival" : null; const resetUserId = row.evidenceUserId || row.userId; const canResetMonitoringVisit = canEdit && Boolean(resetStatus && resetUserId); const resetMonitoringVisit = () => { if (!resetStatus || !resetUserId) return; if (!confirm("방문 정보를 정말 삭제하시겠습니까?")) return; resetMutation.mutate({ performanceId: performance.id, userId: resetUserId, }); }; return (
모니터링 {index + 1}
{display.label} {canResetMonitoringVisit && ( )}
{row.slot.visit?.length ? ( <>
출발: {getMonitoringRecordedAt(row.slot.timeline.departure)} 도착: {getMonitoringRecordedAt(row.slot.timeline.arrival)}
{row.slot.timeline.arrival && row.evidenceUserId && ( )} ) : null}
); } function WrittenReviewRows({ performance, codes, userMap, canEdit, }: Readonly<{ performance: PerformanceFull | PerformanceCompact; codes: CodeMap; userMap: Map; canEdit: boolean; }>) { if(performance.id % 100 !== 1){ return null; } const rows = getWrittenReviewRows(performance as PerformanceFull); if(rows.length === 0){ rows.push({userId: "", assign: undefined, review: undefined}); } const openWrittenReviewLink = (userId: string, complete: boolean) => { openWrittenReviewWindow(performance.id, userId, complete); }; return (
서면평가
{rows.map(({userId, assign, review}) => { const user = userMap.get(userId); const complete = isReviewComplete(review); const reviewType = review?.reviewType ?? assign?.assignType ?? 2; const label = getCodeLabel(codes, "review_status", review?.reviewStatus); const display = getReviewStatusDisplay(label, review, Boolean(assign)); return (
openWrittenReviewLink(userId, true) : undefined}> {display.label} {canEdit && ( )}
); })}
); } export function PerformanceDetailDialog({ open, onOpenChange, performance, codes, canEdit, canDelete, onSave, onDelete, }: Readonly<{ open: boolean; onOpenChange: (open: boolean) => void; performance: PerformanceFull | PerformanceCompact | null; codes: CodeMap; canEdit: boolean; canDelete: boolean; onSave?: (performance: PerformanceCompact) => void; onDelete?: (performanceId: number) => void; }>) { const {auth} = useAuth(); const [draft, setDraft] = useState(null); const [isEditing, setIsEditing] = useState(false); const {data: monitoringUsers = []} = useUsersQuery(ROLE.MONITORING, open); const {data: writtenUsers = []} = useUsersQuery(ROLE.WRITTEN_REVIEWER, open); const monitoringUserMap = useMemo( () => new Map(monitoringUsers.map((user) => [user.userId, user])), [monitoringUsers] ); const writtenUserMap = useMemo( () => new Map(writtenUsers.map((user) => [user.userId, user])), [writtenUsers] ); const userId = auth.user?.userId; useEffect(() => { if (!performance) { setDraft(null); setIsEditing(false); return; } setDraft({ id: performance.id, businessType: performance.businessType, performanceGenre: performance.performanceGenre, performanceArea: performance.performanceArea, artistName: performance.artistName, performanceName: performance.performanceName, performanceStartMonth: performance.performanceStartMonth, performanceDtInfo: performance.performanceDtInfo, performanceTimeInfo: performance.performanceTimeInfo, ticketReservationStatus: performance.ticketReservationStatus, ticketReservationMemo: performance.ticketReservationMemo, performanceMemo: performance.performanceMemo, performanceDetail: performance.performanceDetail, performanceStaff: performance.performanceStaff, performanceMonitoringSchedule: performance.performanceMonitoringSchedule, }); setIsEditing(false); }, [performance]); const updateDraft = (key: K, value: PerformanceCompact[K]) => { setDraft((prev) => prev ? {...prev, [key]: value} : prev); }; const updateDetail = (key: K, value: PerformanceDetail[K]) => { setDraft((prev) => prev ? { ...prev, performanceDetail: { ...prev.performanceDetail, [key]: value, }, } : prev); }; const updateSchedule = (key: K, value: PerformanceMonitoringSchedule[K]) => { setDraft((prev) => prev ? { ...prev, performanceMonitoringSchedule: { ...prev.performanceMonitoringSchedule, [key]: value, }, } : prev); }; const updateStaff = (index: number, key: keyof PerformanceStaff, value: string | number) => { setDraft((prev) => { if (!prev) return prev; const next = [...(prev.performanceStaff ?? [])]; next[index] = {...next[index], [key]: value}; return {...prev, performanceStaff: next}; }); }; const resetDraft = () => { if (!performance) return; setDraft({ id: performance.id, businessType: performance.businessType, performanceGenre: performance.performanceGenre, performanceArea: performance.performanceArea, artistName: performance.artistName, performanceName: performance.performanceName, performanceStartMonth: performance.performanceStartMonth, performanceDtInfo: performance.performanceDtInfo, performanceTimeInfo: performance.performanceTimeInfo, ticketReservationStatus: performance.ticketReservationStatus, ticketReservationMemo: performance.ticketReservationMemo, performanceMemo: performance.performanceMemo, performanceDetail: performance.performanceDetail, performanceStaff: performance.performanceStaff, performanceMonitoringSchedule: performance.performanceMonitoringSchedule, }); }; const save = () => { if (!draft) return; const detail = draft.performanceDetail ?? {}; const ncas = detail["NCAS"] ?? ""; const updateNoticeTarget = detail["UpdateNoticeTarget"] ?? ""; const updateNoticeMemo = detail["UpdateNoticeMemo"] ?? ""; if (!/^\d*$/.test(ncas)) { alert(`${PERFORMANCE_FIELD_LABELS.NCAS}는 숫자만 입력할 수 있습니다.`); return; } if (ncas.length > DETAIL_TEXT_MAX_LENGTH || updateNoticeMemo.length > DETAIL_TEXT_MAX_LENGTH) { alert(`${PERFORMANCE_FIELD_LABELS.NCAS}와 ${PERFORMANCE_FIELD_LABELS.UpdateNoticeMemo}은 최대 2,048자까지 입력할 수 있습니다.`); return; } if (updateNoticeTarget !== "" && updateNoticeMemo.trim() === "") { alert(`${PERFORMANCE_FIELD_LABELS.UpdateNoticeTarget}을 선택한 경우 ${PERFORMANCE_FIELD_LABELS.UpdateNoticeMemo}을 입력해 주세요.`); return; } const performanceDetail: PerformanceDetail = { ...detail, NCAS: ncas, UpdateNoticeTarget: updateNoticeTarget, UpdateNoticeMemo: updateNoticeMemo, }; // 변경 일시는 서버에서 생성하므로 요청에서 제외한다. delete performanceDetail["UpdateNoticeDt"]; onSave?.({...draft, performanceDetail}); setIsEditing(false); }; const deletePerformance = () => { if(!draft) return; if(confirm("삭제 되면 복구할 수 없습니다. 삭제를 진행 하시겠습니까?")){ onDelete?.(draft.id); } } const downloadTemplate = (reviewType: number, classification: number) => { downloadFromUrl(`/api/review/template/download/${reviewType}/${classification}`); }; return ( 사업 상세 정보
{draft && (
{draft.performanceDetail["performanceNo"] ?? ""} {draft.id} {isEditing ? updateDetail("NCAS", event.target.value.replace(/\D/g, ""))} /> : draft.performanceDetail["NCAS"] ?? ""} {draft.id % 100 !== 1? "추가" : ""} {getCodeLabel(codes, "business_type", draft.businessType)} {getCodeLabel(codes, "genre", draft.performanceGenre)} {isEditing ? ( updateDraft("performanceArea", Number(value))} options={codes.area ?? []} placeholder={PERFORMANCE_FIELD_LABELS.performanceArea} /> ) : getCodeLabel(codes, "area", draft.performanceArea)} {isEditing ? updateDetail("performanceAreaDetail", event.target.value)} /> : draft.performanceDetail["performanceAreaDetail"] ?? ""} {draft.artistName} {isEditing ? updateDraft("performanceName", event.target.value)} /> : draft.performanceName} {isEditing ? updateDraft("performanceStartMonth", Number(event.target.value))} /> : `${draft.performanceStartMonth}월`} {isEditing ? updateDraft("performanceDtInfo", event.target.value)} /> : draft.performanceDtInfo} {isEditing ? updateDraft("performanceTimeInfo", event.target.value)} /> : draft.performanceTimeInfo} {isEditing ? ( updateDraft("ticketReservationStatus", Number(value))} options={codes.ticket_reservation_status ?? []} placeholder={PERFORMANCE_FIELD_LABELS.ticketReservationStatus} /> ) : getCodeLabel(codes, "ticket_reservation_status", draft.ticketReservationStatus)} {isEditing ? updateDraft("ticketReservationMemo", event.target.value)} /> : draft.ticketReservationMemo} {isEditing ? updateSchedule("monitoringDate", value)} /> : draft.performanceMonitoringSchedule?.monitoringDate ?? ""} {isEditing ? updateSchedule("monitoringTimeInfo", event.target.value)} /> : draft.performanceMonitoringSchedule?.monitoringTimeInfo} {isEditing ? updateDetail("needMonitoring", event.target.value)} /> : draft.performanceDetail["needMonitoring"] ?? ""} {isEditing ? updateDetail("needWrittenReview", event.target.value)} /> : draft.performanceDetail["needWrittenReview"] ?? ""} {isEditing ? updateDetail("checkDeliver", event.target.value)} /> : draft.performanceDetail["checkDeliver"] ?? ""} {isEditing ? updateDetail("timeTreeCheckDt", value)} /> : draft.performanceDetail["timeTreeCheckDt"] ?? ""} {isEditing ? updateSchedule("monitoringAddress", event.target.value)} /> : draft.performanceMonitoringSchedule?.monitoringAddress} {isEditing ? updateDraft("performanceMemo", event.target.value)} /> : draft.performanceMemo} {isEditing ? updateDetail("checkReport", event.target.value)} /> : draft.performanceDetail["checkReport"] ?? ""}
변경 정보
{PERFORMANCE_FIELD_LABELS.UpdateNoticeTarget} {PERFORMANCE_FIELD_LABELS.UpdateNoticeMemo} {PERFORMANCE_FIELD_LABELS.UpdateNoticeDt}
{isEditing ? ( updateDetail("UpdateNoticeTarget", value)} options={codes.update_notice_target ?? []} placeholder={PERFORMANCE_FIELD_LABELS.UpdateNoticeTarget} /> ) : getCodeLabel(codes, "update_notice_target", draft.performanceDetail["UpdateNoticeTarget"])} {isEditing ? updateDetail("UpdateNoticeMemo", event.target.value)} /> : draft.performanceDetail["UpdateNoticeMemo"] ?? ""} {formatUpdateNoticeDt(draft.performanceDetail["UpdateNoticeDt"])}
관계자 정보
{draft.performanceStaff?.map((staff, index) => ( ))}
유형 이름 연락처1 연락처2 이메일
{getCodeLabel(codes, "staff_type", staff.staffType)} {isEditing ? updateStaff(index, "staffName", event.target.value)} /> : staff.staffName} {isEditing ? updateStaff(index, "staffTel1", event.target.value)} /> : staff.staffTel1} {isEditing ? updateStaff(index, "staffTel2", event.target.value)} /> : staff.staffTel2} {isEditing ? updateStaff(index, "staffEmail", event.target.value)} /> : staff.staffEmail}
평가 및 모니터링 현황
)}
{canDelete && draft && } {canEdit && draft && !isEditing && } {canEdit && draft && isEditing && ( <> )}
); }