Files
gwcf-review-front/src/components/dialog/PerformanceDetailDialog.tsx

728 lines
33 KiB
TypeScript

"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<Record<CodeGroup, Code[]>>;
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 (
<div className="grid grid-cols-[130px_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 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 (
<Button type="button" size="xs" variant="outline" disabled={disabled} onClick={onClick}>
<Icon className="h-3 w-3" />
{children}
</Button>
);
}
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 (
<div className="rounded-md border bg-muted/30 p-2 text-sm">
<div className="grid gap-1 text-xs text-muted-foreground sm:grid-cols-2">
<span>ID: {userId || "-"}</span>
<span>{metaLabel}: {metaValue || "-"}</span>
<span>{USER_FIELD_LABELS.userTel}: {tel}</span>
<span>{USER_FIELD_LABELS.userEmail}: {email}</span>
{type === "monitoring" && <span>{USER_FIELD_LABELS.userHasCar}: {hasCar}</span>}
</div>
</div>
);
}
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<HTMLInputElement>(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 (
<div className="flex flex-wrap gap-1">
{canEdit && userId && (
<>
<input ref={fileInputRef} type="file" className="hidden" onChange={(event) => void upload(event.target.files?.[0])} />
<FileActionButton icon="upload" disabled={uploadMutation.isPending || !canUpload} onClick={() => fileInputRef.current?.click()}>파일 업로드</FileActionButton>
</>
)}
<FileActionButton icon="download" disabled={!userId || !uploadFileName || originalMutation.isPending} onClick={downloadOriginal}>원본</FileActionButton>
<FileActionButton icon="download" disabled={getReviewPdfDisabled(userId, pdfFileName, pdfConvert) || pdfMutation.isPending} onClick={downloadPdf}>{getReviewPdfStatusLabel(pdfConvert)}</FileActionButton>
<FileActionButton icon="preview" disabled={getReviewPdfDisabled(userId, pdfFileName, pdfConvert)} onClick={previewPdf}>미리보기</FileActionButton>
<span className="text-xs text-red-500">* 파일 크기 및 형식에 따라 PDF 변환이 최대 5분까지 소요됩니다.</span>
</div>
);
}
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 (
<div className="flex flex-wrap gap-1">
<FileActionButton icon="image" disabled={zipMutation.isPending} onClick={download}>다운로드</FileActionButton>
<FileActionButton icon="preview" disabled={evidenceList.length === 0} onClick={preview}>증빙 미리보기</FileActionButton>
</div>
);
}
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 (
<div className="space-y-2 border-b p-3">
<div className="font-semibold">자체 보고서</div>
<div className="flex flex-wrap items-center gap-2">
<StatusPill variant={display.variant}>{display.label}</StatusPill>
<ReviewFileActions
performanceId={performance.id}
reviewType={reviewType}
userId={review?.regUser || userId || loginUserId}
uploadFileName={review?.uploadFileName}
pdfFileName={review?.pdfFileName}
pdfConvert={review?.pdfConvert}
canUpload={true}
canEdit={true}
/>
</div>
</div>
);
}
function MonitoringStatusRow({
performance,
index,
codes,
userMap,
canEdit,
}: Readonly<{
performance: PerformanceFull | PerformanceCompact;
index: 0 | 1;
codes: CodeMap;
userMap: Map<string, UserFull>;
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 (
<div className="space-y-2 border-b p-3">
<div className="font-semibold">모니터링 {index + 1}</div>
<div className="grid gap-1 text-sm">
<AssignedUserInfo userId={row.userId} user={user} codes={codes} type="monitoring" />
<div className="flex flex-wrap items-center gap-2 mb-2">
<StatusPill variant={display.variant}>
<span className="inline-flex items-center gap-1">
{display.label}
{canResetMonitoringVisit && (
<button
type="button"
aria-label={`${display.label} 상태 취소`}
className="inline-flex h-4 w-4 items-center justify-center rounded-full text-red-600 hover:bg-red-50 hover:text-red-700 disabled:pointer-events-none disabled:opacity-50 cursor-pointer"
disabled={resetMutation.isPending}
onClick={(event) => {
event.stopPropagation();
resetMonitoringVisit();
}}
>
<X className="h-3 w-3" />
</button>
)}
</span>
</StatusPill>
<ReviewFileActions
performanceId={performance.id}
reviewType={row.reviewType}
userId={row.review?.regUser || row.userId}
uploadFileName={row.review?.uploadFileName}
pdfFileName={row.review?.pdfFileName}
pdfConvert={row.review?.pdfConvert}
//canUpload={canEdit && isReviewComplete(row.review)}
//canEdit={canEdit}
canUpload={true}
canEdit={true}
/>
</div>
{row.slot.visit?.length ? (
<>
<div className="rounded-md border bg-muted/30 p-2 text-sm">
<div className="grid gap-1 text-xs text-muted-foreground sm:grid-cols-1">
<span>출발: {getMonitoringRecordedAt(row.slot.timeline.departure)}</span>
<span>도착: {getMonitoringRecordedAt(row.slot.timeline.arrival)}</span>
</div>
</div>
{row.slot.timeline.arrival && row.evidenceUserId && (
<EvidenceZipButton
performanceId={performance.id}
userId={row.evidenceUserId}
/>
)}
</>
) : null}
</div>
</div>
);
}
function WrittenReviewRows({
performance,
codes,
userMap,
canEdit,
}: Readonly<{
performance: PerformanceFull | PerformanceCompact;
codes: CodeMap;
userMap: Map<string, UserFull>;
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 (
<div className="space-y-2 border-b p-3">
<div className="font-semibold">서면평가</div>
<div className="grid gap-1 text-sm">
{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 (
<div key={`${userId}-${reviewType}`} className="space-y-2 border-b p-3 last:border-b-0">
<AssignedUserInfo userId={userId} user={user} codes={codes} type="written" />
<div className="flex flex-wrap items-center gap-2">
<StatusPill variant={display.variant} onClick={complete ? () => openWrittenReviewLink(userId, true) : undefined}>
{display.label}
</StatusPill>
{canEdit && (
<Button type="button" size="xs" variant="outline" disabled={!complete} onClick={() => openWrittenReviewLink(userId, false)}>
평가 수정
</Button>
)}
</div>
</div>
);
})}
</div>
</div>
);
}
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<PerformanceCompact | null>(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 = <K extends keyof PerformanceCompact>(key: K, value: PerformanceCompact[K]) => {
setDraft((prev) => prev ? {...prev, [key]: value} : prev);
};
const updateDetail = <K extends keyof PerformanceDetail>(key: K, value: PerformanceDetail[K]) => {
setDraft((prev) => prev ? {
...prev,
performanceDetail: {
...prev.performanceDetail,
[key]: value,
},
} : prev);
};
const updateSchedule = <K extends keyof PerformanceMonitoringSchedule>(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 (
<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.1fr_0.9fr]">
<div className="space-y-4">
<section className="rounded-md border">
<DetailRow label={PERFORMANCE_FIELD_LABELS.no}>{draft.performanceDetail["performanceNo"] ?? ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.id}>{draft.id}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.NCAS}>{isEditing ? <Input inputMode="numeric" maxLength={DETAIL_TEXT_MAX_LENGTH} value={draft.performanceDetail["NCAS"] ?? ""} onChange={(event) => updateDetail("NCAS", event.target.value.replace(/\D/g, ""))} /> : draft.performanceDetail["NCAS"] ?? ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.monitoringAdd}>{draft.id % 100 !== 1? "추가" : ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.businessType}>{getCodeLabel(codes, "business_type", draft.businessType)}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceGenre}>{getCodeLabel(codes, "genre", draft.performanceGenre)}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.performanceArea}>
{isEditing ? (
<FilterSelect value={String(draft.performanceArea ?? "")} onChange={(value) => updateDraft("performanceArea", Number(value))} options={codes.area ?? []} placeholder={PERFORMANCE_FIELD_LABELS.performanceArea} />
) : 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}>{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" 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={PERFORMANCE_FIELD_LABELS.ticketReservationStatus} />
) : 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 ? <DatePicker value={draft.performanceMonitoringSchedule?.monitoringDate ?? ""} onChange={(value) => updateSchedule("monitoringDate", 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.needMonitoring}>{isEditing ? <Input value={draft.performanceDetail["needMonitoring"] ?? ""} onChange={(event) => updateDetail("needMonitoring", event.target.value)} /> : draft.performanceDetail["needMonitoring"] ?? ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.needWrittenReview}>{isEditing ? <Input value={draft.performanceDetail["needWrittenReview"] ?? ""} onChange={(event) => updateDetail("needWrittenReview", event.target.value)} /> : draft.performanceDetail["needWrittenReview"] ?? ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.checkDeliver}>{isEditing ? <Input value={draft.performanceDetail["checkDeliver"] ?? ""} onChange={(event) => updateDetail("checkDeliver", event.target.value)} /> : draft.performanceDetail["checkDeliver"] ?? ""}</DetailRow>
<DetailRow label={PERFORMANCE_FIELD_LABELS.timeTreeCheckDt}>{isEditing ? <DatePicker value={draft.performanceDetail["timeTreeCheckDt"] ?? ""} onChange={(value) => updateDetail("timeTreeCheckDt", value)} /> : draft.performanceDetail["timeTreeCheckDt"] ?? ""}</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.checkReport}>{isEditing ? <Input value={draft.performanceDetail["checkReport"] ?? ""} onChange={(event) => updateDetail("checkReport", event.target.value)} /> : draft.performanceDetail["checkReport"] ?? ""}</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="w-full min-w-[620px] border-collapse text-sm">
<thead>
<tr className="bg-muted">
<th className="w-[180px] border p-2">{PERFORMANCE_FIELD_LABELS.UpdateNoticeTarget}</th>
<th className="border p-2">{PERFORMANCE_FIELD_LABELS.UpdateNoticeMemo}</th>
<th className="w-[170px] border p-2">{PERFORMANCE_FIELD_LABELS.UpdateNoticeDt}</th>
</tr>
</thead>
<tbody>
<tr>
<td className="border p-2">
{isEditing ? (
<FilterSelect value={draft.performanceDetail["UpdateNoticeTarget"] ?? ""} onChange={(value) => updateDetail("UpdateNoticeTarget", value)} options={codes.update_notice_target ?? []} placeholder={PERFORMANCE_FIELD_LABELS.UpdateNoticeTarget} />
) : getCodeLabel(codes, "update_notice_target", draft.performanceDetail["UpdateNoticeTarget"])}
</td>
<td className="border p-2">{isEditing ? <Input maxLength={DETAIL_TEXT_MAX_LENGTH} value={draft.performanceDetail["UpdateNoticeMemo"] ?? ""} onChange={(event) => updateDetail("UpdateNoticeMemo", event.target.value)} /> : draft.performanceDetail["UpdateNoticeMemo"] ?? ""}</td>
<td className="border p-2 text-center">{formatUpdateNoticeDt(draft.performanceDetail["UpdateNoticeDt"])}</td>
</tr>
</tbody>
</table>
</div>
</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="w-full min-w-[620px] border-collapse text-sm">
<thead>
<tr className="bg-muted">
<th className="border p-2">유형</th>
<th className="border p-2">이름</th>
<th className="border p-2">연락처1</th>
<th className="border p-2">연락처2</th>
<th className="border p-2">이메일</th>
</tr>
</thead>
<tbody>
{draft.performanceStaff?.map((staff, index) => (
<tr key={staff.id}>
<td className="border p-2">{getCodeLabel(codes, "staff_type", staff.staffType)}</td>
<td className="border p-2">{isEditing ? <Input value={staff.staffName} onChange={(event) => updateStaff(index, "staffName", event.target.value)} /> : staff.staffName}</td>
<td className="border p-2">{isEditing ? <Input value={staff.staffTel1} onChange={(event) => updateStaff(index, "staffTel1", event.target.value)} /> : staff.staffTel1}</td>
<td className="border p-2">{isEditing ? <Input value={staff.staffTel2} onChange={(event) => updateStaff(index, "staffTel2", event.target.value)} /> : staff.staffTel2}</td>
<td className="border p-2">{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-2">
<Button type="button" size="sm" variant="outline" onClick={() => downloadTemplate(1, Number(String(performance?.id ?? 0).charAt(0)))}>
<Download className="h-4 w-4" />
모니터링 양식
</Button>
</div>
</div>
<LocalGovernmentReviewRow performance={performance ?? draft} codes={codes} loginUserId={userId} />
<MonitoringStatusRow performance={performance ?? draft} index={0} codes={codes} userMap={monitoringUserMap} canEdit={canEdit} />
<MonitoringStatusRow performance={performance ?? draft} index={1} codes={codes} userMap={monitoringUserMap} canEdit={canEdit} />
<WrittenReviewRows performance={performance ?? draft} codes={codes} userMap={writtenUserMap} canEdit={canEdit} />
</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={() => { resetDraft(); setIsEditing(false); }}>취소</Button>
</>
)}
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>닫기</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}