summaryrefslogtreecommitdiff
path: root/lib/form-list
diff options
context:
space:
mode:
authorjoonhoekim <26rote@gmail.com>2025-03-25 15:55:45 +0900
committerjoonhoekim <26rote@gmail.com>2025-03-25 15:55:45 +0900
commit1a2241c40e10193c5ff7008a7b7b36cc1d855d96 (patch)
tree8a5587f10ca55b162d7e3254cb088b323a34c41b /lib/form-list
initial commit
Diffstat (limited to 'lib/form-list')
-rw-r--r--lib/form-list/repository.ts46
-rw-r--r--lib/form-list/service.ts84
-rw-r--r--lib/form-list/table/feature-flags-provider.tsx108
-rw-r--r--lib/form-list/table/formLists-table-columns.tsx132
-rw-r--r--lib/form-list/table/formLists-table-toolbar-actions.tsx53
-rw-r--r--lib/form-list/table/formLists-table.tsx151
-rw-r--r--lib/form-list/table/meta-sheet.tsx245
-rw-r--r--lib/form-list/validation.ts36
8 files changed, 855 insertions, 0 deletions
diff --git a/lib/form-list/repository.ts b/lib/form-list/repository.ts
new file mode 100644
index 00000000..ced320db
--- /dev/null
+++ b/lib/form-list/repository.ts
@@ -0,0 +1,46 @@
+import db from "@/db/db";
+import { Item, items } from "@/db/schema/items";
+import { tagTypeClassFormMappings } from "@/db/schema/vendorData";
+import {
+ eq,
+ inArray,
+ not,
+ asc,
+ desc,
+ and,
+ ilike,
+ gte,
+ lte,
+ count,
+ gt,
+} from "drizzle-orm";
+import { PgTransaction } from "drizzle-orm/pg-core";
+
+export async function selectFormLists(
+ tx: PgTransaction<any, any, any>,
+ params: {
+ where?: any; // drizzle-orm의 조건식 (and, eq...) 등
+ orderBy?: (ReturnType<typeof asc> | ReturnType<typeof desc>)[];
+ offset?: number;
+ limit?: number;
+ }
+ ) {
+ const { where, orderBy, offset = 0, limit = 10 } = params;
+
+ return tx
+ .select()
+ .from(tagTypeClassFormMappings)
+ .where(where)
+ .orderBy(...(orderBy ?? []))
+ .offset(offset)
+ .limit(limit);
+ }
+ /** 총 개수 count */
+ export async function countFormLists(
+ tx: PgTransaction<any, any, any>,
+ where?: any
+ ) {
+ const res = await tx.select({ count: count() }).from(tagTypeClassFormMappings).where(where);
+ return res[0]?.count ?? 0;
+ }
+ \ No newline at end of file
diff --git a/lib/form-list/service.ts b/lib/form-list/service.ts
new file mode 100644
index 00000000..64156cf4
--- /dev/null
+++ b/lib/form-list/service.ts
@@ -0,0 +1,84 @@
+"use server"; // Next.js 서버 액션에서 직접 import하려면 (선택)
+
+import { revalidateTag, unstable_noStore } from "next/cache";
+import db from "@/db/db";
+import { unstable_cache } from "@/lib/unstable-cache";
+import { GetFormListsSchema } from "./validation";
+import { filterColumns } from "@/lib/filter-columns";
+import { tagTypeClassFormMappings } from "@/db/schema/vendorData";
+import { asc, desc, ilike, inArray, and, gte, lte, not, or } from "drizzle-orm";
+import { countFormLists, selectFormLists } from "./repository";
+
+export async function getFormLists(input: GetFormListsSchema) {
+
+ return unstable_cache(
+ async () => {
+ try {
+ const offset = (input.page - 1) * input.perPage;
+
+ // const advancedTable = input.flags.includes("advancedTable");
+ const advancedTable = true;
+
+ // advancedTable 모드면 filterColumns()로 where 절 구성
+ const advancedWhere = filterColumns({
+ table: tagTypeClassFormMappings,
+ filters: input.filters,
+ joinOperator: input.joinOperator,
+ });
+
+
+ let globalWhere
+ if (input.search) {
+ const s = `%${input.search}%`
+ globalWhere = or(ilike(tagTypeClassFormMappings.formCode, s), ilike(tagTypeClassFormMappings.formName, s)
+ , ilike(tagTypeClassFormMappings.tagTypeLabel, s) , ilike(tagTypeClassFormMappings.classLabel, s)
+ )
+ // 필요시 여러 칼럼 OR조건 (status, priority, etc)
+ }
+
+ const finalWhere = and(
+ // advancedWhere or your existing conditions
+ advancedWhere,
+ globalWhere // and()함수로 결합 or or() 등으로 결합
+ )
+
+
+ // 아니면 ilike, inArray, gte 등으로 where 절 구성
+ const where = finalWhere
+
+
+ const orderBy =
+ input.sort.length > 0
+ ? input.sort.map((item) =>
+ item.desc ? desc(tagTypeClassFormMappings[item.id]) : asc(tagTypeClassFormMappings[item.id])
+ )
+ : [asc(tagTypeClassFormMappings.createdAt)];
+
+ // 트랜잭션 내부에서 Repository 호출
+ const { data, total } = await db.transaction(async (tx) => {
+ const data = await selectFormLists(tx, {
+ where,
+ orderBy,
+ offset,
+ limit: input.perPage,
+ });
+
+ const total = await countFormLists(tx, where);
+ return { data, total };
+ });
+
+ const pageCount = Math.ceil(total / input.perPage);
+
+ return { data, pageCount };
+ } catch (err) {
+ // 에러 발생 시 디폴트
+ return { data: [], pageCount: 0 };
+ }
+ },
+ [JSON.stringify(input)], // 캐싱 키
+ {
+ revalidate: 3600,
+ tags: ["form-lists"], // revalidateTag("items") 호출 시 무효화
+ }
+ )();
+ } \ No newline at end of file
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<FeatureFlagsContextProps>({
+ 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<FeatureFlagValue[]>(
+ "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 (
+ <FeatureFlagsContext.Provider
+ value={{
+ featureFlags,
+ setFeatureFlags: (value) => void setFeatureFlags(value),
+ }}
+ >
+ <div className="w-full overflow-x-auto">
+ <ToggleGroup
+ type="multiple"
+ variant="outline"
+ size="sm"
+ value={featureFlags}
+ onValueChange={(value: FeatureFlagValue[]) => setFeatureFlags(value)}
+ className="w-fit gap-0"
+ >
+ {dataTableConfig.featureFlags.map((flag, index) => (
+ <Tooltip key={flag.value}>
+ <ToggleGroupItem
+ value={flag.value}
+ className={cn(
+ "gap-2 whitespace-nowrap rounded-none px-3 text-xs data-[state=on]:bg-accent/70 data-[state=on]:hover:bg-accent/90",
+ {
+ "rounded-l-sm border-r-0": index === 0,
+ "rounded-r-sm":
+ index === dataTableConfig.featureFlags.length - 1,
+ }
+ )}
+ asChild
+ >
+ <TooltipTrigger>
+ <flag.icon className="size-3.5 shrink-0" aria-hidden="true" />
+ {flag.label}
+ </TooltipTrigger>
+ </ToggleGroupItem>
+ <TooltipContent
+ align="start"
+ side="bottom"
+ sideOffset={6}
+ className="flex max-w-60 flex-col space-y-1.5 border bg-background py-2 font-semibold text-foreground"
+ >
+ <div>{flag.tooltipTitle}</div>
+ <div className="text-xs text-muted-foreground">
+ {flag.tooltipDescription}
+ </div>
+ </TooltipContent>
+ </Tooltip>
+ ))}
+ </ToggleGroup>
+ </div>
+ {children}
+ </FeatureFlagsContext.Provider>
+ )
+}
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<React.SetStateAction<DataTableRowAction<TagTypeClassFormMappings> | null>>
+}
+
+/**
+ * tanstack table 컬럼 정의 (중첩 헤더 버전)
+ */
+export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<TagTypeClassFormMappings>[] {
+ // ----------------------------------------------------------------
+ // 1) select 컬럼 (체크박스)
+ // ----------------------------------------------------------------
+
+
+ // ----------------------------------------------------------------
+ // 2) actions 컬럼 (단일 버튼 - Meta Info 바로 보기)
+ // ----------------------------------------------------------------
+ const actionsColumn: ColumnDef<TagTypeClassFormMappings> = {
+ id: "actions",
+ enableHiding: false,
+ cell: function Cell({ row }) {
+ return (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => setRowAction({ row, type: "items" })}
+ >
+ <InfoIcon className="h-4 w-4" aria-hidden="true" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ View Meta Info
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ )
+ },
+ size: 40,
+ }
+
+ // ----------------------------------------------------------------
+ // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성
+ // ----------------------------------------------------------------
+ // 3-1) groupMap: { [groupName]: ColumnDef<TagTypeClassFormMappings>[] }
+ const groupMap: Record<string, ColumnDef<TagTypeClassFormMappings>[]> = {}
+
+ formListsColumnsConfig.forEach((cfg) => {
+ // 만약 group가 없으면 "_noGroup" 처리
+ const groupName = cfg.group || "_noGroup"
+
+ if (!groupMap[groupName]) {
+ groupMap[groupName] = []
+ }
+
+ // child column 정의
+ const childCol: ColumnDef<TagTypeClassFormMappings> = {
+ accessorKey: cfg.id,
+ enableResizing: true,
+ header: ({ column }) => (
+ <DataTableColumnHeaderSimple column={column} title={cfg.label} />
+ ),
+ 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<TagTypeClassFormMappings>[] = []
+
+ // 순서를 고정하고 싶다면 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<TagTypeClassFormMappings>
+}
+
+export function FormListsTableToolbarActions({ table }: ItemsTableToolbarActionsProps) {
+ // 파일 input을 숨기고, 버튼 클릭 시 참조해 클릭하는 방식
+ const fileInputRef = React.useRef<HTMLInputElement>(null)
+
+
+
+ return (
+ <div className="flex items-center gap-2">
+ {/** 4) Export 버튼 */}
+ <Button
+ variant="samsung"
+ size="sm"
+ className="gap-2"
+ >
+ <RefreshCcw className="size-4" aria-hidden="true" />
+ <span className="hidden sm:inline">Get Forms</span>
+ </Button>
+
+ {/** 4) Export 버튼 */}
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() =>
+ exportTableToExcel(table, {
+ filename: "tasks",
+ excludeColumns: ["select", "actions"],
+ })
+ }
+ className="gap-2"
+ >
+ <Download className="size-4" aria-hidden="true" />
+ <span className="hidden sm:inline">Export</span>
+ </Button>
+ </div>
+ )
+} \ 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<ReturnType<typeof getFormLists>>,
+ ]
+ >
+}
+
+export function FormListsTable({ promises }: ItemsTableProps) {
+ const { featureFlags } = useFeatureFlags()
+
+ const [{ data, pageCount }] =
+ React.use(promises)
+
+
+ const [rowAction, setRowAction] =
+ React.useState<DataTableRowAction<TagTypeClassFormMappings> | 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<TagTypeClassFormMappings>[] = [
+
+
+ ]
+
+ /**
+ * 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<TagTypeClassFormMappings>[] = [
+ {
+ 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 (
+ <>
+ <DataTable
+ table={table}
+
+ >
+
+ <DataTableAdvancedToolbar
+ table={table}
+ filterFields={advancedFilterFields}
+ shallow={false}
+ >
+ <FormListsTableToolbarActions table={table} />
+ </DataTableAdvancedToolbar>
+
+ </DataTable>
+ <ViewMetas
+ open={rowAction?.type === "items"}
+ onOpenChange={() => 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<string, FormColumn[]>)
+ }, [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 (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent className="sm:max-w-xl md:max-w-3xl lg:max-w-4xl xl:max-w-5xl overflow-y-auto">
+
+ <SheetHeader className="mb-4">
+ <SheetTitle>Form Metadata</SheetTitle>
+ <SheetDescription>
+ </SheetDescription>
+ {loading ? (
+ <div className="text-muted-foreground">Loading metadata...</div>
+ ) : metadata ? (
+ <div className="flex flex-col gap-1">
+ <div className="flex gap-2 items-center">
+ <span className="font-semibold">Form Code:</span>
+ <Badge variant="outline">{metadata.formCode}</Badge>
+ </div>
+ <div className="flex gap-2 items-center">
+ <span className="font-semibold">Form Name:</span>
+ <span>{metadata.formName}</span>
+ </div>
+ </div>
+ ) : (
+ <div className="text-sm text-muted-foreground">
+ No metadata found for form code: {form.formCode}
+ </div>
+ )}
+
+ </SheetHeader>
+
+ {loading ? (
+ <div className="flex items-center justify-center h-40">
+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
+ </div>
+ ) : metadata ? (
+ <Tabs defaultValue="all" className="mt-4">
+ <TabsList className="mb-4 flex-wrap">
+ <TabsTrigger value="all">All ({metadata.columns.length})</TabsTrigger>
+ {columnTypes.map((type) => (
+ <TabsTrigger key={type} value={type}>
+ {type} ({groupedColumns[type].length})
+ </TabsTrigger>
+ ))}
+ </TabsList>
+
+ <TabsContent value="all">
+ <Card>
+ <CardHeader>
+ <CardTitle>All Fields</CardTitle>
+ <CardDescription>All form fields and their properties</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Key</TableHead>
+ <TableHead>Label</TableHead>
+ <TableHead>Type</TableHead>
+ <TableHead>Options</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {metadata.columns.map((column) => (
+ <TableRow key={column.key}>
+ <TableCell className="font-mono text-sm">{column.key}</TableCell>
+ <TableCell>{column.label}</TableCell>
+ <TableCell>
+ <Badge variant="secondary">{column.type}</Badge>
+ </TableCell>
+ <TableCell>
+ {column.options ? (
+ <div className="flex flex-wrap gap-1">
+ {column.options.map((option) => (
+ <Badge key={option} variant="outline" className="text-xs">
+ {option}
+ </Badge>
+ ))}
+ </div>
+ ) : (
+ "-"
+ )}
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </CardContent>
+ </Card>
+ </TabsContent>
+
+ {columnTypes.map((type) => (
+ <TabsContent key={type} value={type}>
+ <Card>
+ <CardHeader>
+ <CardTitle>{type.charAt(0).toUpperCase() + type.slice(1)} Fields</CardTitle>
+ <CardDescription>Fields with type "{type}"</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Key</TableHead>
+ <TableHead>Label</TableHead>
+ {type === "select" && <TableHead>Options</TableHead>}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {groupedColumns[type].map((column) => (
+ <TableRow key={column.key}>
+ <TableCell className="font-mono text-sm">{column.key}</TableCell>
+ <TableCell>{column.label}</TableCell>
+ {type === "select" && (
+ <TableCell>
+ {column.options ? (
+ <div className="flex flex-wrap gap-1">
+ {column.options.map((option) => (
+ <Badge key={option} variant="outline" className="text-xs">
+ {option}
+ </Badge>
+ ))}
+ </div>
+ ) : (
+ "-"
+ )}
+ </TableCell>
+ )}
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </CardContent>
+ </Card>
+ </TabsContent>
+ ))}
+ </Tabs>
+ ) : (
+ <div className="text-center py-8">
+ <div className="text-lg font-medium">No metadata found</div>
+ <p className="text-muted-foreground mt-2">
+ Could not find metadata for form code: {form.formCode}
+ </p>
+ </div>
+ )}
+
+ </SheetContent>
+ </Sheet>
+ )
+} \ No newline at end of file
diff --git a/lib/form-list/validation.ts b/lib/form-list/validation.ts
new file mode 100644
index 00000000..c8baf960
--- /dev/null
+++ b/lib/form-list/validation.ts
@@ -0,0 +1,36 @@
+import {
+ createSearchParamsCache,
+ parseAsArrayOf,
+ parseAsInteger,
+ parseAsString,
+ parseAsStringEnum,
+} from "nuqs/server"
+import * as z from "zod"
+
+import { getFiltersStateParser, getSortingStateParser } from "@/lib/parsers"
+import { TagTypeClassFormMappings } from "@/db/schema/vendorData";
+
+export const searchParamsCache = createSearchParamsCache({
+ flags: parseAsArrayOf(z.enum(["advancedTable", "floatingBar"])).withDefault(
+ []
+ ),
+ page: parseAsInteger.withDefault(1),
+ perPage: parseAsInteger.withDefault(10),
+ sort: getSortingStateParser<TagTypeClassFormMappings>().withDefault([
+ { id: "createdAt", desc: true },
+ ]),
+ tagTypeLabel: parseAsString.withDefault(""),
+ classLabel: parseAsString.withDefault(""),
+ formCode: parseAsString.withDefault(""),
+ formName: parseAsString.withDefault(""),
+
+ // advanced filter
+ filters: getFiltersStateParser().withDefault([]),
+ joinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"),
+ search: parseAsString.withDefault(""),
+
+})
+
+
+
+export type GetFormListsSchema = Awaited<ReturnType<typeof searchParamsCache.parse>>