260617_01_ENH: 배정 테스트를 위해 개발 중도 커밋
This commit is contained in:
218
src/components/dialog/AssignMonitoringDialog.tsx
Normal file
218
src/components/dialog/AssignMonitoringDialog.tsx
Normal file
@@ -0,0 +1,218 @@
|
||||
"use client";
|
||||
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import {Send} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {Checkbox} from "@/components/ui/checkbox";
|
||||
import {Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle} from "@/components/ui/dialog";
|
||||
import {DataTable} from "@/components/data-table/DataTable";
|
||||
import {DataTableColumn} from "@/components/data-table/DataTable.type";
|
||||
import {StatusPill} from "@/components/gwcf/StatusPill";
|
||||
import {Code, MonitoringApplyUser, PerformanceFull} from "@/types/gwcf";
|
||||
import {CodeGroup} from "@/query/code";
|
||||
import {getCodeLabel, getDetailValue} from "@/lib/gwcf/view";
|
||||
import {getAssignStatusDisplay, MONITORING_ASSIGN_TYPE} from "@/lib/gwcf/performance-status";
|
||||
|
||||
type CodeMap = Partial<Record<CodeGroup, Code[]>>;
|
||||
|
||||
export function AssignMonitoringDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
selected,
|
||||
codes,
|
||||
applyUsers,
|
||||
isSavingAssign,
|
||||
onSaveAssign,
|
||||
onOpenSms,
|
||||
}: Readonly<{
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
selected: PerformanceFull | null;
|
||||
codes: CodeMap;
|
||||
applyUsers: MonitoringApplyUser[];
|
||||
isSavingAssign?: boolean;
|
||||
onSaveAssign: (performanceId: number, userIds: string[]) => void;
|
||||
onOpenSms: (userIds: string[]) => void;
|
||||
}>) {
|
||||
const monitoringAssigns = useMemo(
|
||||
() => (selected?.performanceAssignList ?? []).filter((item) => item.assignType === MONITORING_ASSIGN_TYPE),
|
||||
[selected]
|
||||
);
|
||||
const [checkedIds, setCheckedIds] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setCheckedIds([]);
|
||||
return;
|
||||
}
|
||||
|
||||
setCheckedIds(monitoringAssigns.map((item) => item.assignUser));
|
||||
}, [monitoringAssigns, open, selected?.id]);
|
||||
|
||||
const confirmRequestCount = monitoringAssigns.length;
|
||||
const confirmedCount = monitoringAssigns.filter((item) => item.assignConfirm).length;
|
||||
const smsTargetIds = checkedIds.filter(
|
||||
(userId) => !monitoringAssigns.some((assign) => assign.assignUser === userId && assign.assignConfirm)
|
||||
);
|
||||
|
||||
const updateChecked = (applyUser: MonitoringApplyUser, checked: boolean) => {
|
||||
if (!selected || isSavingAssign) return;
|
||||
|
||||
const currentAssign = monitoringAssigns.find((assign) => assign.assignUser === applyUser.userId);
|
||||
|
||||
if (checked) {
|
||||
if (!checkedIds.includes(applyUser.userId) && checkedIds.length >= 2) {
|
||||
alert("모니터링 배정은 최대 2명까지 선택할 수 있습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
const next = Array.from(new Set([...checkedIds, applyUser.userId]));
|
||||
setCheckedIds(next);
|
||||
onSaveAssign(selected.id, next);
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentAssign?.assignConfirm) {
|
||||
if (!confirm("이미 승인된 상태입니다. 정말로 취소 하시 겠습니까?")) return;
|
||||
} else if (currentAssign) {
|
||||
if (!confirm("이미 문자 발송된 상태입니다. 정말로 취소 하시 겠습니까?")) return;
|
||||
}
|
||||
|
||||
const next = checkedIds.filter((userId) => userId !== applyUser.userId);
|
||||
setCheckedIds(next);
|
||||
onSaveAssign(selected.id, next);
|
||||
};
|
||||
|
||||
const toggleApplyUser = (applyUser: MonitoringApplyUser) => {
|
||||
updateChecked(applyUser, !checkedIds.includes(applyUser.userId));
|
||||
};
|
||||
|
||||
const columns = useMemo<DataTableColumn<MonitoringApplyUser>[]>(() => [
|
||||
{
|
||||
id: "select",
|
||||
header: "선택",
|
||||
cell: ({row}) => {
|
||||
const applyUser = row.original;
|
||||
const checked = checkedIds.includes(applyUser.userId);
|
||||
const disabled = (!checked && checkedIds.length >= 2) || isSavingAssign;
|
||||
|
||||
return (
|
||||
<Checkbox
|
||||
checked={checked}
|
||||
tabIndex={-1}
|
||||
aria-label="배정 선택 상태"
|
||||
aria-disabled={disabled}
|
||||
className={disabled ? "pointer-events-none opacity-50" : "pointer-events-none"}
|
||||
/>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "user",
|
||||
header: "신청자",
|
||||
cell: ({row}) => (
|
||||
<div>
|
||||
<div className="font-semibold">{row.original.user?.userName || row.original.userId}</div>
|
||||
<div className="text-xs text-muted-foreground">{row.original.userId}</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: "area",
|
||||
header: "지역",
|
||||
cell: ({row}) =>
|
||||
getCodeLabel(codes, "area", getDetailValue(row.original.user?.userDetail, ["area", "userArea", "region"])) || "-",
|
||||
},
|
||||
{
|
||||
id: "tel",
|
||||
header: "연락처",
|
||||
cell: ({row}) => getDetailValue(row.original.user?.userDetail, ["tel", "phone", "userTel"], "-"),
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
header: "상태",
|
||||
cell: ({row}) => {
|
||||
const assigned = monitoringAssigns.find((item) => item.assignUser === row.original.userId);
|
||||
if (!assigned) return null;
|
||||
|
||||
const display = getAssignStatusDisplay(assigned.assignConfirm);
|
||||
return <StatusPill variant={display.variant}>{display.label}</StatusPill>;
|
||||
},
|
||||
},
|
||||
], [checkedIds, codes, isSavingAssign, monitoringAssigns]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-5xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>모니터링 요원 배정</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[1fr_1.2fr]">
|
||||
<section className="rounded-md border">
|
||||
<div className="border-b bg-muted px-3 py-2 font-semibold">공연 기본 정보</div>
|
||||
<table className="w-full border-collapse text-sm">
|
||||
<tbody>
|
||||
{[
|
||||
["연번", selected?.id],
|
||||
["사업유형", getCodeLabel(codes, "business_type", selected?.businessType)],
|
||||
["분야(장르)", getCodeLabel(codes, "genre", selected?.performanceGenre)],
|
||||
["지역", getCodeLabel(codes, "area", selected?.performanceArea)],
|
||||
["단체(팀)명", selected?.artistName],
|
||||
["사업명", selected?.performanceName],
|
||||
["사업 일정", selected?.performanceDtInfo],
|
||||
["운영 시간", selected?.performanceTimeInfo],
|
||||
["모니터링 일정", selected?.performanceMonitoringSchedule?.monitoringDate],
|
||||
["모니터링 시간", selected?.performanceMonitoringSchedule?.monitoringTimeInfo],
|
||||
["방문 장소", selected?.performanceMonitoringSchedule?.monitoringAddress],
|
||||
["예매 예약", getCodeLabel(codes, "ticket_reservation_status", selected?.ticketReservationStatus)],
|
||||
["예매 비고", selected?.ticketReservationMemo],
|
||||
].map(([label, value]) => (
|
||||
<tr key={String(label)}>
|
||||
<th className="w-32 border bg-muted p-2 text-left">{label}</th>
|
||||
<td className="border p-2">{value || "-"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<section className="space-y-3 rounded-md border p-3">
|
||||
<div className="grid grid-cols-3 rounded-md border text-center text-sm">
|
||||
<div className="p-2">
|
||||
<div className="text-muted-foreground">신청자</div>
|
||||
<div className="font-semibold">{applyUsers.length}</div>
|
||||
</div>
|
||||
<div className="border-x p-2">
|
||||
<div className="text-muted-foreground">확정요청</div>
|
||||
<div className="font-semibold">{confirmRequestCount}</div>
|
||||
</div>
|
||||
<div className="p-2">
|
||||
<div className="text-muted-foreground">확정</div>
|
||||
<div className="font-semibold">{confirmedCount}</div>
|
||||
</div>
|
||||
</div>
|
||||
<DataTable
|
||||
columns={columns}
|
||||
data={applyUsers}
|
||||
getRowId={(row) => row.userId}
|
||||
defaultPageSize={applyUsers.length || 10}
|
||||
pageSizeOptions={[applyUsers.length || 10]}
|
||||
showPagination={false}
|
||||
selectMode="click-event"
|
||||
onRowClick={toggleApplyUser}
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" disabled={smsTargetIds.length === 0} onClick={() => onOpenSms(smsTargetIds)}>
|
||||
<Send className="h-4 w-4" />
|
||||
확정 문자 발송
|
||||
</Button>
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>닫기</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
102
src/components/dialog/ExcelRegisterDialog.tsx
Normal file
102
src/components/dialog/ExcelRegisterDialog.tsx
Normal file
@@ -0,0 +1,102 @@
|
||||
"use client";
|
||||
|
||||
import {useEffect, useState} from "react";
|
||||
import {Download, FileUp} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {ExcelUploadResult} from "@/types/common";
|
||||
import {downloadBase64File} from "@/lib/utils";
|
||||
|
||||
export function ExcelRegisterDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
onDownloadTemplate,
|
||||
onUpload,
|
||||
isUploading,
|
||||
}: Readonly<{
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title: string;
|
||||
onDownloadTemplate: () => void;
|
||||
onUpload: (file: File) => Promise<ExcelUploadResult>;
|
||||
isUploading?: boolean;
|
||||
}>) {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [uploadResult, setUploadResult] = useState<ExcelUploadResult | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setFile(null);
|
||||
setUploadResult(null);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const upload = async () => {
|
||||
if (!file) return;
|
||||
const result = await onUpload(file);
|
||||
setUploadResult(result);
|
||||
};
|
||||
|
||||
const downloadErrorFile = () => {
|
||||
if (!uploadResult?.errorFileBase64) return;
|
||||
downloadBase64File(uploadResult.errorFileBase64, uploadResult.errorFileName || "excel_upload_error.xlsx");
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-3">
|
||||
<Button type="button" variant="outline" className="w-full" onClick={onDownloadTemplate}>
|
||||
<Download className="h-4 w-4" />
|
||||
양식 다운로드
|
||||
</Button>
|
||||
<label className="flex h-11 cursor-pointer items-center justify-center gap-2 rounded-md border bg-muted text-sm font-medium">
|
||||
<FileUp className="h-4 w-4" />
|
||||
{file ? file.name : "파일 업로드"}
|
||||
<input
|
||||
type="file"
|
||||
accept=".xlsx,.xls"
|
||||
className="hidden"
|
||||
onChange={(event) => {
|
||||
setFile(event.target.files?.[0] ?? null);
|
||||
setUploadResult(null);
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
{uploadResult && (
|
||||
<div className="rounded-md border bg-muted/40 p-3 text-sm">
|
||||
<div>전체: {uploadResult.totalCount}</div>
|
||||
<div>성공: {uploadResult.successCount}</div>
|
||||
<div>실패: {uploadResult.failCount}</div>
|
||||
{uploadResult.hasErrorFile && (
|
||||
<Button type="button" variant="outline" size="sm" className="mt-2 w-full" onClick={downloadErrorFile}>
|
||||
<Download className="h-4 w-4" />
|
||||
오류 파일 다운로드
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={!file || isUploading}
|
||||
onClick={upload}
|
||||
>
|
||||
등록
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
81
src/components/dialog/MonitoringVisitDialog.tsx
Normal file
81
src/components/dialog/MonitoringVisitDialog.tsx
Normal file
@@ -0,0 +1,81 @@
|
||||
"use client";
|
||||
|
||||
import {ReactNode, useEffect, useMemo, useState} from "react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import {PerformanceCompact} from "@/types/gwcf";
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
export function MonitoringVisitDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
performance,
|
||||
mode,
|
||||
onSubmit,
|
||||
isSubmitting,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
performance: PerformanceCompact | null;
|
||||
mode: "departure" | "arrival";
|
||||
onSubmit?: (files?: File[]) => void | Promise<void>;
|
||||
isSubmitting?: boolean;
|
||||
}) {
|
||||
const nowText = useMemo(() => new Date().toLocaleString("ko-KR"), [open]);
|
||||
const [files, setFiles] = useState<File[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) setFiles([]);
|
||||
}, [open]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>모니터링 {mode === "departure" ? "출발" : "도착"}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="rounded-md border">
|
||||
<DetailRow label="현재 시간">{nowText}</DetailRow>
|
||||
<DetailRow label="모니터링 일정">
|
||||
{performance?.performanceMonitoringSchedule?.monitoringDate} {performance?.performanceMonitoringSchedule?.monitoringTimeInfo}
|
||||
</DetailRow>
|
||||
<DetailRow label="사업명">{performance?.performanceName}</DetailRow>
|
||||
<DetailRow label="장소">{performance?.performanceMonitoringSchedule?.monitoringAddress}</DetailRow>
|
||||
{mode === "arrival" && (
|
||||
<DetailRow label="증빙사진">
|
||||
<label className="flex min-h-11 cursor-pointer items-center justify-center rounded-md border bg-muted px-3 py-2 text-sm font-medium">
|
||||
{files.length > 0 ? `${files.length}개 파일 선택됨` : "증빙 사진 선택"}
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={(event) => setFiles(Array.from(event.target.files ?? []))}
|
||||
/>
|
||||
</label>
|
||||
</DetailRow>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" disabled={!performance || isSubmitting} onClick={() => onSubmit?.(files)}>
|
||||
{mode === "departure" ? "출발 저장" : "도착 저장"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
471
src/components/dialog/PerformanceDetailDialog.tsx
Normal file
471
src/components/dialog/PerformanceDetailDialog.tsx
Normal file
@@ -0,0 +1,471 @@
|
||||
"use client";
|
||||
|
||||
import {ReactNode, useEffect, useMemo, useState} from "react";
|
||||
import {Download, ImageIcon, 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 {DatePicker} from "@/components/common/DatePicker";
|
||||
import {FilterSelect} from "@/components/gwcf/FilterSelect";
|
||||
import {StatusPill} from "@/components/gwcf/StatusPill";
|
||||
import {Code, PerformanceCompact, PerformanceFull, PerformanceMonitoringSchedule, PerformanceStaff, UserFull} from "@/types/gwcf";
|
||||
import {CodeGroup} from "@/query/code";
|
||||
import {getCodeLabel, getDetailValue, ROLE} from "@/lib/gwcf/view";
|
||||
import {
|
||||
getMonitoringRecordedAt,
|
||||
getMonitoringRecordedUser,
|
||||
getMonitoringSlots,
|
||||
getMonitoringStatusDisplay,
|
||||
getReviewStatusDisplay,
|
||||
getWrittenReviewRows,
|
||||
isReviewComplete,
|
||||
LOCAL_GOVERNMENT_REVIEW_TYPE,
|
||||
} from "@/lib/gwcf/performance-status";
|
||||
import {buildWrittenReviewLink} from "@/config/gwcf.config";
|
||||
import {
|
||||
useDownloadReviewOriginalMutation,
|
||||
useDownloadReviewPdfMutation,
|
||||
useEndWrittenReviewMutation,
|
||||
useReviewFileQuery,
|
||||
useStartWrittenReviewMutation,
|
||||
useUploadReviewFileMutation,
|
||||
} from "@/query/review";
|
||||
import {useDownloadEvidenceZipMutation} from "@/query/monitoring";
|
||||
import {downloadFile} from "@/lib/utils";
|
||||
import {useUsersQuery} from "@/query/user";
|
||||
|
||||
type CodeMap = Partial<Record<CodeGroup, Code[]>>;
|
||||
|
||||
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,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
icon?: "download" | "upload" | "image";
|
||||
disabled?: boolean;
|
||||
onClick?: () => void;
|
||||
}) {
|
||||
const Icon = icon === "upload" ? Upload : icon === "image" ? ImageIcon : 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,
|
||||
}: {
|
||||
userId?: string;
|
||||
user?: UserFull;
|
||||
codes: CodeMap;
|
||||
type: "monitoring" | "written";
|
||||
}) {
|
||||
const detail = user?.userDetail;
|
||||
const tel = getDetailValue(detail, ["tel", "phone", "userTel"], "-");
|
||||
const email = getDetailValue(detail, ["email", "userEmail"], "-");
|
||||
const metaValue = type === "monitoring"
|
||||
? getCodeLabel(codes, "area", getDetailValue(detail, ["area", "userArea", "region"]))
|
||||
: getCodeLabel(codes, "genre", getDetailValue(detail, ["userGenre", "genre", "reviewGenre"]));
|
||||
const metaLabel = type === "monitoring" ? "지역" : "장르";
|
||||
const hasCar = getCodeLabel(codes, "has_car", getDetailValue(detail, ["userHasCar", "has_car", "hasCar"])) || "-";
|
||||
|
||||
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>연락처: {tel}</span>
|
||||
<span>이메일: {email}</span>
|
||||
{type === "monitoring" && <span>자차유무: {hasCar}</span>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const downloadBlob = (buffer: ArrayBuffer, fileName: string, type = "application/octet-stream") => {
|
||||
const blob = new Blob([buffer], {type});
|
||||
downloadFile(blob, fileName);
|
||||
};
|
||||
|
||||
function ReviewFileActions({
|
||||
performanceId,
|
||||
reviewType,
|
||||
uploadFileName,
|
||||
pdfFileName,
|
||||
}: {
|
||||
performanceId: number;
|
||||
reviewType: number;
|
||||
uploadFileName?: string;
|
||||
pdfFileName?: string;
|
||||
}) {
|
||||
const uploadMutation = useUploadReviewFileMutation();
|
||||
const originalMutation = useDownloadReviewOriginalMutation();
|
||||
const pdfMutation = useDownloadReviewPdfMutation();
|
||||
|
||||
const upload = (file?: File) => {
|
||||
if (!file) return;
|
||||
uploadMutation.mutate({performanceId, reviewType, file});
|
||||
};
|
||||
|
||||
const downloadOriginal = async () => {
|
||||
const buffer = await originalMutation.mutateAsync({performanceId, reviewType});
|
||||
downloadBlob(buffer, uploadFileName || `review-original-${performanceId}-${reviewType}`);
|
||||
};
|
||||
|
||||
const downloadPdf = async () => {
|
||||
const buffer = await pdfMutation.mutateAsync({performanceId, reviewType});
|
||||
downloadBlob(buffer, pdfFileName || `review-pdf-${performanceId}-${reviewType}.pdf`, "application/pdf");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<label>
|
||||
<input type="file" className="hidden" onChange={(event) => upload(event.target.files?.[0])} />
|
||||
<FileActionButton icon="upload" disabled={uploadMutation.isPending}>파일 업로드</FileActionButton>
|
||||
</label>
|
||||
<FileActionButton icon="download" disabled={!uploadFileName || originalMutation.isPending} onClick={downloadOriginal}>원본</FileActionButton>
|
||||
<FileActionButton icon="download" disabled={!pdfFileName || pdfMutation.isPending} onClick={downloadPdf}>PDF</FileActionButton>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EvidenceZipButton({performanceId, userId}: {performanceId: number; userId: string}) {
|
||||
const zipMutation = useDownloadEvidenceZipMutation();
|
||||
const download = async () => {
|
||||
const buffer = await zipMutation.mutateAsync({performanceId, userId});
|
||||
downloadBlob(buffer, `monitoring-evidence-${performanceId}-${userId}.zip`, "application/zip");
|
||||
};
|
||||
|
||||
return <FileActionButton icon="image" disabled={zipMutation.isPending} onClick={download}>증빙사진</FileActionButton>;
|
||||
}
|
||||
|
||||
function LocalGovernmentReviewRow({performanceId, codes}: {performanceId: number; codes: CodeMap}) {
|
||||
const reviewType = LOCAL_GOVERNMENT_REVIEW_TYPE;
|
||||
const {data: review} = useReviewFileQuery(performanceId, reviewType, performanceId > 0);
|
||||
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={performanceId} reviewType={reviewType} uploadFileName={review?.uploadFileName} pdfFileName={review?.pdfFileName} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MonitoringStatusRow({
|
||||
performance,
|
||||
index,
|
||||
codes,
|
||||
userMap,
|
||||
}: {
|
||||
performance: PerformanceFull | PerformanceCompact;
|
||||
index: 0 | 1;
|
||||
codes: CodeMap;
|
||||
userMap: Map<string, UserFull>;
|
||||
}) {
|
||||
const slot = getMonitoringSlots(performance as PerformanceFull)[index];
|
||||
const user = slot.assign?.assignUser ? userMap.get(slot.assign.assignUser) : undefined;
|
||||
const reviewType = index + 1;
|
||||
const {data: review} = useReviewFileQuery(performance.id, reviewType, performance.id > 0);
|
||||
const label = getCodeLabel(codes, "monitoring_visit_status", slot.visit?.monitoringVisitStatus);
|
||||
const display = getMonitoringStatusDisplay(label, slot);
|
||||
|
||||
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={slot.assign?.assignUser} user={user} codes={codes} type="monitoring" />
|
||||
<div>기록 사용자: {getMonitoringRecordedUser(slot.visit)}</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<StatusPill variant={display.variant}>{display.label}</StatusPill>
|
||||
<ReviewFileActions performanceId={performance.id} reviewType={reviewType} uploadFileName={review?.uploadFileName} pdfFileName={review?.pdfFileName} />
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<span>모니터링 출발/도착 기록: {getMonitoringRecordedAt(slot.visit)}</span>
|
||||
{slot.assign?.assignUser ? (
|
||||
<EvidenceZipButton performanceId={performance.id} userId={slot.assign.assignUser} />
|
||||
) : (
|
||||
<FileActionButton icon="image" disabled>증빙사진</FileActionButton>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WrittenReviewRows({
|
||||
performance,
|
||||
codes,
|
||||
isWrittenReviewer,
|
||||
userMap,
|
||||
}: {
|
||||
performance: PerformanceFull | PerformanceCompact;
|
||||
codes: CodeMap;
|
||||
isWrittenReviewer: boolean;
|
||||
userMap: Map<string, UserFull>;
|
||||
}) {
|
||||
const startMutation = useStartWrittenReviewMutation();
|
||||
const endMutation = useEndWrittenReviewMutation();
|
||||
const rows = getWrittenReviewRows(performance as PerformanceFull);
|
||||
|
||||
if(rows.length === 0){
|
||||
rows.push({userId: "", assign: undefined, review: undefined});
|
||||
}
|
||||
|
||||
const openWrittenReviewLink = (userId: string, complete: boolean) => {
|
||||
window.open(buildWrittenReviewLink({performanceId: performance.id, userId, complete}), "_blank", "noopener,noreferrer");
|
||||
};
|
||||
|
||||
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={isWrittenReviewer ? () => openWrittenReviewLink(userId, complete) : undefined}>
|
||||
{display.label}
|
||||
</StatusPill>
|
||||
{isWrittenReviewer && (
|
||||
<Button type="button" size="xs" variant="outline" onClick={() => openWrittenReviewLink(userId, complete)}>
|
||||
평가 링크
|
||||
</Button>
|
||||
)}
|
||||
<Button type="button" size="xs" variant="outline" onClick={() => startMutation.mutate(performance.id)}>
|
||||
평가진행
|
||||
</Button>
|
||||
{complete && (
|
||||
<Button type="button" size="xs" variant="outline" onClick={() => endMutation.mutate({performanceId: performance.id, userId})}>
|
||||
평가완료
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PerformanceDetailDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
performance,
|
||||
codes,
|
||||
canEdit,
|
||||
isWrittenReviewer = false,
|
||||
onSave,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
performance: PerformanceFull | PerformanceCompact | null;
|
||||
codes: CodeMap;
|
||||
canEdit: boolean;
|
||||
isWrittenReviewer?: boolean;
|
||||
onSave?: (performance: PerformanceCompact) => void;
|
||||
}) {
|
||||
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]
|
||||
);
|
||||
|
||||
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 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;
|
||||
onSave?.(draft);
|
||||
setIsEditing(false);
|
||||
};
|
||||
|
||||
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="연번">{draft.id}</DetailRow>
|
||||
<DetailRow label="사업유형">{getCodeLabel(codes, "business_type", draft.businessType)}</DetailRow>
|
||||
<DetailRow label="분야(장르)">{getCodeLabel(codes, "genre", draft.performanceGenre)}</DetailRow>
|
||||
<DetailRow label="지역">{getCodeLabel(codes, "area", draft.performanceArea)}</DetailRow>
|
||||
<DetailRow label="단체(인)명">{draft.artistName}</DetailRow>
|
||||
<DetailRow label="사업명">{isEditing ? <Input value={draft.performanceName} onChange={(event) => updateDraft("performanceName", event.target.value)} /> : draft.performanceName}</DetailRow>
|
||||
<DetailRow label="사업 수행 월">{isEditing ? <Input type="number" value={draft.performanceStartMonth} onChange={(event) => updateDraft("performanceStartMonth", Number(event.target.value))} /> : `${draft.performanceStartMonth}월`}</DetailRow>
|
||||
<DetailRow label="사업 일정">{isEditing ? <Input value={draft.performanceDtInfo} onChange={(event) => updateDraft("performanceDtInfo", event.target.value)} /> : draft.performanceDtInfo}</DetailRow>
|
||||
<DetailRow label="운영 시간">{isEditing ? <Input value={draft.performanceTimeInfo} onChange={(event) => updateDraft("performanceTimeInfo", event.target.value)} /> : draft.performanceTimeInfo}</DetailRow>
|
||||
<DetailRow label="예매 예약">
|
||||
{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="예매 비고">{isEditing ? <Input value={draft.ticketReservationMemo} onChange={(event) => updateDraft("ticketReservationMemo", event.target.value)} /> : draft.ticketReservationMemo}</DetailRow>
|
||||
<DetailRow label="모니터링 일정">{isEditing ? <DatePicker value={draft.performanceMonitoringSchedule?.monitoringDate ?? ""} onChange={(value) => updateSchedule("monitoringDate", value)} /> : draft.performanceMonitoringSchedule?.monitoringDate}</DetailRow>
|
||||
<DetailRow label="모니터링 시간">{isEditing ? <Input value={draft.performanceMonitoringSchedule?.monitoringTimeInfo ?? ""} onChange={(event) => updateSchedule("monitoringTimeInfo", event.target.value)} /> : draft.performanceMonitoringSchedule?.monitoringTimeInfo}</DetailRow>
|
||||
<DetailRow label="방문 장소">{isEditing ? <Input value={draft.performanceMonitoringSchedule?.monitoringAddress ?? ""} onChange={(event) => updateSchedule("monitoringAddress", event.target.value)} /> : draft.performanceMonitoringSchedule?.monitoringAddress}</DetailRow>
|
||||
<DetailRow label="메모">{isEditing ? <Input value={draft.performanceMemo} onChange={(event) => updateDraft("performanceMemo", event.target.value)} /> : draft.performanceMemo}</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="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="border-b bg-muted px-3 py-2 font-semibold">평가 및 모니터링 현황</div>
|
||||
<LocalGovernmentReviewRow performanceId={draft.id} codes={codes} />
|
||||
<MonitoringStatusRow performance={performance ?? draft} index={0} codes={codes} userMap={monitoringUserMap} />
|
||||
<MonitoringStatusRow performance={performance ?? draft} index={1} codes={codes} userMap={monitoringUserMap} />
|
||||
<WrittenReviewRows performance={performance ?? draft} codes={codes} isWrittenReviewer={isWrittenReviewer} userMap={writtenUserMap} />
|
||||
</section>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="shrink-0 border-t pt-4">
|
||||
{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>
|
||||
);
|
||||
}
|
||||
271
src/components/dialog/SmsSendDialog.tsx
Normal file
271
src/components/dialog/SmsSendDialog.tsx
Normal file
@@ -0,0 +1,271 @@
|
||||
"use client";
|
||||
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import {Edit, RotateCcw, Save, Send} 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 {
|
||||
NOTIFICATION_REQUEST_SERVICE,
|
||||
useNotificationTemplateQuery,
|
||||
useSaveNotificationTemplateMutation,
|
||||
useSendSmsBulkMutation,
|
||||
} from "@/query/notification";
|
||||
import {SaveTemplateRequest, Template} from "@/types/notification";
|
||||
import {UserCompact} from "@/types/gwcf";
|
||||
import {getDetailValue} from "@/lib/gwcf/view";
|
||||
import {useAuth} from "@/hooks/useAuth";
|
||||
|
||||
type TemplateDraft = Pick<Template, "tmplatIdx" | "tmplatNm" | "tmplatTitle" | "tmplatBody" | "sendTel">;
|
||||
|
||||
const toText = (value: string | null | undefined) => value ?? "";
|
||||
|
||||
const toDraft = (template: Template, emptyBody = false): TemplateDraft => ({
|
||||
tmplatIdx: template.tmplatIdx,
|
||||
tmplatNm: toText(template.tmplatNm),
|
||||
tmplatTitle: toText(template.tmplatTitle),
|
||||
tmplatBody: emptyBody ? "" : toText(template.tmplatBody),
|
||||
sendTel: toText(template.sendTel),
|
||||
});
|
||||
|
||||
const toParamValue = (value: unknown) => value == null ? "" : String(value);
|
||||
|
||||
const buildUserMsgParam = (user: UserCompact): Record<string, string> => ({
|
||||
...Object.fromEntries(
|
||||
Object.entries(user.userDetail ?? {}).map(([key, value]) => [key, toParamValue(value)])
|
||||
),
|
||||
userId: toParamValue(user.userId),
|
||||
userCmpn: toParamValue(user.userCmpn),
|
||||
userTeam: toParamValue(user.userTeam),
|
||||
userName: toParamValue(user.userName),
|
||||
userRole: toParamValue(user.userRole),
|
||||
});
|
||||
|
||||
export function SmsSendDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
title = "문자 발송",
|
||||
templateIdx,
|
||||
newMessageTemplateIdx,
|
||||
selectedUsers,
|
||||
addParams = {},
|
||||
onSent,
|
||||
}: Readonly<{
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
title?: string;
|
||||
templateIdx: number;
|
||||
newMessageTemplateIdx?: number;
|
||||
selectedUsers: UserCompact[];
|
||||
addParams?: Record<string, string>;
|
||||
onSent?: () => void;
|
||||
}>) {
|
||||
const {auth} = useAuth();
|
||||
const [activeTemplateIdx, setActiveTemplateIdx] = useState(templateIdx);
|
||||
const [isNewMessage, setIsNewMessage] = useState(false);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [draft, setDraft] = useState<TemplateDraft | null>(null);
|
||||
|
||||
const templateQuery = useNotificationTemplateQuery(activeTemplateIdx, open);
|
||||
const saveTemplateMutation = useSaveNotificationTemplateMutation();
|
||||
const sendSmsMutation = useSendSmsBulkMutation();
|
||||
|
||||
const isBusy = templateQuery.isLoading || saveTemplateMutation.isPending || sendSmsMutation.isPending;
|
||||
const canEdit = isNewMessage || isEditing;
|
||||
|
||||
const destinations = useMemo(() => {
|
||||
return selectedUsers
|
||||
.map((user) => ({
|
||||
sid: user.userId,
|
||||
destTel: getDetailValue(user.userDetail, ["userTel"]),
|
||||
destNm: user.userName || user.userId,
|
||||
msgParam: {
|
||||
...buildUserMsgParam(user),
|
||||
...addParams,
|
||||
},
|
||||
}))
|
||||
.filter((item) => item.destTel);
|
||||
}, [selectedUsers, addParams]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
setActiveTemplateIdx(templateIdx);
|
||||
setIsNewMessage(false);
|
||||
setIsEditing(false);
|
||||
setDraft(null);
|
||||
}, [open, templateIdx]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !templateQuery.data) return;
|
||||
|
||||
setDraft(toDraft(templateQuery.data, isNewMessage));
|
||||
setIsEditing(false);
|
||||
}, [isNewMessage, open, templateQuery.data]);
|
||||
|
||||
const updateDraft = <K extends keyof TemplateDraft>(key: K, value: TemplateDraft[K]) => {
|
||||
setDraft((prev) => prev ? {...prev, [key]: value} : prev);
|
||||
};
|
||||
|
||||
const saveTemplate = async () => {
|
||||
if (!draft) return null;
|
||||
|
||||
const payload: SaveTemplateRequest = {
|
||||
tmplatIdx: draft.tmplatIdx,
|
||||
tmplatNm: draft.tmplatNm,
|
||||
tmplatTitle: draft.tmplatTitle,
|
||||
tmplatBody: draft.tmplatBody,
|
||||
sendTel: draft.sendTel,
|
||||
};
|
||||
|
||||
const saved = await saveTemplateMutation.mutateAsync(payload);
|
||||
setDraft(toDraft(saved));
|
||||
setIsEditing(false);
|
||||
return saved;
|
||||
};
|
||||
|
||||
const switchToNewMessage = () => {
|
||||
if (!newMessageTemplateIdx) return;
|
||||
|
||||
setActiveTemplateIdx(newMessageTemplateIdx);
|
||||
setIsNewMessage(true);
|
||||
setIsEditing(false);
|
||||
setDraft(null);
|
||||
};
|
||||
|
||||
const restoreTemplate = () => {
|
||||
setActiveTemplateIdx(templateIdx);
|
||||
setIsNewMessage(false);
|
||||
setIsEditing(false);
|
||||
setDraft(null);
|
||||
};
|
||||
|
||||
const send = async () => {
|
||||
if (!draft) return;
|
||||
|
||||
if (!auth.user?.userCmpn || !auth.user?.userId) {
|
||||
alert("로그인 사용자 정보를 확인할 수 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedUsers.length === 0) {
|
||||
alert("문자를 발송할 사용자를 선택해 주세요.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (destinations.length === 0) {
|
||||
alert("발송 가능한 연락처가 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (destinations.length !== selectedUsers.length) {
|
||||
if (!confirm("연락처가 없는 사용자는 제외하고 발송합니다. 계속하시겠습니까?")) return;
|
||||
}
|
||||
|
||||
if (isNewMessage) {
|
||||
await saveTemplate();
|
||||
}
|
||||
|
||||
const result = await sendSmsMutation.mutateAsync({
|
||||
templateIdx: draft.tmplatIdx,
|
||||
reqstCmpn: auth.user.userCmpn,
|
||||
reqstUser: auth.user.userId,
|
||||
reqstSvc: NOTIFICATION_REQUEST_SERVICE,
|
||||
destinations,
|
||||
});
|
||||
|
||||
alert(`문자 발송 요청이 ${result.requestCount}건 완료되었습니다.`);
|
||||
onSent?.();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="flex max-h-[90vh] flex-col overflow-hidden sm:max-w-2xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto pr-1">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border bg-muted/30 p-3">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
선택 인원: <span className="font-semibold text-foreground">{selectedUsers.length}</span>명
|
||||
{destinations.length !== selectedUsers.length && (
|
||||
<span className="ml-2 text-destructive">발송 가능 {destinations.length}명</span>
|
||||
)}
|
||||
</div>
|
||||
{newMessageTemplateIdx && (
|
||||
isNewMessage ? (
|
||||
<Button type="button" size="sm" variant="outline" onClick={restoreTemplate} disabled={isBusy}>
|
||||
<RotateCcw className="h-4 w-4" />
|
||||
기본 템플릿
|
||||
</Button>
|
||||
) : (
|
||||
<Button type="button" size="sm" variant="outline" onClick={switchToNewMessage} disabled={isBusy}>
|
||||
새문자 보내기
|
||||
</Button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
|
||||
{templateQuery.isLoading && (
|
||||
<div className="rounded-md border p-4 text-sm text-muted-foreground">템플릿 정보를 불러오는 중입니다.</div>
|
||||
)}
|
||||
|
||||
{draft && (
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
<label className="space-y-1 text-sm">
|
||||
<span className="font-medium">템플릿명</span>
|
||||
<Input value={draft.tmplatNm} disabled />
|
||||
</label>
|
||||
<label className="space-y-1 text-sm">
|
||||
<span className="font-medium">발신번호</span>
|
||||
<Input value={draft.sendTel ?? ""} disabled={!canEdit || isBusy} onChange={(event) => updateDraft("sendTel", event.target.value)} />
|
||||
</label>
|
||||
</div>
|
||||
<label className="space-y-1 text-sm">
|
||||
<span className="font-medium">제목</span>
|
||||
<Input value={draft.tmplatTitle} disabled={!canEdit || isBusy} onChange={(event) => updateDraft("tmplatTitle", event.target.value)} />
|
||||
</label>
|
||||
<label className="space-y-1 text-sm">
|
||||
<span className="font-medium">내용</span>
|
||||
<textarea
|
||||
value={draft.tmplatBody}
|
||||
disabled={!canEdit || isBusy}
|
||||
onChange={(event) => updateDraft("tmplatBody", event.target.value)}
|
||||
className="min-h-56 w-full rounded-md border border-input bg-background p-3 text-sm disabled:cursor-not-allowed disabled:opacity-70"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="shrink-0 border-t pt-4">
|
||||
{!isNewMessage && draft && !isEditing && (
|
||||
<Button type="button" variant="outline" onClick={() => setIsEditing(true)} disabled={isBusy}>
|
||||
<Edit className="h-4 w-4" />
|
||||
수정
|
||||
</Button>
|
||||
)}
|
||||
{!isNewMessage && draft && isEditing && (
|
||||
<Button type="button" variant="outline" onClick={saveTemplate} disabled={isBusy}>
|
||||
<Save className="h-4 w-4" />
|
||||
저장
|
||||
</Button>
|
||||
)}
|
||||
<Button type="button" disabled={!draft || isBusy || isEditing || selectedUsers.length === 0} onClick={send}>
|
||||
<Send className="h-4 w-4" />
|
||||
발송
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user