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/repository.ts | 44 +++++++ lib/projects/service.ts | 87 ++++++++++++++ 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 +++++++++++++++++++++ lib/projects/validation.ts | 36 ++++++ 7 files changed, 582 insertions(+) create mode 100644 lib/projects/repository.ts create mode 100644 lib/projects/service.ts 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 create mode 100644 lib/projects/validation.ts (limited to 'lib/projects') diff --git a/lib/projects/repository.ts b/lib/projects/repository.ts new file mode 100644 index 00000000..62b70778 --- /dev/null +++ b/lib/projects/repository.ts @@ -0,0 +1,44 @@ +import db from "@/db/db"; +import { projects } from "@/db/schema"; +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 selectProjectLists( + tx: PgTransaction, + params: { + where?: any; // drizzle-orm의 조건식 (and, eq...) 등 + orderBy?: (ReturnType | ReturnType)[]; + offset?: number; + limit?: number; + } + ) { + const { where, orderBy, offset = 0, limit = 10 } = params; + + return tx + .select() + .from(projects) + .where(where) + .orderBy(...(orderBy ?? [])) + .offset(offset) + .limit(limit); + } +/** 총 개수 count */ +export async function countProjectLists( + tx: PgTransaction, + where?: any +) { + const res = await tx.select({ count: count() }).from(projects).where(where); + return res[0]?.count ?? 0; +} diff --git a/lib/projects/service.ts b/lib/projects/service.ts new file mode 100644 index 00000000..fe1052f6 --- /dev/null +++ b/lib/projects/service.ts @@ -0,0 +1,87 @@ +"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 { 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 { countProjectLists, selectProjectLists } from "./repository"; +import { projects } from "@/db/schema"; +import { GetProjectListsSchema } from "./validation"; + +export async function getProjectLists(input: GetProjectListsSchema) { + + 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: projects, + filters: input.filters, + joinOperator: input.joinOperator, + }); + + + let globalWhere + if (input.search) { + const s = `%${input.search}%` + globalWhere = or( + ilike(projects.name, s), + ilike(projects.code, s), + ilike(projects.type, 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(projects[item.id]) : asc(projects[item.id]) + ) + : [asc(projects.createdAt)]; + + // 트랜잭션 내부에서 Repository 호출 + const { data, total } = await db.transaction(async (tx) => { + const data = await selectProjectLists(tx, { + where, + orderBy, + offset, + limit: input.perPage, + }); + + const total = await countProjectLists(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: ["project-lists"], + } + )(); + } \ No newline at end of file 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 ( + <> + + + + + + + ) +} diff --git a/lib/projects/validation.ts b/lib/projects/validation.ts new file mode 100644 index 00000000..ed1cc9a1 --- /dev/null +++ b/lib/projects/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 { Project } from "@/db/schema"; + +export const searchParamsProjectsCache = createSearchParamsCache({ + flags: parseAsArrayOf(z.enum(["advancedTable", "floatingBar"])).withDefault( + [] + ), + page: parseAsInteger.withDefault(1), + perPage: parseAsInteger.withDefault(10), + sort: getSortingStateParser().withDefault([ + { id: "createdAt", desc: true }, + ]), + + code: parseAsString.withDefault(""), + name: parseAsString.withDefault(""), + type: parseAsString.withDefault(""), + + // advanced filter + filters: getFiltersStateParser().withDefault([]), + joinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"), + search: parseAsString.withDefault(""), + +}) + + + +export type GetProjectListsSchema = Awaited> -- cgit v1.2.3