summaryrefslogtreecommitdiff
path: root/lib/material/table/material-table.tsx
blob: 6870a030f24e05444a0e884c33f2299dd6f5575a (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
"use client"

import * as React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
  DataTableRowAction,
} from "@/types/table"

import { useDataTable } from "@/hooks/use-data-table"
import { DataTable } from "@/components/data-table/data-table"
import { InfiniteDataTable } from "@/components/data-table/infinite-data-table"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { Button } from "@/components/ui/button"
import { Alert, AlertDescription } from "@/components/ui/alert"

import { getMaterials } from "../services"
import { getColumns } from "./material-table-columns"
import { MaterialDetailDialog } from "./material-detail-dialog"
import { ViewModeToggle } from "@/components/data-table/view-mode-toggle"

// Material 타입 정의 (서비스에서 반환되는 타입과 일치)
type Material = {
  id: number;
  MATKL: string | null;    // 자재그룹(=자재그룹코드)
  MATNR: string | null;    // 자재코드
  ZZNAME: string | null;   // 자재명
  ZZPJT: string | null;    // 프로젝트
  createdAt: Date;
  updatedAt: Date;
}

interface MaterialTableProps {
  promises?: Promise<
    [
      Awaited<ReturnType<typeof getMaterials>>,
    ]
  >
}

export function MaterialTable({ promises }: MaterialTableProps) {
  // 페이지네이션 모드 데이터
  const paginationData = promises ? React.use(promises) : null
  const [{ data = [], pageCount = 0 }] = paginationData || [{ data: [], pageCount: 0 }]

  console.log('MaterialTable data:', data.length, 'materials')

  const [rowAction, setRowAction] =
    React.useState<DataTableRowAction<Material> | null>(null)

  const columns = React.useMemo(
    () => getColumns({ setRowAction }),
    [setRowAction]
  )

  // 기존 필터 필드들
  const filterFields: DataTableFilterField<Material>[] = [
    {
      id: "MATKL",
      label: "자재그룹",
    },
    {
      id: "MATNR",
      label: "자재코드",
    },
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<Material>[] = [
    {
      id: "MATKL",
      label: "자재그룹",
      type: "text",
    },
    {
      id: "MATNR",
      label: "자재코드",
      type: "text",
    },
    {
      id: "ZZNAME",
      label: "자재명",
      type: "text",
    },
    {
      id: "ZZPJT",
      label: "프로젝트",
      type: "text",
    },
  ]

  // 확장된 useDataTable 훅 사용 (pageSize 기반 자동 전환)
  const {
    table,
    infiniteScroll,
    isInfiniteMode,
    handlePageSizeChange,
  } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
          initialState: {
        sorting: [{ id: "createdAt", desc: true }],
        columnPinning: { left: ["select"], right: ["actions"] },
      },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
    // 무한 스크롤 설정
    infiniteScrollConfig: {
      apiEndpoint: "/api/table/materials/infinite",
      tableName: "materials",
      maxPageSize: 100,
    },
  })

  return (
    <div className="w-full space-y-2.5 overflow-x-auto" style={{maxWidth:'100vw'}}>

        {/* 모드 토글 */}
        <div className="flex items-center justify-between">
          <ViewModeToggle
            isInfiniteMode={isInfiniteMode}
            onSwitch={handlePageSizeChange}
          />
        </div>

        {/* 에러 상태 (무한 스크롤 모드) */}
        {isInfiniteMode && infiniteScroll?.error && (
          <Alert variant="destructive">
            <AlertDescription>
              데이터를 불러오는 중 오류가 발생했습니다.
              <Button
                variant="link"
                size="sm"
                onClick={() => infiniteScroll.reset()}
                className="ml-2 p-0 h-auto"
              >
                다시 시도
              </Button>
            </AlertDescription>
          </Alert>
        )}

        {/* 로딩 상태가 아닐 때만 테이블 렌더링 */}
        {!(isInfiniteMode && infiniteScroll?.isLoading && infiniteScroll?.isEmpty) ? (
          <>
            {/* 도구 모음 */}
            <DataTableAdvancedToolbar
              table={table}
              filterFields={advancedFilterFields}
              shallow={false}
            />

            {/* 테이블 렌더링 */}
            {isInfiniteMode ? (
              // 무한 스크롤 모드: InfiniteDataTable 사용
              <InfiniteDataTable
                table={table}
                hasNextPage={infiniteScroll?.hasNextPage || false}
                isLoadingMore={infiniteScroll?.isLoadingMore || false}
                onLoadMore={infiniteScroll?.onLoadMore}
                totalCount={infiniteScroll?.totalCount}
                isEmpty={infiniteScroll?.isEmpty || false}
                compact={false}
                autoSizeColumns={true}
              />
            ) : (
              // 페이지네이션 모드: DataTable 사용
              <DataTable
                table={table}
                compact={false}
                autoSizeColumns={true}
              />
            )}
          </>
        ) : (
          /* 로딩 스켈레톤 (무한 스크롤 초기 로딩) */
          <div className="space-y-3">
            <div className="text-sm text-muted-foreground mb-4">
              무한 스크롤 모드로 데이터를 로드하고 있습니다...
            </div>
            {Array.from({ length: 10 }).map((_, i) => (
              <div key={i} className="h-12 w-full bg-muted animate-pulse rounded" />
            ))}
          </div>
        )}

        {/* 상세보기 다이얼로그 */}
        <MaterialDetailDialog
          open={rowAction?.type === "view"}
          onOpenChange={() => setRowAction(null)}
          matnr={rowAction?.row.original?.MATNR || null}
        />
      </div>
      )
}