Files
kmusical-manage-front/src/components/dialog/PerformanceDetailDialog.tsx
kric_jspark cfcc474f6e 261012_01_ENH: ai 하네스 수정 및 배정 캘린더·모니터링 계정 표시 개선
- AI 하네스 참조 문서·스킬 추가 및 AGENTS.md, .agent/project.md 갱신
- 사업정보: 수정 권한(내부·재단) 계정에 배정 캘린더 버튼 추가
- 사업정보: 모니터링 계정은 본인 배정 슬롯만 표시, 툴팁에 모니터링/컨설팅 구분 표시
- 공연 상세: 모니터링 계정에는 관계자 정보 숨김
- 신청자 수·평가위원 조회 hook에 enabled 옵션 추가
2026-10-12 15:52:44 +09:00

445 lines
23 KiB
TypeScript

"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<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>
);
}
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<HTMLInputElement | null>(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 (
<DetailRow label={REQUEST_FORM_LABEL[formType]}>
<div className="flex flex-wrap items-center gap-2">
<span className="min-w-0 flex-1 break-all">{fileName || "등록된 파일 없음"}</span>
<div className="flex flex-wrap gap-1">
{canEdit && (
<>
<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" /> {fileName ? "교체" : "등록"}
</Button>
</>
)}
<Button type="button" size="xs" variant="outline" className="rounded-full" onClick={download} disabled={!fileName || downloadMutation.isPending}>
<Download className="size-3" /> 다운로드
</Button>
</div>
</div>
</DetailRow>
);
}
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) => {
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 (
<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>
{[REQUEST_FORM_TYPE.PUBLIC_OFFERING, REQUEST_FORM_TYPE.ISSUANCE].map((formType) => (
<RequestFormRow
key={formType}
performanceId={draft.performanceId}
formType={formType}
fileName={draft.performanceDetail[REQUEST_FORM_DETAIL_KEY[formType]] || undefined}
canEdit={canEdit}
onUploaded={(uploadedType, savedFileName) => {
updateDetail(REQUEST_FORM_DETAIL_KEY[uploadedType], savedFileName);
onRefresh?.();
}}
/>
))}
</section>
{!isMonitoring && (
<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>
);
}