summaryrefslogtreecommitdiff
path: root/lib/vendor-document-list/plant/upload/components/single-upload-dialog.tsx
blob: a33a7160f5f8e5d5c33ca93f7952e25bbe5f6c37 (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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// lib/vendor-document-list/plant/upload/components/single-upload-dialog.tsx
"use client"

import * as React from "react"
import { useState } from "react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { Alert, AlertDescription } from "@/components/ui/alert"
import {
  FileList,
  FileListAction,
  FileListIcon,
  FileListInfo,
  FileListItem,
  FileListName,
  FileListSize,
} from "@/components/ui/file-list"
import { 
  Upload, 
  X, 
  FileIcon,
  Loader2,
  AlertCircle
} from "lucide-react"
import { toast } from "sonner"
import { StageSubmissionView } from "@/db/schema"

interface SingleUploadDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  submission: StageSubmissionView
  onUploadComplete?: () => void
}

export function SingleUploadDialog({ 
  open, 
  onOpenChange, 
  submission,
  onUploadComplete 
}: SingleUploadDialogProps) {
  const [files, setFiles] = useState<File[]>([])
  const [description, setDescription] = useState("")
  const [isUploading, setIsUploading] = useState(false)
  const fileInputRef = React.useRef<HTMLInputElement>(null)
  
  // 파일 선택
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const fileList = e.target.files
    if (fileList) {
      setFiles(Array.from(fileList))
    }
  }
  
  // 파일 제거
  const removeFile = (index: number) => {
    setFiles(prev => prev.filter((_, i) => i !== index))
  }
  
  // 업로드 처리
  const handleUpload = async () => {
    if (files.length === 0) {
      toast.error("Please select files to upload")
      return
    }
    
    setIsUploading(true)
    
    try {
      const formData = new FormData()
      
      files.forEach((file) => {
        formData.append("files", file)
      })
      
      formData.append("documentId", submission.documentId.toString())
      formData.append("stageId", submission.stageId!.toString())
      formData.append("description", description)
      
      // 현재 리비전 + 1
      const nextRevision = (submission.latestRevisionNumber || 0) + 1
      formData.append("revision", nextRevision.toString())
      
      const response = await fetch("/api/stage-submissions/upload", {
        method: "POST",
        body: formData,
      })
      
      if (!response.ok) {
        throw new Error("Upload failed")
      }
      
      const result = await response.json()
      toast.success(`Successfully uploaded ${files.length} file(s)`)
      
      // 초기화 및 닫기
      setFiles([])
      setDescription("")
      onOpenChange(false)
      onUploadComplete?.()
      
    } catch (error) {
      console.error("Upload error:", error)
      toast.error("Failed to upload files")
    } finally {
      setIsUploading(false)
    }
  }
  
  const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }
  
  const totalSize = files.reduce((acc, file) => acc + file.size, 0)
  
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>Upload Documents</DialogTitle>
          <DialogDescription>
            Upload documents for this stage submission
          </DialogDescription>
        </DialogHeader>
        
        {/* Document Info */}
        <div className="grid gap-2 p-4 bg-muted rounded-lg">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium">Document:</span>
            <span className="text-sm">{submission.docNumber}</span>
            {submission.vendorDocNumber && (
              <span className="text-sm text-muted-foreground">
                ({submission.vendorDocNumber})
              </span>
            )}
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium">Stage:</span>
            <Badge variant="secondary">{submission.stageName}</Badge>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium">Current Revision:</span>
            <span className="text-sm">Rev. {submission.latestRevisionNumber || 0}</span>
            <Badge variant="outline" className="ml-2">
              Next: Rev. {(submission.latestRevisionNumber || 0) + 1}
            </Badge>
          </div>
        </div>
        
        {/* File Upload Area */}
        <div 
          className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-gray-400 transition-colors cursor-pointer"
          onClick={() => fileInputRef.current?.click()}
        >
          <input
            ref={fileInputRef}
            type="file"
            multiple
            className="hidden"
            onChange={handleFileChange}
            accept="*/*"
          />
          <Upload className="mx-auto h-10 w-10 text-gray-400 mb-3" />
          <p className="text-sm font-medium">Click to browse files</p>
          <p className="text-xs text-gray-500 mt-1">
            You can select multiple files
          </p>
        </div>
        
        {/* File List */}
        {files.length > 0 && (
          <>
            <FileList>
              {files.map((file, index) => (
                <FileListItem key={index}>
                  <FileListIcon>
                    <FileIcon className="h-4 w-4 text-muted-foreground" />
                  </FileListIcon>
                  <FileListInfo>
                    <FileListName>{file.name}</FileListName>
                  </FileListInfo>
                  <FileListSize>
                    {file.size}
                  </FileListSize>
                  <FileListAction>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-8 w-8"
                      onClick={(e) => {
                        e.stopPropagation()
                        removeFile(index)
                      }}
                      disabled={isUploading}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </FileListAction>
                </FileListItem>
              ))}
            </FileList>
            
            <div className="flex justify-between text-sm text-muted-foreground">
              <span>{files.length} file(s) selected</span>
              <span>Total: {formatFileSize(totalSize)}</span>
            </div>
          </>
        )}
        
        {/* Description */}
        <div className="space-y-2">
          <Label htmlFor="description">Description (Optional)</Label>
          <Textarea
            id="description"
            placeholder="Add a description for this submission..."
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            rows={3}
          />
        </div>
        
        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isUploading}
          >
            Cancel
          </Button>
          <Button
            onClick={handleUpload}
            disabled={files.length === 0 || isUploading}
            className="gap-2"
          >
            {isUploading ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" />
                Uploading...
              </>
            ) : (
              <>
                <Upload className="h-4 w-4" />
                Upload
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}