summaryrefslogtreecommitdiff
path: root/lib/rfq-last/table/rfq-table.tsx
blob: 46bb46701cde6acdb571c1788c8c213c641c5f42 (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
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
"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 { RfqFilterSheet } from "./rfq-filter-sheet";
import { getRfqColumns } from "./rfq-table-columns";
import { RfqsLastView } from "@/db/schema";
import { getRfqs } from "../service";
import { RfqTableToolbarActions } from "./rfq-table-toolbar-actions";
import { RfqAttachmentsDialog } from "./rfq-attachments-dialog";
import { RfqItemsDialog } from "../shared/rfq-items-dialog";

interface RfqTableProps {
    data: Awaited<ReturnType<typeof getRfqs>>;
    rfqCategory?:  "general" | "itb" | "rfq";
  className?: string;
}

export function RfqTable({ 
    data, 
  rfqCategory = "itb",
  className 
}: RfqTableProps) {
  const router = useRouter();
  const searchParams = useSearchParams();
  
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<RfqsLastView> | null>(null);
  const [isFilterPanelOpen, setIsFilterPanelOpen] = React.useState(false);
  
  // 외부 필터 상태
  const [externalFilters, setExternalFilters] = React.useState<any[]>([]);
  const [externalJoinOperator, setExternalJoinOperator] = React.useState<"and" | "or">("and");

  // 필터 적용 핸들러
  const handleFiltersApply = React.useCallback((filters: any[], joinOperator: "and" | "or") => {
    console.log("=== 폼에서 필터 전달받음 ===", filters, joinOperator);
    setExternalFilters(filters);
    setExternalJoinOperator(joinOperator);
    setIsFilterPanelOpen(false);
  }, []);

  const searchString = React.useMemo(
    () => searchParams.toString(),
    [searchParams]
  );

  const getSearchParam = React.useCallback(
    (key: string, def = "") =>
      new URLSearchParams(searchString).get(key) ?? def,
    [searchString]
  );

  // 초기 데이터 설정
  const [tableData, setTableData] = React.useState(data);
  const [isDataLoading, setIsDataLoading] = React.useState(false);

  // URL 필터 변경 감지 및 데이터 새로고침
  React.useEffect(() => {
    const refetchData = async () => {
      try {
        setIsDataLoading(true);
        
        const currentFilters = getSearchParam("filters");
        const currentJoinOperator = getSearchParam("joinOperator", "and");
        const currentPage = parseInt(getSearchParam("page", "1"));
        const currentPerPage = parseInt(getSearchParam("perPage", "10"));
        const currentSort = getSearchParam('sort') ? JSON.parse(getSearchParam('sort')!) : [{ id: "createdAt", desc: true }];
        const currentSearch = getSearchParam("search", "");
        
        const searchParams = {
          filters: currentFilters ? JSON.parse(currentFilters) : [],
          joinOperator: currentJoinOperator as "and" | "or",
          page: currentPage,
          perPage: currentPerPage,
          sort: currentSort,
          search: currentSearch,
          rfqCategory: rfqCategory,
        };
        
        console.log("=== 새 데이터 요청 ===", searchParams);
        
        const newData = await getRfqs(searchParams);
        setTableData(newData);
        
        console.log("=== 데이터 업데이트 완료 ===", newData.data.length, "건");
      } catch (error) {
        console.error("데이터 새로고침 오류:", error);
      } finally {
        setIsDataLoading(false);
      }
    };

    const timeoutId = setTimeout(() => {
      const hasChanges = getSearchParam("filters") || 
                        getSearchParam("search") || 
                        getSearchParam("page") !== "1" || 
                        getSearchParam("perPage") !== "10" ||
                        getSearchParam("sort");
      
      if (hasChanges) {
        refetchData();
      }
    }, 300);

    return () => clearTimeout(timeoutId);
  }, [searchString, rfqCategory, getSearchParam]);

  const refreshData = React.useCallback(async () => {
    try {
      setIsDataLoading(true);
      
      const currentFilters = getSearchParam("filters");
      const currentJoinOperator = getSearchParam("joinOperator", "and");
      const currentPage = parseInt(getSearchParam("page", "1"));
      const currentPerPage = parseInt(getSearchParam("perPage", "10"));
      const currentSort = getSearchParam('sort') ? JSON.parse(getSearchParam('sort')!) : [{ id: "createdAt", desc: true }];
      const currentSearch = getSearchParam("search", "");
      
      const searchParams = {
        filters: currentFilters ? JSON.parse(currentFilters) : [],
        joinOperator: currentJoinOperator as "and" | "or",
        page: currentPage,
        perPage: currentPerPage,
        sort: currentSort,
        search: currentSearch,
        rfqCategory: rfqCategory,
      };
      
      const newData = await getRfqs(searchParams);
      setTableData(newData);
      
      console.log("=== 데이터 새로고침 완료 ===", newData.data.length, "건");
    } catch (error) {
      console.error("데이터 새로고침 오류:", error);
    } finally {
      setIsDataLoading(false);
    }
  }, [rfqCategory, getSearchParam]);

  // 컨테이너 위치 추적
  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;
      });
    }
  }, []);

  React.useEffect(() => {
    updateContainerBounds();
    
    const handleResize = () => {
      updateContainerBounds();
    };
    
    window.addEventListener('resize', handleResize);
    window.addEventListener('scroll', updateContainerBounds);
    
    return () => {
      window.removeEventListener('resize', handleResize);
      window.removeEventListener('scroll', updateContainerBounds);
    };
  }, [updateContainerBounds]);

  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: parseSearchParam("filters", []),
    joinOperator: (getSearchParam("joinOperator") as "and" | "or") || "and",
    search: getSearchParam("search", ""),
    columnVisibility: {},
    columnOrder: [],
    pinnedColumns: { left: [], right: ["actions"] },
    groupBy: [],
    expandedRows: []
  }), [getSearchParam, parseSearchParam]);

  // 탭별로 독립적인 tableId 사용 (정렬 상태 분리)
  const tableId = React.useMemo(() => `rfq-table-${rfqCategory}`, [rfqCategory]);

  const {
    presets,
    activePresetId,
    hasUnsavedChanges,
    isLoading: presetsLoading,
    createPreset,
    applyPreset,
    updatePreset,
    deletePreset,
    setDefaultPreset,
    renamePreset,
    getCurrentSettings,
  } = useTablePresets<RfqsLastView>(tableId, initialSettings);

  // 컬럼 정의
  const columns = React.useMemo(() => {
    return getRfqColumns({ 
      setRowAction,
      rfqCategory ,
      router
    });
  }, [rfqCategory, setRowAction, router]);

  const filterFields: DataTableFilterField<RfqsLastView>[] = [
    { id: "rfqCode", label: "견적 No." },
    { id: "projectName", label: "프로젝트명" },
    { id: "itemName", label: "자재명" },
    { id: "status", label: "상태" },
  ];

  const advancedFilterFields: DataTableAdvancedFilterField<RfqsLastView>[] = [
    { id: "rfqCode", label: "견적 No.", type: "text" },
    {
      id: "status",
      label: "견적상태",
      type: "select",
      options: [
        { label: "RFQ 생성", value: "RFQ 생성" },
        { label: "구매담당지정", value: "구매담당지정" },
        { label: "견적요청문서 확정", value: "견적요청문서 확정" },
        { label: "Short List 확정", value: "Short List 확정" },
        { label: "TBE 완료", value: "TBE 완료" },
        { label: "RFQ 발송", value: "RFQ 발송" },
        { label: "견적접수", value: "견적접수" },
        { label: "최종업체선정", value: "최종업체선정" },
      ]
    },
    { id: "projectCode", label: "프로젝트 코드", type: "text" },
    { id: "projectName", label: "프로젝트명", type: "text" },
    { id: "itemCode", label: "자재코드", type: "text" },
    { id: "itemName", label: "자재명", type: "text" },
    { id: "packageNo", label: "패키지 번호", type: "text" },
    { id: "picUserName", label: "구매담당자", type: "text" },
    { id: "vendorCount", label: "업체수", type: "number" },
    { id: "dueDate", label: "마감일", type: "date" },
    { id: "rfqSendDate", label: "발송일", type: "date" },
    ...(rfqCategory === "general"  ? [
      {
        id: "rfqType",
        label: "견적 유형",
        type: "select",
        options: [
          { label: "단가계약", value: "단가계약" },
          { label: "매각계약", value: "매각계약" },
          { label: "일반계약", value: "일반계약" },
        ]
      },
      { id: "rfqTitle", label: "견적 제목", type: "text" },
    ] as DataTableAdvancedFilterField<RfqsLastView>[] : []),
    ...(rfqCategory === "itb" ? [
      { id: "smCode", label: "SM 코드", type: "text" },
    ] as DataTableAdvancedFilterField<RfqsLastView>[] : []),
    ...(rfqCategory === "rfq" ? [
      { id: "prNumber", label: "PR 번호", type: "text" },
      { id: "prIssueDate", label: "PR 발행일", type: "date" },
      {
        id: "series",
        label: "시리즈",
        type: "select",
        options: [
          { label: "시리즈 통합", value: "SS" },
          { label: "품목 통합", value: "II" },
          { label: "통합 없음", value: "" },
        ]
      },
    ] as DataTableAdvancedFilterField<RfqsLastView>[] : []),
  ];

  const currentSettings = React.useMemo(() => getCurrentSettings(), [getCurrentSettings]);

  // 탭별로 독립적인 정렬 상태 관리
  // rfqCategory가 변경되면 정렬 상태를 재계산하여 탭 간 정렬 충돌 방지
  const initialState = React.useMemo(() => {
    // 현재 탭의 컬럼에 존재하는 정렬만 유효한 것으로 필터링
    const validSorting = initialSettings.sort.filter((s: any) => 
      columns.some((c: any) => ("accessorKey" in c ? c.accessorKey : c.id) === s.id)
    );
    
    // 유효한 정렬이 없으면 기본 정렬 사용
    const sorting = validSorting.length > 0 
      ? validSorting 
      : [{ id: "createdAt", desc: true }];
    
    return {
      sorting,
      columnVisibility: currentSettings.columnVisibility,
      columnPinning: currentSettings.pinnedColumns,
    };
  }, [columns, currentSettings, initialSettings.sort, rfqCategory]);

  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 getActiveFilterCount = React.useCallback(() => {
    try {
      const filtersParam = getSearchParam("filters");
      if (filtersParam) {
        const filters = JSON.parse(filtersParam);
        return Array.isArray(filters) ? filters.length : 0;
      }
      return 0;
    } catch {
      return 0;
    }
  }, [getSearchParam]);

  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)`
        }}
      >
        <RfqFilterSheet
          isOpen={isFilterPanelOpen}
          onClose={() => setIsFilterPanelOpen(false)}
          onFiltersApply={handleFiltersApply}
          rfqCategory={rfqCategory}
          isLoading={false}
        />
      </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" />}
                  {getActiveFilterCount() > 0 && (
                    <span className="ml-2 bg-primary text-primary-foreground rounded-full px-2 py-0.5 text-xs">
                      {getActiveFilterCount()}
                    </span>
                  )}
                </Button>

              
                  <Badge variant="outline" className="text-sm">
                    {rfqCategory === "general" ? "일반견적" : 
                     rfqCategory === "itb" ? "ITB" : "RFQ"}
                  </Badge>
           
              </div>

              <div className="flex items-center gap-4">
                <div className="text-sm text-muted-foreground">
                  {tableData && (
                    <span>총 {tableData.total || tableData.data.length}건</span>
                  )}
                </div>
              </div>
            </div>

            {/* Table Content Area */}
            <div className="flex-1 overflow-hidden relative" style={{ height: 'calc(100vh - 200px)' }}>
              {isDataLoading && (
                <div className="absolute inset-0 bg-background/50 backdrop-blur-sm z-10 flex items-center justify-center">
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <div className="w-4 h-4 border-2 border-primary border-t-transparent rounded-full animate-spin" />
                    필터링 중...
                  </div>
                </div>
              )}
              <div className="h-full w-full">
                <DataTable table={table} className="h-full">
                  <DataTableAdvancedToolbar
                    table={table}
                    filterFields={advancedFilterFields}
                    debounceMs={300}
                    shallow={false}
                    externalFilters={externalFilters}
                    externalJoinOperator={externalJoinOperator}
                    onFiltersChange={(filters, joinOperator) => {
                      console.log("=== 필터 변경 감지 ===", filters, joinOperator);
                    }}
                  >
                    <div className="flex items-center gap-2">
                      <TablePresetManager<RfqsLastView>
                        presets={presets}
                        activePresetId={activePresetId}
                        currentSettings={currentSettings}
                        hasUnsavedChanges={hasUnsavedChanges}
                        isLoading={presetsLoading}
                        onCreatePreset={createPreset}
                        onUpdatePreset={updatePreset}
                        onDeletePreset={deletePreset}
                        onApplyPreset={applyPreset}
                        onSetDefaultPreset={setDefaultPreset}
                        onRenamePreset={renamePreset}
                      />

                      <RfqTableToolbarActions 
                        table={table} 
                        rfqCategory={rfqCategory}
                        onRefresh={refreshData}
                      />
                    </div>
                  </DataTableAdvancedToolbar>
                </DataTable>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 다이얼로그들 */}
      {rowAction?.type === "attachment" && (
        <RfqAttachmentsDialog
          isOpen={true}
          onClose={() => setRowAction(null)}
          rfqData={rowAction.row.original}
        />
      )}

      {rowAction?.type === "items" && (
        <RfqItemsDialog
          isOpen={true}
          onClose={() => setRowAction(null)}
          rfqData={rowAction.row.original}
          viewerType="evcp"
        />
      )}
    </>
  );
}