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
|
/**
* WBS 코드 단일 선택 다이얼로그
*
* @description
* - WBS 코드를 하나만 선택할 수 있는 다이얼로그
* - 트리거 버튼과 다이얼로그가 분리된 구조
* - 외부에서 open 상태를 제어 가능
*/
import { useState, useCallback, useMemo, useTransition, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Search, Check, X } from 'lucide-react'
import {
ColumnDef,
flexRender,
getCoreRowModel,
getFilteredRowModel,
getPaginationRowModel,
getSortedRowModel,
useReactTable,
SortingState,
ColumnFiltersState,
VisibilityState,
RowSelectionState,
} from '@tanstack/react-table'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import {
getWbsCodes,
WbsCode
} from './wbs-code-service'
import { toast } from 'sonner'
export interface WbsCodeSingleSelectorProps {
open: boolean
onOpenChange: (open: boolean) => void
selectedCode?: WbsCode
onCodeSelect: (code: WbsCode) => void
onConfirm?: (code: WbsCode | undefined) => void
onCancel?: () => void
title?: string
description?: string
showConfirmButtons?: boolean
projNo?: string // 프로젝트 번호 필터
}
export function WbsCodeSingleSelector({
open,
onOpenChange,
selectedCode,
onCodeSelect,
onConfirm,
onCancel,
title = "WBS 코드 선택",
description = "WBS 코드를 선택하세요",
showConfirmButtons = false,
projNo
}: WbsCodeSingleSelectorProps) {
const [codes, setCodes] = useState<WbsCode[]>([])
const [sorting, setSorting] = useState<SortingState>([])
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([])
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
const [globalFilter, setGlobalFilter] = useState('')
const [isPending, startTransition] = useTransition()
const [tempSelectedCode, setTempSelectedCode] = useState<WbsCode | undefined>(selectedCode)
// WBS 코드 선택 핸들러
const handleCodeSelect = useCallback((code: WbsCode) => {
if (showConfirmButtons) {
setTempSelectedCode(code)
} else {
onCodeSelect(code)
onOpenChange(false)
}
}, [onCodeSelect, onOpenChange, showConfirmButtons])
// 확인 버튼 핸들러
const handleConfirm = useCallback(() => {
if (tempSelectedCode) {
onCodeSelect(tempSelectedCode)
}
onConfirm?.(tempSelectedCode)
onOpenChange(false)
}, [tempSelectedCode, onCodeSelect, onConfirm, onOpenChange])
// 취소 버튼 핸들러
const handleCancel = useCallback(() => {
setTempSelectedCode(selectedCode)
onCancel?.()
onOpenChange(false)
}, [selectedCode, onCancel, onOpenChange])
// 테이블 컬럼 정의
const columns: ColumnDef<WbsCode>[] = useMemo(() => [
{
accessorKey: 'PROJ_NO',
header: '프로젝트 번호',
cell: ({ row }) => (
<div className="font-mono text-sm">{row.getValue('PROJ_NO')}</div>
),
},
{
accessorKey: 'WBS_ELMT',
header: 'WBS 요소',
cell: ({ row }) => (
<div className="font-mono text-sm">{row.getValue('WBS_ELMT')}</div>
),
},
{
accessorKey: 'WBS_ELMT_NM',
header: 'WBS 요소명',
cell: ({ row }) => (
<div>{row.getValue('WBS_ELMT_NM')}</div>
),
},
{
accessorKey: 'WBS_LVL',
header: '레벨',
cell: ({ row }) => (
<div className="text-center">{row.getValue('WBS_LVL')}</div>
),
},
{
id: 'actions',
header: '선택',
cell: ({ row }) => {
const isSelected = showConfirmButtons
? tempSelectedCode?.WBS_ELMT === row.original.WBS_ELMT && tempSelectedCode?.PROJ_NO === row.original.PROJ_NO
: selectedCode?.WBS_ELMT === row.original.WBS_ELMT && selectedCode?.PROJ_NO === row.original.PROJ_NO
return (
<Button
variant={isSelected ? "default" : "ghost"}
size="sm"
onClick={(e) => {
e.stopPropagation()
handleCodeSelect(row.original)
}}
>
<Check className="h-4 w-4" />
</Button>
)
},
},
], [handleCodeSelect, selectedCode, tempSelectedCode, showConfirmButtons])
// WBS 코드 테이블 설정
const table = useReactTable({
data: codes,
columns,
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
onColumnVisibilityChange: setColumnVisibility,
onRowSelectionChange: setRowSelection,
onGlobalFilterChange: setGlobalFilter,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
getFilteredRowModel: getFilteredRowModel(),
state: {
sorting,
columnFilters,
columnVisibility,
rowSelection,
globalFilter,
},
})
// 서버에서 WBS 코드 전체 목록 로드 (한 번만)
const loadCodes = useCallback(async () => {
startTransition(async () => {
try {
const result = await getWbsCodes(projNo)
if (result.success) {
setCodes(result.data)
// 폴백 데이터를 사용하는 경우 알림
if (result.isUsingFallback) {
toast.info('Oracle 연결 실패', {
description: '테스트 데이터를 사용합니다.',
duration: 4000,
})
}
} else {
toast.error(result.error || 'WBS 코드를 불러오는데 실패했습니다.')
setCodes([])
}
} catch (error) {
console.error('WBS 코드 목록 로드 실패:', error)
toast.error('WBS 코드를 불러오는 중 오류가 발생했습니다.')
setCodes([])
}
})
}, [projNo])
// 다이얼로그 열릴 때 코드 로드 (open prop 변화 감지)
useEffect(() => {
if (open) {
setTempSelectedCode(selectedCode)
if (codes.length === 0) {
console.log('🚀 [WbsCodeSingleSelector] 다이얼로그 열림 - loadCodes 호출')
loadCodes()
} else {
console.log('📦 [WbsCodeSingleSelector] 다이얼로그 열림 - 기존 데이터 사용 (' + codes.length + '건)')
}
}
}, [open, selectedCode, loadCodes, codes.length])
// 검색어 변경 핸들러 (클라이언트 사이드 필터링)
const handleSearchChange = useCallback((value: string) => {
setGlobalFilter(value)
}, [])
const currentSelectedCode = showConfirmButtons ? tempSelectedCode : selectedCode
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-5xl max-h-[80vh]">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<div className="text-sm text-muted-foreground">
{description}
</div>
</DialogHeader>
<div className="space-y-4">
{/* 현재 선택된 WBS 코드 표시 */}
{currentSelectedCode && (
<div className="p-3 bg-muted rounded-md">
<div className="text-sm font-medium">선택된 WBS 코드:</div>
<div className="flex items-center gap-2 mt-1">
<span className="font-mono text-sm">[{currentSelectedCode.PROJ_NO}]</span>
<span className="font-mono text-sm">{currentSelectedCode.WBS_ELMT}</span>
<span>{currentSelectedCode.WBS_ELMT_NM}</span>
</div>
</div>
)}
<div className="flex items-center space-x-2">
<Search className="h-4 w-4" />
<Input
placeholder="프로젝트 번호, WBS 요소, WBS 요소명으로 검색..."
value={globalFilter}
onChange={(e) => handleSearchChange(e.target.value)}
className="flex-1"
/>
</div>
{isPending ? (
<div className="flex justify-center py-8">
<div className="text-sm text-muted-foreground">WBS 코드를 불러오는 중...</div>
</div>
) : (
<div className="border rounded-md">
<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) => {
const isRowSelected = currentSelectedCode?.WBS_ELMT === row.original.WBS_ELMT &&
currentSelectedCode?.PROJ_NO === row.original.PROJ_NO
return (
<TableRow
key={row.id}
data-state={isRowSelected && "selected"}
className={`cursor-pointer hover:bg-muted/50 ${
isRowSelected ? 'bg-muted' : ''
}`}
onClick={() => handleCodeSelect(row.original)}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
))}
</TableRow>
)
})
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-24 text-center"
>
검색 결과가 없습니다.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
)}
<div className="flex items-center justify-between">
<div className="text-sm text-muted-foreground">
총 {table.getFilteredRowModel().rows.length}개 WBS 코드
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
size="sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
이전
</Button>
<div className="text-sm">
{table.getState().pagination.pageIndex + 1} / {table.getPageCount()}
</div>
<Button
variant="outline"
size="sm"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
다음
</Button>
</div>
</div>
</div>
{showConfirmButtons && (
<DialogFooter>
<Button variant="outline" onClick={handleCancel}>
<X className="h-4 w-4 mr-2" />
취소
</Button>
<Button onClick={handleConfirm} disabled={!tempSelectedCode}>
<Check className="h-4 w-4 mr-2" />
확인
</Button>
</DialogFooter>
)}
</DialogContent>
</Dialog>
)
}
|