From 9ceed79cf32c896f8a998399bf1b296506b2cd4a Mon Sep 17 00:00:00 2001 From: dujinkim Date: Tue, 8 Apr 2025 03:08:19 +0000 Subject: 로그인 및 미들웨어 처리. 구조 변경 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/projects/table/feature-flags-provider.tsx | 108 +++++++++++++++++ lib/projects/table/projects-table-columns.tsx | 90 +++++++++++++++ .../table/projects-table-toolbar-actions.tsx | 89 ++++++++++++++ lib/projects/table/projects-table.tsx | 128 +++++++++++++++++++++ 4 files changed, 415 insertions(+) create mode 100644 lib/projects/table/feature-flags-provider.tsx create mode 100644 lib/projects/table/projects-table-columns.tsx create mode 100644 lib/projects/table/projects-table-toolbar-actions.tsx create mode 100644 lib/projects/table/projects-table.tsx (limited to 'lib/projects/table') diff --git a/lib/projects/table/feature-flags-provider.tsx b/lib/projects/table/feature-flags-provider.tsx new file mode 100644 index 00000000..81131894 --- /dev/null +++ b/lib/projects/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/projects/table/projects-table-columns.tsx b/lib/projects/table/projects-table-columns.tsx new file mode 100644 index 00000000..77899212 --- /dev/null +++ b/lib/projects/table/projects-table-columns.tsx @@ -0,0 +1,90 @@ +"use client" + +import * as React from "react" +import { type DataTableRowAction } from "@/types/table" +import { type ColumnDef } from "@tanstack/react-table" + +import { formatDate } from "@/lib/utils" + +import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header" +import { Project } from "@/db/schema" +import { projectsColumnsConfig } from "@/config/projectsColumnsConfig" + +interface GetColumnsProps { + setRowAction: React.Dispatch | null>> +} + +/** + * tanstack table 컬럼 정의 (중첩 헤더 버전) + */ +export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef[] { + + + // ---------------------------------------------------------------- + // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성 + // ---------------------------------------------------------------- + // 3-1) groupMap: { [groupName]: ColumnDef[] } + const groupMap: Record[]> = {} + + projectsColumnsConfig.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, + ] +} \ No newline at end of file diff --git a/lib/projects/table/projects-table-toolbar-actions.tsx b/lib/projects/table/projects-table-toolbar-actions.tsx new file mode 100644 index 00000000..dc55423d --- /dev/null +++ b/lib/projects/table/projects-table-toolbar-actions.tsx @@ -0,0 +1,89 @@ +"use client" + +import * as React from "react" +import { type Table } from "@tanstack/react-table" +import { Download, RefreshCcw } from "lucide-react" +import { toast } from "sonner" + +import { exportTableToExcel } from "@/lib/export" +import { Button } from "@/components/ui/button" +import { Project } from "@/db/schema" + +interface ItemsTableToolbarActionsProps { + table: Table +} + +export function ProjectTableToolbarActions({ table }: ItemsTableToolbarActionsProps) { + const [isLoading, setIsLoading] = React.useState(false) + + // 프로젝트 동기화 API 호출 함수 + const syncProjects = async () => { + try { + setIsLoading(true) + + // API 엔드포인트 호출 + const response = await fetch('/api/cron/projects') + + if (!response.ok) { + const errorData = await response.json() + throw new Error(errorData.error || 'Failed to sync projects') + } + + const data = await response.json() + + // 성공 메시지 표시 + toast.success( + `Projects synced successfully! ${data.result.items} items processed.` + ) + + // 페이지 새로고침으로 테이블 데이터 업데이트 + window.location.reload() + } catch (error) { + console.error('Error syncing projects:', error) + toast.error( + error instanceof Error + ? error.message + : 'An error occurred while syncing projects' + ) + } finally { + setIsLoading(false) + } + } + + return ( +
+ + + {/** 4) Export 버튼 */} + +
+ ) +} \ No newline at end of file diff --git a/lib/projects/table/projects-table.tsx b/lib/projects/table/projects-table.tsx new file mode 100644 index 00000000..3da54b7c --- /dev/null +++ b/lib/projects/table/projects-table.tsx @@ -0,0 +1,128 @@ +"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 { getColumns } from "./projects-table-columns" +import { getProjectLists } from "../service" +import { Project } from "@/db/schema" +import { ProjectTableToolbarActions } from "./projects-table-toolbar-actions" + +interface ItemsTableProps { + promises: Promise< + [ + Awaited>, + ] + > +} + +export function ProjectsTable({ 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: "code", + label: "Project Code", + type: "text", + // group: "Basic Info", + }, + { + id: "name", + label: "Project Name", + type: "text", + // group: "Basic Info", + }, + + + { + id: "createdAt", + label: "Created At", + type: "date", + // group: "Metadata",a + }, + { + id: "updatedAt", + label: "Updated At", + type: "date", + // group: "Metadata", + }, + ] + + + 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 ( + <> + + + + + + + ) +} -- cgit v1.2.3