"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, RequestFormType, } from "@/types/kmusical"; import {PDF_CONVERT_STATUS, REQUEST_FORM_DETAIL_KEY, REQUEST_FORM_LABEL, REQUEST_FORM_TYPE} from "@/types/kmusical"; import type {CodeGroup} from "@/query/code"; import {HttpError} from "@kri/common/http"; import { getReviewTemplateClassification, useDownloadReviewOriginalMutation, useDownloadReviewPdfMutation, useDownloadReviewTemplateMutation, useUploadReviewFileMutation, } from "@/query/review"; import {useDownloadRequestFormMutation, useUploadRequestFormMutation} from "@/query/performance"; 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>; function DetailRow({label, children}: {label: string; children: ReactNode}) { return (
{label}
{children || "-"}
); } 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(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 (
{slot.reviewLabel}
{reviewerLabel}: {assignedUser?.userName || assignUser || "-"}
{reviewDateLabel}: {review?.reviewDt ? toLocalDateString(new Date(review.reviewDt)) : "-"}
연락처: {getDetailValue(assignedUser?.userDetail, "userTel", "-")}
이메일: {getDetailValue(assignedUser?.userDetail, "userEmail", "-")}
{isReviewComplete(review) ? "완료" : assignUser ? "미진행" : "미배정"}
{canUpload && ( <> void upload(event.target.files?.[0])} /> )}

* 파일 크기 및 형식에 따라 PDF 변환이 최대 5분까지 소요됩니다.

); } function RequestFormRow({ performanceId, formType, fileName, canEdit, onUploaded, }: Readonly<{ performanceId: string; formType: RequestFormType; fileName?: string; canEdit: boolean; onUploaded?: (formType: RequestFormType, savedFileName: string) => void; }>) { const fileInputRef = useRef(null); const uploadMutation = useUploadRequestFormMutation(); const downloadMutation = useDownloadRequestFormMutation(); const upload = async (file?: File) => { try { if (!file) return; const formData = new FormData(); formData.append("file", file, file.name); const savedFileName = await uploadMutation.mutateAsync({performanceId, formType, formData}); alert(`${REQUEST_FORM_LABEL[formType]} 파일이 등록되었습니다.`); onUploaded?.(formType, savedFileName); } finally { if (fileInputRef.current) fileInputRef.current.value = ""; } }; const download = async () => { try { await downloadMutation.mutateAsync({performanceId, formType}); } catch (error) { if (error instanceof HttpError && error.status === 404) { alert("등록된 파일이 없습니다."); return; } throw error; } }; return (
{fileName || "등록된 파일 없음"}
{canEdit && ( <> void upload(event.target.files?.[0])} /> )}
); } 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; onDelete?: (performanceId: string) => Promise | void; onRefresh?: () => void; }>) { const {auth, isMonitoring} = useAuth(); const [draft, setDraft] = useState(null); const [isEditing, setIsEditing] = useState(false); useEffect(() => { setDraft(performance ? clonePerformance(performance) : null); setIsEditing(false); }, [performance, open]); const updateDraft = (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 = (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) => { if (!draft) return; const performanceId = draft.performanceId; const classification = getReviewTemplateClassification(reviewType, performanceId); const downloadUrl = `/api/review/template/download/${reviewType}${classification ? `?classification=${encodeURIComponent(classification)}` : ""}`; reviewTemplateMutation.mutate({reviewType, performanceId}, { onSuccess: () => downloadFromUrl(downloadUrl), }); }; return ( 공연 상세 정보
{draft && (
{draft.performanceId} {getCodeLabel(codes, "business_type", draft.businessType)} {isEditing ? ( updateDraft("performanceArea", Number(value))} options={codes.area ?? []} placeholder="지역" /> ) : getCodeLabel(codes, "area", draft.performanceArea)} {isEditing ? updateDetail("performanceAreaDetail", event.target.value)} /> : draft.performanceDetail.performanceAreaDetail} {isEditing ? updateDraft("artistName", event.target.value)} /> : 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="티켓 예약" /> : getCodeLabel(codes, "ticket_reservation_status", draft.ticketReservationStatus)} {isEditing ? updateDraft("ticketReservationMemo", event.target.value)} /> : draft.ticketReservationMemo} {isEditing ? updateSchedule("monitoringDate", event.target.value)} /> : draft.performanceMonitoringSchedule.monitoringDate} {isEditing ? updateSchedule("monitoringTimeInfo", event.target.value)} /> : draft.performanceMonitoringSchedule.monitoringTimeInfo} {isEditing ? updateSchedule("monitoringAddress", event.target.value)} /> : draft.performanceMonitoringSchedule.monitoringAddress} {isEditing ? updateDraft("performanceMemo", event.target.value)} /> : draft.performanceMemo} {isEditing ? updateDetail("consultingStatus", event.target.value)} /> : draft.performanceDetail.consultingStatus} {isEditing ? updateDetail("clientManagerName", event.target.value)} /> : draft.performanceDetail.clientManagerName}
신청서 파일
{[REQUEST_FORM_TYPE.PUBLIC_OFFERING, REQUEST_FORM_TYPE.ISSUANCE].map((formType) => ( { updateDetail(REQUEST_FORM_DETAIL_KEY[uploadedType], savedFileName); onRefresh?.(); }} /> ))}
{!isMonitoring && (
관계자 정보
{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}
) }
현장모니터링 및 컨설팅
{visibleReviewTypes.map((reviewType) => ( ))}
{visibleReviewSlots.map((slot) => ( assign.reviewSlot === slot.reviewSlot)?.assignUser} review={Object.values(fullPerformance?.performanceReviewMap ?? {}).find((item) => item.reviewSlot === slot.reviewSlot)} onChanged={onRefresh} /> ))} {visibleReviewSlots.length === 0 &&
등록된 평가 슬롯이 없습니다.
}
)}
{canDelete && draft && } {canEdit && draft && !isEditing && } {canEdit && draft && isEditing && ( <> )}
); }