summaryrefslogtreecommitdiff
path: root/lib/incoterms/table/incoterms-table.tsx
blob: c98de81081f3a0be5c8b3e7377587f6262d063e1 (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
"use client";
import * as React from "react";
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 type {
  DataTableAdvancedFilterField,
  DataTableRowAction,
} from "@/types/table"
import { getIncoterms } from "../service";
import { getColumns } from "./incoterms-table-columns";
import { DeleteIncotermsDialog } from "./delete-incoterms-dialog";
import { IncotermsEditSheet } from "./incoterms-edit-sheet";
import { IncotermsTableToolbarActions } from "./incoterms-table-toolbar";
import { incoterms } from "@/db/schema/procurementRFQ";

interface IncotermsTableProps {
  promises?: Promise<[{ data: typeof incoterms.$inferSelect[]; pageCount: number }] >;
}

export function IncotermsTable({ promises }: IncotermsTableProps) {
  const [rawData, setRawData] = React.useState<{ data: typeof incoterms.$inferSelect[]; pageCount: number }>({ data: [], pageCount: 0 });
  const [rowAction, setRowAction] = React.useState<DataTableRowAction<typeof incoterms.$inferSelect> | null>(null);

  React.useEffect(() => {
    if (promises) {
      promises.then(([result]) => {
        setRawData(result);
      });
    } else {
      // fallback: 클라이언트에서 직접 fetch (CSR)
      (async () => {
        try {
          const result = await getIncoterms({
            page: 1,
            perPage: 10,
            search: "",
            sort: [{ id: "createdAt", desc: true }],
            filters: [],
            joinOperator: "and",
            flags: ["advancedTable"],
            code: "",
            description: "",
            isActive: ""
          });
          setRawData(result);
        } catch (error) {
          console.error("Error refreshing data:", error);
        }
      })();
    }
  }, [promises]);

  const refreshData = React.useCallback(async () => {
    try {
      const result = await getIncoterms({
        page: 1,
        perPage: 10,
        search: "",
        sort: [{ id: "createdAt", desc: true }],
        filters: [],
        joinOperator: "and",
        flags: ["advancedTable"],
        code: "",
        description: "",
        isActive: ""
      });
      setRawData(result);
    } catch (error) {
      console.error("Error refreshing data:", error);
    }
  }, []);

  // 컬럼 설정 - 외부 파일에서 가져옴
  const columns = React.useMemo(
    () => getColumns({ setRowAction }),
    [setRowAction]
  )

  // 고급 필터 필드 설정
  const advancedFilterFields: DataTableAdvancedFilterField<typeof incoterms.$inferSelect>[] = [
    { id: "code", label: "코드", type: "text" },
    {
      id: "isActive", label: "상태", type: "select", options: [
        { label: "활성", value: "true" },
        { label: "비활성", value: "false" },
      ]
    },
    { id: "description", label: "설명", type: "text" },
    { id: "createdAt", label: "생성일", type: "date" },
  ];

  const { table } = useDataTable({
      data: rawData.data,
      columns,
      pageCount: rawData.pageCount,
      enablePinning: true,
      enableAdvancedFilter: true,
      initialState: {
        sorting: [{ id: "createdAt", desc: true }],
        columnPinning: { right: ["actions"] },
      },
      getRowId: (originalRow) => String(originalRow.code),
      shallow: false,
      clearOnDefault: true,
    })

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
        >
          <IncotermsTableToolbarActions table={table} onSuccess={refreshData} />
        </DataTableAdvancedToolbar>
      </DataTable>

      <DeleteIncotermsDialog
        open={rowAction?.type === "delete"}
        onOpenChange={() => setRowAction(null)}
        incoterms={rowAction?.row.original ? [rowAction?.row.original] : []}
        showTrigger={false}
        onSuccess={() => {
          rowAction?.row.toggleSelected(false)
          refreshData()
        }}
      />

      <IncotermsEditSheet
        open={rowAction?.type === "update"}
        onOpenChange={() => setRowAction(null)}
        data={rowAction?.row.original ?? null}
        onSuccess={refreshData}
      />
    </>
  );
}