summaryrefslogtreecommitdiff
path: root/lib/swp/table/swp-inbox-table.tsx
blob: c3f3a243305828c592071cf1747dc05fd6bdb028 (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
"use client";

import React, { useState, useMemo } from "react";
import {
  useReactTable,
  getCoreRowModel,
  flexRender,
} from "@tanstack/react-table";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { ColumnDef } from "@tanstack/react-table";
import { SwpInboxDocumentDetailDialog } from "./swp-inbox-document-detail-dialog";
import type { SwpFileApiResponse } from "@/lib/swp/api-client";

interface SwpInboxTableProps {
  files: SwpFileApiResponse[];
  projNo: string;
  vendorCode: string;
  userId: string;
}

// 문서별로 그룹핑된 데이터 타입
export interface InboxDocumentItem {
  ownDocNo: string;
  latestRevFileCount: number; // 최신 REV의 파일 개수
  latestStage: string;
  latestRevNo: string;
  latestStatus: string | null;
  latestStatusNm: string | null;
  files: SwpFileApiResponse[];
}

// 테이블 컬럼 정의
const inboxDocumentColumns: ColumnDef<InboxDocumentItem>[] = [
  {
    accessorKey: "latestStatusNm",
    header: "상태",
    cell: ({ row }) => {
      const statNm = row.original.latestStatusNm;
      const stat = row.original.latestStatus;
      const displayStatus = statNm || stat || "-";
      
      if (!stat) return displayStatus;

      // STAT 코드 기반 색상 결정
      const color =
        stat === "SCW03" || stat === "SCW08" ? "bg-green-100 text-green-800" :      // Complete, Checked
        stat === "SCW02" ? "bg-blue-100 text-blue-800" :                            // Processing
        stat === "SCW01" ? "bg-yellow-100 text-yellow-800" :                        // Standby
        stat === "SCW04" || stat === "SCW05" || stat === "SCW06" ? "bg-red-100 text-red-800" : // Reject, Error Zip, Error Meta
        stat === "SCW07" ? "bg-purple-100 text-purple-800" :                        // Send for Eng Verification
        stat === "SCW09" ? "bg-gray-100 text-gray-800" :                            // Cancelled
        stat === "SCW00" ? "bg-orange-100 text-orange-800" :                        // Upload
        "bg-gray-100 text-gray-800";                                                 // 기타

      return (
        <Badge variant="outline" className={color}>
          {displayStatus}
        </Badge>
      );
    },
    size: 120,
  },
  {
    accessorKey: "ownDocNo",
    header: "OWN_DOC_NO",
    cell: ({ row }) => (
      <div className="font-mono text-sm">{row.original.ownDocNo}</div>
    ),
    size: 300,
  },
  {
    accessorKey: "latestStage",
    header: "최신 스테이지",
    cell: ({ row }) => {
      const stage = row.original.latestStage;
      if (!stage) return "-";

      const color =
        stage === "IFC" ? "bg-green-100 text-green-800" :
        stage === "IFA" ? "bg-blue-100 text-blue-800" :
        "bg-gray-100 text-gray-800";

      return (
        <Badge variant="outline" className={color}>
          {stage}
        </Badge>
      );
    },
    size: 120,
  },
  {
    accessorKey: "latestRevNo",
    header: "최신 REV",
    cell: ({ row }) => row.original.latestRevNo || "-",
    size: 100,
  },
  {
    accessorKey: "latestRevFileCount",
    header: "최신 REV 파일 수",
    cell: ({ row }) => (
      <div className="text-center">
        <div className="text-sm font-medium">
          {row.original.latestRevFileCount}개
        </div>
      </div>
    ),
    size: 100,
  },
];

export function SwpInboxTable({
  files,
  projNo,
  vendorCode,
  userId,
}: SwpInboxTableProps) {
  const [dialogOpen, setDialogOpen] = useState(false);
  const [selectedDocument, setSelectedDocument] = useState<InboxDocumentItem | null>(null);

  // 파일들을 문서별로 그룹핑
  const documents = useMemo(() => {
    const docMap = new Map<string, SwpFileApiResponse[]>();

    files.forEach((file) => {
      const docNo = file.OWN_DOC_NO;
      if (!docMap.has(docNo)) {
        docMap.set(docNo, []);
      }
      docMap.get(docNo)!.push(file);
    });

    const result: InboxDocumentItem[] = [];

    docMap.forEach((docFiles, ownDocNo) => {
      // 최신 REV 찾기 (REV_NO 기준으로 정렬)
      const sortedByRev = [...docFiles].sort((a, b) => 
        (b.REV_NO || "").localeCompare(a.REV_NO || "")
      );
      const latestRevNo = sortedByRev[0].REV_NO || "";

      // 최신 REV의 파일들만 필터링
      const latestRevFiles = docFiles.filter(file => file.REV_NO === latestRevNo);

      // 최신 REV 내에서 가장 최근 생성된 파일 찾기 (상태 표시용)
      const sortedLatestRevFiles = [...latestRevFiles].sort((a, b) => 
        (b.CRTE_DTM || "").localeCompare(a.CRTE_DTM || "")
      );
      const latestFile = sortedLatestRevFiles[0];

      result.push({
        ownDocNo,
        latestRevFileCount: latestRevFiles.length, // 최신 REV의 파일 개수
        latestStage: latestFile.STAGE || "",
        latestRevNo: latestRevNo,
        latestStatus: latestFile.STAT,
        latestStatusNm: latestFile.STAT_NM,
        files: docFiles, // 전체 파일 목록 (상세보기용)
      });
    });

    return result.sort((a, b) => a.ownDocNo.localeCompare(b.ownDocNo));
  }, [files]);

  const table = useReactTable({
    data: documents,
    columns: inboxDocumentColumns,
    getCoreRowModel: getCoreRowModel(),
  });

  // 문서 클릭 핸들러
  const handleDocumentClick = (document: InboxDocumentItem) => {
    setSelectedDocument(document);
    setDialogOpen(true);
  };

  return (
    <div className="space-y-4">
      {/* 테이블 */}
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            {table.getHeaderGroups().map((headerGroup) => (
              <TableRow key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <TableHead key={header.id}>
                    {header.isPlaceholder
                      ? null
                      : flexRender(
                          header.column.columnDef.header,
                          header.getContext()
                        )}
                  </TableHead>
                ))}
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows?.length ? (
              table.getRowModel().rows.map((row) => (
                <TableRow
                  key={row.id}
                  data-state={row.getIsSelected() && "selected"}
                  className="hover:bg-muted/50 cursor-pointer"
                  onClick={() => handleDocumentClick(row.original)}
                >
                  {row.getVisibleCells().map((cell) => (
                    <TableCell key={cell.id}>
                      {flexRender(cell.column.columnDef.cell, cell.getContext())}
                    </TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={inboxDocumentColumns.length} className="h-24 text-center">
                  업로드한 파일이 없습니다.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      {/* 문서 상세 Dialog */}
      <SwpInboxDocumentDetailDialog
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        document={selectedDocument}
        projNo={projNo}
        vendorCode={vendorCode}
        userId={userId}
      />
    </div>
  );
}