From bac0228d21b7195065e9cddcc327ae33659c7bcc Mon Sep 17 00:00:00 2001
From: dujinkim <dujin.kim@dtsolution.co.kr>
Date: Sun, 1 Jun 2025 13:52:21 +0000
Subject: (대표님) 20250601까지 작업사항
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 components/form-data/delete-form-data-dialog.tsx | 217 +++++++++++++++++++++++
 1 file changed, 217 insertions(+)
 create mode 100644 components/form-data/delete-form-data-dialog.tsx

(limited to 'components/form-data/delete-form-data-dialog.tsx')

diff --git a/components/form-data/delete-form-data-dialog.tsx b/components/form-data/delete-form-data-dialog.tsx
new file mode 100644
index 00000000..ca2f8729
--- /dev/null
+++ b/components/form-data/delete-form-data-dialog.tsx
@@ -0,0 +1,217 @@
+"use client"
+
+import * as React from "react"
+import { Loader, Trash } from "lucide-react"
+import { toast } from "sonner"
+
+import { useMediaQuery } from "@/hooks/use-media-query"
+import { Button } from "@/components/ui/button"
+import {
+  Dialog,
+  DialogClose,
+  DialogContent,
+  DialogDescription,
+  DialogFooter,
+  DialogHeader,
+  DialogTitle,
+  DialogTrigger,
+} from "@/components/ui/dialog"
+import {
+  Drawer,
+  DrawerClose,
+  DrawerContent,
+  DrawerDescription,
+  DrawerFooter,
+  DrawerHeader,
+  DrawerTitle,
+  DrawerTrigger,
+} from "@/components/ui/drawer"
+
+import { deleteFormDataByTags } from "@/lib/forms/services"
+
+interface GenericData {
+  [key: string]: any
+  TAG_NO?: string
+}
+
+interface DeleteFormDataDialogProps
+  extends React.ComponentPropsWithoutRef<typeof Dialog> {
+  formData: GenericData[]
+  formCode: string
+  contractItemId: number
+  showTrigger?: boolean
+  onSuccess?: () => void
+  triggerVariant?: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link"
+}
+
+export function DeleteFormDataDialog({
+  formData,
+  formCode,
+  contractItemId,
+  showTrigger = true,
+  onSuccess,
+  triggerVariant = "outline",
+  ...props
+}: DeleteFormDataDialogProps) {
+  const [isDeletePending, startDeleteTransition] = React.useTransition()
+  const isDesktop = useMediaQuery("(min-width: 640px)")
+
+  // TAG_NO가 있는 항목들만 필터링
+  const validItems = formData.filter(item => item.TAG_NO?.trim())
+  const tagNos = validItems.map(item => item.TAG_NO).filter(Boolean) as string[]
+
+  function onDelete() {
+    startDeleteTransition(async () => {
+      if (tagNos.length === 0) {
+        toast.error("No valid items to delete")
+        return
+      }
+
+      const result = await deleteFormDataByTags({
+        formCode,
+        contractItemId,
+        tagNos,
+      })
+
+      if (result.error) {
+        toast.error(result.error)
+        return
+      }
+
+      props.onOpenChange?.(false)
+      
+      // 성공 메시지 (개수는 같을 것으로 예상)
+      const deletedCount = result.deletedCount || 0
+      const deletedTagsCount = result.deletedTagsCount || 0
+      
+      if (deletedCount !== deletedTagsCount) {
+        // 데이터 불일치 경고
+        console.warn(`Data inconsistency: FormEntries deleted: ${deletedCount}, Tags deleted: ${deletedTagsCount}`)
+        toast.error(
+          `Deleted ${deletedCount} form entries and ${deletedTagsCount} tags (data inconsistency detected)`
+        )
+      } else {
+        // 정상적인 삭제 완료
+        toast.success(
+          `Successfully deleted ${deletedCount} item${deletedCount === 1 ? "" : "s"}`
+        )
+      }
+      
+      onSuccess?.()
+    })
+  }
+
+  const itemCount = tagNos.length
+  const hasValidItems = itemCount > 0
+
+  if (isDesktop) {
+    return (
+      <Dialog {...props}>
+        {showTrigger ? (
+          <DialogTrigger asChild>
+            <Button 
+              variant={triggerVariant} 
+              size="sm"
+              disabled={!hasValidItems}
+            >
+              <Trash className="mr-2 size-4" aria-hidden="true" />
+              Delete ({itemCount})
+            </Button>
+          </DialogTrigger>
+        ) : null}
+        <DialogContent>
+          <DialogHeader>
+            <DialogTitle>Are you absolutely sure?</DialogTitle>
+            <DialogDescription>
+              This action cannot be undone. This will permanently delete{" "}
+              <span className="font-medium">{itemCount}</span>
+              {itemCount === 1 ? " item" : " items"} and related tag records from the database.
+              {itemCount > 0 && (
+                <>
+                  <br />
+                  <br />
+                  <span className="text-sm text-muted-foreground">
+                    TAG_NO(s): {tagNos.slice(0, 3).join(", ")}
+                    {tagNos.length > 3 && ` and ${tagNos.length - 3} more...`}
+                  </span>
+                </>
+              )}
+            </DialogDescription>
+          </DialogHeader>
+          <DialogFooter className="gap-2 sm:space-x-0">
+            <DialogClose asChild>
+              <Button variant="outline">Cancel</Button>
+            </DialogClose>
+            <Button
+              aria-label="Delete selected entries"
+              variant="destructive"
+              onClick={onDelete}
+              disabled={isDeletePending || !hasValidItems}
+            >
+              {isDeletePending && (
+                <Loader
+                  className="mr-2 size-4 animate-spin"
+                  aria-hidden="true"
+                />
+              )}
+              Delete
+            </Button>
+          </DialogFooter>
+        </DialogContent>
+      </Dialog>
+    )
+  }
+
+  return (
+    <Drawer {...props}>
+      {showTrigger ? (
+        <DrawerTrigger asChild>
+          <Button 
+            variant={triggerVariant} 
+            size="sm"
+            disabled={!hasValidItems}
+          >
+            <Trash className="mr-2 size-4" aria-hidden="true" />
+            Delete ({itemCount})
+          </Button>
+        </DrawerTrigger>
+      ) : null}
+      <DrawerContent>
+        <DrawerHeader>
+          <DrawerTitle>Are you absolutely sure?</DrawerTitle>
+          <DrawerDescription>
+            This action cannot be undone. This will permanently delete{" "}
+            <span className="font-medium">{itemCount}</span>
+            {itemCount === 1 ? " item" : " items"} and related tag records from the database.
+            {itemCount > 0 && (
+              <>
+                <br />
+                <br />
+                <span className="text-sm text-muted-foreground">
+                  TAG_NO(s): {tagNos.slice(0, 3).join(", ")}
+                  {tagNos.length > 3 && ` and ${tagNos.length - 3} more...`}
+                </span>
+              </>
+            )}
+          </DrawerDescription>
+        </DrawerHeader>
+        <DrawerFooter className="gap-2 sm:space-x-0">
+          <DrawerClose asChild>
+            <Button variant="outline">Cancel</Button>
+          </DrawerClose>
+          <Button
+            aria-label="Delete selected entries"
+            variant="destructive"
+            onClick={onDelete}
+            disabled={isDeletePending || !hasValidItems}
+          >
+            {isDeletePending && (
+              <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" />
+            )}
+            Delete
+          </Button>
+        </DrawerFooter>
+      </DrawerContent>
+    </Drawer>
+  )
+}
\ No newline at end of file
-- 
cgit v1.2.3

