summaryrefslogtreecommitdiff
path: root/lib/rfq-last/table/rfq-attachments-dialog.tsx
blob: 161e446a672a5a9d0ff62b04570584d0ecc1ff3f (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
"use client"

import * as React from "react"
import { format } from "date-fns"
import { Download, FileText, Eye, ExternalLink, Loader2, RefreshCw } from "lucide-react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Skeleton } from "@/components/ui/skeleton"
import { toast } from "sonner"
import { RfqsLastView } from "@/db/schema"
import { getRfqAttachmentsAction } from "../service"
import { downloadFile, quickPreview, smartFileAction, formatFileSize, getFileInfo } from "@/lib/file-download"
// import { syncRfqPosFiles } from "@/lib/pos" // 주석 처리: ECC 매핑 시 자동 처리로 변경
// import { useSession } from "next-auth/react" // 주석 처리: 동기화 UI 제거로 불필요

// 첨부파일 타입
interface RfqAttachment {
  attachmentId: number
  attachmentType: string
  serialNo: string
  description: string | null
  currentRevision: string
  fileName: string
  originalFileName: string
  filePath: string
  fileSize: number | null
  fileType: string | null
  createdByName: string | null
  createdAt: Date | null
  updatedAt: Date | null
  revisionComment?: string | null
}

interface RfqAttachmentsDialogProps {
  isOpen: boolean
  onClose: () => void
  rfqData: RfqsLastView
}

export function RfqAttachmentsDialog({ isOpen, onClose, rfqData }: RfqAttachmentsDialogProps) {
  const [attachments, setAttachments] = React.useState<RfqAttachment[]>([])
  const [isLoading, setIsLoading] = React.useState(false)
  const [downloadingFiles, setDownloadingFiles] = React.useState<Set<number>>(new Set())
  // const [isSyncing, setIsSyncing] = React.useState(false) // 주석 처리: 동기화 UI 제거
  
  // const { data: session } = useSession() // 주석 처리: 동기화 UI 제거로 불필요

  // 첨부파일 목록 로드
  React.useEffect(() => {
    if (!isOpen || !rfqData.id) return

    const loadAttachments = async () => {
      setIsLoading(true)
      try {
        const result = await getRfqAttachmentsAction(rfqData.id)
        
        if (result.success) {
          setAttachments(result.data)
        } else {
          toast.error(result.error || "첨부파일을 불러오는데 실패했습니다")
          setAttachments([])
        }
      } catch (error) {
        console.error("첨부파일 로드 오류:", error)
        toast.error("첨부파일을 불러오는데 실패했습니다")
        setAttachments([])
      } finally {
        setIsLoading(false)
      }
    }

    loadAttachments()
  }, [isOpen, rfqData.id])

  // 파일 다운로드 핸들러
  const handleDownload = async (attachment: RfqAttachment) => {
    const attachmentId = attachment.attachmentId
    setDownloadingFiles(prev => new Set([...prev, attachmentId]))

    try {
      const result = await downloadFile(
        attachment.filePath,
        attachment.originalFileName,
        {
          action: 'download',
          showToast: true,
          showSuccessToast: true,
          onSuccess: (fileName, fileSize) => {
            console.log(`다운로드 완료: ${fileName} (${formatFileSize(fileSize || 0)})`)
          },
          onError: (error) => {
            console.error(`다운로드 실패: ${error}`)
          }
        }
      )

      if (!result.success) {
        console.error("다운로드 결과:", result)
      }
    } catch (error) {
      console.error("파일 다운로드 오류:", error)
      toast.error("파일 다운로드에 실패했습니다")
    } finally {
      setDownloadingFiles(prev => {
        const newSet = new Set(prev)
        newSet.delete(attachmentId)
        return newSet
      })
    }
  }

  // 파일 미리보기 핸들러
  const handlePreview = async (attachment: RfqAttachment) => {
    const fileInfo = getFileInfo(attachment.originalFileName)
    
    if (!fileInfo.canPreview) {
      toast.info("이 파일 형식은 미리보기를 지원하지 않습니다. 다운로드를 진행합니다.")
      return handleDownload(attachment)
    }

    try {
      const result = await quickPreview(attachment.filePath, attachment.originalFileName)
      
      if (!result.success) {
        console.error("미리보기 결과:", result)
      }
    } catch (error) {
      console.error("파일 미리보기 오류:", error)
      toast.error("파일 미리보기에 실패했습니다")
    }
  }

  // 스마트 파일 액션 (미리보기 가능하면 미리보기, 아니면 다운로드)
  const handleSmartAction = async (attachment: RfqAttachment) => {
    const attachmentId = attachment.attachmentId
    const fileInfo = getFileInfo(attachment.originalFileName)
    
    if (fileInfo.canPreview) {
      return handlePreview(attachment)
    } else {
      return handleDownload(attachment)
    }
  }

  // POS 파일 동기화 핸들러 - 주석 처리: ECC 매핑 시 자동 처리로 변경
  // const handlePosSync = async () => {
  //   if (!session?.user?.id || !rfqData.id) {
  //     toast.error("로그인이 필요하거나 RFQ 정보가 없습니다")
  //     return
  //   }

  //   setIsSyncing(true)
    
  //   try {
  //     const result = await syncRfqPosFiles(rfqData.id, parseInt(session.user.id))
      
  //     if (result.success) {
  //       toast.success(
  //         `POS 파일 동기화 완료: 성공 ${result.successCount}건, 실패 ${result.failedCount}건`
  //       )
        
  //       // 성공한 경우 첨부파일 목록 새로고침
  //       if (result.successCount > 0) {
  //         const refreshResult = await getRfqAttachmentsAction(rfqData.id)
  //         if (refreshResult.success) {
  //           setAttachments(refreshResult.data)
  //         }
  //       }
        
  //       // 상세 결과 표시
  //       if (result.details.length > 0) {
  //         const failedItems = result.details.filter(d => d.status === 'failed')
  //         if (failedItems.length > 0) {
  //           console.warn("POS 동기화 실패 항목:", failedItems)
  //         }
  //       }
  //     } else {
  //       toast.error(`POS 파일 동기화 실패: ${result.errors.join(', ')}`)
  //     }
  //   } catch (error) {
  //     console.error("POS 동기화 오류:", error)
  //     toast.error("POS 파일 동기화 중 오류가 발생했습니다")
  //   } finally {
  //     setIsSyncing(false)
  //   }
  // }

  // 첨부파일 타입별 색상
  const getAttachmentTypeBadgeVariant = (type: string) => {
    switch (type.toLowerCase()) {
      case "견적요청서": return "default"
      case "기술사양서": return "secondary"
      case "도면": return "outline"
      default: return "outline"
    }
  }

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-6xl h-[85vh] flex flex-col">
        <DialogHeader>
          <div className="flex items-center justify-between">
            <div className="flex-1">
              <DialogTitle>견적 첨부파일</DialogTitle>
              <DialogDescription>
                {rfqData.rfqCode} - {rfqData.rfqTitle || rfqData.itemName || "견적"} 
                {attachments.length > 0 && ` (${attachments.length}개 파일)`}
              </DialogDescription>
            </div>
            
            {/* POS 동기화 버튼 - 주석 처리: ECC 매핑 시 자동 처리로 변경 */}
            {/* <Button
              variant="outline"
              size="sm"
              onClick={handlePosSync}
              disabled={isSyncing || isLoading}
              className="flex items-center gap-2"
            >
              {isSyncing ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <RefreshCw className="h-4 w-4" />
              )}
              {isSyncing ? "동기화 중..." : "POS 파일 동기화"}
            </Button> */}
          </div>
        </DialogHeader>

        <ScrollArea className="flex-1">
          {isLoading ? (
            <div className="space-y-3">
              {[...Array(3)].map((_, i) => (
                <div key={i} className="flex items-center space-x-4 p-3 border rounded-lg">
                  <Skeleton className="h-8 w-8" />
                  <div className="space-y-2 flex-1">
                    <Skeleton className="h-4 w-[300px]" />
                    <Skeleton className="h-3 w-[200px]" />
                  </div>
                  <div className="flex gap-2">
                    <Skeleton className="h-8 w-20" />
                    <Skeleton className="h-8 w-20" />
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[120px]">타입</TableHead>
                  <TableHead>파일명</TableHead>
                  {/* <TableHead>설명</TableHead> */}
                  <TableHead className="w-[90px]">리비전</TableHead>
                  <TableHead className="w-[100px]">크기</TableHead>
                  <TableHead className="w-[120px]">생성자</TableHead>
                  <TableHead className="w-[120px]">생성일</TableHead>
                  <TableHead className="w-[140px]">액션</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {attachments.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="text-center text-muted-foreground py-12">
                      <div className="flex flex-col items-center gap-2">
                        <FileText className="h-8 w-8 text-muted-foreground" />
                        <span>첨부된 파일이 없습니다.</span>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : (
                  attachments.map((attachment) => {
                    const fileInfo = getFileInfo(attachment.originalFileName)
                    const isDownloading = downloadingFiles.has(attachment.attachmentId)
                    
                    return (
                      <TableRow key={attachment.attachmentId}>
                        <TableCell>
                          <Badge 
                            variant={getAttachmentTypeBadgeVariant(attachment.attachmentType)}
                            className="text-xs"
                          >
                            {attachment.attachmentType}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-2">
                            <span className="text-lg">{fileInfo.icon}</span>
                            <div className="flex flex-col min-w-0">
                              <span className="text-sm font-medium truncate" title={attachment.originalFileName}>
                                {attachment.originalFileName}
                              </span>
                            </div>
                          </div>
                        </TableCell>
                        {/* <TableCell>
                          <span className="text-sm" title={attachment.description || ""}>
                            {attachment.description || "-"}
                          </span>
                          {attachment.revisionComment && (
                            <div className="text-xs text-muted-foreground mt-1">
                              {attachment.revisionComment}
                            </div>
                          )}
                        </TableCell> */}
                        <TableCell>
                          <Badge variant="secondary" className="font-mono text-xs">
                            {attachment.currentRevision}
                          </Badge>
                        </TableCell>
                        <TableCell className="text-xs text-muted-foreground">
                          {attachment.fileSize ? formatFileSize(attachment.fileSize) : "-"}
                        </TableCell>
                        <TableCell className="text-sm">
                          {attachment.createdByName || "-"}
                        </TableCell>
                        <TableCell className="text-xs text-muted-foreground">
                          {attachment.createdAt ? format(new Date(attachment.createdAt), "MM-dd HH:mm") : "-"}
                        </TableCell>
                        <TableCell>
                          <div className="flex items-center gap-1">
                            {/* 미리보기 버튼 (미리보기 가능한 파일만) */}
                            {fileInfo.canPreview && (
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handlePreview(attachment)}
                                disabled={isDownloading}
                                title="미리보기"
                              >
                                <Eye className="h-4 w-4" />
                              </Button>
                            )}
                            
                            {/* 다운로드 버튼 */}
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleDownload(attachment)}
                              disabled={isDownloading}
                              title="다운로드"
                            >
                              {isDownloading ? (
                                <Loader2 className="h-4 w-4 animate-spin" />
                              ) : (
                                <Download className="h-4 w-4" />
                              )}
                            </Button>
                            
                            {/* 스마트 액션 버튼 (메인 액션) */}
                            {/* <Button
                              variant="outline"
                              size="sm"
                              onClick={() => handleSmartAction(attachment)}
                              disabled={isDownloading}
                              className="ml-1"
                            >
                              {isDownloading ? (
                                <Loader2 className="h-4 w-4 animate-spin mr-1" />
                              ) : fileInfo.canPreview ? (
                                <Eye className="h-4 w-4 mr-1" />
                              ) : (
                                <Download className="h-4 w-4 mr-1" />
                              )}
                              {fileInfo.canPreview ? "보기" : "다운로드"}
                            </Button> */}
                          </div>
                        </TableCell>
                      </TableRow>
                    )
                  })
                )}
              </TableBody>
            </Table>
          )}
        </ScrollArea>

        {/* 하단 정보 */}
        {attachments.length > 0 && !isLoading && (
          <div className="border-t pt-4 text-xs text-muted-foreground">
            <div className="flex justify-between items-center">
              <span>
                총 {attachments.length}개 파일
                {attachments.some(a => a.fileSize) && 
                  ` · 전체 크기: ${formatFileSize(
                    attachments.reduce((sum, a) => sum + (a.fileSize || 0), 0)
                  )}`
                }
              </span>
            </div>
          </div>
        )}
      </DialogContent>
    </Dialog>
  )
}