summaryrefslogtreecommitdiff
path: root/lib/swp/table/swp-document-detail-dialog.tsx
blob: 77ef77f783cb5b8831677a2e63dd2b195be8f125 (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
"use client";

import React, { useState, useEffect, useMemo } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { 
  Loader2, 
  Download, 
  FileIcon,
  AlertCircle,
} from "lucide-react";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { 
  fetchGetRevTreeCompleteList,
  parseRevisionTree,
  fetchGetActivityFileList,
  type ActivityFileApiResponse,
} from "@/lib/swp/api-client";
import { downloadVendorFile } from "@/lib/swp/vendor-actions";
import type { DocumentListItem } from "@/lib/swp/document-service";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { formatSwpDateShort, formatFileSize } from "@/lib/swp/utils";

interface SwpDocumentDetailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  document: DocumentListItem | null;
  projNo: string;
  vendorCode: string;
  userId: string;
}

// Activity 행 데이터
interface ActivityRow {
  revNo: string;
  revSeq: string;
  stage: string;
  actvNo: string;
  inOut: "IN" | "OUT";
  statusCode: string;
  statusName: string;
  transmittalNo: string;
  refActivityNo: string;
  createDate: string;
  createEmpNo: string;
}

export function SwpDocumentDetailDialog({
  open,
  onOpenChange,
  document,
  projNo,
}: SwpDocumentDetailDialogProps) {
  const [activities, setActivities] = useState<ActivityRow[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedActivity, setSelectedActivity] = useState<ActivityRow | null>(null);
  const [activityFiles, setActivityFiles] = useState<ActivityFileApiResponse[]>([]);
  const [isLoadingFiles, setIsLoadingFiles] = useState(false);

  // 문서 상세 로드
  useEffect(() => {
    if (open && document) {
      loadDocumentDetail();
    } else {
      // 다이얼로그 닫힐 때 초기화
      setSelectedActivity(null);
      setActivityFiles([]);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, document?.DOC_NO]);

  const loadDocumentDetail = async () => {
    if (!document) return;

    setIsLoading(true);
    setSelectedActivity(null);
    setActivityFiles([]);
    
    try {
      // GetRevTreeCompleteList 호출
      const tree = await fetchGetRevTreeCompleteList({
        proj_no: projNo,
        doc_no: document.DOC_NO,
      });

      const parsed = await parseRevisionTree(tree);

      // Activity를 flat한 배열로 변환 (테이블용)
      const flatActivities: ActivityRow[] = [];
      parsed.revisions.forEach((rev) => {
        rev.activities.forEach((act) => {
          flatActivities.push({
            revNo: rev.revNo,
            revSeq: rev.revSeq,
            stage: rev.stage,
            actvNo: act.actvNo,
            inOut: act.inOut,
            statusCode: act.statusCode,
            statusName: act.statusName,
            transmittalNo: act.transmittalNo,
            refActivityNo: act.refActivityNo,
            createDate: act.createDate,
            createEmpNo: act.createEmpNo,
          });
        });
      });

      setActivities(flatActivities);
    } catch (error) {
      console.error("문서 상세 조회 실패:", error);
      toast.error("문서 리비전 트리를 불러오는데 실패했습니다");
    } finally {
      setIsLoading(false);
    }
  };

  // Activity 선택 및 파일 로드
  const handleActivityClick = async (activity: ActivityRow) => {
    if (selectedActivity?.actvNo === activity.actvNo) {
      // 같은 Activity 클릭 시 토글
      setSelectedActivity(null);
      setActivityFiles([]);
      return;
    }

    setSelectedActivity(activity);
    setIsLoadingFiles(true);
    setActivityFiles([]);

    try {
      // GetActivityFileList 호출
      const files = await fetchGetActivityFileList({
        proj_no: projNo,
        doc_no: document?.DOC_NO || "",
        rev_seq: activity.revSeq,
      });

      // 해당 Activity의 파일만 필터링
      const activitySpecificFiles = files.filter(
        (f) => f.ACTV_NO === activity.actvNo
      );

      setActivityFiles(activitySpecificFiles);
    } catch (error) {
      console.error("파일 목록 조회 실패:", error);
      toast.error("파일 목록을 불러오는데 실패했습니다");
    } finally {
      setIsLoadingFiles(false);
    }
  };

  const handleDownloadFile = async (fileName: string, ownDocNo: string) => {
    try {
      toast.info("파일 다운로드 중...");
      const result = await downloadVendorFile(projNo, ownDocNo, fileName);
      
      if (!result.success || !result.data) {
        toast.error(result.error || "파일 다운로드 실패");
        return;
      }

      // Blob 생성 및 다운로드
      const blob = new Blob([Buffer.from(result.data)], { type: result.mimeType });
      const url = URL.createObjectURL(blob);
      const link = window.document.createElement("a");
      link.href = url;
      link.download = result.fileName || fileName;
      window.document.body.appendChild(link);
      link.click();
      window.document.body.removeChild(link);
      URL.revokeObjectURL(url);

      toast.success(`파일 다운로드 완료: ${fileName}`);
    } catch (error) {
      console.error("파일 다운로드 실패:", error);
      toast.error("파일 다운로드에 실패했습니다");
    }
  };

  // Revision별로 Activity 그룹핑 및 정렬 (rowspan용)
  const groupedActivities = useMemo(() => {
    // 1. REV 내림차순, createDate 내림차순으로 정렬
    const sortedActivities = [...activities].sort((a, b) => {
      // REV 비교 (내림차순)
      const revCompare = b.revNo.localeCompare(a.revNo);
      if (revCompare !== 0) return revCompare;
      
      // 같은 REV 내에서는 createDate 내림차순
      return b.createDate.localeCompare(a.createDate);
    });

    // 2. 그룹핑
    const groups: Map<string, ActivityRow[]> = new Map();
    sortedActivities.forEach((activity) => {
      const key = `${activity.revNo}|${activity.stage}`;
      if (!groups.has(key)) {
        groups.set(key, []);
      }
      groups.get(key)!.push(activity);
    });
    
    return groups;
  }, [activities]);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[95vw] h-[90vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle className="text-base">문서 리비전 히스토리</DialogTitle>
          {document && (
            <DialogDescription className="text-xs">
              {document.DOC_NO} - {document.DOC_TITLE}
            </DialogDescription>
          )}
        </DialogHeader>

        {document && (
          <div className="flex-1 flex flex-col space-y-2 overflow-hidden">
            {/* 문서 정보 */}
            <div className="flex items-center gap-4 px-3 py-2 bg-muted/30 rounded text-xs">
              <div className="flex items-center gap-1">
                <span className="font-semibold">프로젝트:</span>
                <span>{document.PROJ_NO}</span>
                {document.PROJ_NM && (
                  <span className="text-muted-foreground">({document.PROJ_NM})</span>
                )}
              </div>
              <div className="flex items-center gap-1">
                <span className="font-semibold">패키지:</span>
                <span>{document.PKG_NO || "-"}</span>
              </div>
              <div className="flex items-center gap-1">
                <span className="font-semibold">업체:</span>
                <span>{document.CPY_NM || "-"}</span>
                {document.VNDR_CD && (
                  <span className="text-muted-foreground">({document.VNDR_CD})</span>
                )}
              </div>
              <div className="flex items-center gap-1">
                <span className="font-semibold">최신 리비전:</span>
                <span>{document.LTST_REV_NO || "-"}</span>
              </div>
              <div className="flex items-center gap-1">
                <span className="font-semibold">총 Activity:</span>
                <span>{activities.length}개</span>
              </div>
            </div>

            {/* Activity 테이블 */}
            {isLoading ? (
              <div className="flex items-center justify-center p-8">
                <Loader2 className="h-5 w-5 animate-spin" />
                <span className="ml-2 text-sm">리비전 트리 로딩 중...</span>
              </div>
            ) : activities.length > 0 ? (
              <>
                {/* Activity 테이블 (위) */}
                <div className="h-[40vh] overflow-auto border rounded-lg">
                  <Table>
                    <TableHeader className="sticky top-0 bg-background z-10">
                      <TableRow className="text-xs">
                        <TableHead className="w-[70px] text-xs h-8">Rev</TableHead>
                        <TableHead className="w-[70px] text-xs h-8">Stage</TableHead>
                        <TableHead className="w-[70px] text-xs h-8">IN/OUT</TableHead>
                        <TableHead className="w-[90px] text-xs h-8">Status</TableHead>
                        <TableHead className="min-w-[130px] text-xs h-8">Transmittal No</TableHead>
                        <TableHead className="min-w-[130px] text-xs h-8">Activity No</TableHead>
                        <TableHead className="min-w-[90px] text-xs h-8">Ref Activity</TableHead>
                        <TableHead className="w-[100px] text-xs h-8">Modified</TableHead>
                        <TableHead className="w-[70px] text-xs h-8">By</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {Array.from(groupedActivities.entries()).map(([key, groupActivities]) => {
                        const [revNo, stage] = key.split("|");
                        return groupActivities.map((activity, idx) => (
                          <TableRow
                            key={activity.actvNo}
                            className={cn(
                              "cursor-pointer hover:bg-muted/50 h-8",
                              selectedActivity?.actvNo === activity.actvNo &&
                                "bg-blue-50 hover:bg-blue-100"
                            )}
                            onClick={() => handleActivityClick(activity)}
                          >
                            {/* Rev 컬럼 (첫 행만 표시, rowspan) */}
                            {idx === 0 && (
                              <TableCell 
                                className="font-mono text-xs font-semibold align-top border-r py-1"
                                rowSpan={groupActivities.length}
                              >
                                {revNo}
                              </TableCell>
                            )}
                            {/* Stage 컬럼 (첫 행만 표시, rowspan) */}
                            {idx === 0 && (
                              <TableCell 
                                className="align-top border-r text-xs py-1"
                                rowSpan={groupActivities.length}
                              >
                                {stage}
                              </TableCell>
                            )}
                            <TableCell className="py-1">
                              <Badge
                                variant="outline"
                                className={cn(
                                  "text-[10px] h-4 px-1",
                                  activity.inOut === "IN"
                                    ? "bg-blue-100 text-blue-800"
                                    : "bg-green-100 text-green-800"
                                )}
                              >
                                {activity.inOut}
                              </Badge>
                            </TableCell>
                            <TableCell className="text-xs py-1">
                              <div className="font-medium">{activity.statusName}</div>
                            </TableCell>
                            <TableCell className="text-xs py-1">
                              {activity.transmittalNo || "-"}
                            </TableCell>
                            <TableCell className="font-mono text-xs py-1">
                              {activity.actvNo}
                            </TableCell>
                            <TableCell className="font-mono text-xs py-1">
                              {activity.refActivityNo || "-"}
                            </TableCell>
                            <TableCell className="text-xs py-1">
                              {formatSwpDateShort(activity.createDate)}
                            </TableCell>
                            <TableCell className="text-xs py-1">
                              {activity.createEmpNo}
                            </TableCell>
                          </TableRow>
                        ));
                      })}
                    </TableBody>
                  </Table>
                </div>

                {/* 파일 목록 (아래) */}
                <div className="border rounded-lg overflow-hidden h-[30vh] flex flex-col">
                  <div className="px-3 py-1.5 bg-muted/50 border-b flex-shrink-0">
                    <h3 className="font-semibold text-xs">파일 목록</h3>
                    {selectedActivity ? (
                      <p className="text-[10px] text-muted-foreground mt-0.5">
                        Activity: {selectedActivity.actvNo} / Rev {selectedActivity.revNo} ({selectedActivity.stage}) / {selectedActivity.inOut}
                      </p>
                    ) : (
                      <p className="text-[10px] text-muted-foreground mt-0.5">
                        Activity를 선택하면 파일 목록이 표시됩니다
                      </p>
                    )}
                  </div>
                  <div className="overflow-auto flex-1">
                    {selectedActivity ? (
                      isLoadingFiles ? (
                        <div className="flex items-center justify-center h-full">
                          <Loader2 className="h-4 w-4 animate-spin" />
                          <span className="ml-2 text-xs">파일 로딩 중...</span>
                        </div>
                      ) : activityFiles.length > 0 ? (
                        <Table>
                          <TableHeader className="sticky top-0 bg-background">
                            <TableRow>
                              <TableHead className="min-w-[200px] text-xs h-8">파일명</TableHead>
                              <TableHead className="w-[90px] text-xs h-8">크기</TableHead>
                              <TableHead className="w-[100px] text-xs h-8">날짜</TableHead>
                              <TableHead className="w-[90px] text-xs h-8">다운로드</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {activityFiles.map((file) => (
                              <TableRow key={file.FILE_SEQ} className="h-8">
                                <TableCell className="font-medium text-xs py-1">
                                  {file.FILE_NM}
                                </TableCell>
                                <TableCell className="text-xs text-muted-foreground py-1">
                                  {file.FILE_SZ ? formatFileSize(file.FILE_SZ) : "-"}
                                </TableCell>
                                <TableCell className="text-xs text-muted-foreground py-1">
                                  {file.CRTE_DTM ? formatSwpDateShort(file.CRTE_DTM) : "-"}
                                </TableCell>
                                <TableCell className="py-1">
                                  <Button
                                    variant="outline"
                                    size="sm"
                                    className="h-6 px-2 text-[10px]"
                                    onClick={() => handleDownloadFile(file.FILE_NM, document.OWN_DOC_NO || document.DOC_NO)}
                                  >
                                    <Download className="h-3 w-3 mr-1" />
                                    다운로드
                                  </Button>
                                </TableCell>
                              </TableRow>
                            ))}
                          </TableBody>
                        </Table>
                      ) : (
                        <div className="flex items-center justify-center h-full text-xs text-muted-foreground">
                          <div className="text-center">
                            <AlertCircle className="h-6 w-6 mx-auto mb-1 opacity-50" />
                            <p>파일이 없습니다</p>
                          </div>
                        </div>
                      )
                    ) : (
                      <div className="flex items-center justify-center h-full text-xs text-muted-foreground">
                        <div className="text-center">
                          <FileIcon className="h-8 w-8 mx-auto mb-1 opacity-30" />
                          <p>Activity를 선택해주세요</p>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </>
            ) : (
              <div className="p-8 text-center text-muted-foreground">
                <AlertCircle className="h-10 w-10 mx-auto mb-2 opacity-50" />
                <p className="text-sm">Activity 정보가 없습니다</p>
              </div>
            )}
          </div>
        )}
      </DialogContent>
    </Dialog>
  );
}