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/tag-numbering/repository.ts | 45 ++++ lib/tag-numbering/service.ts | 123 +++++++++++ lib/tag-numbering/table/feature-flags-provider.tsx | 108 ++++++++++ lib/tag-numbering/table/meta-sheet.tsx | 226 +++++++++++++++++++++ .../table/tagNumbering-table-columns.tsx | 131 ++++++++++++ .../table/tagNumbering-table-toolbar-actions.tsx | 53 +++++ lib/tag-numbering/table/tagNumbering-table.tsx | 151 ++++++++++++++ lib/tag-numbering/validation.ts | 39 ++++ 8 files changed, 876 insertions(+) create mode 100644 lib/tag-numbering/repository.ts create mode 100644 lib/tag-numbering/service.ts create mode 100644 lib/tag-numbering/table/feature-flags-provider.tsx create mode 100644 lib/tag-numbering/table/meta-sheet.tsx create mode 100644 lib/tag-numbering/table/tagNumbering-table-columns.tsx create mode 100644 lib/tag-numbering/table/tagNumbering-table-toolbar-actions.tsx create mode 100644 lib/tag-numbering/table/tagNumbering-table.tsx create mode 100644 lib/tag-numbering/validation.ts (limited to 'lib/tag-numbering') diff --git a/lib/tag-numbering/repository.ts b/lib/tag-numbering/repository.ts new file mode 100644 index 00000000..6ebf84db --- /dev/null +++ b/lib/tag-numbering/repository.ts @@ -0,0 +1,45 @@ +import db from "@/db/db"; +import { viewTagSubfields } 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 selectTagNumbering( + 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(viewTagSubfields) + .where(where) + .orderBy(...(orderBy ?? [])) + .offset(offset) + .limit(limit); + } + /** 총 개수 count */ + export async function countTagNumbering( + tx: PgTransaction, + where?: any + ) { + const res = await tx.select({ count: count() }).from(viewTagSubfields).where(where); + return res[0]?.count ?? 0; + } + \ No newline at end of file diff --git a/lib/tag-numbering/service.ts b/lib/tag-numbering/service.ts new file mode 100644 index 00000000..9b1c1172 --- /dev/null +++ b/lib/tag-numbering/service.ts @@ -0,0 +1,123 @@ +"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 { GetTagNumberigSchema } from "./validation"; +import { filterColumns } from "@/lib/filter-columns"; +import { TagSubfieldOption, tagSubfieldOptions, ViewTagSubfields, viewTagSubfields } from "@/db/schema/vendorData"; +import { asc, desc, ilike, inArray, and, gte, lte, not, or, eq } from "drizzle-orm"; +import { countTagNumbering, selectTagNumbering } from "./repository"; + +export async function getTagNumbering(input: GetTagNumberigSchema) { + + 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: viewTagSubfields, + filters: input.filters, + joinOperator: input.joinOperator, + }); + + + let globalWhere + if (input.search) { + const s = `%${input.search}%` + globalWhere = or(ilike(viewTagSubfields.tagTypeCode, s), ilike(viewTagSubfields.tagTypeDescription, s) + , ilike(viewTagSubfields.attributesId, s) , ilike(viewTagSubfields.attributesDescription, s), ilike(viewTagSubfields.expression, 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(viewTagSubfields[item.id]) : asc(viewTagSubfields[item.id]) + ) + : [asc(viewTagSubfields.createdAt)]; + + // 트랜잭션 내부에서 Repository 호출 + const { data, total } = await db.transaction(async (tx) => { + const data = await selectTagNumbering(tx, { + where, + orderBy, + offset, + limit: input.perPage, + }); + + const total = await countTagNumbering(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: ["tag-numbering"], // revalidateTag("items") 호출 시 무효화 + } + )(); + } + + + + export const fetchTagSubfieldOptions = (async (attributesId: string): Promise => { + try { + // (A) findMany -> 스키마 제네릭 누락 에러 발생 → 대신 select().from().where() 사용 + const rows = await db + .select() + .from(tagSubfieldOptions) + .where(eq(tagSubfieldOptions.attributesId, attributesId)) + .orderBy(asc(tagSubfieldOptions.code)) + + // rows는 TagSubfieldOption[] 형태 + return rows + } catch (error) { + console.error("Error fetching tag subfield options:", error) + return [] + } + }) + + export const getTagNumberingRules = (async (tagType: string): Promise => { + try { + if (!tagType) { + return [] + } + + // 기존 findMany 대신 select().from().where() + orderBy + const rules = await db + .select() + .from(viewTagSubfields) + .where(eq(viewTagSubfields.tagTypeDescription, tagType)) + .orderBy(asc(viewTagSubfields.sortOrder)) + + return rules + } catch (error) { + console.error("Error fetching tag numbering rules:", error) + return [] + } + }) \ No newline at end of file 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({ + 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/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([]) + const [loading, setLoading] = useState(false) + const [copied, setCopied] = useState(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 ( + + + + + + Field Options + + {options.length} options + + + + Field information and available options + + +
+
+
+ Attributes ID: +
+ + {tagSubfield.attributesId} + + + {copied === 'attributesId' && ( + Copied + )} +
+
+
+ Tag Type: + {tagSubfield.tagTypeCode} +
+
+
+
+ Description: + {tagSubfield.attributesDescription} +
+
+ Expression: + + {tagSubfield.expression || 'N/A'} + +
+
+
+ {tagSubfield.tagTypeDescription && ( +
+ Type Description: + {tagSubfield.tagTypeDescription} +
+ )} + +
+ + + + {loading ? ( +
+
+
+ ) : options.length > 0 ? ( + + + Available Options + + All available options for field {tagSubfield.attributesId} + + + + + + + Code + Label + Actions + + + + {options.map((option) => ( + + + {option.code} + + {option.label} + + + + + ))} + +
+
+ +
+ {options.length} options found for {tagSubfield.attributesId} +
+ {tagSubfield.delimiter && ( +
+ Delimiter: {tagSubfield.delimiter} +
+ )} +
+
+ ) : ( +
+
No options found
+

+ This field ({tagSubfield.attributesId}) has no defined options. +

+
+ )} + +
+
+ ) +} \ 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 | 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 Option Info. + + + + ) + }, + size: 40, + } + + // ---------------------------------------------------------------- + // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성 + // ---------------------------------------------------------------- + // 3-1) groupMap: { [groupName]: ColumnDef[] } + const groupMap: Record[]> = {} + + tagNumberingColumnsConfig.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/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 +} + +export function TagNumberingTableToolbarActions({ table }: ItemsTableToolbarActionsProps) { + // 파일 input을 숨기고, 버튼 클릭 시 참조해 클릭하는 방식 + const fileInputRef = React.useRef(null) + + + + return ( +
+ {/** 4) Export 버튼 */} + + + {/** 4) Export 버튼 */} + +
+ ) +} \ 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>, + ] + > +} + +export function TagNumberingTable({ 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: "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 ( + <> + + + + + + + + + setRowAction(null)} + tagSubfield={rowAction?.row.original ?? null} + /> + + + ) +} diff --git a/lib/tag-numbering/validation.ts b/lib/tag-numbering/validation.ts new file mode 100644 index 00000000..36199f24 --- /dev/null +++ b/lib/tag-numbering/validation.ts @@ -0,0 +1,39 @@ +import { + createSearchParamsCache, + parseAsArrayOf, + parseAsInteger, + parseAsString, + parseAsStringEnum, +} from "nuqs/server" +import * as z from "zod" + +import { getFiltersStateParser, getSortingStateParser } from "@/lib/parsers" +import { ViewTagSubfields } 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().withDefault([ + { id: "createdAt", desc: true }, + ]), + tagTypeCode: parseAsString.withDefault(""), + tagTypeDescription: parseAsString.withDefault(""), + attributesId: parseAsString.withDefault(""), + attributesDescription: parseAsString.withDefault(""), + expression: parseAsString.withDefault(""), + delimiter: parseAsString.withDefault(""), + sortOrder: parseAsString.withDefault(""), + + // advanced filter + filters: getFiltersStateParser().withDefault([]), + joinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"), + search: parseAsString.withDefault(""), + +}) + + + +export type GetTagNumberigSchema = Awaited> -- cgit v1.2.3