diff options
Diffstat (limited to 'lib/project-avl')
| -rw-r--r-- | lib/project-avl/repository.ts | 49 | ||||
| -rw-r--r-- | lib/project-avl/service.ts | 106 | ||||
| -rw-r--r-- | lib/project-avl/table/proejctAVL-table.tsx | 159 | ||||
| -rw-r--r-- | lib/project-avl/table/projectAVL-table-columns.tsx | 104 | ||||
| -rw-r--r-- | lib/project-avl/validations.ts | 41 |
5 files changed, 459 insertions, 0 deletions
diff --git a/lib/project-avl/repository.ts b/lib/project-avl/repository.ts new file mode 100644 index 00000000..5fef8560 --- /dev/null +++ b/lib/project-avl/repository.ts @@ -0,0 +1,49 @@ +// src/lib/projectApprovedVendors/repository.ts +import { projectApprovedVendors } 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"; + +/** + * 단건/복수 조회 시 공통으로 사용 가능한 SELECT 함수 예시 + * - 트랜잭션(tx)을 받아서 사용하도록 구현 + */ +export async function selectProejctAVLs( + 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(projectApprovedVendors) + .where(where) + .orderBy(...(orderBy ?? [])) + .offset(offset) + .limit(limit); +} +/** 총 개수 count */ +export async function countProjectAVLs( + tx: PgTransaction<any, any, any>, + where?: any +) { + const res = await tx.select({ count: count() }).from(projectApprovedVendors).where(where); + return res[0]?.count ?? 0; +} + diff --git a/lib/project-avl/service.ts b/lib/project-avl/service.ts new file mode 100644 index 00000000..6ba10c5e --- /dev/null +++ b/lib/project-avl/service.ts @@ -0,0 +1,106 @@ +// src/lib/projectApprovedVendors/service.ts +"use server"; // Next.js 서버 액션에서 직접 import하려면 (선택) + +import { revalidateTag, unstable_noStore } from "next/cache"; +import db from "@/db/db"; +import { customAlphabet } from "nanoid"; + +import { filterColumns } from "@/lib/filter-columns"; +import { unstable_cache } from "@/lib/unstable-cache"; +import { getErrorMessage } from "@/lib/handle-error"; + +import { asc, desc, ilike, inArray, and, gte, lte, not, or ,eq} from "drizzle-orm"; +import { GetProjectAVLSchema } from "./validations"; +import { projectApprovedVendors } from "@/db/schema"; +import { countProjectAVLs, selectProejctAVLs } from "./repository"; + + +/* ----------------------------------------------------- + 1) 조회 관련 +----------------------------------------------------- */ + +/** + * 복잡한 조건으로 Item 목록을 조회 (+ pagination) 하고, + * 총 개수에 따라 pageCount를 계산해서 리턴. + * Next.js의 unstable_cache를 사용해 일정 시간 캐시. + */ +export async function getProjecTAVL(input: GetProjectAVLSchema) { + + 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: projectApprovedVendors, + filters: input.filters, + joinOperator: input.joinOperator, + }); + + + let globalWhere + if (input.search) { + const s = `%${input.search}%` + globalWhere = + or( + ilike(projectApprovedVendors.vendor_name, s), + ilike(projectApprovedVendors.tax_id, s) + , ilike(projectApprovedVendors.vendor_email, s) + , ilike(projectApprovedVendors.vendor_type_name_ko, s) + , ilike(projectApprovedVendors.project_name, s) + , ilike(projectApprovedVendors.project_code, 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(projectApprovedVendors[item.id]) : asc(projectApprovedVendors[item.id]) + ) + : [asc(projectApprovedVendors.approved_at)]; + + // 트랜잭션 내부에서 Repository 호출 + const { data, total } = await db.transaction(async (tx) => { + const data = await selectProejctAVLs(tx, { + where, + orderBy, + offset, + limit: input.perPage, + }); + + const total = await countProjectAVLs(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-approved-vendors"], // revalidateTag("projectApprovedVendors") 호출 시 무효화 + } + )(); +} + diff --git a/lib/project-avl/table/proejctAVL-table.tsx b/lib/project-avl/table/proejctAVL-table.tsx new file mode 100644 index 00000000..b9d6e142 --- /dev/null +++ b/lib/project-avl/table/proejctAVL-table.tsx @@ -0,0 +1,159 @@ +"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 { getColumns } from "./projectAVL-table-columns" +import { ProjectApprovedVendors } from "@/db/schema" +import { getProjecTAVL } from "../service" + +interface ProjectAVLTableProps { + promises: Promise< + [ + Awaited<ReturnType<typeof getProjecTAVL>>, + ] + > +} + +export function ProjectAVLTable({ promises }: ProjectAVLTableProps) { + + const [{ data, pageCount }] = + React.use(promises) + + + const [rowAction, setRowAction] = + React.useState<DataTableRowAction<ProjectApprovedVendors> | 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<ProjectApprovedVendors>[] = [ + + + ] + + /** + * 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<ProjectApprovedVendors>[] = [ + { + id: "project_code", + label: "프로젝트 코드", + type: "text", + }, + { + id: "project_name", + label: "프로젝트명", + type: "text", + }, + { + id: "vendor_name", + label: "업체명", + type: "text", + }, + { + id: "vendor_code", + label: "업체코드", + type: "text", + }, + { + id: "tax_id", + label: "사업자등록번호", + type: "text", + }, + { + id: "vendor_email", + label: "대표이메일", + type: "text", + }, + { + id: "vendor_phone", + label: "대표전화번호", + type: "text", + }, + { + id: "vendor_type_name_ko", + label: "업체유형", + type: "text", + }, + + + { + id: "submitted_at", + label: "PQ 제출일", + type: "date", + + }, + { + id: "approved_at", + label: "PQ 승인일", + type: "date", + + }, + ] + + + const { table } = useDataTable({ + data, + columns, + pageCount, + filterFields, + enablePinning: true, + enableAdvancedFilter: true, + initialState: { + sorting: [{ id: "approved_at", desc: true }], + columnPinning: { right: ["actions"] }, + }, + getRowId: (originalRow) => String(originalRow.vendor_id), + shallow: false, + clearOnDefault: true, + }) + + return ( + <> + <DataTable + table={table} + + > + + <DataTableAdvancedToolbar + table={table} + filterFields={advancedFilterFields} + shallow={false} + > + </DataTableAdvancedToolbar> + + </DataTable> + + + </> + ) +} diff --git a/lib/project-avl/table/projectAVL-table-columns.tsx b/lib/project-avl/table/projectAVL-table-columns.tsx new file mode 100644 index 00000000..916380e3 --- /dev/null +++ b/lib/project-avl/table/projectAVL-table-columns.tsx @@ -0,0 +1,104 @@ +"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 { ProjectApprovedVendors } from "@/db/schema" +import { projectAVLColumnsConfig } from "@/config/projectAVLColumnsConfig" + +interface GetColumnsProps { + setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<ProjectApprovedVendors> | null>> +} + +/** + * tanstack table 컬럼 정의 (중첩 헤더 버전) + */ +export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<ProjectApprovedVendors>[] { + // ---------------------------------------------------------------- + // 1) select 컬럼 (체크박스) + // ---------------------------------------------------------------- + + + + // ---------------------------------------------------------------- + // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성 + // ---------------------------------------------------------------- + // 3-1) groupMap: { [groupName]: ColumnDef<TagTypeClassFormMappings>[] } + const groupMap: Record<string, ColumnDef<ProjectApprovedVendors>[]> = {} + + projectAVLColumnsConfig.forEach((cfg) => { + // 만약 group가 없으면 "_noGroup" 처리 + const groupName = cfg.group || "_noGroup" + + if (!groupMap[groupName]) { + groupMap[groupName] = [] + } + + // child column 정의 + const childCol: ColumnDef<ProjectApprovedVendors> = { + 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 === "submitted_at"||cfg.id === "approved_at") { + const dateVal = cell.getValue() as Date + return formatDate(dateVal) + } + + return row.getValue(cfg.id) ?? "" + }, + } + + groupMap[groupName].push(childCol) + }) + + // ---------------------------------------------------------------- + // 3-2) groupMap에서 실제 상위 컬럼(그룹)을 만들기 + // ---------------------------------------------------------------- + const nestedColumns: ColumnDef<ProjectApprovedVendors>[] = [] + + // 순서를 고정하고 싶다면 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/project-avl/validations.ts b/lib/project-avl/validations.ts new file mode 100644 index 00000000..2d3b262e --- /dev/null +++ b/lib/project-avl/validations.ts @@ -0,0 +1,41 @@ +import { + createSearchParamsCache, + parseAsArrayOf, + parseAsInteger, + parseAsString, + parseAsStringEnum, +} from "nuqs/server" +import * as z from "zod" + +import { getFiltersStateParser, getSortingStateParser } from "@/lib/parsers" +import { ProjectApprovedVendors } from "@/db/schema" + +export const searchProjectAVLParamsCache = createSearchParamsCache({ + flags: parseAsArrayOf(z.enum(["advancedTable", "floatingBar"])).withDefault( + [] + ), + page: parseAsInteger.withDefault(1), + perPage: parseAsInteger.withDefault(10), + sort: getSortingStateParser<ProjectApprovedVendors>().withDefault([ + { id: "approved_at", desc: true }, + ]), + vendor_code: parseAsString.withDefault(""), + vendor_name: parseAsString.withDefault(""), + tax_id: parseAsString.withDefault(""), + vendor_email: parseAsString.withDefault(""), + vendor_phone: parseAsString.withDefault(""), + vendor_status: parseAsString.withDefault(""), + vendor_type_name_ko: parseAsString.withDefault(""), + project_code: parseAsString.withDefault(""), + project_name: parseAsString.withDefault(""), + pq_status: parseAsString.withDefault(""), + + // advanced filter + filters: getFiltersStateParser().withDefault([]), + joinOperator: parseAsStringEnum(["and", "or"]).withDefault("and"), + search: parseAsString.withDefault(""), + +}) + + +export type GetProjectAVLSchema = Awaited<ReturnType<typeof searchProjectAVLParamsCache.parse>> |
