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

301 lines
13 KiB
TypeScript

"use client";
import {ReactNode, useMemo, useRef} from "react";
import {Download, ImageIcon, ScanSearch, Upload} from "lucide-react";
import {Button} from "@/components/ui/button";
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
import {StatusPill} from "@/components/gwcf/StatusPill";
import {Code, PDF_CONVERT_STATUS, PdfConvertStatus, PerformanceFull} from "@/types/gwcf";
import {CodeGroup} from "@/query/code";
import {getCodeLabel} from "@/lib/gwcf/view";
import {
getMonitoringDisplayRow,
getMonitoringDisplayStatus,
getMonitoringRecordedAt,
} from "@/lib/gwcf/performance-status";
import {
useDownloadReviewOriginalMutation,
useDownloadReviewPdfMutation,
useUploadReviewFileMutation,
} from "@/query/review";
import {useDownloadEvidenceZipMutation, useMonitoringEvidenceQuery} from "@/query/monitoring";
import {useLoading} from "@/hooks/useLoading";
import {
buildEvidenceImageSrc,
buildImagePreviewUrl,
buildReviewPdfPreviewUrl,
buildReviewTemplatePdfPreviewUrl,
downloadBlob,
downloadFromUrl,
getEvidenceZipDownloadName,
getReviewOriginalDownloadName, getReviewPdfDisabled,
getReviewPdfDownloadName, getReviewPdfStatusLabel,
openPreviewWindow,
} from "@/lib/gwcf/file";
import {PERFORMANCE_FIELD_LABELS} from "@/lib/gwcf/field-labels";
type CodeMap = Partial<Record<CodeGroup, Code[]>>;
function MobileDetailRow({label, children}: {label: string; children: ReactNode}) {
return (
<div className="space-y-1 border-b px-3 py-2 last:border-b-0">
<div className="text-xs font-semibold text-muted-foreground">{label}</div>
<div className="break-words text-sm">{children ?? "-"}</div>
</div>
);
}
function ActionButton({
children,
className,
icon = "download",
disabled = false,
onClick,
}: Readonly<{
children: ReactNode;
className?: string;
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="sm" variant="outline" disabled={disabled} onClick={onClick} className={className? className : "min-h-10 flex-1"}>
<Icon className="h-4 w-4" />
{children}
</Button>
);
}
function MonitoringReviewActions({
canUpload,
performanceId,
reviewType,
userId,
uploadFileName,
pdfConvert,
pdfFileName,
}: Readonly<{
canUpload: boolean;
performanceId: number;
reviewType: number;
userId?: string;
uploadFileName?: string;
pdfConvert?: PdfConvertStatus;
pdfFileName?: string;
}>) {
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}));
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>
<div className="grid grid-cols-2 gap-2">
<input ref={fileInputRef} type="file" className="hidden" onChange={(event) => void upload(event.target.files?.[0])} />
<ActionButton icon="upload" disabled={!canUpload || uploadMutation.isPending} onClick={() => fileInputRef.current?.click()}>파일 업로드</ActionButton>
<ActionButton disabled={!userId || !uploadFileName || originalMutation.isPending} onClick={downloadOriginal}>원본</ActionButton>
<ActionButton disabled={getReviewPdfDisabled(userId, pdfFileName, pdfConvert) || pdfMutation.isPending} onClick={downloadPdf}>{getReviewPdfStatusLabel(pdfConvert)}</ActionButton>
<ActionButton icon="preview" disabled={getReviewPdfDisabled(userId, pdfFileName, pdfConvert)} onClick={previewPdf}>미리보기</ActionButton>
</div>
<span className="text-xs text-red-500">* 파일 크기 및 형식에 따라 PDF 변환이 최대 5분까지 소요됩니다.</span>
</div>
);
}
function EvidenceActions({performanceId, userId}: {performanceId: number; userId?: string}) {
const enabled = performanceId > 0 && Boolean(userId);
const {data: evidenceList = []} = useMonitoringEvidenceQuery(performanceId, userId ?? "", enabled);
const zipMutation = useDownloadEvidenceZipMutation();
const download = async () => {
if (!userId) return;
const buffer = await zipMutation.mutateAsync({performanceId, userId});
downloadBlob(buffer, getEvidenceZipDownloadName(performanceId, userId), "application/zip");
};
const preview = () => {
if (!userId) return;
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="grid grid-cols-2 gap-2">
<ActionButton icon="image" disabled={!userId || zipMutation.isPending} onClick={download}>증빙사진</ActionButton>
<ActionButton icon="preview" disabled={!userId || evidenceList.length === 0} onClick={preview}>증빙 미리보기</ActionButton>
</div>
);
}
export function MonitoringPerformanceDetailDialog({
open,
onOpenChange,
performance,
codes,
userId,
}: Readonly<{
open: boolean;
onOpenChange: (open: boolean) => void;
performance: PerformanceFull | null;
codes: CodeMap;
userId?: string;
}>) {
const row = useMemo(() => {
if (!performance || !userId) return undefined;
return ([0, 1] as const)
.map((index) => getMonitoringDisplayRow(performance, index))
.find((item) => item.userId === userId);
}, [performance, userId]);
const latestVisit = row?.slot.visit?.[0];
const status = row
? getMonitoringDisplayStatus(
row,
getCodeLabel(codes, "monitoring_visit_status", latestVisit?.monitoringVisitStatus),
getCodeLabel(codes, "review_status", row.review?.reviewStatus)
)
: {label: "미배치", variant: "danger" as const};
const reviewType = row?.reviewType ?? 1;
const templateClassification = Number(String(performance?.id ?? 0).charAt(0));
const buildTemplateDownloadUrl = (classification: number) => `/api/review/template/download/${reviewType}/${classification}`;
const downloadTemplate = () => downloadFromUrl(buildTemplateDownloadUrl(templateClassification));
const previewTemplateFile = async (classification: number, title: string) => {
const previewWindow = window.open("about:blank", "_blank");
if (previewWindow) previewWindow.opener = null;
const previewUrl = buildReviewTemplatePdfPreviewUrl(reviewType, classification, title);
if (previewWindow) {
previewWindow.location.href = previewUrl;
return;
}
openPreviewWindow(previewUrl);
};
const previewTemplate = () => void previewTemplateFile(templateClassification, "모니터링 현장 점검표.pdf");
const previewEduFile = () => void previewTemplateFile(99, "도민 모니터링단 매뉴얼.pdf");
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[92vh] w-[calc(100vw-24px)] max-w-[430px] flex-col overflow-hidden p-0">
<DialogHeader className="border-b px-4 py-3">
<DialogTitle className="text-base">모니터링 상세</DialogTitle>
</DialogHeader>
<div className="min-h-0 flex-1 space-y-3 overflow-y-auto p-3">
{performance ? (
<>
<section className="overflow-hidden rounded-md border">
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.id}>{performance.id}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.businessType}>{getCodeLabel(codes, "business_type", performance.businessType)}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceGenre}>{getCodeLabel(codes, "genre", performance.performanceGenre)}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceArea}>{getCodeLabel(codes, "area", performance.performanceArea)}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.artistName}>{performance.artistName}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceName}>{performance.performanceName}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceStartMonth}>{performance.performanceStartMonth}월</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceDtInfo}>{performance.performanceDtInfo}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceTimeInfo}>{performance.performanceTimeInfo}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.ticketReservationStatus}>{getCodeLabel(codes, "ticket_reservation_status", performance.ticketReservationStatus)}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.ticketReservationMemo}>{performance.ticketReservationMemo}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.monitoringDate}>{performance.performanceMonitoringSchedule?.monitoringDate ?? ""}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.monitoringTimeInfo}>{performance.performanceMonitoringSchedule?.monitoringTimeInfo}</MobileDetailRow>
<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.monitoringAddress}>{performance.performanceMonitoringSchedule?.monitoringAddress}</MobileDetailRow>
{/*<MobileDetailRow label={PERFORMANCE_FIELD_LABELS.performanceMemo}>{performance.performanceMemo}</MobileDetailRow>*/}
</section>
<section className="space-y-3 rounded-md border p-3">
<div className="flex items-start justify-between gap-3">
<div className="shrink-0 font-semibold leading-6">나의 진행 상태</div>
<StatusPill variant={status.variant}>{status.label}</StatusPill>
</div>
<div className="flex items-center justify-end gap-2">
<ActionButton icon="preview" onClick={previewEduFile} className="h-8 min-h-0 shrink-0 px-2 text-xs">교육자료</ActionButton>
<ActionButton icon="preview" onClick={previewTemplate} className="h-8 min-h-0 shrink-0 px-2 text-xs">양식</ActionButton>
<ActionButton icon="download" onClick={downloadTemplate} className="h-8 min-h-0 shrink-0 px-2 text-xs">양식 다운로드</ActionButton>
</div>
{row ? (
<MonitoringReviewActions
canUpload={[3, 10].includes(row.review?.reviewStatus ?? 0)}
performanceId={performance.id}
reviewType={row.reviewType}
userId={row.review?.regUser || row.userId}
uploadFileName={row.review?.uploadFileName}
pdfFileName={row.review?.pdfFileName}
pdfConvert={row.review?.pdfConvert}
/>
) : (
<div className="rounded-md bg-muted p-3 text-sm text-muted-foreground">나의 모니터링 배정 정보를 찾을 수 없습니다.</div>
)}
</section>
{row?.slot.visit?.length ? (
<section className="space-y-3 rounded-md border p-3">
<div className="font-semibold">모니터링 방문 기록</div>
<div className="grid gap-1 text-sm text-muted-foreground">
<div>출발: {getMonitoringRecordedAt(row.slot.timeline.departure)}</div>
<div>도착: {getMonitoringRecordedAt(row.slot.timeline.arrival)}</div>
</div>
{row.slot.timeline.arrival && (
<EvidenceActions performanceId={performance.id} userId={row.evidenceUserId} />
)}
</section>
) : null}
</>
) : (
<div className="rounded-md border p-4 text-sm text-muted-foreground">공연 정보를 불러오는 중입니다.</div>
)}
</div>
<DialogFooter className="border-t px-4 py-3">
<Button type="button" variant="outline" className="w-full" onClick={() => onOpenChange(false)}>닫기</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}