From bc7d627f61a4d055b19d0679b3a4c128b7afcfda Mon Sep 17 00:00:00 2001
From: dujinkim <dujin.kim@dtsolution.co.kr>
Date: Wed, 28 May 2025 17:29:43 +0000
Subject: (대표님) admin / api / components
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 .../form-data/form-data-report-batch-dialog.tsx    | 283 +++++++++++++--------
 1 file changed, 181 insertions(+), 102 deletions(-)

(limited to 'components/form-data/form-data-report-batch-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 ef921a91..53f8c489 100644
--- a/components/form-data/form-data-report-batch-dialog.tsx
+++ b/components/form-data/form-data-report-batch-dialog.tsx
@@ -51,6 +51,7 @@ import {
 import { Button } from "@/components/ui/button";
 import { getReportTempList, getOrigin } from "@/lib/forms/services";
 import { DataTableColumnJSON } from "./form-data-table-columns";
+import { PublishDialog } from "./publish-dialog";
 
 const MAX_FILE_SIZE = 3000000;
 
@@ -87,6 +88,10 @@ export const FormDataReportBatchDialog: FC<FormDataReportBatchDialogProps> = ({
   const [selectTemp, setSelectTemp] = useState<string>("");
   const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
   const [isUploading, setIsUploading] = useState(false);
+  
+  // Add new state for publish dialog
+  const [publishDialogOpen, setPublishDialogOpen] = useState<boolean>(false);
+  const [generatedFileBlob, setGeneratedFileBlob] = useState<Blob | null>(null);
 
   useEffect(() => {
     updateReportTempList(packageId, formId, setTempList);
@@ -125,48 +130,43 @@ export const FormDataReportBatchDialog: FC<FormDataReportBatchDialogProps> = ({
     setSelectedFiles(updatedFiles);
   };
 
+  // Create and download document
   const submitData = async () => {
     setIsUploading(true);
 
     try {
       const origin = await getOrigin();
-
       const targetFiles = selectedFiles[0];
 
       const reportDatas = reportData.map((c) => {
         const reportValue = stringifyAllValues(c);
-
         const reportValueMapping: { [key: string]: any } = {};
 
         columnsJSON.forEach((c2) => {
           const { key } = c2;
-
-          // const objKey = label.split(" ").join("_");
-
           reportValueMapping[key] = reportValue?.[key] ?? "";
         });
 
         return reportValueMapping;
       });
+      
       const formData = new FormData();
       formData.append("file", targetFiles);
       formData.append("customFileName", `${formCode}.pdf`);
       formData.append("reportDatas", JSON.stringify(reportDatas));
       formData.append("reportTempPath", selectTemp);
 
-      const reqeustCreateReport = await fetch(
+      const requestCreateReport = await fetch(
         `${origin}/api/pdftron/createVendorDataReports`,
         { method: "POST", body: formData }
       );
 
-      if (reqeustCreateReport.ok) {
-        const blob = await reqeustCreateReport.blob();
-
+      if (requestCreateReport.ok) {
+        const blob = await requestCreateReport.blob();
         saveAs(blob, `${formCode}.pdf`);
-
         toastMessage.success("Report 다운로드 완료!");
       } else {
-        const err = await reqeustCreateReport.json();
+        const err = await requestCreateReport.json();
         console.error("에러:", err);
         throw new Error(err.message);
       }
@@ -184,100 +184,179 @@ export const FormDataReportBatchDialog: FC<FormDataReportBatchDialogProps> = ({
     }
   };
 
+  // New function to prepare the file for publishing
+  const prepareFileForPublishing = async () => {
+    setIsUploading(true);
+
+    try {
+      const origin = await getOrigin();
+      const targetFiles = selectedFiles[0];
+
+      const reportDatas = reportData.map((c) => {
+        const reportValue = stringifyAllValues(c);
+        const reportValueMapping: { [key: string]: any } = {};
+
+        columnsJSON.forEach((c2) => {
+          const { key } = c2;
+          reportValueMapping[key] = reportValue?.[key] ?? "";
+        });
+
+        return reportValueMapping;
+      });
+      
+      const formData = new FormData();
+      formData.append("file", targetFiles);
+      formData.append("customFileName", `${formCode}.pdf`);
+      formData.append("reportDatas", JSON.stringify(reportDatas));
+      formData.append("reportTempPath", selectTemp);
+
+      const requestCreateReport = await fetch(
+        `${origin}/api/pdftron/createVendorDataReports`,
+        { method: "POST", body: formData }
+      );
+
+      if (requestCreateReport.ok) {
+        const blob = await requestCreateReport.blob();
+        setGeneratedFileBlob(blob);
+        setPublishDialogOpen(true);
+        toastMessage.success("문서가 생성되었습니다. 발행 정보를 입력해주세요.");
+      } else {
+        const err = await requestCreateReport.json();
+        console.error("에러:", err);
+        throw new Error(err.message);
+      }
+    } catch (err) {
+      console.error(err);
+      toast({
+        title: "Error",
+        description: "문서 생성 중 오류가 발생했습니다.",
+        variant: "destructive",
+      });
+    } finally {
+      setIsUploading(false);
+    }
+  };
+
   return (
-    <Dialog open={open} onOpenChange={onClose}>
-      <DialogContent className="w-[600px]" style={{ maxWidth: "none" }}>
-        <DialogHeader>
-          <DialogTitle>Vendor Document Create</DialogTitle>
-          <DialogDescription>
-            Vendor Document Template을 선택하신 후 갑지를 업로드하여 주시기
-            바랍니다.
-          </DialogDescription>
-        </DialogHeader>
-        <div className="h-[60px]">
-          <Label>Vendor Document Template Select</Label>
-          <Select value={selectTemp} onValueChange={setSelectTemp}>
-            <SelectTrigger className="w-[100%]">
-              <SelectValue placeholder="사용하시고자하는 Report Template를 선택하여 주시기 바랍니다." />
-            </SelectTrigger>
-            <SelectContent>
-              {tempList.map((c) => {
-                const { fileName, filePath } = c;
-
-                return (
-                  <SelectItem key={filePath} value={filePath}>
-                    {fileName}
-                  </SelectItem>
-                );
-              })}
-            </SelectContent>
-          </Select>
-        </div>
-        <div>
-          <Label>Vendor Document Cover Page Upload(.docx)</Label>
-          <Dropzone
-            maxSize={MAX_FILE_SIZE}
-            multiple={false}
-            accept={{ accept: [".docx"] }}
-            onDropAccepted={handleDropAccepted}
-            onDropRejected={handleDropRejected}
-            disabled={isUploading}
-          >
-            {({ maxSize }) => (
-              <>
-                <DropzoneZone className="flex justify-center">
-                  <DropzoneInput />
-                  <div className="flex items-center gap-6">
-                    <DropzoneUploadIcon />
-                    <div className="grid gap-0.5">
-                      <DropzoneTitle>파일을 여기에 드롭하세요</DropzoneTitle>
-                      <DropzoneDescription>
-                        또는 클릭하여 파일을 선택하세요. 최대 크기:{" "}
-                        {maxSize ? prettyBytes(maxSize) : "무제한"}
-                      </DropzoneDescription>
+    <>
+      <Dialog open={open} onOpenChange={onClose}>
+        <DialogContent className="w-[600px]" style={{ maxWidth: "none" }}>
+          <DialogHeader>
+            <DialogTitle>Vendor Document Create</DialogTitle>
+            <DialogDescription>
+              Vendor Document Template을 선택하신 후 갑지를 업로드하여 주시기
+              바랍니다.
+            </DialogDescription>
+          </DialogHeader>
+          <div className="h-[60px]">
+            <Label>Vendor Document Template Select</Label>
+            <Select value={selectTemp} onValueChange={setSelectTemp}>
+              <SelectTrigger className="w-[100%]">
+                <SelectValue placeholder="사용하시고자하는 Report Template를 선택하여 주시기 바랍니다." />
+              </SelectTrigger>
+              <SelectContent>
+                {tempList.map((c) => {
+                  const { fileName, filePath } = c;
+
+                  return (
+                    <SelectItem key={filePath} value={filePath}>
+                      {fileName}
+                    </SelectItem>
+                  );
+                })}
+              </SelectContent>
+            </Select>
+          </div>
+          <div>
+            <Label>Vendor Document Cover Page Upload(.docx)</Label>
+            <Dropzone
+              maxSize={MAX_FILE_SIZE}
+              multiple={false}
+              accept={{ accept: [".docx"] }}
+              onDropAccepted={handleDropAccepted}
+              onDropRejected={handleDropRejected}
+              disabled={isUploading}
+            >
+              {({ maxSize }) => (
+                <>
+                  <DropzoneZone className="flex justify-center">
+                    <DropzoneInput />
+                    <div className="flex items-center gap-6">
+                      <DropzoneUploadIcon />
+                      <div className="grid gap-0.5">
+                        <DropzoneTitle>파일을 여기에 드롭하세요</DropzoneTitle>
+                        <DropzoneDescription>
+                          또는 클릭하여 파일을 선택하세요. 최대 크기:{" "}
+                          {maxSize ? prettyBytes(maxSize) : "무제한"}
+                        </DropzoneDescription>
+                      </div>
                     </div>
-                  </div>
-                </DropzoneZone>
-                <Label className="text-xs text-muted-foreground">
-                  여러 파일을 선택할 수 있습니다.
-                </Label>
-              </>
-            )}
-          </Dropzone>
-        </div>
-
-        {selectedFiles.length > 0 && (
-          <div className="grid gap-2">
-            <div className="flex items-center justify-between">
-              <h6 className="text-sm font-semibold">
-                선택된 파일 ({selectedFiles.length})
-              </h6>
-              <Badge variant="secondary">{selectedFiles.length}개 파일</Badge>
-            </div>
-            <ScrollArea>
-              <UploadFileItem
-                selectedFiles={selectedFiles}
-                removeFile={removeFile}
-                isUploading={isUploading}
-              />
-            </ScrollArea>
+                  </DropzoneZone>
+                  <Label className="text-xs text-muted-foreground">
+                    여러 파일을 선택할 수 있습니다.
+                  </Label>
+                </>
+              )}
+            </Dropzone>
           </div>
-        )}
-
-        <DialogFooter>
-          <Button
-            disabled={
-              selectedFiles.length === 0 ||
-              selectTemp.length === 0 ||
-              isUploading
-            }
-            onClick={submitData}
-          >
-            {isUploading && <Loader2 />}Vendor Document Create
-          </Button>
-        </DialogFooter>
-      </DialogContent>
-    </Dialog>
+
+          {selectedFiles.length > 0 && (
+            <div className="grid gap-2">
+              <div className="flex items-center justify-between">
+                <h6 className="text-sm font-semibold">
+                  선택된 파일 ({selectedFiles.length})
+                </h6>
+                <Badge variant="secondary">{selectedFiles.length}개 파일</Badge>
+              </div>
+              <ScrollArea>
+                <UploadFileItem
+                  selectedFiles={selectedFiles}
+                  removeFile={removeFile}
+                  isUploading={isUploading}
+                />
+              </ScrollArea>
+            </div>
+          )}
+
+          <DialogFooter>
+            {/* Add the new Publish button */}
+            <Button
+              onClick={prepareFileForPublishing}
+              disabled={
+                selectedFiles.length === 0 ||
+                selectTemp.length === 0 ||
+                isUploading
+              }
+              variant="outline"
+              className="mr-2"
+            >
+              {isUploading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+              Publish
+            </Button>
+            <Button
+              disabled={
+                selectedFiles.length === 0 ||
+                selectTemp.length === 0 ||
+                isUploading
+              }
+              onClick={submitData}
+            >
+              {isUploading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
+              Create Vendor Document
+            </Button>
+          </DialogFooter>
+        </DialogContent>
+      </Dialog>
+
+      {/* Add the PublishDialog component */}
+      <PublishDialog
+        open={publishDialogOpen}
+        onOpenChange={setPublishDialogOpen}
+        packageId={packageId}
+        formCode={formCode}
+        fileBlob={generatedFileBlob || undefined}
+      />
+    </>
   );
 };
 
-- 
cgit v1.2.3

