summaryrefslogtreecommitdiff
path: root/lib/vendor-document-list/table/delete-docs-dialog.tsx
blob: 8813c742ac29807e4a71f8cb856f9eabd81e9f8b (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
"use client"

import * as React from "react"
import { type Row } from "@tanstack/react-table"
import { Loader, Trash, AlertCircle } 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 { Alert, AlertDescription } from "@/components/ui/alert"
import { DocumentStagesView } from "@/db/schema/vendorDocu"
import { removeDocuments } from "../service"

interface DeleteDocumentsDialogProps
  extends React.ComponentPropsWithoutRef<typeof Dialog> {
  documents: Row<DocumentStagesView>["original"][]
  showTrigger?: boolean
  onSuccess?: () => void
}

export function DeleteDocumentsDialog({
  documents,
  showTrigger = true,
  onSuccess,
  ...props
}: DeleteDocumentsDialogProps) {
  const [isDeletePending, startDeleteTransition] = React.useTransition()
  const isDesktop = useMediaQuery("(min-width: 640px)")
  
  // "pending" 상태인 문서만 필터링
  const pendingDocuments = documents.filter(doc => doc.status === "pending")
  const nonPendingDocuments = documents.filter(doc => doc.status !== "pending")
  
  const hasMixedStatus = pendingDocuments.length > 0 && nonPendingDocuments.length > 0
  const hasNoPendingDocuments = pendingDocuments.length === 0
  
  function onDelete() {
    // 삭제할 문서가 없으면 경고
    if (pendingDocuments.length === 0) {
      toast.error("No pending documents to delete")
      props.onOpenChange?.(false)
      return
    }
    
    startDeleteTransition(async () => {
      // "pending" 상태인 문서 ID만 전달
      const { success, error } = await removeDocuments({
        ids: pendingDocuments.map((document) => document.documentId)
      })

      if (!success) {
        toast.error(error || "Failed to delete documents")
        return
      }

      props.onOpenChange?.(false)
      
      // 적절한 성공 메시지 표시
      if (hasMixedStatus) {
        toast.success(`${pendingDocuments.length} pending document(s) deleted successfully. ${nonPendingDocuments.length} non-pending document(s) were not affected.`)
      } else {
        toast.success(`${pendingDocuments.length} document(s) deleted successfully`)
      }
      
      onSuccess?.()
    })
  }
  
  // 선택된 문서 상태에 대한 알림 메시지 렌더링
  const renderStatusAlert = () => {
    if (hasNoPendingDocuments) {
      return (
        <Alert variant="destructive" className="mb-4">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>
            None of the selected documents are in "pending" status. Only pending documents can be deleted.
          </AlertDescription>
        </Alert>
      )
    }
    
    if (hasMixedStatus) {
      return (
        <Alert className="mb-4">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>
            Only the {pendingDocuments.length} document(s) with "pending" status will be deleted. 
            {nonPendingDocuments.length} document(s) cannot be deleted because they are not in pending status.
          </AlertDescription>
        </Alert>
      )
    }
    
    return null
  }

  if (isDesktop) {
    return (
      <Dialog {...props}>
        {showTrigger ? (
          <DialogTrigger asChild>
            <Button variant="outline" size="sm">
              <Trash className="mr-2 size-4" aria-hidden="true" />
              Delete ({documents.length})
            </Button>
          </DialogTrigger>
        ) : null}
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Are you absolutely sure?</DialogTitle>
            <DialogDescription>
              This action cannot be undone. Only documents with "pending" status can be deleted.
            </DialogDescription>
          </DialogHeader>
          
          {renderStatusAlert()}
          
          <div>
            {pendingDocuments.length > 0 && (
              <p className="text-sm text-muted-foreground mb-2">
                {pendingDocuments.length} pending document(s) will be deleted:
              </p>
            )}
            {pendingDocuments.length > 0 && (
              <ul className="text-sm list-disc pl-5 mb-4 max-h-40 overflow-y-auto">
                {pendingDocuments.map(doc => (
                  <li key={doc.documentId} className="text-muted-foreground">{doc.docNumber} - {doc.title}</li>
                ))}
              </ul>
            )}
          </div>
          
          <DialogFooter className="gap-2 sm:space-x-0">
            <DialogClose asChild>
              <Button variant="outline">Cancel</Button>
            </DialogClose>
            <Button
              aria-label="Delete selected rows"
              variant="destructive"
              onClick={onDelete}
              disabled={isDeletePending || pendingDocuments.length === 0}
            >
              {isDeletePending && (
                <Loader
                  className="mr-2 size-4 animate-spin"
                  aria-hidden="true"
                />
              )}
              Delete {pendingDocuments.length > 0 ? `(${pendingDocuments.length})` : ""}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    )
  }

  return (
    <Drawer {...props}>
      {showTrigger ? (
        <DrawerTrigger asChild>
          <Button variant="outline" size="sm">
            <Trash className="mr-2 size-4" aria-hidden="true" />
            Delete ({documents.length})
          </Button>
        </DrawerTrigger>
      ) : null}
      <DrawerContent>
        <DrawerHeader>
          <DrawerTitle>Are you absolutely sure?</DrawerTitle>
          <DrawerDescription>
            This action cannot be undone. Only documents with "pending" status can be deleted.
          </DrawerDescription>
        </DrawerHeader>
        
        {renderStatusAlert()}
        
        <div className="px-4">
          {pendingDocuments.length > 0 && (
            <p className="text-sm text-muted-foreground mb-2">
              {pendingDocuments.length} pending document(s) will be deleted:
            </p>
          )}
          {pendingDocuments.length > 0 && (
            <ul className="text-sm list-disc pl-5 mb-4 max-h-40 overflow-y-auto">
              {pendingDocuments.map(doc => (
                <li key={doc.documentId} className="text-muted-foreground">{doc.docNumber} - {doc.title}</li>
              ))}
            </ul>
          )}
        </div>
        
        <DrawerFooter className="gap-2 sm:space-x-0">
          <DrawerClose asChild>
            <Button variant="outline">Cancel</Button>
          </DrawerClose>
          <Button
            aria-label="Delete selected rows"
            variant="destructive"
            onClick={onDelete}
            disabled={isDeletePending || pendingDocuments.length === 0}
          >
            {isDeletePending && (
              <Loader className="mr-2 size-4 animate-spin" aria-hidden="true" />
            )}
            Delete {pendingDocuments.length > 0 ? `(${pendingDocuments.length})` : ""}
          </Button>
        </DrawerFooter>
      </DrawerContent>
    </Drawer>
  )
}