From 92ddb4f13d48cbf344dc2bf63df4457b3c713608 Mon Sep 17 00:00:00 2001 From: rlaks5757 Date: Wed, 26 Mar 2025 16:51:54 +0900 Subject: feat: report batch download 기능 완료 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/form-data/form-data-report-dialog.tsx | 457 +++++++++++++++++++++++ 1 file changed, 457 insertions(+) create mode 100644 components/form-data/form-data-report-dialog.tsx (limited to 'components/form-data/form-data-report-dialog.tsx') diff --git a/components/form-data/form-data-report-dialog.tsx b/components/form-data/form-data-report-dialog.tsx new file mode 100644 index 00000000..deb0873b --- /dev/null +++ b/components/form-data/form-data-report-dialog.tsx @@ -0,0 +1,457 @@ +"use client"; + +import React, { + FC, + Dispatch, + SetStateAction, + useState, + useEffect, + useRef, +} from "react"; +import { WebViewerInstance, Core } from "@pdftron/webviewer"; +import { useToast } from "@/hooks/use-toast"; +import prettyBytes from "pretty-bytes"; +import { X, Loader2 } from "lucide-react"; +import { Badge } from "@/components/ui/badge"; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, +} from "@/components/ui/dialog"; +import { Label } from "@/components/ui/label"; +import { + Select, + SelectContent, + SelectGroup, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Button } from "@/components/ui/button"; +import { getReportTempList } from "@/lib/forms/services"; +import { DataTableColumnJSON } from "./form-data-table-columns"; + +type ReportData = { + [key: string]: any; +}; + +interface tempFile { + fileName: string; + filePath: string; +} + +interface FormDataReportDialogProps { + columnsJSON: DataTableColumnJSON[]; + reportData: ReportData[]; + setReportData: Dispatch>; + packageId: number; + formId: number; + formCode: string; +} + +export const FormDataReportDialog: FC = ({ + columnsJSON, + reportData, + setReportData, + packageId, + formId, +}) => { + const [tempList, setTempList] = useState([]); + const [selectTemp, setSelectTemp] = useState(""); + const [instance, setInstance] = useState(null); + const [fileLoading, setFileLoading] = useState(true); + + useEffect(() => { + updateReportTempList(packageId, formId, setTempList); + }, [packageId, formId]); + + const onClose = async (value: boolean) => { + if (fileLoading) { + return; + } + if (!value) { + setTimeout(() => cleanupHtmlStyle(), 1000); + setReportData([]); + } + }; + + const downloadFileData = async () => { + if (instance) { + const { UI, Core } = instance; + const { documentViewer } = Core; + + const doc = documentViewer.getDocument(); + const fileName = doc.getFilename(); + const fileData = await doc.getFileData({ + includeAnnotations: true, // 사용자가 추가한 폼 필드 및 입력 포함 + // officeOptions: { + // outputFormat: "docx", + // }, + }); + + const blob = new Blob([fileData], { + type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + }); + + const link = document.createElement("a"); + link.href = URL.createObjectURL(blob); + link.download = fileName; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + + // const allTabs = UI.TabManager.getAllTabs() as { + // id: number; + // src: Core.Document; + // }[]; + + // for (const tab of allTabs) { + // // await UI.TabManager.setActiveTab(tab.id); + // await activateTabAndWaitForLoad(instance, tab.id); + // const tabDoc = tab.src; + // const fileName = tabDoc.getFilename(); + + // const fileData = await tabDoc.getFileData({ + // includeAnnotations: true, + // }); + + // console.log({ fileData }); + + // const blob = new Blob([fileData], { + // type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + // }); + + // // 다운로드 + // // const link = document.createElement("a"); + // // link.href = URL.createObjectURL(blob); + // // link.download = fileName; + // // document.body.appendChild(link); + // // link.click(); + // // document.body.removeChild(link); + // } + } + }; + + return ( + 0} onOpenChange={onClose}> + + + Report + + 사용하시고자 하는 Report Template를 선택하여 주시기 바랍니다. + + +
+ + +
+
+ +
+ + + + +
+
+ ); +}; + +interface ReportWebViewerProps { + columnsJSON: DataTableColumnJSON[]; + reportTempPath: string; + reportDatas: ReportData[]; + instance: null | WebViewerInstance; + setInstance: Dispatch>; + setFileLoading: Dispatch>; +} + +const ReportWebViewer: FC = ({ + columnsJSON, + reportTempPath, + reportDatas, + instance, + setInstance, + setFileLoading, +}) => { + const [viwerLoading, setViewerLoading] = useState(true); + const viewer = useRef(null); + const initialized = React.useRef(false); + const isCancelled = React.useRef(false); // 초기화 중단용 flag + + useEffect(() => { + if (!initialized.current) { + initialized.current = true; + isCancelled.current = false; // 다시 열릴 때는 false로 리셋 + + requestAnimationFrame(() => { + if (viewer.current) { + import("@pdftron/webviewer").then(({ default: WebViewer }) => { + console.log(isCancelled.current); + if (isCancelled.current) { + console.log("📛 WebViewer 초기화 취소됨 (Dialog 닫힘)"); + + return; + } + + WebViewer( + { + path: "/pdftronWeb", + licenseKey: process.env.NEXT_PUBLIC_PDFTRON_WEBVIEW_KEY, + fullAPI: true, + }, + viewer.current as HTMLDivElement + ).then(async (instance: WebViewerInstance) => { + setInstance(instance); + // //Tab 메뉴 사용 필요시 활성화 + // instance.UI.enableFeatures([instance.UI.Feature.MultiTab]); + // instance.UI.disableElements([ + // "addTabButton", + // "multiTabsEmptyPage", + // ]); + setViewerLoading(false); + }); + }); + } + }); + } + + return () => { + // cleanup 시에는 중단 flag 세움 + if (instance) { + instance.UI.dispose(); + } + setTimeout(() => cleanupHtmlStyle(), 500); + }; + }, []); + + useEffect(() => { + importReportData( + columnsJSON, + instance, + reportDatas, + reportTempPath, + setFileLoading + ); + }, [reportTempPath, reportDatas, instance, columnsJSON]); + + return ( +
+ {viwerLoading && ( +
+ +

문서 뷰어 로딩 중...

+
+ )} +
+ ); +}; + +const cleanupHtmlStyle = () => { + const htmlElement = document.documentElement; + + // 기존 style 속성 가져오기 + const originalStyle = htmlElement.getAttribute("style") || ""; + + // "color-scheme: light" 또는 "color-scheme: dark" 찾기 + const colorSchemeStyle = originalStyle + .split(";") + .map((s) => s.trim()) + .find((s) => s.startsWith("color-scheme:")); + + // 새로운 스타일 적용 (color-scheme만 유지) + if (colorSchemeStyle) { + htmlElement.setAttribute("style", colorSchemeStyle + ";"); + } else { + htmlElement.removeAttribute("style"); // color-scheme도 없으면 style 속성 자체 삭제 + } + + console.log("html style 삭제"); +}; + +const stringifyAllValues = (obj: any): any => { + if (Array.isArray(obj)) { + return obj.map((item) => stringifyAllValues(item)); + } else if (typeof obj === "object" && obj !== null) { + const result: any = {}; + for (const key in obj) { + result[key] = stringifyAllValues(obj[key]); + } + return result; + } else { + return obj !== null && obj !== undefined ? String(obj) : ""; + } +}; + +type ImportReportData = ( + columnsJSON: DataTableColumnJSON[], + instance: null | WebViewerInstance, + reportDatas: ReportData[], + reportTempPath: string, + setFileLoading: Dispatch> +) => void; + +const importReportData: ImportReportData = async ( + columnsJSON, + instance, + reportDatas, + reportTempPath, + setFileLoading +) => { + setFileLoading(true); + try { + if (instance && reportDatas.length > 0 && reportTempPath.length > 0) { + const { UI, Core } = instance; + const { documentViewer, createDocument } = Core; + + const getFileData = await fetch(reportTempPath); + const reportFileBlob = await getFileData.blob(); + + const reportData = reportDatas[0]; + const reportValue = stringifyAllValues(reportData); + + const reportValueMapping: { [key: string]: any } = {}; + + columnsJSON.forEach((c) => { + const { key, label } = c; + + const objKey = label.split(" ").join("_"); + + reportValueMapping[objKey] = reportValue?.[key] ?? ""; + }); + + const doc = await createDocument(reportFileBlob, { + extension: "docx", + }); + + await doc.applyTemplateValues(reportValueMapping); + + documentViewer.loadDocument(doc, { + extension: "docx", + enableOfficeEditing: true, + officeOptions: { + formatOptions: { + applyPageBreaksToSheet: true, + }, + }, + }); + } + } catch (err) { + } finally { + setFileLoading(false); + } +}; + +const importReportDataTab: ImportReportData = async ( + columnJSON, + instance, + reportDatas, + reportTempPath, + setFileLoading +) => { + setFileLoading(true); + try { + if (instance && reportDatas.length > 0 && reportTempPath.length > 0) { + const { UI, Core } = instance; + const { createDocument } = Core; + + const getFileData = await fetch(reportTempPath); + const reportFileBlob = await getFileData.blob(); + + const prevTab = UI.TabManager.getAllTabs(); + + (prevTab as object[] as { id: number }[]).forEach((c) => { + const { id } = c; + UI.TabManager.deleteTab(id); + }); + + const fileOptions = reportDatas.map((c) => { + const { tagNumber } = c; + + const options = { + filename: `${tagNumber}_report.docx`, + }; + + return { options, reportData: c }; + }); + + const tabIds = []; + + for (const fileOption of fileOptions) { + let doc = await createDocument(reportFileBlob, { + ...fileOption.options, + extension: "docx", + }); + + await doc.applyTemplateValues( + stringifyAllValues(fileOption.reportData) + ); + + const tab = await UI.TabManager.addTab(doc, { + ...fileOption.options, + }); + + tabIds.push(tab); // 탭 ID 저장 + } + + if (tabIds.length > 0) { + await UI.TabManager.setActiveTab(tabIds[0]); + } + } + } catch (err) { + } finally { + setFileLoading(false); + } +}; + +type UpdateReportTempList = ( + packageId: number, + formId: number, + setPrevReportTemp: Dispatch> +) => void; + +const updateReportTempList: UpdateReportTempList = async ( + packageId, + formId, + setTempList +) => { + const tempList = await getReportTempList(packageId, formId); + + setTempList( + tempList.map((c) => { + const { fileName, filePath } = c; + return { fileName, filePath }; + }) + ); +}; -- cgit v1.2.3 From c4c3f12b4a6d1a3c09b797e1a160747cac8761e9 Mon Sep 17 00:00:00 2001 From: rlaks5757 Date: Fri, 28 Mar 2025 11:27:25 +0900 Subject: template file download 개발 완료 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../form-data/form-data-report-batch-dialog.tsx | 13 +- components/form-data/form-data-report-dialog.tsx | 139 ++------- .../form-data-report-temp-upload-dialog.tsx | 340 ++++++++++++++++++--- components/form-data/form-data-table.tsx | 47 +-- db/schema/vendorData.ts | 19 -- lib/forms/services.ts | 53 +++- .../sample_template_file.docx | Bin 0 -> 24773 bytes 7 files changed, 399 insertions(+), 212 deletions(-) create mode 100644 public/vendorFormReportSample/sample_template_file.docx (limited to 'components/form-data/form-data-report-dialog.tsx') diff --git a/components/form-data/form-data-report-batch-dialog.tsx b/components/form-data/form-data-report-batch-dialog.tsx index 614f890e..6c690363 100644 --- a/components/form-data/form-data-report-batch-dialog.tsx +++ b/components/form-data/form-data-report-batch-dialog.tsx @@ -8,8 +8,10 @@ import React, { useEffect, } from "react"; import { useToast } from "@/hooks/use-toast"; +import { toast as toastMessage} from "sonner"; import prettyBytes from "pretty-bytes"; import { X, Loader2 } from "lucide-react"; +import { saveAs } from 'file-saver'; import { Badge } from "@/components/ui/badge"; import { Dialog, @@ -159,15 +161,14 @@ export const FormDataReportBatchDialog: FC = ({ if (reqeustCreateReport.ok) { const blob = await reqeustCreateReport.blob(); - const url = window.URL.createObjectURL(blob); - const a = document.createElement("a"); - a.href = url; - a.download = `${formCode}.pdf`; - a.click(); - window.URL.revokeObjectURL(url); + + saveAs(blob, `${formCode}.pdf`); + + toastMessage.success("Report 다운로드 완료!") } else { const err = await reqeustCreateReport.json(); console.error("에러:", err); + throw new Error(err.message) } } catch (err) { console.error(err); diff --git a/components/form-data/form-data-report-dialog.tsx b/components/form-data/form-data-report-dialog.tsx index deb0873b..e28b4345 100644 --- a/components/form-data/form-data-report-dialog.tsx +++ b/components/form-data/form-data-report-dialog.tsx @@ -8,11 +8,10 @@ import React, { useEffect, useRef, } from "react"; -import { WebViewerInstance, Core } from "@pdftron/webviewer"; -import { useToast } from "@/hooks/use-toast"; -import prettyBytes from "pretty-bytes"; -import { X, Loader2 } from "lucide-react"; -import { Badge } from "@/components/ui/badge"; +import { WebViewerInstance } from "@pdftron/webviewer"; +import { Loader2 } from "lucide-react"; +import { saveAs } from "file-saver"; +import { toast } from "sonner"; import { Dialog, DialogContent, @@ -25,11 +24,11 @@ import { Label } from "@/components/ui/label"; import { Select, SelectContent, - SelectGroup, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; + import { Button } from "@/components/ui/button"; import { getReportTempList } from "@/lib/forms/services"; import { DataTableColumnJSON } from "./form-data-table-columns"; @@ -58,7 +57,9 @@ export const FormDataReportDialog: FC = ({ setReportData, packageId, formId, + formCode, }) => { + const [tempList, setTempList] = useState([]); const [selectTemp, setSelectTemp] = useState(""); const [instance, setInstance] = useState(null); @@ -92,46 +93,9 @@ export const FormDataReportDialog: FC = ({ // }, }); - const blob = new Blob([fileData], { - type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - }); + saveAs(new Blob([fileData]), fileName); - const link = document.createElement("a"); - link.href = URL.createObjectURL(blob); - link.download = fileName; - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - - // const allTabs = UI.TabManager.getAllTabs() as { - // id: number; - // src: Core.Document; - // }[]; - - // for (const tab of allTabs) { - // // await UI.TabManager.setActiveTab(tab.id); - // await activateTabAndWaitForLoad(instance, tab.id); - // const tabDoc = tab.src; - // const fileName = tabDoc.getFilename(); - - // const fileData = await tabDoc.getFileData({ - // includeAnnotations: true, - // }); - - // console.log({ fileData }); - - // const blob = new Blob([fileData], { - // type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - // }); - - // // 다운로드 - // // const link = document.createElement("a"); - // // link.href = URL.createObjectURL(blob); - // // link.download = fileName; - // // document.body.appendChild(link); - // // link.click(); - // // document.body.removeChild(link); - // } + toast.success("Report 다운로드 완료!"); } }; @@ -175,6 +139,7 @@ export const FormDataReportDialog: FC = ({ instance={instance} setInstance={setInstance} setFileLoading={setFileLoading} + formCode={formCode} /> @@ -195,6 +160,7 @@ interface ReportWebViewerProps { instance: null | WebViewerInstance; setInstance: Dispatch>; setFileLoading: Dispatch>; + formCode: string; } const ReportWebViewer: FC = ({ @@ -204,6 +170,7 @@ const ReportWebViewer: FC = ({ instance, setInstance, setFileLoading, + formCode, }) => { const [viwerLoading, setViewerLoading] = useState(true); const viewer = useRef(null); @@ -234,12 +201,6 @@ const ReportWebViewer: FC = ({ viewer.current as HTMLDivElement ).then(async (instance: WebViewerInstance) => { setInstance(instance); - // //Tab 메뉴 사용 필요시 활성화 - // instance.UI.enableFeatures([instance.UI.Feature.MultiTab]); - // instance.UI.disableElements([ - // "addTabButton", - // "multiTabsEmptyPage", - // ]); setViewerLoading(false); }); }); @@ -262,9 +223,10 @@ const ReportWebViewer: FC = ({ instance, reportDatas, reportTempPath, - setFileLoading + setFileLoading, + formCode ); - }, [reportTempPath, reportDatas, instance, columnsJSON]); + }, [reportTempPath, reportDatas, instance, columnsJSON, formCode]); return (
@@ -319,7 +281,8 @@ type ImportReportData = ( instance: null | WebViewerInstance, reportDatas: ReportData[], reportTempPath: string, - setFileLoading: Dispatch> + setFileLoading: Dispatch>, + formCode: string ) => void; const importReportData: ImportReportData = async ( @@ -327,7 +290,8 @@ const importReportData: ImportReportData = async ( instance, reportDatas, reportTempPath, - setFileLoading + setFileLoading, + formCode ) => { setFileLoading(true); try { @@ -352,12 +316,13 @@ const importReportData: ImportReportData = async ( }); const doc = await createDocument(reportFileBlob, { + filename: `${formCode}_report.docx`, extension: "docx", }); await doc.applyTemplateValues(reportValueMapping); - documentViewer.loadDocument(doc, { + documentViewer.loadDocument(doc, { extension: "docx", enableOfficeEditing: true, officeOptions: { @@ -373,68 +338,6 @@ const importReportData: ImportReportData = async ( } }; -const importReportDataTab: ImportReportData = async ( - columnJSON, - instance, - reportDatas, - reportTempPath, - setFileLoading -) => { - setFileLoading(true); - try { - if (instance && reportDatas.length > 0 && reportTempPath.length > 0) { - const { UI, Core } = instance; - const { createDocument } = Core; - - const getFileData = await fetch(reportTempPath); - const reportFileBlob = await getFileData.blob(); - - const prevTab = UI.TabManager.getAllTabs(); - - (prevTab as object[] as { id: number }[]).forEach((c) => { - const { id } = c; - UI.TabManager.deleteTab(id); - }); - - const fileOptions = reportDatas.map((c) => { - const { tagNumber } = c; - - const options = { - filename: `${tagNumber}_report.docx`, - }; - - return { options, reportData: c }; - }); - - const tabIds = []; - - for (const fileOption of fileOptions) { - let doc = await createDocument(reportFileBlob, { - ...fileOption.options, - extension: "docx", - }); - - await doc.applyTemplateValues( - stringifyAllValues(fileOption.reportData) - ); - - const tab = await UI.TabManager.addTab(doc, { - ...fileOption.options, - }); - - tabIds.push(tab); // 탭 ID 저장 - } - - if (tabIds.length > 0) { - await UI.TabManager.setActiveTab(tabIds[0]); - } - } - } catch (err) { - } finally { - setFileLoading(false); - } -}; - type UpdateReportTempList = ( packageId: number, formId: number, diff --git a/components/form-data/form-data-report-temp-upload-dialog.tsx b/components/form-data/form-data-report-temp-upload-dialog.tsx index 413c1e51..69df704e 100644 --- a/components/form-data/form-data-report-temp-upload-dialog.tsx +++ b/components/form-data/form-data-report-temp-upload-dialog.tsx @@ -8,8 +8,11 @@ import React, { useEffect, } from "react"; import { useToast } from "@/hooks/use-toast"; +import { toast as toastMessage } from "sonner"; import prettyBytes from "pretty-bytes"; -import { X, Loader2, Download } from "lucide-react"; +import { X, Loader2, Download, Delete, Trash2 } from "lucide-react"; +import ExcelJS from "exceljs"; +import { saveAs } from "file-saver"; import { Badge } from "@/components/ui/badge"; import { Dialog, @@ -40,10 +43,28 @@ import { FileListItem, FileListName, } from "@/components/ui/file-list"; -import { getReportTempList, uploadReportTemp } from "@/lib/forms/services"; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, + AlertDialogTrigger, +} from "@/components/ui/alert-dialog"; +import { + getReportTempList, + uploadReportTemp, + getReportTempFileData, + deleteReportTempFile, +} from "@/lib/forms/services"; import { VendorDataReportTemps } from "@/db/schema/vendorData"; +import { DataTableColumnJSON } from "./form-data-table-columns"; interface FormDataReportTempUploadDialogProps { + columnsJSON: DataTableColumnJSON[]; open: boolean; setOpen: Dispatch>; packageId: number; @@ -57,7 +78,15 @@ const MAX_FILE_SIZE = 3000000; export const FormDataReportTempUploadDialog: FC< FormDataReportTempUploadDialogProps -> = ({ open, setOpen, packageId, formId, uploaderType }) => { +> = ({ + columnsJSON, + open, + setOpen, + packageId, + formId, + formCode, + uploaderType, +}) => { const { toast } = useToast(); const [selectedFiles, setSelectedFiles] = useState([]); const [isUploading, setIsUploading] = useState(false); @@ -131,29 +160,106 @@ export const FormDataReportTempUploadDialog: FC< } }; + const downloadTempFile = async () => { + try { + const { fileName, fileType, base64 } = await getReportTempFileData(); + + saveAs(`data:${fileType};base64,${base64}`, fileName); + + toastMessage.success("Report Sample File 다운로드 완료!"); + } catch (err) { + console.log(err); + toast({ + title: "Error", + description: "Sample File을 찾을 수가 없습니다.", + variant: "destructive", + }); + } + }; + + const downloadReportVarList = async () => { + try { + // Create a new workbook + const workbook = new ExcelJS.Workbook(); + + // 데이터 시트 생성 + const worksheet = workbook.addWorksheet("Data"); + + // 유효성 검사용 숨김 시트 생성 + const validationSheet = workbook.addWorksheet("ValidationData"); + validationSheet.state = "hidden"; // 시트 숨김 처리 + + // 1. 데이터 시트에 헤더 추가 + const headers = ["Table Column Label", "Report Variable"]; + worksheet.addRow(headers); + + // 헤더 스타일 적용 + const headerRow = worksheet.getRow(1); + headerRow.font = { bold: true }; + headerRow.alignment = { horizontal: "center" }; + headerRow.eachCell((cell) => { + cell.fill = { + type: "pattern", + pattern: "solid", + fgColor: { argb: "FFCCCCCC" }, + }; + }); + + // 2. 데이터 행 추가 + columnsJSON.forEach((row) => { + const { displayLabel, label } = row; + + const labelConvert = label.replaceAll(" ", "_"); + + worksheet.addRow([displayLabel, labelConvert]); + }); + + // 3. 컬럼 너비 자동 조정 + headers.forEach((col, idx) => { + const column = worksheet.getColumn(idx + 1); + + // 최적 너비 계산 + let maxLength = col.length; + columnsJSON.forEach((row) => { + const valueKey = idx === 0 ? "displayLabel" : "label"; + + const value = row[valueKey]; + if (value !== undefined && value !== null) { + const valueLength = String(value).length; + if (valueLength > maxLength) { + maxLength = valueLength; + } + } + }); + + // 너비 설정 (최소 10, 최대 50) + column.width = Math.min(Math.max(maxLength + 2, 10), 50); + }); + + const buffer = await workbook.xlsx.writeBuffer(); + saveAs(new Blob([buffer]), `${formCode}_report_varible_list.xlsx`); + toastMessage.success("Report Varible List File 다운로드 완료!"); + } catch (err) { + console.log(err); + toast({ + title: "Error", + description: "Variable List 파일을 찾을 수가 없습니다.", + variant: "destructive", + }); + } + }; + return ( Report Template Upload - 사용하시고자 하는 Report Template(docx File)를 업로드 하여주시기 + 사용하시고자 하는 Report Template(.docx)를 업로드 하여주시기 바랍니다. - {/* {prevReportTemp.length > 0 && ( - <> - - - {prevReportTemp.map((c, i) => { - return
{i}
; - })} -
- - )} */} -
+
@@ -163,10 +269,19 @@ export const FormDataReportTempUploadDialog: FC< sample_template_file.docx - removeFile(index)} - // disabled={isUploading} - > + + + Download + + + + + + + + report_variable_list.xlsx + + Download @@ -174,36 +289,48 @@ export const FormDataReportTempUploadDialog: FC<
+
+ + + updateReportTempList(packageId, formId, setPrevReportTemp) + } + /> +
- - {({ maxSize }) => ( - <> - - -
- -
- 파일을 여기에 드롭하세요 - - 또는 클릭하여 파일을 선택하세요. 최대 크기:{" "} - {maxSize ? prettyBytes(maxSize) : "무제한"} - +
+ + + {({ maxSize }) => ( + <> + + +
+ +
+ 파일을 여기에 드롭하세요 + + 또는 클릭하여 파일을 선택하세요. 최대 크기:{" "} + {maxSize ? prettyBytes(maxSize) : "무제한"} + +
-
- - - - )} - + + + + )} + +
{selectedFiles.length > 0 && (
@@ -247,7 +374,7 @@ const UploadFileItem: FC = ({ isUploading, }) => { return ( - + {selectedFiles.map((file, index) => ( @@ -327,3 +454,116 @@ const updateReportTempList: UpdateReportTempList = async ( const tempList = await getReportTempList(packageId, formId); setPrevReportTemp(tempList); }; + +interface UploadedTempFiles { + prevReportTemp: VendorDataReportTemps[]; + updateReportTempList: () => void; +} + +const UploadedTempFiles: FC = ({ + prevReportTemp, + updateReportTempList, +}) => { + const { toast } = useToast(); + + const downloadTempFile = async (fileName: string, filePath: string) => { + try { + const getTempFile = await fetch(filePath); + + if (getTempFile.ok) { + const blob = await getTempFile.blob(); + + saveAs(blob, fileName); + + toastMessage.success("Report 다운로드 완료!"); + } else { + const err = await getTempFile.json(); + console.error("에러:", err); + throw new Error(err.message); + } + + toastMessage.success("Template File 다운로드 완료!"); + } catch (err) { + console.error(err) + toast({ + title: "Error", + description: "Template File 다운로드 중 오류가 발생했습니다.", + variant: "destructive", + }); + } + }; + + const deleteTempFile = async (id: number) => { + try { + const { result, error } = await deleteReportTempFile(id); + + if (result) { + updateReportTempList(); + toastMessage.success("Template File 삭제 완료!"); + } else { + throw new Error(error); + } + } catch (err) { + toast({ + title: "Error", + description: "Template File 삭제 중 오류가 발생했습니다.", + variant: "destructive", + }); + } + }; + + return ( + + + {prevReportTemp.map((c) => { + const { fileName, filePath, id } = c; + + return ( + + + + + + {fileName} + + { + downloadTempFile(fileName, filePath); + }} + > + + Download + + + + + Delete + + + + + + Report Templete File({fileName})을 삭제하시겠습니까? + + + + + 취소 + { + deleteTempFile(id); + }} + > + 삭제 + + + + + + + ); + })} + + + ); +}; diff --git a/components/form-data/form-data-table.tsx b/components/form-data/form-data-table.tsx index 50c4f267..823416c1 100644 --- a/components/form-data/form-data-table.tsx +++ b/components/form-data/form-data-table.tsx @@ -11,19 +11,22 @@ import { DataTableColumnJSON, ColumnType, } from "./form-data-table-columns"; - import type { DataTableAdvancedFilterField } from "@/types/table"; import { Button } from "../ui/button"; import { Download, Loader, Save, Upload } from "lucide-react"; import { toast } from "sonner"; import { syncMissingTags, updateFormDataInDB } from "@/lib/forms/services"; import { UpdateTagSheet } from "./update-form-sheet"; - import ExcelJS from "exceljs"; import { saveAs } from "file-saver"; import { FormDataReportTempUploadDialog } from "./form-data-report-temp-upload-dialog"; import { FormDataReportDialog } from "./form-data-report-dialog"; import { FormDataReportBatchDialog } from "./form-data-report-batch-dialog"; +import { + Popover, + PopoverContent, + PopoverTrigger, +} from "@/components/ui/popover"; interface GenericData { [key: string]: any; @@ -526,20 +529,29 @@ export default function DynamicTable({ {/* 버튼 그룹 */}
{/* 태그 불러오기 버튼 */} - - + + + + + + + + +