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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
|
"use client"
import * as React from "react"
import { useSearchParams } from "next/navigation"
import { Button } from "@/components/ui/button"
import { PanelLeftClose, PanelLeftOpen } from "lucide-react"
import type {
DataTableAdvancedFilterField,
DataTableRowAction,
} from "@/types/table"
import {
ResizablePanelGroup,
ResizablePanel,
ResizableHandle,
} from "@/components/ui/resizable"
import { useDataTable } from "@/hooks/use-data-table"
import { DataTable } from "@/components/data-table/data-table"
import { getColumns } from "./rfq-table-column"
import { useEffect, useMemo } from "react"
import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"
import { RFQTableToolbarActions } from "./rfq-table-toolbar-actions"
import { getTechSalesRfqsWithJoin, getTechSalesRfqAttachments } from "@/lib/techsales-rfq/service"
import { toast } from "sonner"
import { useTablePresets } from "@/components/data-table/use-table-presets"
import { TablePresetManager } from "@/components/data-table/data-table-preset"
import { RfqDetailTables } from "./detail-table/rfq-detail-table"
import { cn } from "@/lib/utils"
import { ProjectDetailDialog } from "./project-detail-dialog"
import { RFQFilterSheet } from "./rfq-filter-sheet"
import { TechSalesRfqAttachmentsSheet, ExistingTechSalesAttachment } from "./tech-sales-rfq-attachments-sheet"
// 기본적인 RFQ 타입 정의 (repository selectTechSalesRfqsWithJoin 반환 타입에 맞춤)
interface TechSalesRfq {
id: number
rfqCode: string | null
itemId: number
itemName: string | null
materialCode: string | null
dueDate: Date
rfqSendDate: Date | null
status: "RFQ Created" | "RFQ Vendor Assignned" | "RFQ Sent" | "Quotation Analysis" | "Closed"
picCode: string | null
remark: string | null
cancelReason: string | null
createdAt: Date
updatedAt: Date
createdBy: number | null
createdByName: string
updatedBy: number | null
updatedByName: string
sentBy: number | null
sentByName: string | null
projectSnapshot: Record<string, unknown>
seriesSnapshot: Record<string, unknown>
pspid: string
projNm: string
sector: string
projMsrm: number
ptypeNm: string
attachmentCount: number
quotationCount: number
// 필요에 따라 다른 필드들 추가
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: unknown
}
interface RFQListTableProps {
promises: Promise<[Awaited<ReturnType<typeof getTechSalesRfqsWithJoin>>]>
className?: string;
calculatedHeight?: string; // 계산된 높이 추가
}
export function RFQListTable({
promises,
className,
calculatedHeight
}: RFQListTableProps) {
const searchParams = useSearchParams()
// 필터 패널 상태
const [isFilterPanelOpen, setIsFilterPanelOpen] = React.useState(false)
// 선택된 RFQ 상태
const [selectedRfq, setSelectedRfq] = React.useState<TechSalesRfq | null>(null)
// 프로젝트 상세정보 다이얼로그 상태
const [isProjectDetailOpen, setIsProjectDetailOpen] = React.useState(false)
const [projectDetailRfq, setProjectDetailRfq] = React.useState<TechSalesRfq | null>(null)
// 첨부파일 시트 상태
const [attachmentsOpen, setAttachmentsOpen] = React.useState(false)
const [selectedRfqForAttachments, setSelectedRfqForAttachments] = React.useState<TechSalesRfq | null>(null)
const [attachmentsDefault, setAttachmentsDefault] = React.useState<ExistingTechSalesAttachment[]>([])
// 패널 collapse 상태
const [panelHeight, setPanelHeight] = React.useState<number>(55)
// 고정 높이 설정을 위한 상수 (실제 측정값으로 조정 필요)
const LAYOUT_HEADER_HEIGHT = 64 // Layout Header 높이
const LAYOUT_FOOTER_HEIGHT = 60 // Layout Footer 높이 (있다면 실제 값)
const LOCAL_HEADER_HEIGHT = 72 // 로컬 헤더 바 높이 (p-4 + border)
const FILTER_PANEL_WIDTH = 400 // 필터 패널 너비
// 높이 계산
// 필터 패널 높이 - Layout Header와 Footer 사이
const FIXED_FILTER_HEIGHT = `calc(100vh - ${LAYOUT_HEADER_HEIGHT*2}px)`
console.log(calculatedHeight)
// 테이블 컨텐츠 높이 - 전달받은 높이에서 로컬 헤더 제외
const FIXED_TABLE_HEIGHT = calculatedHeight
? `calc(${calculatedHeight} - ${LOCAL_HEADER_HEIGHT}px)`
: `calc(100vh - ${LAYOUT_HEADER_HEIGHT + LAYOUT_FOOTER_HEIGHT + LOCAL_HEADER_HEIGHT+76}px)` // fallback
// Suspense 방식으로 데이터 처리
const [promiseData] = React.use(promises)
const tableData = promiseData
const [rowAction, setRowAction] = React.useState<DataTableRowAction<TechSalesRfq> | null>(null)
// 초기 설정 정의
const initialSettings = React.useMemo(() => ({
page: parseInt(searchParams?.get('page') || '1'),
perPage: parseInt(searchParams?.get('perPage') || '10'),
sort: searchParams?.get('sort') ? JSON.parse(searchParams.get('sort')!) : [{ id: "updatedAt", desc: true }],
filters: searchParams?.get('filters') ? JSON.parse(searchParams.get('filters')!) : [],
joinOperator: (searchParams?.get('joinOperator') as "and" | "or") || "and",
basicFilters: searchParams?.get('basicFilters') ? JSON.parse(searchParams.get('basicFilters')!) : [],
basicJoinOperator: (searchParams?.get('basicJoinOperator') as "and" | "or") || "and",
search: searchParams?.get('search') || '',
from: searchParams?.get('from') || undefined,
to: searchParams?.get('to') || undefined,
columnVisibility: {},
columnOrder: [],
pinnedColumns: { left: [], right: [] },
groupBy: [],
expandedRows: []
}), [searchParams])
// DB 기반 프리셋 훅 사용
const {
presets,
activePresetId,
hasUnsavedChanges,
isLoading: presetsLoading,
createPreset,
applyPreset,
updatePreset,
deletePreset,
setDefaultPreset,
renamePreset,
getCurrentSettings,
} = useTablePresets<TechSalesRfq>('rfq-list-table', initialSettings)
// 조회 버튼 클릭 핸들러
const handleSearch = () => {
setIsFilterPanelOpen(false)
}
// 행 액션 처리
useEffect(() => {
if (rowAction) {
switch (rowAction.type) {
case "select":
// 객체 참조 안정화를 위해 필요한 필드만 추출
const rfqData = rowAction.row.original;
setSelectedRfq({
id: rfqData.id,
rfqCode: rfqData.rfqCode,
itemId: rfqData.itemId,
itemName: rfqData.itemName,
materialCode: rfqData.materialCode,
dueDate: rfqData.dueDate,
rfqSendDate: rfqData.rfqSendDate,
status: rfqData.status,
picCode: rfqData.picCode,
remark: rfqData.remark,
cancelReason: rfqData.cancelReason,
createdAt: rfqData.createdAt,
updatedAt: rfqData.updatedAt,
createdBy: rfqData.createdBy,
createdByName: rfqData.createdByName,
updatedBy: rfqData.updatedBy,
updatedByName: rfqData.updatedByName,
sentBy: rfqData.sentBy,
sentByName: rfqData.sentByName,
projectSnapshot: rfqData.projectSnapshot,
seriesSnapshot: rfqData.seriesSnapshot,
pspid: rfqData.pspid,
projNm: rfqData.projNm,
sector: rfqData.sector,
projMsrm: rfqData.projMsrm,
ptypeNm: rfqData.ptypeNm,
attachmentCount: rfqData.attachmentCount,
quotationCount: rfqData.quotationCount,
});
break;
case "view":
// 프로젝트 상세정보 다이얼로그 열기
const projectRfqData = rowAction.row.original;
setProjectDetailRfq({
id: projectRfqData.id,
rfqCode: projectRfqData.rfqCode,
itemId: projectRfqData.itemId,
itemName: projectRfqData.itemName,
materialCode: projectRfqData.materialCode,
dueDate: projectRfqData.dueDate,
rfqSendDate: projectRfqData.rfqSendDate,
status: projectRfqData.status,
picCode: projectRfqData.picCode,
remark: projectRfqData.remark,
cancelReason: projectRfqData.cancelReason,
createdAt: projectRfqData.createdAt,
updatedAt: projectRfqData.updatedAt,
createdBy: projectRfqData.createdBy,
createdByName: projectRfqData.createdByName,
updatedBy: projectRfqData.updatedBy,
updatedByName: projectRfqData.updatedByName,
sentBy: projectRfqData.sentBy,
sentByName: projectRfqData.sentByName,
projectSnapshot: projectRfqData.projectSnapshot || {},
seriesSnapshot: projectRfqData.seriesSnapshot || {},
pspid: projectRfqData.pspid,
projNm: projectRfqData.projNm,
sector: projectRfqData.sector,
projMsrm: projectRfqData.projMsrm,
ptypeNm: projectRfqData.ptypeNm,
attachmentCount: projectRfqData.attachmentCount,
quotationCount: projectRfqData.quotationCount,
});
setIsProjectDetailOpen(true);
break;
case "update":
console.log("Update rfq:", rowAction.row.original)
break;
case "delete":
console.log("Delete rfq:", rowAction.row.original)
break;
}
setRowAction(null)
}
}, [rowAction])
// 첨부파일 시트 열기 함수
const openAttachmentsSheet = React.useCallback(async (rfqId: number) => {
try {
// 선택된 RFQ 찾기
const rfq = tableData?.data?.find(r => r.id === rfqId)
if (!rfq) {
toast.error("RFQ를 찾을 수 없습니다.")
return
}
// 실제 첨부파일 목록 조회 API 호출
const result = await getTechSalesRfqAttachments(rfqId)
if (result.error) {
toast.error(result.error)
return
}
// API 응답을 ExistingTechSalesAttachment 형식으로 변환
const attachments: ExistingTechSalesAttachment[] = result.data.map(att => ({
id: att.id,
techSalesRfqId: att.techSalesRfqId || rfqId, // null인 경우 rfqId 사용
fileName: att.fileName,
originalFileName: att.originalFileName,
filePath: att.filePath,
fileSize: att.fileSize || undefined,
fileType: att.fileType || undefined,
attachmentType: att.attachmentType as "RFQ_COMMON" | "VENDOR_SPECIFIC",
description: att.description || undefined,
createdBy: att.createdBy,
createdAt: att.createdAt,
}))
setAttachmentsDefault(attachments)
setSelectedRfqForAttachments({
...rfq,
projectSnapshot: rfq.projectSnapshot || {},
seriesSnapshot: rfq.seriesSnapshot || {},
})
setAttachmentsOpen(true)
} catch (error) {
console.error("첨부파일 조회 오류:", error)
toast.error("첨부파일 조회 중 오류가 발생했습니다.")
}
}, [tableData?.data])
// 첨부파일 업데이트 콜백
const handleAttachmentsUpdated = React.useCallback((rfqId: number, newAttachmentCount: number) => {
// TODO: 실제로는 테이블 데이터를 다시 조회하거나 상태를 업데이트해야 함
// 현재는 로그만 출력하고 토스트 메시지로 피드백 제공
console.log(`RFQ ${rfqId}의 첨부파일 개수가 ${newAttachmentCount}개로 업데이트됨`)
// 성공 피드백 (중복되지 않도록 짧은 지연 후 표시)
setTimeout(() => {
toast.success(`첨부파일 개수가 업데이트되었습니다. (${newAttachmentCount}개)`, {
duration: 3000
})
}, 500)
// TODO: 나중에 실제 테이블 데이터 업데이트 로직 구현
// 예: setTableData() 또는 데이터 재조회
}, [])
const columns = React.useMemo(
() => getColumns({
setRowAction,
openAttachmentsSheet
}),
[openAttachmentsSheet]
)
// 고급 필터 필드 정의
const advancedFilterFields: DataTableAdvancedFilterField<TechSalesRfq>[] = [
{
id: "rfqCode",
label: "RFQ No.",
type: "text",
},
{
id: "materialCode",
label: "자재코드",
type: "text",
},
{
id: "itemName",
label: "자재명",
type: "text",
},
{
id: "projNm",
label: "프로젝트명",
type: "text",
},
{
id: "ptypeNm",
label: "선종명",
type: "text",
},
{
id: "rfqSendDate",
label: "RFQ 전송일",
type: "date",
},
{
id: "dueDate",
label: "RFQ 마감일",
type: "date",
},
{
id: "createdByName",
label: "요청자",
type: "text",
},
{
id: "status",
label: "상태",
type: "text",
},
]
// 현재 설정 가져오기
const currentSettings = useMemo(() => {
return getCurrentSettings()
}, [getCurrentSettings])
// useDataTable 초기 상태 설정
const initialState = useMemo(() => {
return {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
sorting: initialSettings.sort.filter((sortItem: any) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const columnExists = columns.some((col: any) => col.accessorKey === sortItem.id)
return columnExists
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}) as any,
columnVisibility: currentSettings.columnVisibility,
columnPinning: currentSettings.pinnedColumns,
}
}, [currentSettings, initialSettings.sort, columns])
// useDataTable 훅 설정
const { table } = useDataTable({
data: tableData?.data || [],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
columns: columns as any,
pageCount: tableData?.pageCount || 0,
rowCount: tableData?.total || 0,
filterFields: [],
enablePinning: true,
enableAdvancedFilter: true,
initialState,
getRowId: (originalRow) => String(originalRow.id),
shallow: false,
clearOnDefault: true,
columnResizeMode: "onEnd",
})
// Get active basic filter count
const getActiveBasicFilterCount = () => {
try {
const basicFilters = searchParams?.get('basicFilters')
return basicFilters ? JSON.parse(basicFilters).length : 0
} catch {
return 0
}
}
console.log(panelHeight)
return (
<div
className={cn("flex flex-col relative", className)}
style={{ height: calculatedHeight }}
>
{/* Filter Panel - 계산된 높이 적용 */}
<div
className={cn(
"fixed left-0 bg-background border-r z-30 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: `${LAYOUT_HEADER_HEIGHT*2}px`,
height: FIXED_FILTER_HEIGHT
}}
>
{/* Filter Content */}
<div className="h-full">
<RFQFilterSheet
isOpen={isFilterPanelOpen}
onClose={() => setIsFilterPanelOpen(false)}
onSearch={handleSearch}
isLoading={false}
/>
</div>
</div>
{/* Main Content */}
<div
className="flex flex-col transition-all duration-300 ease-in-out"
style={{
width: isFilterPanelOpen ? `calc(100% - ${FILTER_PANEL_WIDTH}px)` : '100%',
marginLeft: isFilterPanelOpen ? `${FILTER_PANEL_WIDTH}px` : '0px',
height: '100%'
}}
>
{/* Header Bar - 고정 높이 */}
<div
className="flex items-center justify-between p-4 bg-background border-b"
style={{
height: `${LOCAL_HEADER_HEIGHT}px`,
flexShrink: 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>
{/* Right side info */}
<div className="text-sm text-muted-foreground">
{tableData && (
<span>총 {tableData.total || 0}건</span>
)}
</div>
</div>
{/* Table Content Area - 계산된 높이 사용 */}
<div
className="relative bg-background"
style={{
height: FIXED_TABLE_HEIGHT,
display: 'grid',
gridTemplateRows: '1fr',
gridTemplateColumns: '1fr'
}}
>
<ResizablePanelGroup
direction="vertical"
className="w-full h-full"
>
<ResizablePanel
defaultSize={60}
minSize={25}
maxSize={75}
collapsible={false}
onResize={(size) => {
setPanelHeight(size)
}}
className="flex flex-col overflow-hidden"
>
{/* 상단 테이블 영역 */}
<div className="flex-1 min-h-0 overflow-hidden">
<DataTable
table={table}
maxHeight={`${panelHeight*0.5}vh`}
>
<DataTableAdvancedToolbar
// eslint-disable-next-line @typescript-eslint/no-explicit-any
table={table as any}
filterFields={advancedFilterFields}
shallow={false}
>
<div className="flex items-center gap-2">
<TablePresetManager<TechSalesRfq>
presets={presets}
activePresetId={activePresetId}
currentSettings={currentSettings}
hasUnsavedChanges={hasUnsavedChanges}
isLoading={presetsLoading}
onCreatePreset={createPreset}
onUpdatePreset={updatePreset}
onDeletePreset={deletePreset}
onApplyPreset={applyPreset}
onSetDefaultPreset={setDefaultPreset}
onRenamePreset={renamePreset}
/>
<RFQTableToolbarActions
selection={table}
onRefresh={() => {}}
/>
</div>
</DataTableAdvancedToolbar>
</DataTable>
</div>
</ResizablePanel>
<ResizableHandle withHandle />
<ResizablePanel
minSize={25}
defaultSize={40}
collapsible={false}
className="flex flex-col overflow-hidden"
>
{/* 하단 상세 테이블 영역 */}
<div className="flex-1 min-h-0 overflow-hidden bg-background">
<RfqDetailTables selectedRfq={selectedRfq} maxHeight={`${(100-panelHeight)*0.4}vh`}/>
</div>
</ResizablePanel>
</ResizablePanelGroup>
</div>
</div>
{/* 프로젝트 상세정보 다이얼로그 */}
<ProjectDetailDialog
open={isProjectDetailOpen}
onOpenChange={setIsProjectDetailOpen}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
selectedRfq={projectDetailRfq as any}
/>
{/* 첨부파일 관리 시트 */}
<TechSalesRfqAttachmentsSheet
open={attachmentsOpen}
onOpenChange={setAttachmentsOpen}
defaultAttachments={attachmentsDefault}
rfq={selectedRfqForAttachments}
onAttachmentsUpdated={handleAttachmentsUpdated}
/>
</div>
)
}
|