summaryrefslogtreecommitdiff
path: root/lib/tag-numbering/table
diff options
context:
space:
mode:
authordujinkim <dujin.kim@dtsolution.co.kr>2025-03-26 00:37:41 +0000
committerdujinkim <dujin.kim@dtsolution.co.kr>2025-03-26 00:37:41 +0000
commite0dfb55c5457aec489fc084c4567e791b4c65eb1 (patch)
tree68543a65d88f5afb3a0202925804103daa91bc6f /lib/tag-numbering/table
3/25 까지의 대표님 작업사항
Diffstat (limited to 'lib/tag-numbering/table')
-rw-r--r--lib/tag-numbering/table/feature-flags-provider.tsx108
-rw-r--r--lib/tag-numbering/table/meta-sheet.tsx226
-rw-r--r--lib/tag-numbering/table/tagNumbering-table-columns.tsx131
-rw-r--r--lib/tag-numbering/table/tagNumbering-table-toolbar-actions.tsx53
-rw-r--r--lib/tag-numbering/table/tagNumbering-table.tsx151
5 files changed, 669 insertions, 0 deletions
diff --git a/lib/tag-numbering/table/feature-flags-provider.tsx b/lib/tag-numbering/table/feature-flags-provider.tsx
new file mode 100644
index 00000000..81131894
--- /dev/null
+++ b/lib/tag-numbering/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/tag-numbering/table/meta-sheet.tsx b/lib/tag-numbering/table/meta-sheet.tsx
new file mode 100644
index 00000000..4221837c
--- /dev/null
+++ b/lib/tag-numbering/table/meta-sheet.tsx
@@ -0,0 +1,226 @@
+"use client"
+
+import * as React from "react"
+import { useEffect, useState } from "react"
+import { Copy } from "lucide-react"
+import { Badge } from "@/components/ui/badge"
+import { Button } from "@/components/ui/button"
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle
+} from "@/components/ui/sheet"
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow
+} from "@/components/ui/table"
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ CardFooter
+} from "@/components/ui/card"
+import { Separator } from "@/components/ui/separator"
+import { ViewTagSubfields } from "@/db/schema/vendorData"
+import { fetchTagSubfieldOptions } from "../service"
+
+interface TagOption {
+ id: number
+ attributesId: string
+ code: string
+ label: string
+ createdAt?: Date
+ updatedAt?: Date
+}
+
+interface ViewTagOptionsProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ tagSubfield: ViewTagSubfields | null
+}
+
+export function ViewTagOptions({
+ open,
+ onOpenChange,
+ tagSubfield
+}: ViewTagOptionsProps) {
+ const [options, setOptions] = useState<TagOption[]>([])
+ const [loading, setLoading] = useState(false)
+ const [copied, setCopied] = useState<string | null>(null)
+
+ // 옵션 데이터 가져오기
+ useEffect(() => {
+ async function fetchOptions() {
+ if (!tagSubfield || !open) return
+
+ setLoading(true)
+ try {
+ // 서버 액션 호출 - attributesId와 일치하는 모든 옵션 가져오기
+ const optionsData = await fetchTagSubfieldOptions(tagSubfield.attributesId)
+ setOptions(optionsData || [])
+ } catch (error) {
+ console.error("Error fetching tag options:", error)
+ setOptions([])
+ } finally {
+ setLoading(false)
+ }
+ }
+
+ fetchOptions()
+ }, [tagSubfield, open])
+
+ // 코드 복사 기능
+ const copyToClipboard = (text: string, type: string) => {
+ navigator.clipboard.writeText(text).then(() => {
+ setCopied(type)
+ setTimeout(() => setCopied(null), 2000)
+ })
+ }
+
+ if (!tagSubfield) 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-6">
+ <SheetTitle className="text-xl flex items-center gap-2">
+ Field Options
+ <Badge variant="outline" className="ml-2">
+ {options.length} options
+ </Badge>
+ </SheetTitle>
+ <SheetDescription className="mb-4">
+ Field information and available options
+ </SheetDescription>
+
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">Attributes ID:</span>
+ <div className="flex items-center gap-1">
+ <Badge variant="secondary">
+ {tagSubfield.attributesId}
+ </Badge>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6"
+ onClick={() => copyToClipboard(tagSubfield.attributesId, 'attributesId')}
+ >
+ <Copy className="h-3 w-3" />
+ </Button>
+ {copied === 'attributesId' && (
+ <span className="text-xs text-green-600">Copied</span>
+ )}
+ </div>
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">Tag Type:</span>
+ <Badge>{tagSubfield.tagTypeCode}</Badge>
+ </div>
+ </div>
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">Description:</span>
+ <span className="text-sm">{tagSubfield.attributesDescription}</span>
+ </div>
+ <div className="flex items-center justify-between">
+ <span className="text-sm font-medium">Expression:</span>
+ <code className="bg-muted px-2 py-1 rounded text-xs">
+ {tagSubfield.expression || 'N/A'}
+ </code>
+ </div>
+ </div>
+ </div>
+ {tagSubfield.tagTypeDescription && (
+ <div className="mt-4 text-sm bg-muted p-2 rounded">
+ <span className="font-medium">Type Description: </span>
+ {tagSubfield.tagTypeDescription}
+ </div>
+ )}
+
+ </SheetHeader>
+
+ <Separator className="my-4" />
+
+ {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>
+ ) : options.length > 0 ? (
+ <Card>
+ <CardHeader>
+ <CardTitle>Available Options</CardTitle>
+ <CardDescription>
+ All available options for field {tagSubfield.attributesId}
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="w-24">Code</TableHead>
+ <TableHead>Label</TableHead>
+ <TableHead className="text-right">Actions</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {options.map((option) => (
+ <TableRow key={option.id}>
+ <TableCell className="font-mono">
+ {option.code}
+ </TableCell>
+ <TableCell>{option.label}</TableCell>
+ <TableCell className="text-right">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-8 w-8 p-0"
+ onClick={() => copyToClipboard(`${option.code} - ${option.label}`, `option-${option.id}`)}
+ >
+ <Copy className="h-4 w-4" />
+ {copied === `option-${option.id}` && (
+ <span className="absolute -top-2 -right-2 text-xs text-green-600 bg-white px-1 rounded-sm">
+ Copied
+ </span>
+ )}
+ </Button>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </CardContent>
+ <CardFooter className="flex justify-between text-sm text-muted-foreground">
+ <div>
+ {options.length} options found for {tagSubfield.attributesId}
+ </div>
+ {tagSubfield.delimiter && (
+ <div>
+ Delimiter: <code className="bg-muted px-2 py-1 rounded text-xs">{tagSubfield.delimiter}</code>
+ </div>
+ )}
+ </CardFooter>
+ </Card>
+ ) : (
+ <div className="text-center py-8">
+ <div className="text-lg font-medium">No options found</div>
+ <p className="text-muted-foreground mt-2">
+ This field ({tagSubfield.attributesId}) has no defined options.
+ </p>
+ </div>
+ )}
+
+ </SheetContent>
+ </Sheet>
+ )
+} \ No newline at end of file
diff --git a/lib/tag-numbering/table/tagNumbering-table-columns.tsx b/lib/tag-numbering/table/tagNumbering-table-columns.tsx
new file mode 100644
index 00000000..6e9b8191
--- /dev/null
+++ b/lib/tag-numbering/table/tagNumbering-table-columns.tsx
@@ -0,0 +1,131 @@
+"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 {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@/components/ui/tooltip"
+
+import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
+import { ViewTagSubfields } from "@/db/schema/vendorData"
+import { tagNumberingColumnsConfig } from "@/config/tagNumberingColumnsConfig"
+
+interface GetColumnsProps {
+ setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<ViewTagSubfields> | null>>
+}
+
+/**
+ * tanstack table 컬럼 정의 (중첩 헤더 버전)
+ */
+export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<ViewTagSubfields>[] {
+ // ----------------------------------------------------------------
+ // 1) select 컬럼 (체크박스)
+ // ----------------------------------------------------------------
+
+
+ // ----------------------------------------------------------------
+ // 2) actions 컬럼 (단일 버튼 - Meta Info 바로 보기)
+ // ----------------------------------------------------------------
+ const actionsColumn: ColumnDef<ViewTagSubfields> = {
+ 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 Option Info.
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ )
+ },
+ size: 40,
+ }
+
+ // ----------------------------------------------------------------
+ // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성
+ // ----------------------------------------------------------------
+ // 3-1) groupMap: { [groupName]: ColumnDef<ViewTagSubfields>[] }
+ const groupMap: Record<string, ColumnDef<ViewTagSubfields>[]> = {}
+
+ tagNumberingColumnsConfig.forEach((cfg) => {
+ // 만약 group가 없으면 "_noGroup" 처리
+ const groupName = cfg.group || "_noGroup"
+
+ if (!groupMap[groupName]) {
+ groupMap[groupName] = []
+ }
+
+ // child column 정의
+ const childCol: ColumnDef<ViewTagSubfields> = {
+ 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<ViewTagSubfields>[] = []
+
+ // 순서를 고정하고 싶다면 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/tag-numbering/table/tagNumbering-table-toolbar-actions.tsx b/lib/tag-numbering/table/tagNumbering-table-toolbar-actions.tsx
new file mode 100644
index 00000000..1a7af254
--- /dev/null
+++ b/lib/tag-numbering/table/tagNumbering-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 { ViewTagSubfields } from "@/db/schema/vendorData"
+
+
+
+interface ItemsTableToolbarActionsProps {
+ table: Table<ViewTagSubfields>
+}
+
+export function TagNumberingTableToolbarActions({ 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 Tag Numbering</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/tag-numbering/table/tagNumbering-table.tsx b/lib/tag-numbering/table/tagNumbering-table.tsx
new file mode 100644
index 00000000..7997aad9
--- /dev/null
+++ b/lib/tag-numbering/table/tagNumbering-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 { ViewTagSubfields } from "@/db/schema/vendorData"
+import { getTagNumbering } from "../service"
+import { getColumns } from "./tagNumbering-table-columns"
+import { TagNumberingTableToolbarActions } from "./tagNumbering-table-toolbar-actions"
+import { ViewTagOptions } from "./meta-sheet"
+
+interface ItemsTableProps {
+ promises: Promise<
+ [
+ Awaited<ReturnType<typeof getTagNumbering>>,
+ ]
+ >
+}
+
+export function TagNumberingTable({ promises }: ItemsTableProps) {
+ const { featureFlags } = useFeatureFlags()
+
+ const [{ data, pageCount }] =
+ React.use(promises)
+
+
+ const [rowAction, setRowAction] =
+ React.useState<DataTableRowAction<ViewTagSubfields> | 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<ViewTagSubfields>[] = [
+
+ ]
+
+ /**
+ * 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<ViewTagSubfields>[] = [
+ {
+ id: "tagTypeCode",
+ label: "Tag Type Code",
+ type: "text",
+ },
+ {
+ id: "tagTypeDescription",
+ label: "Tag Type Description",
+ type: "text",
+ },
+
+ {
+ id: "attributesId",
+ label: "Attributes Id",
+ type: "text",
+ },
+
+ {
+ id: "attributesDescription",
+ label: "Attributes Description",
+ type: "text",
+ },
+ {
+ id: "expression",
+ label: "expression",
+ 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}
+ >
+ <TagNumberingTableToolbarActions table={table} />
+ </DataTableAdvancedToolbar>
+
+ </DataTable>
+
+ <ViewTagOptions
+ open={rowAction?.type === "items"}
+ onOpenChange={() => setRowAction(null)}
+ tagSubfield={rowAction?.row.original ?? null}
+ />
+
+ </>
+ )
+}