summaryrefslogtreecommitdiff
path: root/lib/tbe-last/vendor/vendor-document-upload-dialog.tsx
blob: c6f6c3d56f0df7205e8fbd9696cda6ef1f4df637 (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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// lib/vendor-rfq-response/vendor-tbe-table/vendor-document-upload-dialog.tsx

"use client"

import * as React from "react"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { ScrollArea } from "@/components/ui/scroll-area"
import { toast } from "sonner"
import { Upload, FileText, X, Loader2 } from "lucide-react"
import { uploadVendorDocument } from "@/lib/tbe-last/service"

interface VendorDocumentUploadDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  sessionId: number | null
  sessionDetail: any
  onUploadSuccess: () => void
}

interface FileUpload {
  id: string
  file: File
  documentType: string
  description: string
  status: "pending" | "uploading" | "success" | "error"
  errorMessage?: string
}

export function VendorDocumentUploadDialog({
  open,
  onOpenChange,
  sessionId,
  sessionDetail,
  onUploadSuccess
}: VendorDocumentUploadDialogProps) {
  
  const [files, setFiles] = React.useState<FileUpload[]>([])
  const [isUploading, setIsUploading] = React.useState(false)
  const fileInputRef = React.useRef<HTMLInputElement>(null)
  
  // Document types for vendor
  const documentTypes = [
    { value: "technical_spec", label: "Technical Specification" },
    { value: "compliance_cert", label: "Compliance Certificate" },
    { value: "test_report", label: "Test Report" },
    { value: "drawing", label: "Drawing" },
    { value: "datasheet", label: "Datasheet" },
    { value: "quality_doc", label: "Quality Document" },
    { value: "warranty", label: "Warranty Document" },
    { value: "other", label: "Other" },
  ]
  
  // Handle file selection
  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFiles = Array.from(e.target.files || [])
    
    const newFiles: FileUpload[] = selectedFiles.map(file => ({
      id: Math.random().toString(36).substr(2, 9),
      file,
      documentType: "technical_spec",
      description: "",
      status: "pending" as const
    }))
    
    setFiles(prev => [...prev, ...newFiles])
    
    // Reset input
    if (fileInputRef.current) {
      fileInputRef.current.value = ""
    }
  }
  
  // Remove file
  const handleRemoveFile = (id: string) => {
    setFiles(prev => prev.filter(f => f.id !== id))
  }
  
  // Update file details
  const handleUpdateFile = (id: string, field: keyof FileUpload, value: string) => {
    setFiles(prev => prev.map(f => 
      f.id === id ? { ...f, [field]: value } : f
    ))
  }
  
  // Upload all files
  const handleUploadAll = async () => {
    if (!sessionId || files.length === 0) return
    
    setIsUploading(true)
    
    try {
      for (const fileUpload of files) {
        if (fileUpload.status === "success") continue
        
        // Update status to uploading
        setFiles(prev => prev.map(f => 
          f.id === fileUpload.id ? { ...f, status: "uploading" } : f
        ))
        
        try {
          // Create FormData for upload
          const formData = new FormData()
          formData.append("file", fileUpload.file)
          formData.append("sessionId", sessionId.toString())
          formData.append("documentType", fileUpload.documentType)
          formData.append("description", fileUpload.description)
          
          // Upload file (API call)
          const response = await fetch("/api/tbe/vendor-documents/upload", {
            method: "POST",
            body: formData
          })
          
          if (!response.ok) throw new Error("Upload failed")
          
          // Update status to success
          setFiles(prev => prev.map(f => 
            f.id === fileUpload.id ? { ...f, status: "success" } : f
          ))
          
        } catch (error) {
          // Update status to error
          setFiles(prev => prev.map(f => 
            f.id === fileUpload.id ? { 
              ...f, 
              status: "error",
              errorMessage: error instanceof Error ? error.message : "Upload failed"
            } : f
          ))
        }
      }
      
      // Check if all files uploaded successfully
      const allSuccess = files.every(f => f.status === "success")
      
      if (allSuccess) {
        toast.success("모든 문서가 업로드되었습니다")
        onUploadSuccess()
        onOpenChange(false)
        setFiles([])
      } else {
        const failedCount = files.filter(f => f.status === "error").length
        toast.error(`${failedCount}개 문서 업로드 실패`)
      }
      
    } catch (error) {
      console.error("Upload error:", error)
      toast.error("문서 업로드 중 오류가 발생했습니다")
    } finally {
      setIsUploading(false)
    }
  }
  
  // Get file size in readable format
  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return bytes + " B"
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB"
    return (bytes / (1024 * 1024)).toFixed(1) + " MB"
  }
  
  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[80vh]">
        <DialogHeader>
          <DialogTitle>Upload Documents for TBE</DialogTitle>
          <DialogDescription>
            {sessionDetail?.session?.sessionCode} - Technical Bid Evaluation 문서 업로드
          </DialogDescription>
        </DialogHeader>
        
        <div className="space-y-4">
          {/* File Upload Area */}
          <div className="border-2 border-dashed rounded-lg p-6 text-center">
            <Upload className="h-12 w-12 mx-auto text-muted-foreground mb-2" />
            <p className="text-sm text-muted-foreground mb-2">
              파일을 드래그하거나 클릭하여 선택하세요
            </p>
            <Input
              ref={fileInputRef}
              type="file"
              multiple
              onChange={handleFileSelect}
              className="hidden"
              accept=".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpg,.jpeg,.png,.zip"
            />
            <Button
              variant="outline"
              onClick={() => fileInputRef.current?.click()}
              disabled={isUploading}
            >
              파일 선택
            </Button>
          </div>
          
          {/* Selected Files List */}
          {files.length > 0 && (
            <ScrollArea className="h-[300px] border rounded-lg p-4">
              <div className="space-y-4">
                {files.map(fileUpload => (
                  <div key={fileUpload.id} className="border rounded-lg p-4 space-y-3">
                    <div className="flex items-start justify-between">
                      <div className="flex items-center gap-2">
                        <FileText className="h-5 w-5 text-muted-foreground" />
                        <div>
                          <p className="font-medium text-sm">{fileUpload.file.name}</p>
                          <p className="text-xs text-muted-foreground">
                            {formatFileSize(fileUpload.file.size)}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        {fileUpload.status === "uploading" && (
                          <Loader2 className="h-4 w-4 animate-spin" />
                        )}
                        {fileUpload.status === "success" && (
                          <Badge variant="default">Uploaded</Badge>
                        )}
                        {fileUpload.status === "error" && (
                          <Badge variant="destructive">Failed</Badge>
                        )}
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => handleRemoveFile(fileUpload.id)}
                          disabled={isUploading}
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      </div>
                    </div>
                    
                    {fileUpload.status !== "success" && (
                      <>
                        <div className="grid grid-cols-2 gap-3">
                          <div>
                            <Label className="text-xs">Document Type</Label>
                            <Select
                              value={fileUpload.documentType}
                              onValueChange={(value) => handleUpdateFile(fileUpload.id, "documentType", value)}
                              disabled={isUploading}
                            >
                              <SelectTrigger className="h-8 text-xs">
                                <SelectValue />
                              </SelectTrigger>
                              <SelectContent>
                                {documentTypes.map(type => (
                                  <SelectItem key={type.value} value={type.value}>
                                    {type.label}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                          </div>
                        </div>
                        
                        <div>
                          <Label className="text-xs">Description (Optional)</Label>
                          <Textarea
                            value={fileUpload.description}
                            onChange={(e) => handleUpdateFile(fileUpload.id, "description", e.target.value)}
                            placeholder="문서에 대한 설명을 입력하세요..."
                            className="min-h-[60px] text-xs"
                            disabled={isUploading}
                          />
                        </div>
                      </>
                    )}
                    
                    {fileUpload.errorMessage && (
                      <p className="text-xs text-red-600">{fileUpload.errorMessage}</p>
                    )}
                  </div>
                ))}
              </div>
            </ScrollArea>
          )}
        </div>
        
        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isUploading}
          >
            취소
          </Button>
          <Button
            onClick={handleUploadAll}
            disabled={files.length === 0 || isUploading}
          >
            {isUploading ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                업로드 중...
              </>
            ) : (
              <>
                <Upload className="h-4 w-4 mr-2" />
                업로드 ({files.filter(f => f.status !== "success").length}개)
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}