summaryrefslogtreecommitdiff
path: root/components/documents/StageList.tsx
blob: 64510ddaaa30acb46dba75d4feb6abb221fa556e (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
"use client"

import React, { useEffect, useState, useMemo } from "react"
import { ScrollArea } from "@/components/ui/scroll-area"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { 
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger 
} from "@/components/ui/tooltip"
import { Building2, FileIcon, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button"
import { AddDocumentDialog } from "./add-document-dialog"
import { ViewDocumentDialog } from "./view-document-dialog"
import { getDocumentVersionsByDocId, getStageNamesByDocumentId } from "@/lib/vendor-document/service"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
import { formatDate } from "@/lib/utils"

type StageListProps = {
  document: {
    id: number
    docNumber: string
    title: string
    // ...
  }
}

// 인터페이스
interface Attachment {
  id: number
  fileName: string
  filePath: string
  fileType?: string
}

interface Version {
  id: number
  stage: string
  revision: string
  uploaderType: string
  uploaderName: string | null
  comment: string | null
  status: string | null
  planDate: string | null
  actualDate: string | null
  approvedDate: string | null
  DocumentSubmitDate: Date 
  attachments: Attachment[]
  selected?: boolean
}

export default function StageList({ document }: StageListProps) {
  const [versions, setVersions] = useState<Version[]>([])

  const [stageOptions, setStageOptions] = useState<string[]>([])

  const [isLoading, setIsLoading] = useState<boolean>(false)

  useEffect(() => {
    if (!document?.id) return
    
    // 로딩 상태 시작
    setIsLoading(true)
    
    // 데이터 로딩 프로미스들
    const loadVersions = getDocumentVersionsByDocId(document.id)
      .then((data) => {
        setVersions(data.map(c => {{return {...c, selected: false}}}))
      })
      .catch((error) => {
        console.error("Failed to load document versions:", error)
      })
    
    const loadStageOptions = getStageNamesByDocumentId(document.id)
      .then((stageNames) => {
        setStageOptions(stageNames)
      })
      .catch((error) => {
        console.error("Failed to load stage options:", error)
      })
    
    // 모든 데이터 로딩이 완료되면 로딩 상태 종료
    Promise.all([loadVersions, loadStageOptions])
      .finally(() => {
        setIsLoading(false)
      })
  }, [document])

  // Handle file download with original filename
  const handleDownload = (attachmentPath: string, fileName: string) => {
    if (attachmentPath) {
      // Use window.document to avoid collision with the document prop
      const link = window.document.createElement('a');
      link.href = attachmentPath;
      link.download = fileName || 'download'; // Use the original filename or a default
      window.document.body.appendChild(link);
      link.click();
      window.document.body.removeChild(link);
    }
  }

  // 파일 확장자에 따른 아이콘 색상 반환
  const getFileIconColor = (fileName: string) => {
    const ext = fileName.split('.').pop()?.toLowerCase();
    
    switch(ext) {
      case 'pdf':
        return 'text-red-500';
      case 'doc':
      case 'docx':
        return 'text-blue-500';
      case 'xls':
      case 'xlsx':
        return 'text-green-500';
      case 'dwg':
        return 'text-amber-500';
      default:
        return 'text-gray-500';
    }
  }

  const selectItems = useMemo(() => {    
    return versions.filter(c => c.selected && c.attachments && c.attachments.length > 0)
  }, [versions])

  return (
    <>
      <div className="flex items-center justify-between p-2">
        <h2 className="font-semibold text-base flex items-center gap-2">
          {/* <Building2 className="h-4 w-4 text-blue-600" /> */}
         Document: {document.docNumber} {document.title}
        </h2>

        <div className="flex flex-row gap-2">
        {selectItems.length > 0 && <ViewDocumentDialog versions={selectItems}/>}
        

        <AddDocumentDialog
          stageOptions={stageOptions}
          documentId={document.id}
          documentNo={document.docNumber}
          uploaderType="vendor"
          onSuccess={() => {
            // 새 데이터 생성 후 목록을 다시 불러오려면
            getDocumentVersionsByDocId(document.id).then((data) => {
              setVersions(data.map(c => {{return {...c, selected: false}}}))
            })
          }}
          buttonLabel="업체 문서 추가"
        />
        </div>
      </div>

      <ScrollArea className="h-full p-2">
        {isLoading ? (
          <div className="flex flex-col items-center justify-center py-12">
            <Loader2 className="h-8 w-8 text-blue-500 animate-spin mb-4" />
            <p className="text-sm text-muted-foreground">문서 로딩 중...</p>
          </div>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[40px]"></TableHead>
                <TableHead className="w-[100px]"></TableHead>
                <TableHead className="w-[100px]">Stage</TableHead>
                <TableHead className="w-[100px]">Revision</TableHead>
                <TableHead className="w-[150px]">첨부파일</TableHead>
                <TableHead className="w-[150px]">등록자</TableHead>
                <TableHead className="w-[150px]">Comment</TableHead>
                <TableHead className="w-[150px]">생성일</TableHead>
                <TableHead className="w-[120px]">계획일</TableHead>
                <TableHead className="w-[120px]">실제일</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {versions.length ? (
                versions.map((ver) => (
                  <TableRow key={ver.id}>
                    <TableCell>
                      <Checkbox
                        checked={ver.selected}                                                
                        onCheckedChange={(value) => {                          
                          setVersions(prev => prev.map(c => {
                            if(c.id === ver.id){
                              return {...c, selected: !c.selected}
                            }

                            return {...c}
                          }))
                        }}
                        aria-label="Select row"
                        className="translate-y-0.5"
                      />
                    </TableCell>
                    <TableCell>{ver.uploaderType}</TableCell>
                    <TableCell>{ver.stage}</TableCell>
                    <TableCell>{ver.revision}</TableCell>
                    <TableCell>
                      <div className="flex flex-wrap gap-2">
                        {ver.attachments && ver.attachments.length > 0 ? (
                          ver.attachments.map((file) => (
                            <TooltipProvider key={file.id}>
                              <Tooltip>
                                <TooltipTrigger asChild>
                                  <Button 
                                    variant="ghost" 
                                    size="sm" 
                                    className="h-4 w-4 p-0"
                                    onClick={() => handleDownload(file.filePath, file.fileName)}
                                  >
                                    <FileIcon className={`h-5 w-5 ${getFileIconColor(file.fileName)}`} />
                                  </Button>
                                </TooltipTrigger>
                                <TooltipContent>
                                  <p>{file.fileName || "Download file"}</p>
                                </TooltipContent>
                              </Tooltip>
                            </TooltipProvider>
                          ))
                        ) : (
                          <Badge variant="outline" className="text-xs">
                            파일 없음
                          </Badge>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>{ver.uploaderName}</TableCell>
                    <TableCell>{ver.comment}</TableCell>
                    <TableCell>{formatDate(ver.DocumentSubmitDate) ?? "-"}</TableCell>
                    <TableCell>{ver.planDate ?? "-"}</TableCell>
                    <TableCell>{ver.actualDate ?? "-"}</TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={7} className="text-center">
                    업체 문서가 없습니다.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        )}
      </ScrollArea>
    </>
  )
}