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
|
"use client"
import * as React from "react"
import { Loader, Database, Check } from "lucide-react"
import { toast } from "sonner"
import {
useReactTable,
getCoreRowModel,
getPaginationRowModel,
getFilteredRowModel,
ColumnDef,
flexRender,
} from "@tanstack/react-table"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { Checkbox } from "@/components/ui/checkbox"
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area"
import { getCPVWWabQustListViewData, CPVWWabQustListView } from "@/lib/basic-contract/cpvw-service"
interface CPVWWabQustListViewDialogProps {
onConfirm?: (selectedRows: CPVWWabQustListView[]) => void
requireSingleSelection?: boolean
triggerDisabled?: boolean
triggerTitle?: string
}
export function CPVWWabQustListViewDialog({
onConfirm,
requireSingleSelection = false,
triggerDisabled = false,
triggerTitle,
}: CPVWWabQustListViewDialogProps) {
const [open, setOpen] = React.useState(false)
const [isLoading, setIsLoading] = React.useState(false)
const [data, setData] = React.useState<CPVWWabQustListView[]>([])
const [error, setError] = React.useState<string | null>(null)
const [rowSelection, setRowSelection] = React.useState<Record<string, boolean>>({})
const loadData = async () => {
setIsLoading(true)
setError(null)
try {
const result = await getCPVWWabQustListViewData()
if (result.success) {
setData(result.data)
if (result.isUsingFallback) {
toast.info("테스트 데이터를 표시합니다.")
}
} else {
setError(result.error || "데이터 로딩 실패")
toast.error(result.error || "데이터 로딩 실패")
}
} catch (err) {
const errorMessage = err instanceof Error ? err.message : "알 수 없는 오류"
setError(errorMessage)
toast.error(errorMessage)
} finally {
setIsLoading(false)
}
}
React.useEffect(() => {
if (open) {
loadData()
} else {
// 다이얼로그 닫힐 때 데이터 초기화
setData([])
setError(null)
setRowSelection({})
}
}, [open])
// 테이블 컬럼 정의 (동적 생성)
const columns = React.useMemo<ColumnDef<CPVWWabQustListView>[]>(() => {
if (data.length === 0) return []
const dataKeys = Object.keys(data[0])
return [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && "indeterminate")
}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="모든 행 선택"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="행 선택"
/>
),
enableSorting: false,
enableHiding: false,
},
...dataKeys.map((key) => ({
accessorKey: key,
header: key,
cell: ({ getValue }: any) => {
const value = getValue()
return value !== null && value !== undefined ? String(value) : ""
},
})),
]
}, [data])
// 테이블 인스턴스 생성
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getFilteredRowModel: getFilteredRowModel(),
onRowSelectionChange: setRowSelection,
state: {
rowSelection,
},
})
// 선택된 행들 가져오기
const selectedRows = table.getFilteredSelectedRowModel().rows.map(row => row.original)
// 확인 버튼 핸들러
const handleConfirm = () => {
if (selectedRows.length === 0) {
toast.error("행을 선택해주세요.")
return
}
if (requireSingleSelection && selectedRows.length !== 1) {
toast.error("하나의 행만 선택해주세요.")
return
}
if (onConfirm) {
onConfirm(selectedRows)
toast.success(
requireSingleSelection
? "선택한 행으로 준법문의 상태를 동기화합니다."
: `${selectedRows.length}개의 행을 선택했습니다.`
)
} else {
// 임시로 선택된 데이터 콘솔 출력
console.log("선택된 행들:", selectedRows)
toast.success(`${selectedRows.length}개의 행이 선택되었습니다. (콘솔 확인)`)
}
setOpen(false)
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button
variant="outline"
size="sm"
disabled={triggerDisabled}
title={triggerTitle}
>
<Database className="mr-2 size-4" aria-hidden="true" />
준법문의 요청 데이터 조회
</Button>
</DialogTrigger>
<DialogContent className="max-w-7xl h-[90vh] flex flex-col overflow-hidden">
<DialogHeader>
<DialogTitle>준법문의 요청 데이터</DialogTitle>
<DialogDescription>
준법문의 요청 데이터를 조회합니다.
{data.length > 0 && ` (${data.length}건, ${selectedRows.length}개 선택됨)`}
</DialogDescription>
</DialogHeader>
<div className="flex flex-col flex-1 min-h-0">
{isLoading ? (
<div className="flex items-center justify-center flex-1 min-h-[200px]">
<Loader className="mr-2 size-6 animate-spin" />
<span>데이터 로딩 중...</span>
</div>
) : error ? (
<div className="flex items-center justify-center flex-1 min-h-[200px] text-red-500">
<span>오류: {error}</span>
</div>
) : data.length === 0 ? (
<div className="flex items-center justify-center flex-1 min-h-[200px] text-muted-foreground">
<span>데이터가 없습니다.</span>
</div>
) : (
<div className="flex flex-col flex-1 min-h-0">
{/* 테이블 영역 - 스크롤 가능 */}
<ScrollArea className="flex-1 overflow-auto border rounded-md">
<Table className="min-w-full">
<TableHeader className="sticky top-0 bg-background z-10">
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<TableHead key={header.id} className="font-medium bg-background">
{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"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id} className="text-sm">
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center"
>
데이터가 없습니다.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
<ScrollBar orientation="horizontal" />
</ScrollArea>
{/* 페이지네이션 컨트롤 - 고정 영역 */}
<div className="flex items-center justify-between px-2 py-4 border-t bg-background flex-shrink-0">
<div className="flex-1 text-sm text-muted-foreground">
{table.getFilteredSelectedRowModel().rows.length}개 행 선택됨
</div>
<div className="flex items-center space-x-6 lg:space-x-8">
<div className="flex items-center space-x-2">
<p className="text-sm font-medium">페이지당 행 수</p>
<select
value={table.getState().pagination.pageSize}
onChange={(e) => {
table.setPageSize(Number(e.target.value))
}}
className="h-8 w-[70px] rounded border border-input bg-transparent px-3 py-1 text-sm ring-offset-background focus:ring-2 focus:ring-ring focus:ring-offset-2"
>
{[10, 20, 30, 40, 50].map((pageSize) => (
<option key={pageSize} value={pageSize}>
{pageSize}
</option>
))}
</select>
</div>
<div className="flex w-[100px] items-center justify-center text-sm font-medium">
{table.getState().pagination.pageIndex + 1} /{" "}
{table.getPageCount()}
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">첫 페이지로</span>
{"<<"}
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">이전 페이지</span>
{"<"}
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">다음 페이지</span>
{">"}
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0"
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">마지막 페이지로</span>
{">>"}
</Button>
</div>
</div>
</div>
</div>
)}
</div>
<DialogFooter className="gap-2 flex-shrink-0">
<Button variant="outline" onClick={() => setOpen(false)}>
닫기
</Button>
<Button onClick={loadData} disabled={isLoading} variant="outline">
{isLoading ? (
<>
<Loader className="mr-2 size-4 animate-spin" />
로딩 중...
</>
) : (
"새로고침"
)}
</Button>
<Button
onClick={handleConfirm}
disabled={
requireSingleSelection
? selectedRows.length !== 1
: selectedRows.length === 0
}
>
<Check className="mr-2 size-4" />
확인 ({selectedRows.length})
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
|