diff options
Diffstat (limited to 'lib/basic-contract/status')
3 files changed, 348 insertions, 0 deletions
diff --git a/lib/basic-contract/status/basic-contract-columns.tsx b/lib/basic-contract/status/basic-contract-columns.tsx new file mode 100644 index 00000000..6ca4a096 --- /dev/null +++ b/lib/basic-contract/status/basic-contract-columns.tsx @@ -0,0 +1,213 @@ +"use client" + +import * as React from "react" +import { type DataTableRowAction } from "@/types/table" +import { type ColumnDef } from "@tanstack/react-table" +import { Paperclip } from "lucide-react" +import { toast } from "sonner" + +import { getErrorMessage } from "@/lib/handle-error" +import { formatDate, formatDateTime } from "@/lib/utils" +import { Badge } from "@/components/ui/badge" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuSeparator, + DropdownMenuShortcut, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" + +import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header" +import { basicContractColumnsConfig } from "@/config/basicContractColumnsConfig" +import { BasicContractView } from "@/db/schema" + +interface GetColumnsProps { + setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<BasicContractView> | null>> +} + +/** + * 파일 다운로드 함수 + */ +/** + * 파일 다운로드 함수 + */ +const handleFileDownload = (filePath: string | null, fileName: string | null) => { + if (!filePath || !fileName) { + toast.error("파일 정보가 없습니다."); + return; + } + + try { + // 전체 URL 생성 + const fullUrl = `${window.location.origin}${filePath}`; + + // a 태그를 생성하여 다운로드 실행 + const link = document.createElement('a'); + link.href = fullUrl; + link.download = fileName; // 다운로드될 파일명 설정 + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + + toast.success("파일 다운로드를 시작합니다."); + } catch (error) { + console.error("파일 다운로드 오류:", error); + toast.error("파일 다운로드 중 오류가 발생했습니다."); + } +}; + +/** + * tanstack table 컬럼 정의 (중첩 헤더 버전) + */ +export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<BasicContractView>[] { + // ---------------------------------------------------------------- + // 1) select 컬럼 (체크박스) + // ---------------------------------------------------------------- + const selectColumn: ColumnDef<BasicContractView> = { + id: "select", + header: ({ table }) => ( + <Checkbox + checked={ + table.getIsAllPageRowsSelected() || + (table.getIsSomePageRowsSelected() && "indeterminate") + } + onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)} + aria-label="Select all" + className="translate-y-0.5" + /> + ), + cell: ({ row }) => ( + <Checkbox + checked={row.getIsSelected()} + onCheckedChange={(value) => row.toggleSelected(!!value)} + aria-label="Select row" + className="translate-y-0.5" + /> + ), + maxSize: 30, + enableSorting: false, + enableHiding: false, + } + + // ---------------------------------------------------------------- + // 2) 파일 다운로드 컬럼 (아이콘) + // ---------------------------------------------------------------- + const downloadColumn: ColumnDef<BasicContractView> = { + id: "download", + header: "", + cell: ({ row }) => { + const template = row.original; + + return ( + <Button + variant="ghost" + size="icon" + onClick={() => handleFileDownload(template.filePath, template.fileName)} + title={`${template.fileName} 다운로드`} + className="hover:bg-muted" + > + <Paperclip className="h-4 w-4" /> + <span className="sr-only">다운로드</span> + </Button> + ); + }, + maxSize: 30, + enableSorting: false, + } + + + // ---------------------------------------------------------------- + // 4) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성 + // ---------------------------------------------------------------- + // 4-1) groupMap: { [groupName]: ColumnDef<BasicContractView>[] } + const groupMap: Record<string, ColumnDef<BasicContractView>[]> = {} + + basicContractColumnsConfig.forEach((cfg) => { + // 만약 group가 없으면 "_noGroup" 처리 + const groupName = cfg.group || "_noGroup" + + if (!groupMap[groupName]) { + groupMap[groupName] = [] + } + + // child column 정의 + const childCol: ColumnDef<BasicContractView> = { + 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 formatDateTime(dateVal) + } + + // Status 컬럼에 Badge 적용 + if (cfg.id === "status") { + const status = row.getValue(cfg.id) as string + const isActive = status === "ACTIVE" + + return ( + <Badge + variant={isActive ? "default" : "secondary"} + > + {isActive ? "활성" : "비활성"} + </Badge> + ) + } + + // 나머지 컬럼은 그대로 값 표시 + return row.getValue(cfg.id) ?? "" + }, + minSize: 80, + + } + + groupMap[groupName].push(childCol) + }) + + // ---------------------------------------------------------------- + // 4-2) groupMap에서 실제 상위 컬럼(그룹)을 만들기 + // ---------------------------------------------------------------- + const nestedColumns: ColumnDef<BasicContractView>[] = [] + + // 순서를 고정하고 싶다면 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, + }) + } + }) + + // ---------------------------------------------------------------- + // 5) 최종 컬럼 배열: select, download, nestedColumns, actions + // ---------------------------------------------------------------- + return [ + selectColumn, + downloadColumn, // 다운로드 컬럼 추가 + ...nestedColumns, + ] +}
\ No newline at end of file diff --git a/lib/basic-contract/status/basic-contract-table.tsx b/lib/basic-contract/status/basic-contract-table.tsx new file mode 100644 index 00000000..22845144 --- /dev/null +++ b/lib/basic-contract/status/basic-contract-table.tsx @@ -0,0 +1,95 @@ +"use client"; + +import * as React from "react"; +import { DataTable } from "@/components/data-table/data-table"; +import { Button } from "@/components/ui/button"; +import { Plus, Loader2 } from "lucide-react"; +import { useDataTable } from "@/hooks/use-data-table"; +import { DataTableAdvancedToolbar } from "@/components/data-table/data-table-advanced-toolbar"; +import type { + DataTableAdvancedFilterField, + DataTableFilterField, + DataTableRowAction, +} from "@/types/table" +import { toast } from "sonner"; +import { getColumns } from "./basic-contract-columns"; +import { getBasicContracts } from "../service"; +import { BasicContractView } from "@/db/schema"; +import { BasicContractTableToolbarActions } from "./basicContract-table-toolbar-actions"; + + +interface BasicTemplateTableProps { + promises: Promise< + [ + Awaited<ReturnType<typeof getBasicContracts>>, + ] + > +} + + +export function BasicContractsTable({ promises }: BasicTemplateTableProps) { + + + const [rowAction, setRowAction] = + React.useState<DataTableRowAction<BasicContractView> | null>(null) + + + const [{ data, pageCount }] = + React.use(promises) + + // 컬럼 설정 - 외부 파일에서 가져옴 + const columns = React.useMemo( + () => getColumns({ setRowAction }), + [setRowAction] + ) + + // config 기반으로 필터 필드 설정 + const advancedFilterFields: DataTableAdvancedFilterField<BasicContractView>[] = [ + { id: "templateName", label: "템플릿명", type: "text" }, + { + id: "status", label: "상태", type: "select", options: [ + { label: "활성", value: "ACTIVE" }, + { label: "비활성", value: "INACTIVE" }, + ] + }, + { id: "userName", label: "요청자", type: "text" }, + { id: "vendorName", label: "업체명", type: "text" }, + { id: "vendorCode", label: "업체코드", type: "text" }, + { id: "vendorEmail", label: "업체대표이메일", type: "text" }, + { id: "createdAt", label: "생성일", type: "date" }, + { id: "updatedAt", label: "수정일", 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} + > + <BasicContractTableToolbarActions table={table} /> + + </DataTableAdvancedToolbar> + </DataTable> + + </> + + ); +}
\ No newline at end of file diff --git a/lib/basic-contract/status/basicContract-table-toolbar-actions.tsx b/lib/basic-contract/status/basicContract-table-toolbar-actions.tsx new file mode 100644 index 00000000..cee94790 --- /dev/null +++ b/lib/basic-contract/status/basicContract-table-toolbar-actions.tsx @@ -0,0 +1,40 @@ +"use client" + +import * as React from "react" +import { type Task } from "@/db/schema/tasks" +import { type Table } from "@tanstack/react-table" +import { Download, Upload } from "lucide-react" + +import { exportTableToExcel } from "@/lib/export" +import { Button } from "@/components/ui/button" +import { BasicContractView } from "@/db/schema" + +interface TemplateTableToolbarActionsProps { + table: Table<BasicContractView> +} + +export function BasicContractTableToolbarActions({ table }: TemplateTableToolbarActionsProps) { + // 파일 input을 숨기고, 버튼 클릭 시 참조해 클릭하는 방식 + + + return ( + <div className="flex items-center gap-2"> + + {/** 4) Export 버튼 */} + <Button + variant="outline" + size="sm" + onClick={() => + exportTableToExcel(table, { + filename: "basci-contract", + 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 |
