summaryrefslogtreecommitdiff
path: root/components/form-data-plant/delete-form-data-dialog.tsx
blob: 6ac8f67c7df1e22ce681011c86d779d577c294f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"use client"

import * as React from "react"
import { Loader, Trash } from "lucide-react"
import { toast } from "sonner"
import { useParams } from "next/navigation"
import { useTranslation } from "@/i18n/client"

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-plant/services"

interface GenericData {
  [key: string]: any
  TAG_NO?: string
}

interface DeleteFormDataDialogProps
  extends React.ComponentPropsWithoutRef<typeof Dialog> {
  formData: GenericData[]
  formCode: string
  contractItemId: number
  projectId?: number
  showTrigger?: boolean
  onSuccess?: () => void
  triggerVariant?: "default" | "destructive" | "outline" | "secondary" | "ghost" | "link"
}

export function DeleteFormDataDialog({
  formData,
  formCode,
  contractItemId,
  projectId,
  showTrigger = true,
  onSuccess,
  triggerVariant = "outline",
  ...props
}: DeleteFormDataDialogProps) {
  const [isDeletePending, startDeleteTransition] = React.useTransition()
  const isDesktop = useMediaQuery("(min-width: 640px)")
  
  const params = useParams();
  const lng = (params?.lng as string) || "ko";
  const { t } = useTranslation(lng, "engineering");

  // TAG_NO가 있는 항목들만 필터링
  const validItems = formData.filter(item => item.TAG_IDX?.trim())
  const tagIdxs = validItems.map(item => item.TAG_IDX).filter(Boolean) as string[]

  function onDelete() {
    startDeleteTransition(async () => {
      if (tagIdxs.length === 0) {
        toast.error(t("delete.noValidItems"))
        return
      }

      const result = await deleteFormDataByTags({
        formCode,
        contractItemId,
        tagIdxs,
        projectId,
      })

      if (result.error) {
        toast.error(result.error)
        return
      }

      props.onOpenChange?.(false)
      
      // 성공 메시지 (개수는 같을 것으로 예상)
      const deletedCount = result.deletedCount || 0
      const deletedTagsCount = result.deletedTagsCount || 0
      
      // SEDP 삭제 결과도 포함
      if (result.sedpDeleteSuccess) {
        console.log("SEDP에서도 성공적으로 삭제되었습니다.")
      } else if (result.sedpDeleteError) {
        console.warn("SEDP 삭제 실패:", result.sedpDeleteError)
        toast.warning(`로컬 삭제는 성공했으나 SEDP 삭제 실패: ${result.sedpDeleteError}`)
      }
      
      if (deletedCount !== deletedTagsCount) {
        // 데이터 불일치 경고
        console.warn(`Data inconsistency: FormEntries deleted: ${deletedCount}, Tags deleted: ${deletedTagsCount}`)
        toast.error(
          t("delete.dataInconsistency", { deletedCount, deletedTagsCount })
        )
      } else {
        // 정상적인 삭제 완료
        const successMessage = result.sedpDeleteSuccess 
          ? t("delete.successMessage", { 
              count: deletedCount,
              items: deletedCount === 1 ? t("delete.item") : t("delete.items")
            }) + " (SEDP 포함)"
          : t("delete.successMessage", { 
              count: deletedCount,
              items: deletedCount === 1 ? t("delete.item") : t("delete.items")
            })
        
        toast.success(successMessage)
      }
      
      onSuccess?.()
    })
  }

  const itemCount = tagIdxs.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" />
              {t("buttons.delete")} ({itemCount})
            </Button>
          </DialogTrigger>
        ) : null}
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("delete.confirmTitle")}</DialogTitle>
            <DialogDescription>
              {t("delete.confirmDescription", { 
                count: itemCount,
                items: itemCount === 1 ? t("delete.item") : t("delete.items")
              })}
              {itemCount > 0 && (
                <>
                  <br />
                  <br />
                  <span className="text-sm text-muted-foreground">
                    {t("delete.tagNumbers")}: {tagIdxs.slice(0, 3).join(", ")}
                    {tagIdxs.length > 3 && t("delete.andMore", { count: tagIdxs.length - 3 })}
                  </span>
                </>
              )}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="gap-2 sm:space-x-0">
            <DialogClose asChild>
              <Button variant="outline">{t("buttons.cancel")}</Button>
            </DialogClose>
            <Button
              aria-label={t("delete.deleteButtonLabel")}
              variant="destructive"
              onClick={onDelete}
              disabled={isDeletePending || !hasValidItems}
            >
              {isDeletePending && (
                <Loader
                  className="mr-2 size-4 animate-spin"
                  aria-hidden="true"
                />
              )}
              {t("buttons.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" />
            {t("buttons.delete")} ({itemCount})
          </Button>
        </DrawerTrigger>
      ) : null}
      <DrawerContent>
        <DrawerHeader>
          <DrawerTitle>{t("delete.confirmTitle")}</DrawerTitle>
          <DrawerDescription>
            {t("delete.confirmDescription", { 
              count: itemCount,
              items: itemCount === 1 ? t("delete.item") : t("delete.items")
            })}
            {itemCount > 0 && (
              <>
                <br />
                <br />
                <span className="text-sm text-muted-foreground">
                  {t("delete.tagNumbers")}: {tagIdxs.slice(0, 3).join(", ")}
                  {tagIdxs.length > 3 && t("delete.andMore", { count: tagIdxs.length - 3 })}
                </span>
              </>
            )}
          </DrawerDescription>
        </DrawerHeader>
        <DrawerFooter className="gap-2 sm:space-x-0">
          <DrawerClose asChild>
            <Button variant="outline">{t("buttons.cancel")}</Button>
          </DrawerClose>
          <Button
            aria-label={t("delete.deleteButtonLabel")}
            variant="destructive"
            onClick={onDelete}
            disabled={isDeletePending || !hasValidItems}
          >
            {isDeletePending && (
              <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" />
            )}
            {t("buttons.delete")}
          </Button>
        </DrawerFooter>
      </DrawerContent>
    </Drawer>
  )
}