From 1a2241c40e10193c5ff7008a7b7b36cc1d855d96 Mon Sep 17 00:00:00 2001 From: joonhoekim <26rote@gmail.com> Date: Tue, 25 Mar 2025 15:55:45 +0900 Subject: initial commit --- lib/form-list/table/feature-flags-provider.tsx | 108 +++++++++ lib/form-list/table/formLists-table-columns.tsx | 132 +++++++++++ .../table/formLists-table-toolbar-actions.tsx | 53 +++++ lib/form-list/table/formLists-table.tsx | 151 +++++++++++++ lib/form-list/table/meta-sheet.tsx | 245 +++++++++++++++++++++ 5 files changed, 689 insertions(+) create mode 100644 lib/form-list/table/feature-flags-provider.tsx create mode 100644 lib/form-list/table/formLists-table-columns.tsx create mode 100644 lib/form-list/table/formLists-table-toolbar-actions.tsx create mode 100644 lib/form-list/table/formLists-table.tsx create mode 100644 lib/form-list/table/meta-sheet.tsx (limited to 'lib/form-list/table') diff --git a/lib/form-list/table/feature-flags-provider.tsx b/lib/form-list/table/feature-flags-provider.tsx new file mode 100644 index 00000000..81131894 --- /dev/null +++ b/lib/form-list/table/feature-flags-provider.tsx @@ -0,0 +1,108 @@ +"use client" + +import * as React from "react" +import { useQueryState } from "nuqs" + +import { dataTableConfig, type DataTableConfig } from "@/config/data-table" +import { cn } from "@/lib/utils" +import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group" +import { + Tooltip, + TooltipContent, + TooltipTrigger, +} from "@/components/ui/tooltip" + +type FeatureFlagValue = DataTableConfig["featureFlags"][number]["value"] + +interface FeatureFlagsContextProps { + featureFlags: FeatureFlagValue[] + setFeatureFlags: (value: FeatureFlagValue[]) => void +} + +const FeatureFlagsContext = React.createContext({ + featureFlags: [], + setFeatureFlags: () => {}, +}) + +export function useFeatureFlags() { + const context = React.useContext(FeatureFlagsContext) + if (!context) { + throw new Error( + "useFeatureFlags must be used within a FeatureFlagsProvider" + ) + } + return context +} + +interface FeatureFlagsProviderProps { + children: React.ReactNode +} + +export function FeatureFlagsProvider({ children }: FeatureFlagsProviderProps) { + const [featureFlags, setFeatureFlags] = useQueryState( + "flags", + { + defaultValue: [], + parse: (value) => value.split(",") as FeatureFlagValue[], + serialize: (value) => value.join(","), + eq: (a, b) => + a.length === b.length && a.every((value, index) => value === b[index]), + clearOnDefault: true, + shallow: false, + } + ) + + return ( + void setFeatureFlags(value), + }} + > +
+ setFeatureFlags(value)} + className="w-fit gap-0" + > + {dataTableConfig.featureFlags.map((flag, index) => ( + + + + + + +
{flag.tooltipTitle}
+
+ {flag.tooltipDescription} +
+
+
+ ))} +
+
+ {children} +
+ ) +} diff --git a/lib/form-list/table/formLists-table-columns.tsx b/lib/form-list/table/formLists-table-columns.tsx new file mode 100644 index 00000000..f638c4df --- /dev/null +++ b/lib/form-list/table/formLists-table-columns.tsx @@ -0,0 +1,132 @@ +"use client" + +import * as React from "react" +import { type DataTableRowAction } from "@/types/table" +import { type ColumnDef } from "@tanstack/react-table" +import { InfoIcon } from "lucide-react" + +import { formatDate } from "@/lib/utils" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, +} from "@/components/ui/tooltip" + +import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header" +import { formListsColumnsConfig } from "@/config/formListsColumnsConfig" +import { TagTypeClassFormMappings } from "@/db/schema/vendorData" + +interface GetColumnsProps { + setRowAction: React.Dispatch | null>> +} + +/** + * tanstack table 컬럼 정의 (중첩 헤더 버전) + */ +export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef[] { + // ---------------------------------------------------------------- + // 1) select 컬럼 (체크박스) + // ---------------------------------------------------------------- + + + // ---------------------------------------------------------------- + // 2) actions 컬럼 (단일 버튼 - Meta Info 바로 보기) + // ---------------------------------------------------------------- + const actionsColumn: ColumnDef = { + id: "actions", + enableHiding: false, + cell: function Cell({ row }) { + return ( + + + + + + + View Meta Info + + + + ) + }, + size: 40, + } + + // ---------------------------------------------------------------- + // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성 + // ---------------------------------------------------------------- + // 3-1) groupMap: { [groupName]: ColumnDef[] } + const groupMap: Record[]> = {} + + formListsColumnsConfig.forEach((cfg) => { + // 만약 group가 없으면 "_noGroup" 처리 + const groupName = cfg.group || "_noGroup" + + if (!groupMap[groupName]) { + groupMap[groupName] = [] + } + + // child column 정의 + const childCol: ColumnDef = { + accessorKey: cfg.id, + enableResizing: true, + header: ({ column }) => ( + + ), + meta: { + excelHeader: cfg.excelHeader, + group: cfg.group, + type: cfg.type, + }, + cell: ({ row, cell }) => { + + if (cfg.id === "createdAt"||cfg.id === "updatedAt") { + const dateVal = cell.getValue() as Date + return formatDate(dateVal) + } + + return row.getValue(cfg.id) ?? "" + }, + } + + groupMap[groupName].push(childCol) + }) + + // ---------------------------------------------------------------- + // 3-2) groupMap에서 실제 상위 컬럼(그룹)을 만들기 + // ---------------------------------------------------------------- + const nestedColumns: ColumnDef[] = [] + + // 순서를 고정하고 싶다면 group 순서를 미리 정의하거나 sort해야 함 + // 여기서는 그냥 Object.entries 순서 + Object.entries(groupMap).forEach(([groupName, colDefs]) => { + if (groupName === "_noGroup") { + // 그룹 없음 → 그냥 최상위 레벨 컬럼 + nestedColumns.push(...colDefs) + } else { + // 상위 컬럼 + nestedColumns.push({ + id: groupName, + header: groupName, // "Basic Info", "Metadata" 등 + columns: colDefs, + }) + } + }) + + // ---------------------------------------------------------------- + // 4) 최종 컬럼 배열: select, nestedColumns, actions + // ---------------------------------------------------------------- + return [ + ...nestedColumns, + actionsColumn, + ] +} \ No newline at end of file diff --git a/lib/form-list/table/formLists-table-toolbar-actions.tsx b/lib/form-list/table/formLists-table-toolbar-actions.tsx new file mode 100644 index 00000000..346a3980 --- /dev/null +++ b/lib/form-list/table/formLists-table-toolbar-actions.tsx @@ -0,0 +1,53 @@ +"use client" + +import * as React from "react" +import { type Table } from "@tanstack/react-table" +import { Download, RefreshCcw, Upload } from "lucide-react" +import { toast } from "sonner" + +import { exportTableToExcel } from "@/lib/export" +import { Button } from "@/components/ui/button" +import { TagTypeClassFormMappings } from "@/db/schema/vendorData" + + + +interface ItemsTableToolbarActionsProps { + table: Table +} + +export function FormListsTableToolbarActions({ table }: ItemsTableToolbarActionsProps) { + // 파일 input을 숨기고, 버튼 클릭 시 참조해 클릭하는 방식 + const fileInputRef = React.useRef(null) + + + + return ( +
+ {/** 4) Export 버튼 */} + + + {/** 4) Export 버튼 */} + +
+ ) +} \ No newline at end of file diff --git a/lib/form-list/table/formLists-table.tsx b/lib/form-list/table/formLists-table.tsx new file mode 100644 index 00000000..be252655 --- /dev/null +++ b/lib/form-list/table/formLists-table.tsx @@ -0,0 +1,151 @@ +"use client" + +import * as React from "react" +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 { useFeatureFlags } from "./feature-flags-provider" + +import { TagTypeClassFormMappings } from "@/db/schema/vendorData" +import { getFormLists } from "../service" +import { getColumns } from "./formLists-table-columns" +import { FormListsTableToolbarActions } from "./formLists-table-toolbar-actions" +import { ViewMetas } from "./meta-sheet" + +interface ItemsTableProps { + promises: Promise< + [ + Awaited>, + ] + > +} + +export function FormListsTable({ promises }: ItemsTableProps) { + const { featureFlags } = useFeatureFlags() + + const [{ data, pageCount }] = + React.use(promises) + + + const [rowAction, setRowAction] = + React.useState | null>(null) + + const columns = React.useMemo( + () => getColumns({ setRowAction }), + [setRowAction] + ) + + /** + * This component can render either a faceted filter or a search filter based on the `options` prop. + * + * @prop options - An array of objects, each representing a filter option. If provided, a faceted filter is rendered. If not, a search filter is rendered. + * + * Each `option` object has the following properties: + * @prop {string} label - The label for the filter option. + * @prop {string} value - The value for the filter option. + * @prop {React.ReactNode} [icon] - An optional icon to display next to the label. + * @prop {boolean} [withCount] - An optional boolean to display the count of the filter option. + */ + const filterFields: DataTableFilterField[] = [ + + + ] + + /** + * Advanced filter fields for the data table. + * These fields provide more complex filtering options compared to the regular filterFields. + * + * Key differences from regular filterFields: + * 1. More field types: Includes 'text', 'multi-select', 'date', and 'boolean'. + * 2. Enhanced flexibility: Allows for more precise and varied filtering options. + * 3. Used with DataTableAdvancedToolbar: Enables a more sophisticated filtering UI. + * 4. Date and boolean types: Adds support for filtering by date ranges and boolean values. + */ + const advancedFilterFields: DataTableAdvancedFilterField[] = [ + { + id: "formCode", + label: "Form Code", + type: "text", + + }, + { + id: "formName", + label: "Form Name", + type: "text", + + }, + { + id: "tagTypeLabel", + label: "Tag Type", + type: "text", + + }, + { + id: "classLabel", + label: "Class", + type: "text", + + }, + + { + id: "createdAt", + label: "Created At", + type: "date", + + }, + { + id: "updatedAt", + label: "Updated At", + type: "date", + + }, + ] + + + const { table } = useDataTable({ + data, + columns, + pageCount, + filterFields, + enablePinning: true, + enableAdvancedFilter: true, + initialState: { + sorting: [{ id: "createdAt", desc: true }], + columnPinning: { right: ["actions"] }, + }, + getRowId: (originalRow) => String(originalRow.id), + shallow: false, + clearOnDefault: true, + }) + + return ( + <> + + + + + + + + setRowAction(null)} + form={rowAction?.row.original ?? null} + /> + + + ) +} diff --git a/lib/form-list/table/meta-sheet.tsx b/lib/form-list/table/meta-sheet.tsx new file mode 100644 index 00000000..155e4f5a --- /dev/null +++ b/lib/form-list/table/meta-sheet.tsx @@ -0,0 +1,245 @@ +"use client" + +import * as React from "react" +import { useMemo } from "react" +import { Badge } from "@/components/ui/badge" +import { + Sheet, + SheetContent, + SheetDescription, + SheetHeader, + SheetTitle +} from "@/components/ui/sheet" +import { + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow +} from "@/components/ui/table" +import { + Tabs, + TabsContent, + TabsList, + TabsTrigger +} from "@/components/ui/tabs" +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle +} from "@/components/ui/card" +import type { TagTypeClassFormMappings } from "@/db/schema/vendorData" // or your actual type +import { fetchFormMetadata, FormColumn } from "@/lib/forms/services" + + +interface ViewMetasProps { + open: boolean + onOpenChange: (open: boolean) => void + form: TagTypeClassFormMappings | null +} + +export function ViewMetas({ open, onOpenChange, form }: ViewMetasProps) { + // metadata & loading + const [metadata, setMetadata] = React.useState<{ + formName: string + formCode: string + columns: FormColumn[] + } | null>(null) + const [loading, setLoading] = React.useState(false) + + // Group columns by type for better organization + const groupedColumns = useMemo(() => { + if (!metadata?.columns) return {} + + return metadata.columns.reduce((acc, column) => { + const type = column.type + if (!acc[type]) { + acc[type] = [] + } + acc[type].push(column) + return acc + }, {} as Record) + }, [metadata]) + + // Types for the tabs + const columnTypes = useMemo(() => { + return Object.keys(groupedColumns) + }, [groupedColumns]) + + // Fetch metadata when form changes and dialog is opened + React.useEffect(() => { + async function fetchMeta() { + if (!form || !open) return + + setLoading(true) + try { + // 서버 액션 호출 + const metaData = await fetchFormMetadata(form.formCode) + if (metaData) { + setMetadata(metaData) + } else { + setMetadata(null) + } + } catch (error) { + console.error("Error fetching form metadata:", error) + setMetadata(null) + } finally { + setLoading(false) + } + } + + fetchMeta() + }, [form, open]) + + if (!form) return null + + return ( + + + + + Form Metadata + + + {loading ? ( +
Loading metadata...
+ ) : metadata ? ( +
+
+ Form Code: + {metadata.formCode} +
+
+ Form Name: + {metadata.formName} +
+
+ ) : ( +
+ No metadata found for form code: {form.formCode} +
+ )} + +
+ + {loading ? ( +
+
+
+ ) : metadata ? ( + + + All ({metadata.columns.length}) + {columnTypes.map((type) => ( + + {type} ({groupedColumns[type].length}) + + ))} + + + + + + All Fields + All form fields and their properties + + + + + + Key + Label + Type + Options + + + + {metadata.columns.map((column) => ( + + {column.key} + {column.label} + + {column.type} + + + {column.options ? ( +
+ {column.options.map((option) => ( + + {option} + + ))} +
+ ) : ( + "-" + )} +
+
+ ))} +
+
+
+
+
+ + {columnTypes.map((type) => ( + + + + {type.charAt(0).toUpperCase() + type.slice(1)} Fields + Fields with type "{type}" + + + + + + Key + Label + {type === "select" && Options} + + + + {groupedColumns[type].map((column) => ( + + {column.key} + {column.label} + {type === "select" && ( + + {column.options ? ( +
+ {column.options.map((option) => ( + + {option} + + ))} +
+ ) : ( + "-" + )} +
+ )} +
+ ))} +
+
+
+
+
+ ))} +
+ ) : ( +
+
No metadata found
+

+ Could not find metadata for form code: {form.formCode} +

+
+ )} + +
+
+ ) +} \ No newline at end of file -- cgit v1.2.3