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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
|
"use client"
import * as React from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Button } from "@/components/ui/button"
import { PanelLeftClose, PanelLeftOpen } from "lucide-react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import type {
DataTableAdvancedFilterField,
DataTableFilterField,
DataTableRowAction,
} from "@/types/table"
import { useDataTable } from "@/hooks/use-data-table"
import { DataTable } from "@/components/data-table/data-table"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { cn } from "@/lib/utils"
import { useTablePresets } from "@/components/data-table/use-table-presets"
import { TablePresetManager } from "@/components/data-table/data-table-preset"
import { useMemo } from "react"
import { PeriodicEvaluationFilterSheet } from "./evaluation-filter-sheet"
import { getPeriodicEvaluationsColumns } from "./evaluation-columns"
import { PeriodicEvaluationView } from "@/db/schema"
import { getPeriodicEvaluations, getPeriodicEvaluationsStats } from "../service"
import { PeriodicEvaluationsTableToolbarActions } from "./periodic-evaluations-toolbar-actions"
import { EvaluationDetailsDialog } from "./evaluation-details-dialog"
interface PeriodicEvaluationsTableProps {
promises: Promise<[Awaited<ReturnType<typeof getPeriodicEvaluations>>]>
evaluationYear: number
className?: string
}
// 통계 카드 컴포넌트
function PeriodicEvaluationsStats({ evaluationYear }: { evaluationYear: number }) {
const [stats, setStats] = React.useState<any>(null)
const [isLoading, setIsLoading] = React.useState(true)
const [error, setError] = React.useState<string | null>(null)
React.useEffect(() => {
let isMounted = true
async function fetchStats() {
try {
setIsLoading(true)
setError(null)
// 실제 통계 함수 호출
const statsData = await getPeriodicEvaluationsStats(evaluationYear)
if (isMounted) {
setStats(statsData)
}
} catch (err) {
if (isMounted) {
setError(err instanceof Error ? err.message : 'Failed to fetch stats')
console.error('Error fetching periodic evaluations stats:', err)
}
} finally {
if (isMounted) {
setIsLoading(false)
}
}
}
fetchStats()
return () => {
isMounted = false
}
}, [evaluationYear]) // evaluationYear 의존성 추가
if (isLoading) {
return (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4 mb-6">
{Array.from({ length: 4 }).map((_, i) => (
<Card key={i}>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<Skeleton className="h-4 w-20" />
</CardHeader>
<CardContent>
<Skeleton className="h-8 w-16" />
</CardContent>
</Card>
))}
</div>
)
}
if (error || !stats) {
return (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4 mb-6">
<Card className="col-span-full">
<CardContent className="pt-6">
<div className="text-center text-sm text-muted-foreground">
{error ? `통계 데이터를 불러올 수 없습니다: ${error}` : "통계 데이터가 없습니다."}
</div>
</CardContent>
</Card>
</div>
)
}
const totalEvaluations = stats.total || 0
const pendingSubmission = stats.pendingSubmission || 0
const inProgress = (stats.submitted || 0) + (stats.inReview || 0) + (stats.reviewCompleted || 0)
const finalized = stats.finalized || 0
const completionRate = stats.completionRate || 0
return (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4 mb-6">
{/* 총 평가 */}
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">총 평가</CardTitle>
<Badge variant="outline">{evaluationYear}년</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totalEvaluations.toLocaleString()}</div>
<div className="text-xs text-muted-foreground mt-1">
평균점수 {stats.averageScore?.toFixed(1) || 0}점
</div>
</CardContent>
</Card>
{/* 제출대기 */}
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">제출대기</CardTitle>
<Badge variant="outline">대기</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-orange-600">{pendingSubmission.toLocaleString()}</div>
<div className="text-xs text-muted-foreground mt-1">
{totalEvaluations > 0 ? Math.round((pendingSubmission / totalEvaluations) * 100) : 0}% of total
</div>
</CardContent>
</Card>
{/* 진행중 */}
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">진행중</CardTitle>
<Badge variant="secondary">진행</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-blue-600">{inProgress.toLocaleString()}</div>
<div className="text-xs text-muted-foreground mt-1">
{totalEvaluations > 0 ? Math.round((inProgress / totalEvaluations) * 100) : 0}% of total
</div>
</CardContent>
</Card>
{/* 완료율 */}
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">완료율</CardTitle>
<Badge variant={completionRate >= 80 ? "default" : completionRate >= 60 ? "secondary" : "destructive"}>
{completionRate}%
</Badge>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold text-green-600">{finalized.toLocaleString()}</div>
<div className="text-xs text-muted-foreground mt-1">
최종확정 완료
</div>
</CardContent>
</Card>
</div>
)
}
export function PeriodicEvaluationsTable({ promises, evaluationYear, className }: PeriodicEvaluationsTableProps) {
const [rowAction, setRowAction] = React.useState<DataTableRowAction<PeriodicEvaluationView> | null>(null)
const [isFilterPanelOpen, setIsFilterPanelOpen] = React.useState(false)
const router = useRouter()
const searchParams = useSearchParams()
const containerRef = React.useRef<HTMLDivElement>(null)
const [containerTop, setContainerTop] = React.useState(0)
const updateContainerBounds = React.useCallback(() => {
if (containerRef.current) {
const rect = containerRef.current.getBoundingClientRect()
const newTop = rect.top
setContainerTop(prevTop => {
if (Math.abs(prevTop - newTop) > 1) {
return newTop
}
return prevTop
})
}
}, [])
const throttledUpdateBounds = React.useCallback(() => {
let timeoutId: NodeJS.Timeout
return () => {
clearTimeout(timeoutId)
timeoutId = setTimeout(updateContainerBounds, 16)
}
}, [updateContainerBounds])
React.useEffect(() => {
updateContainerBounds()
const throttledHandler = throttledUpdateBounds()
const handleResize = () => {
updateContainerBounds()
}
window.addEventListener('resize', handleResize)
window.addEventListener('scroll', throttledHandler)
return () => {
window.removeEventListener('resize', handleResize)
window.removeEventListener('scroll', throttledHandler)
}
}, [updateContainerBounds, throttledUpdateBounds])
const [promiseData] = React.use(promises)
const tableData = promiseData
const getSearchParam = React.useCallback((key: string, defaultValue?: string): string => {
return searchParams?.get(key) ?? defaultValue ?? "";
}, [searchParams]);
const parseSearchParamHelper = React.useCallback((key: string, defaultValue: any): any => {
try {
const value = getSearchParam(key);
return value ? JSON.parse(value) : defaultValue;
} catch {
return defaultValue;
}
}, [getSearchParam]);
const parseSearchParam = <T,>(key: string, defaultValue: T): T => {
return parseSearchParamHelper(key, defaultValue);
};
const initialSettings = React.useMemo(() => ({
page: parseInt(getSearchParam('page') || '1'),
perPage: parseInt(getSearchParam('perPage') || '10'),
sort: getSearchParam('sort') ? JSON.parse(getSearchParam('sort')!) : [{ id: "createdAt", desc: true }],
filters: getSearchParam('filters') ? JSON.parse(getSearchParam('filters')!) : [],
joinOperator: (getSearchParam('joinOperator') as "and" | "or") || "and",
basicFilters: getSearchParam('basicFilters') ?
JSON.parse(getSearchParam('basicFilters')!) : [],
basicJoinOperator: (getSearchParam('basicJoinOperator') as "and" | "or") || "and",
search: getSearchParam('search') || '',
columnVisibility: {},
columnOrder: [],
pinnedColumns: { left: [], right: ["actions"] },
groupBy: [],
expandedRows: []
}), [searchParams])
const {
presets,
activePresetId,
hasUnsavedChanges,
isLoading: presetsLoading,
createPreset,
applyPreset,
updatePreset,
deletePreset,
setDefaultPreset,
renamePreset,
updateClientState,
getCurrentSettings,
} = useTablePresets<PeriodicEvaluationView>('periodic-evaluations-table', initialSettings)
const columns = React.useMemo(
() => getPeriodicEvaluationsColumns({ setRowAction }),
[setRowAction]
)
const filterFields: DataTableFilterField<PeriodicEvaluationView>[] = [
{ id: "vendorCode", label: "벤더 코드" },
{ id: "vendorName", label: "벤더명" },
{ id: "status", label: "진행상태" },
]
const advancedFilterFields: DataTableAdvancedFilterField<PeriodicEvaluationView>[] = [
{ id: "evaluationYear", label: "평가년도", type: "number" },
{ id: "evaluationPeriod", label: "평가기간", type: "text" },
{
id: "division", label: "구분", type: "select", options: [
{ label: "해양", value: "PLANT" },
{ label: "조선", value: "SHIP" },
]
},
{ id: "vendorCode", label: "벤더 코드", type: "text" },
{ id: "vendorName", label: "벤더명", type: "text" },
{
id: "status", label: "진행상태", type: "select", options: [
{ label: "제출대기", value: "PENDING_SUBMISSION" },
{ label: "제출완료", value: "SUBMITTED" },
{ label: "검토중", value: "IN_REVIEW" },
{ label: "검토완료", value: "REVIEW_COMPLETED" },
{ label: "최종확정", value: "FINALIZED" },
]
},
{
id: "documentsSubmitted", label: "문서제출", type: "select", options: [
{ label: "제출완료", value: "true" },
{ label: "미제출", value: "false" },
]
},
{ id: "totalScore", label: "총점", type: "number" },
{ id: "finalScore", label: "최종점수", type: "number" },
{ id: "submissionDate", label: "제출일", type: "date" },
{ id: "reviewCompletedAt", label: "검토완료일", type: "date" },
{ id: "finalizedAt", label: "최종확정일", type: "date" },
]
const currentSettings = React.useMemo(() => getCurrentSettings(), [getCurrentSettings]);
const initialState = React.useMemo(() => ({
sorting: initialSettings.sort.filter((s: any) => columns.some((c: any) => ("accessorKey" in c ? c.accessorKey : c.id) === s.id)),
columnVisibility: currentSettings.columnVisibility,
columnPinning: currentSettings.pinnedColumns,
}), [columns, currentSettings, initialSettings.sort]);
const { table } = useDataTable({
data: tableData.data,
columns,
pageCount: tableData.pageCount,
rowCount: tableData.total || tableData.data.length,
filterFields,
enablePinning: true,
enableAdvancedFilter: true,
initialState,
getRowId: (originalRow) => String(originalRow.id),
shallow: false,
clearOnDefault: true,
})
const handleSearch = () => {
setIsFilterPanelOpen(false)
}
const getActiveBasicFilterCount = () => {
try {
const basicFilters = getSearchParam('basicFilters')
return basicFilters ? JSON.parse(basicFilters).length : 0
} catch (e) {
return 0
}
}
const FILTER_PANEL_WIDTH = 400;
return (
<>
{/* Filter Panel */}
<div
className={cn(
"fixed left-0 bg-background border-r z-50 flex flex-col transition-all duration-300 ease-in-out overflow-hidden",
isFilterPanelOpen ? "border-r shadow-lg" : "border-r-0"
)}
style={{
width: isFilterPanelOpen ? `${FILTER_PANEL_WIDTH}px` : '0px',
top: `${containerTop}px`,
height: `calc(100vh - ${containerTop}px)`
}}
>
<div className="h-full">
<PeriodicEvaluationFilterSheet
isOpen={isFilterPanelOpen}
onClose={() => setIsFilterPanelOpen(false)}
onSearch={handleSearch}
isLoading={false}
/>
</div>
</div>
{/* Main Content Container */}
<div
ref={containerRef}
className={cn("relative w-full overflow-hidden", className)}
>
<div className="flex w-full h-full">
<div
className="flex flex-col min-w-0 overflow-hidden transition-all duration-300 ease-in-out"
style={{
width: isFilterPanelOpen ? `calc(100% - ${FILTER_PANEL_WIDTH}px)` : '100%',
marginLeft: isFilterPanelOpen ? `${FILTER_PANEL_WIDTH}px` : '0px'
}}
>
{/* Header Bar */}
<div className="flex items-center justify-between p-4 bg-background shrink-0">
<div className="flex items-center gap-3">
<Button
variant="outline"
size="sm"
type='button'
onClick={() => setIsFilterPanelOpen(!isFilterPanelOpen)}
className="flex items-center shadow-sm"
>
{isFilterPanelOpen ? <PanelLeftClose className="size-4" /> : <PanelLeftOpen className="size-4" />}
{getActiveBasicFilterCount() > 0 && (
<span className="ml-2 bg-primary text-primary-foreground rounded-full px-2 py-0.5 text-xs">
{getActiveBasicFilterCount()}
</span>
)}
</Button>
</div>
<div className="text-sm text-muted-foreground">
{tableData && (
<span>총 {tableData.total || tableData.data.length}건</span>
)}
</div>
</div>
{/* 통계 카드들 */}
<div className="px-4">
<PeriodicEvaluationsStats evaluationYear={evaluationYear} />
</div>
{/* Table Content Area */}
<div className="flex-1 overflow-hidden" style={{ height: 'calc(100vh - 500px)' }}>
<div className="h-full w-full">
<DataTable table={table} className="h-full">
<DataTableAdvancedToolbar
table={table}
filterFields={advancedFilterFields}
shallow={false}
>
<div className="flex items-center gap-2">
<TablePresetManager<PeriodicEvaluationView>
presets={presets}
activePresetId={activePresetId}
currentSettings={currentSettings}
hasUnsavedChanges={hasUnsavedChanges}
isLoading={presetsLoading}
onCreatePreset={createPreset}
onUpdatePreset={updatePreset}
onDeletePreset={deletePreset}
onApplyPreset={applyPreset}
onSetDefaultPreset={setDefaultPreset}
onRenamePreset={renamePreset}
/>
<PeriodicEvaluationsTableToolbarActions
table={table}
/>
</div>
</DataTableAdvancedToolbar>
</DataTable>
<EvaluationDetailsDialog
open={rowAction?.type === "view"}
onOpenChange={(open) => {
if (!open) {
setRowAction(null)
}
}}
evaluation={rowAction?.row.original || null}
/>
</div>
</div>
</div>
</div>
</div>
</>
)
}
|