summaryrefslogtreecommitdiff
path: root/components/investigation/supplement-response-dialog.tsx
blob: 8490c15c399ca4f3c4e65315239b11461e5d269d (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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
"use client"

import * as React from "react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Badge } from "@/components/ui/badge"
import { useToast } from "@/hooks/use-toast"
import { 
  Dropzone,
  DropzoneDescription,
  DropzoneInput,
  DropzoneTitle,
  DropzoneUploadIcon,
  DropzoneZone,
} from "@/components/ui/dropzone"
import {
  FileList,
  FileListAction,
  FileListDescription,
  FileListHeader,
  FileListIcon,
  FileListInfo,
  FileListItem,
  FileListName,
} from "@/components/ui/file-list"
import { X, Download } from "lucide-react"
import prettyBytes from "pretty-bytes"
import { 
  submitSupplementDocumentResponseAction
} from "@/lib/vendor-investigation/service"
import { uploadVendorFileAction } from "@/lib/pq/service"

interface SupplementResponseDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  investigationId: number
  supplementType: "REINSPECT" | "DOCUMENT"
  vendorName: string
  requiredDocuments?: string[]
  additionalRequests?: string
}

interface LocalFileState {
  fileObj: File
  uploaded: boolean
}

export function SupplementResponseDialog({
  open,
  onOpenChange,
  investigationId,
  supplementType,
  vendorName,
  requiredDocuments = [],
  additionalRequests = ""
}: SupplementResponseDialogProps) {
  const { toast } = useToast()
  const [isSubmitting, setIsSubmitting] = React.useState(false)
  const [isUploading, setIsUploading] = React.useState(false)
  
  // 서류제출 응답 데이터
  const [responseData, setResponseData] = React.useState({
    responseText: "",
    uploadedFiles: [] as Array<{
      fileName: string
      url: string
      size?: number
    }>,
    newUploads: [] as LocalFileState[]
  })

  // 재실사 응답 데이터
  const [reinspectData, setReinspectData] = React.useState({
    inspectionDate: "",
    inspectionDuration: 1.0,
    inspectionResults: "",
    additionalNotes: ""
  })

  const handleFileDrop = (files: File[]) => {
    const newFiles: LocalFileState[] = files.map(file => ({
      fileObj: file,
      uploaded: false
    }))
    
    setResponseData(prev => ({
      ...prev,
      newUploads: [...prev.newUploads, ...newFiles]
    }))
  }

  const removeNewUpload = (index: number) => {
    setResponseData(prev => ({
      ...prev,
      newUploads: prev.newUploads.filter((_, i) => i !== index)
    }))
  }

  const removeUploadedFile = (index: number) => {
    setResponseData(prev => ({
      ...prev,
      uploadedFiles: prev.uploadedFiles.filter((_, i) => i !== index)
    }))
  }

  const uploadFiles = async () => {
    if (responseData.newUploads.length === 0) return

    setIsUploading(true)
    try {
      for (const localFile of responseData.newUploads) {
        const uploadResult = await uploadVendorFileAction(localFile.fileObj)
        setResponseData(prev => ({
          ...prev,
          uploadedFiles: [...prev.uploadedFiles, {
            fileName: uploadResult.fileName,
            url: uploadResult.url,
            size: uploadResult.size
          }]
        }))
      }
      
      setResponseData(prev => ({
        ...prev,
        newUploads: []
      }))
      
      toast({
        title: "파일 업로드 완료",
        description: "파일이 성공적으로 업로드되었습니다.",
      })
    } catch (error) {
      console.error("파일 업로드 오류:", error)
      toast({
        title: "업로드 실패",
        description: "파일 업로드 중 오류가 발생했습니다.",
        variant: "destructive"
      })
    } finally {
      setIsUploading(false)
    }
  }

  const handleSubmit = async () => {
    if (supplementType === "DOCUMENT") {
      // 서류제출 응답 검증
      if (!responseData.responseText.trim()) {
        toast({
          title: "응답 필요",
          description: "응답 내용을 입력해주세요.",
          variant: "destructive"
        })
        return
      }

      if (responseData.uploadedFiles.length === 0 && responseData.newUploads.length > 0) {
        toast({
          title: "파일 업로드 필요",
          description: "새로 추가한 파일을 먼저 업로드해주세요.",
          variant: "destructive"
        })
        return
      }
    } else {
      // 재실사 응답 검증
      if (!reinspectData.inspectionDate || !reinspectData.inspectionResults.trim()) {
        toast({
          title: "필수 정보 필요",
          description: "실사 일정과 결과를 입력해주세요.",
          variant: "destructive"
        })
        return
      }
    }

    try {
      setIsSubmitting(true)

      if (supplementType === "DOCUMENT") {
        const result = await submitSupplementDocumentResponseAction({
          investigationId,
          responseData: {
            responseText: responseData.responseText,
            attachments: responseData.uploadedFiles.map(file => ({
              fileName: file.fileName,
              url: file.url,
              size: file.size
            }))
          }
        })

        if (result.success) {
          toast({
            title: "서류제출 응답 완료",
            description: "서류제출 응답이 성공적으로 제출되었습니다.",
          })
          onOpenChange(false)
        } else {
          toast({
            title: "제출 실패",
            description: result.error || "서류제출 응답 중 오류가 발생했습니다.",
            variant: "destructive"
          })
        }
      } else {
        // 재실사 응답은 별도 액션 필요 (구현 예정)
        toast({
          title: "재실사 응답",
          description: "재실사 응답 기능은 구현 예정입니다.",
        })
      }
    } catch (error) {
      console.error("보완 응답 오류:", error)
      toast({
        title: "제출 실패",
        description: "보완 응답 중 오류가 발생했습니다.",
        variant: "destructive"
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-3xl">
        <DialogHeader>
          <DialogTitle>
            {supplementType === "REINSPECT" ? "보완-재실사 응답" : "보완-서류제출 응답"}
          </DialogTitle>
          <DialogDescription>
            {vendorName}에 대한 보완 요청에 응답합니다.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-6">
          {/* 서류제출 응답 폼 */}
          {supplementType === "DOCUMENT" && (
            <>
              {/* 요청된 서류 목록 */}
              {requiredDocuments.length > 0 && (
                <div className="space-y-2">
                  <Label>요청된 서류 목록</Label>
                  <div className="space-y-1">
                    {requiredDocuments.map((doc, index) => (
                      <div key={index} className="flex items-center gap-2">
                        <Badge variant="outline">{index + 1}</Badge>
                        <span className="text-sm">{doc}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* 추가 요청사항 */}
              {additionalRequests && (
                <div className="space-y-2">
                  <Label>추가 요청사항</Label>
                  <div className="p-3 bg-muted rounded-md text-sm">
                    {additionalRequests}
                  </div>
                </div>
              )}

              {/* 응답 내용 */}
              <div className="space-y-2">
                <Label htmlFor="responseText">응답 내용 *</Label>
                <Textarea
                  id="responseText"
                  placeholder="요청된 서류에 대한 응답 내용을 입력하세요"
                  value={responseData.responseText}
                  onChange={(e) => setResponseData(prev => ({
                    ...prev,
                    responseText: e.target.value
                  }))}
                  className="min-h-32"
                />
              </div>

              {/* 파일 업로드 */}
              <div className="space-y-4">
                <Label>첨부 파일</Label>
                
                <Dropzone
                  maxSize={6e8} // 600MB
                  onDropAccepted={handleFileDrop}
                  disabled={isUploading}
                >
                  {() => (
                    <DropzoneZone className="flex justify-center h-32">
                      <DropzoneInput />
                      <div className="flex items-center gap-6">
                        <DropzoneUploadIcon />
                        <div className="grid gap-0.5">
                          <DropzoneTitle>파일을 드래그하거나 클릭하여 업로드</DropzoneTitle>
                          <DropzoneDescription>
                            PDF, Word, Excel, 이미지 파일 (최대 600MB)
                          </DropzoneDescription>
                        </div>
                      </div>
                    </DropzoneZone>
                  )}
                </Dropzone>

                {/* 업로드된 파일 목록 */}
                {(responseData.uploadedFiles.length > 0 || responseData.newUploads.length > 0) && (
                  <div className="space-y-2">
                    <Label>업로드된 파일</Label>
                    <FileList>
                      {responseData.uploadedFiles.map((file, index) => (
                        <FileListItem key={`uploaded-${index}`}>
                          <FileListHeader>
                            <FileListIcon />
                            <FileListInfo>
                              <FileListName>{file.fileName}</FileListName>
                              {file.size && (
                                <FileListDescription>
                                  {prettyBytes(file.size)}
                                </FileListDescription>
                              )}
                            </FileListInfo>
                            <div className="flex gap-1">
                              <FileListAction
                                onClick={async () => {
                                  try {
                                    const { downloadFile } = await import('@/lib/file-download')
                                    await downloadFile(file.url, file.fileName, {
                                      showToast: true,
                                      onError: (error) => {
                                        console.error('다운로드 오류:', error)
                                        toast({
                                          title: "다운로드 실패",
                                          description: error,
                                          variant: "destructive"
                                        })
                                      }
                                    })
                                  } catch (error) {
                                    console.error('다운로드 오류:', error)
                                    toast({
                                      title: "다운로드 실패",
                                      description: "파일 다운로드 중 오류가 발생했습니다.",
                                      variant: "destructive"
                                    })
                                  }
                                }}
                              >
                                <Download className="h-4 w-4" />
                              </FileListAction>
                              <FileListAction
                                onClick={() => removeUploadedFile(index)}
                              >
                                <X className="h-4 w-4" />
                              </FileListAction>
                            </div>
                          </FileListHeader>
                        </FileListItem>
                      ))}

                      {responseData.newUploads.map((file, index) => (
                        <FileListItem key={`new-${index}`}>
                          <FileListHeader>
                            <FileListIcon />
                            <FileListInfo>
                              <FileListName>{file.fileObj.name}</FileListName>
                              <FileListDescription>
                                {prettyBytes(file.fileObj.size)}
                              </FileListDescription>
                            </FileListInfo>
                            <div className="flex gap-1">
                              <FileListAction
                                onClick={() => removeNewUpload(index)}
                              >
                                <X className="h-4 w-4" />
                              </FileListAction>
                            </div>
                          </FileListHeader>
                        </FileListItem>
                      ))}
                    </FileList>

                    {responseData.newUploads.length > 0 && (
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={uploadFiles}
                        disabled={isUploading}
                      >
                        {isUploading ? "업로드 중..." : "파일 업로드"}
                      </Button>
                    )}
                  </div>
                )}
              </div>
            </>
          )}

          {/* 재실사 응답 폼 */}
          {supplementType === "REINSPECT" && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label htmlFor="inspectionDate">실사 일정 *</Label>
                  <Input
                    id="inspectionDate"
                    type="date"
                    value={reinspectData.inspectionDate}
                    onChange={(e) => setReinspectData(prev => ({
                      ...prev,
                      inspectionDate: e.target.value
                    }))}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="duration">실사 기간 (일)</Label>
                  <Input
                    id="duration"
                    type="number"
                    step="0.1"
                    min="0.1"
                    value={reinspectData.inspectionDuration}
                    onChange={(e) => setReinspectData(prev => ({
                      ...prev,
                      inspectionDuration: parseFloat(e.target.value) || 0
                    }))}
                  />
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="inspectionResults">실사 결과 *</Label>
                <Textarea
                  id="inspectionResults"
                  placeholder="실사 결과를 상세히 입력하세요"
                  value={reinspectData.inspectionResults}
                  onChange={(e) => setReinspectData(prev => ({
                    ...prev,
                    inspectionResults: e.target.value
                  }))}
                  className="min-h-32"
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="additionalNotes">추가 메모</Label>
                <Textarea
                  id="additionalNotes"
                  placeholder="추가 메모나 특이사항을 입력하세요"
                  value={reinspectData.additionalNotes}
                  onChange={(e) => setReinspectData(prev => ({
                    ...prev,
                    additionalNotes: e.target.value
                  }))}
                  className="min-h-20"
                />
              </div>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button onClick={handleSubmit} disabled={isSubmitting || isUploading}>
            {isSubmitting ? "제출 중..." : "응답 제출"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}