diff options
Diffstat (limited to 'lib/tbe-tech')
| -rw-r--r-- | lib/tbe-tech/table/tbe-table-columns.tsx | 347 | ||||
| -rw-r--r-- | lib/tbe-tech/table/tbe-table-toolbar-actions.tsx | 68 | ||||
| -rw-r--r-- | lib/tbe-tech/table/tbe-table.tsx | 304 |
3 files changed, 719 insertions, 0 deletions
diff --git a/lib/tbe-tech/table/tbe-table-columns.tsx b/lib/tbe-tech/table/tbe-table-columns.tsx new file mode 100644 index 00000000..2349db7e --- /dev/null +++ b/lib/tbe-tech/table/tbe-table-columns.tsx @@ -0,0 +1,347 @@ +"use client" + +import * as React from "react" +import { type DataTableRowAction } from "@/types/table" +import { type ColumnDef } from "@tanstack/react-table" +import { Download, MessageSquare } from "lucide-react" +import { toast } from "sonner" + +import { formatDate } from "@/lib/utils" +import { Badge } from "@/components/ui/badge" +import { Button } from "@/components/ui/button" +import { Checkbox } from "@/components/ui/checkbox" + +import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header" +import { useRouter } from "next/navigation" + +import { + + vendorTbeColumnsConfig, + VendorWithTbeFields, +} from "@/config/vendorTbeColumnsConfig" + +type NextRouter = ReturnType<typeof useRouter> + +interface GetColumnsProps { + setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<VendorWithTbeFields> | null>> + router: NextRouter + openCommentSheet: (vendorId: number, rfqId: number) => void + openFilesDialog: (tbeId: number, vendorId: number, rfqId: number) => void + openVendorContactsDialog: (vendorId: number, vendor: VendorWithTbeFields) => void // 수정된 시그니처 + +} + + +/** + * tanstack table 컬럼 정의 (중첩 헤더 버전) + */ +export function getColumns({ + setRowAction, + router, + openCommentSheet, + openFilesDialog, + openVendorContactsDialog +}: GetColumnsProps): ColumnDef<VendorWithTbeFields>[] { + // ---------------------------------------------------------------- + // 1) Select 컬럼 (체크박스) + // ---------------------------------------------------------------- + const selectColumn: ColumnDef<VendorWithTbeFields> = { + 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" + /> + ), + size: 40, + enableSorting: false, + enableHiding: false, + } + + // ---------------------------------------------------------------- + // 2) 그룹화(Nested) 컬럼 구성 + // ---------------------------------------------------------------- + const groupMap: Record<string, ColumnDef<VendorWithTbeFields>[]> = {} + + vendorTbeColumnsConfig.forEach((cfg) => { + const groupName = cfg.group || "_noGroup" + if (!groupMap[groupName]) { + groupMap[groupName] = [] + } + + // childCol: ColumnDef<VendorWithTbeFields> + const childCol: ColumnDef<VendorWithTbeFields> = { + 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, getValue }) => { + // 1) 필드값 가져오기 + const val = getValue() + + if (cfg.id === "vendorName") { + const vendor = row.original; + const vendorId = vendor.vendorId; + + // 협력업체 이름을 클릭할 수 있는 버튼으로 렌더링 + const handleVendorNameClick = () => { + if (vendorId) { + openVendorContactsDialog(vendorId, vendor); // vendor 전체 객체 전달 + } else { + toast.error("협력업체 ID를 찾을 수 없습니다."); + } + }; + + return ( + <Button + variant="link" + className="p-0 h-auto text-left font-normal justify-start hover:underline" + onClick={handleVendorNameClick} + > + {val as string} + </Button> + ); + } + if (cfg.id === "tbeResult") { + const vendor = row.original; + const tbeResult = vendor.tbeResult; + const filesCount = vendor.files?.length ?? 0; + + // Only show button or link if there are files + if (filesCount > 0) { + // Function to handle clicking on the result + const handleTbeResultClick = () => { + setRowAction({ row, type: "tbeResult" }); + }; + + if (!tbeResult) { + // No result yet, but files exist - show "결과 입력" button + return ( + <Button + variant="outline" + size="sm" + onClick={handleTbeResultClick} + > + 결과 입력 + </Button> + ); + } else { + // Result exists - show as a hyperlink + let badgeVariant: "default" | "outline" | "destructive" | "secondary" = "outline"; + + // Set badge variant based on result + if (tbeResult === "pass") { + badgeVariant = "default"; + } else if (tbeResult === "non-pass") { + badgeVariant = "destructive"; + } else if (tbeResult === "conditional pass") { + badgeVariant = "secondary"; + } + + return ( + <Button + variant="link" + className="p-0 h-auto underline" + onClick={handleTbeResultClick} + > + <Badge variant={badgeVariant}> + {tbeResult} + </Badge> + </Button> + ); + } + } + + // No files available, return empty cell + return null; + } + + + if (cfg.id === "vendorStatus") { + const statusVal = row.original.vendorStatus + if (!statusVal) return null + // const Icon = getStatusIcon(statusVal) + return ( + <Badge variant="outline"> + {statusVal} + </Badge> + ) + } + + + if (cfg.id === "rfqVendorStatus") { + const statusVal = row.original.rfqVendorStatus + if (!statusVal) return null + // const Icon = getStatusIcon(statusVal) + const variant = statusVal ==="INVITED"?"default" :statusVal ==="DECLINED"?"destructive":statusVal ==="ACCEPTED"?"secondary":"outline" + return ( + <Badge variant={variant}> + {statusVal} + </Badge> + ) + } + + // 예) TBE Updated (날짜) + if (cfg.id === "tbeUpdated") { + const dateVal = val as Date | undefined + if (!dateVal) return null + return formatDate(dateVal) + } + + // 그 외 필드는 기본 값 표시 + return val ?? "" + }, + } + + groupMap[groupName].push(childCol) + }) + + // groupMap → nestedColumns + const nestedColumns: ColumnDef<VendorWithTbeFields>[] = [] + Object.entries(groupMap).forEach(([groupName, colDefs]) => { + if (groupName === "_noGroup") { + nestedColumns.push(...colDefs) + } else { + nestedColumns.push({ + id: groupName, + header: groupName, + columns: colDefs, + }) + } + }) +// 파일 칼럼 +const filesColumn: ColumnDef<VendorWithTbeFields> = { + id: "files", + header: ({ column }) => ( + <DataTableColumnHeaderSimple column={column} title="Response Files" /> + ), + cell: ({ row }) => { + const vendor = row.original + const filesCount = vendor.files?.length ?? 0 + + function handleClick() { + // setRowAction으로 타입만 설정하고 끝내는 방법도 가능하지만 + // 혹은 바로 openFilesDialog()를 호출해도 됨. + setRowAction({ row, type: "files" }) + // 필요한 값을 직접 호출해서 넘겨줄 수도 있음. + openFilesDialog( + vendor.tbeId ?? 0, + vendor.vendorId ?? 0, + vendor.rfqId ?? 0, + ) + } + + return ( + <Button + variant="ghost" + size="sm" + className="relative h-8 w-8 p-0 group" + onClick={handleClick} + aria-label={filesCount > 0 ? `View ${filesCount} files` : "Upload file"} + > + <Download className="h-4 w-4" /> + {filesCount > 0 && ( + <Badge variant="secondary" className="absolute -top-1 -right-1 h-4 min-w-[1rem] p-0 text-[0.625rem] leading-none flex items-center justify-center"> + {filesCount} + </Badge> + )} + </Button> + ) + }, + enableSorting: false, + minSize: 80, +} + // ---------------------------------------------------------------- + // 2) 액션컬럼 (빈 상태로 유지하여 에러 방지) + // ---------------------------------------------------------------- + const actionsColumn: ColumnDef<VendorWithTbeFields> = { + id: "actions", + enableHiding: false, + cell: () => { + // 빈 셀 반환 (액션 없음) + return null + }, + size: 0, + enableSorting: false, + } + +// 댓글 칼럼 +const commentsColumn: ColumnDef<VendorWithTbeFields> = { + id: "comments", + header: ({ column }) => ( + <DataTableColumnHeaderSimple column={column} title="Comments" /> + ), + cell: ({ row }) => { + const vendor = row.original + const commCount = vendor.comments?.length ?? 0 + + function handleClick() { + // setRowAction() 로 type 설정 + setRowAction({ row, type: "comments" }) + // 필요하면 즉시 openCommentSheet() 직접 호출 + openCommentSheet( + vendor.vendorId ?? 0, + vendor.rfqId ?? 0, + ) + } + + return ( + <Button + variant="ghost" + size="sm" + className="relative h-8 w-8 p-0 group" + onClick={handleClick} + aria-label={ + commCount > 0 ? `View ${commCount} comments` : "No comments" + } + > + <MessageSquare className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" /> + {commCount > 0 && ( + <Badge + variant="secondary" + className="pointer-events-none absolute -top-1 -right-1 h-4 min-w-[1rem] p-0 text-[0.625rem] leading-none flex items-center justify-center" + > + {commCount} + </Badge> + )} + <span className="sr-only"> + {commCount > 0 ? `${commCount} Comments` : "No Comments"} + </span> + </Button> + ) + }, + enableSorting: false, + minSize: 80, +} +// ---------------------------------------------------------------- +// 5) 최종 컬럼 배열 - Update to include the files column +// ---------------------------------------------------------------- +return [ + selectColumn, + ...nestedColumns, + filesColumn, // Add the files column before comments + commentsColumn, + actionsColumn, +] + +}
\ No newline at end of file diff --git a/lib/tbe-tech/table/tbe-table-toolbar-actions.tsx b/lib/tbe-tech/table/tbe-table-toolbar-actions.tsx new file mode 100644 index 00000000..d3502032 --- /dev/null +++ b/lib/tbe-tech/table/tbe-table-toolbar-actions.tsx @@ -0,0 +1,68 @@ +"use client" + +import * as React from "react" +import { type Table } from "@tanstack/react-table" +import { Download } from "lucide-react" +import { toast } from "sonner" +import { useRouter } from "next/navigation" + +import { exportTableToExcel } from "@/lib/export" +import { Button } from "@/components/ui/button" + +import { InviteVendorsDialog } from "@/lib/rfqs-tech/tbe-table/invite-vendors-dialog" +import { VendorWithTbeFields } from "@/config/vendorTbeColumnsConfig" + +interface VendorsTableToolbarActionsProps { + table: Table<VendorWithTbeFields> + rfqId: number +} + +export function VendorsTableToolbarActions({ table, rfqId }: VendorsTableToolbarActionsProps) { + const router = useRouter() + + const invitationPossibleVendors = React.useMemo(() => { + const selectedRows = table.getSelectedRowModel().rows; + const vendors = selectedRows.map(row => row.original); + + const rfqIds = new Set(vendors.map(vendor => vendor.rfqId)); + if (rfqIds.size > 1) { + toast.error("동일한 rfq에 대해 초대가 가능합니다"); + return []; + } + + return vendors.filter(vendor => vendor.technicalResponseStatus === null); + }, [table.getSelectedRowModel().rows]); + + const selectedRfqId = invitationPossibleVendors[0]?.rfqId ?? 0; + console.log("selectedRfqId", selectedRfqId) + + return ( + <div className="flex items-center gap-2"> + {invitationPossibleVendors.length > 0 && ( + <InviteVendorsDialog + vendors={invitationPossibleVendors} + rfqId={selectedRfqId} + onSuccess={() => { + table.toggleAllRowsSelected(false); + router.refresh(); + }} + showTrigger={true} + /> + )} + <Button + variant="outline" + size="sm" + onClick={() => + exportTableToExcel(table, { + filename: "tasks", + 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 diff --git a/lib/tbe-tech/table/tbe-table.tsx b/lib/tbe-tech/table/tbe-table.tsx new file mode 100644 index 00000000..3d981450 --- /dev/null +++ b/lib/tbe-tech/table/tbe-table.tsx @@ -0,0 +1,304 @@ +"use client" + +import * as React from "react" +import { useRouter } from "next/navigation" +import type { + DataTableAdvancedFilterField, + DataTableFilterField, + DataTableRowAction, +} from "@/types/table" + +import { toSentenceCase } from "@/lib/utils" +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 "./tbe-table-columns" +import { vendors } from "@/db/schema/vendors" +import { CommentSheet, TbeComment } from "@/lib/rfqs-tech/tbe-table/comments-sheet" +import { VendorWithTbeFields } from "@/config/vendorTbeColumnsConfig" +import { TBEFileDialog } from "@/lib/rfqs-tech/tbe-table/file-dialog" +import { fetchRfqAttachmentsbyCommentId, getAllTBE } from "@/lib/rfqs-tech/service" +import { VendorsTableToolbarActions } from "./tbe-table-toolbar-actions" +import { TbeResultDialog } from "@/lib/rfqs-tech/tbe-table/tbe-result-dialog" +import { toast } from "sonner" +import { VendorContactsDialog } from "@/lib/rfqs-tech/tbe-table/vendor-contact-dialog" +import { InviteVendorsDialog } from "@/lib/rfqs-tech/tbe-table/invite-vendors-dialog" + +interface VendorsTableProps { + promises: Promise<[ + Awaited<ReturnType<typeof getAllTBE>>, + ]> +} + +export function AllTbeTable({ promises }: VendorsTableProps) { + const router = useRouter() + + // Suspense로 받아온 데이터 + const [{ data: rawData, pageCount }] = React.use(promises) + + // 벤더별로 데이터 그룹화 + const data = React.useMemo(() => { + const vendorMap = new Map<number, VendorWithTbeFields>() + + rawData.forEach((item) => { + const vendorId = item.vendorId + + if (vendorMap.has(vendorId)) { + // 기존 벤더 데이터가 있으면 파일과 댓글을 합침 + const existing = vendorMap.get(vendorId)! + + // 파일 합치기 (중복 제거) + const existingFileIds = new Set(existing.files.map(f => f.id)) + const newFiles = item.files.filter(f => !existingFileIds.has(f.id)) + existing.files = [...existing.files, ...newFiles] + + // 댓글 합치기 (중복 제거) + const existingCommentIds = new Set(existing.comments.map(c => c.id)) + const newComments = item.comments.filter(c => !existingCommentIds.has(c.id)) + existing.comments = [...existing.comments, ...newComments] + + } else { + // 새로운 벤더 데이터 추가 + vendorMap.set(vendorId, { + ...item, + vendorResponseId: item.id, + technicalResponseId: item.id, + rfqId: item.rfqId + }) + } + }) + + return Array.from(vendorMap.values()) + }, [rawData]) + + const [rowAction, setRowAction] = React.useState<DataTableRowAction<VendorWithTbeFields> | null>(null) + + // 댓글 시트 관련 state + const [initialComments, setInitialComments] = React.useState<TbeComment[]>([]) + const [isLoadingComments, setIsLoadingComments] = React.useState(false) + + const [commentSheetOpen, setCommentSheetOpen] = React.useState(false) + const [selectedVendorIdForComments, setSelectedVendorIdForComments] = React.useState<number | null>(null) + const [selectedRfqIdForComments, setSelectedRfqIdForComments] = React.useState<number | null>(null) + + // 파일 다이얼로그 관련 state + const [isFileDialogOpen, setIsFileDialogOpen] = React.useState(false) + const [selectedVendorIdForFiles, setSelectedVendorIdForFiles] = React.useState<number | null>(null) + const [selectedTbeIdForFiles, setSelectedTbeIdForFiles] = React.useState<number | null>(null) + const [selectedRfqIdForFiles, setSelectedRfqIdForFiles] = React.useState<number | null>(null) + + const [isContactDialogOpen, setIsContactDialogOpen] = React.useState(false) + const [selectedVendor, setSelectedVendor] = React.useState<VendorWithTbeFields | null>(null) + const [selectedVendorId, setSelectedVendorId] = React.useState<number | null>(null) + + // 테이블 리프레시용 + const handleRefresh = React.useCallback(() => { + router.refresh(); + }, [router]); + + // ----------------------------------------------------------- + // 특정 action이 설정될 때마다 실행되는 effect + // ----------------------------------------------------------- + React.useEffect(() => { + if (!rowAction) return + + if (rowAction.type === "comments") { + openCommentSheet( + rowAction.row.original.vendorId ?? 0, + rowAction.row.original.rfqId ?? 0, + ) + } else if (rowAction.type === "files") { + openFilesDialog( + rowAction.row.original.tbeId ?? 0, + rowAction.row.original.vendorId ?? 0, + rowAction.row.original.rfqId ?? 0, + ) + } else if (rowAction.type === "invite") { + // 선택된 row 정보 로그 출력 + const selectedRows = table.getSelectedRowModel().rows + console.log("선택된 Row 정보:", { + selectedRows: selectedRows.map(row => ({ + rfqId: row.original.rfqId, + vendorId: row.original.vendorId, + vendorName: row.original.vendorName, + 전체데이터: row.original + })), + 총선택수: selectedRows.length + }) + + // 선택된 벤더들의 RFQ ID가 모두 동일한지 체크 + const rfqIds = new Set(selectedRows.map(row => row.original.rfqId)) + + if (rfqIds.size > 1) { + toast.error("동일한 rfq에 대해 초대가 가능합니다") + setRowAction(null) + return + } + + // 선택된 첫 번째 row의 rfqId 사용 + const selectedRfqId = selectedRows[0]?.original.rfqId + console.log("사용될 RFQ ID:", selectedRfqId) + } + }, [rowAction]) + + // ----------------------------------------------------------- + // 댓글 시트 열기 + // ----------------------------------------------------------- + async function openCommentSheet(vendorId: number, rfqId: number) { + setInitialComments([]) + setIsLoadingComments(true) + const comments = rowAction?.row.original.comments + try { + if (comments && comments.length > 0) { + const commentWithAttachments: TbeComment[] = await Promise.all( + comments.map(async (c) => { + const attachments = await fetchRfqAttachmentsbyCommentId(c.id) + return { + ...c, + commentedBy: 1, // DB나 API 응답에 있다고 가정 + attachments, + } + }) + ) + setInitialComments(commentWithAttachments) + } + + setSelectedVendorIdForComments(vendorId) + setSelectedRfqIdForComments(rfqId) + setCommentSheetOpen(true) + } catch (error) { + console.error("Error loading comments:", error) + toast.error("Failed to load comments") + } finally { + // End loading regardless of success/failure + setIsLoadingComments(false) + } + } + + // ----------------------------------------------------------- + // 파일 다이얼로그 열기 + // ----------------------------------------------------------- + const openFilesDialog = (tbeId: number, vendorId: number, rfqId: number) => { + setSelectedTbeIdForFiles(tbeId) + setSelectedVendorIdForFiles(vendorId) + setSelectedRfqIdForFiles(rfqId) + setIsFileDialogOpen(true) + } + + const openVendorContactsDialog = (vendorId: number, vendor: VendorWithTbeFields) => { + setSelectedVendorId(vendorId) + setSelectedVendor(vendor) + setIsContactDialogOpen(true) + } + + + // ----------------------------------------------------------- + // 테이블 컬럼 + // ----------------------------------------------------------- + const columns = React.useMemo( + () => + getColumns({ + setRowAction, + router, + openCommentSheet, // 필요하면 직접 호출 가능 + openFilesDialog, + openVendorContactsDialog, + }), + [setRowAction, router] + ) + + // ----------------------------------------------------------- + // 필터 필드 + // ----------------------------------------------------------- + const filterFields: DataTableFilterField<VendorWithTbeFields>[] = [ + // 예: 표준 필터 + ] + const advancedFilterFields: DataTableAdvancedFilterField<VendorWithTbeFields>[] = [ + { id: "vendorName", label: "Vendor Name", type: "text" }, + { id: "vendorCode", label: "Vendor Code", type: "text" }, + { id: "email", label: "Email", type: "text" }, + { id: "country", label: "Country", type: "text" }, + { + id: "vendorStatus", + label: "Vendor Status", + type: "multi-select", + options: vendors.status.enumValues.map((status) => ({ + label: toSentenceCase(status), + value: status, + })), + }, + { id: "rfqVendorUpdated", label: "Updated at", type: "date" }, + ] + + // ----------------------------------------------------------- + // 테이블 생성 훅 + // ----------------------------------------------------------- + const { table } = useDataTable({ + data, + columns, + pageCount, + filterFields, + enablePinning: true, + enableAdvancedFilter: true, + initialState: { + sorting: [{ id: "rfqVendorUpdated", desc: true }], + columnPinning: { right: ["files", "comments"] }, + }, + getRowId: (originalRow) => (`${originalRow.id}${originalRow.rfqId}`), + shallow: false, + clearOnDefault: true, + }) + + return ( + <> + <DataTable table={table}> + <DataTableAdvancedToolbar + table={table} + filterFields={advancedFilterFields} + shallow={false} + > + <VendorsTableToolbarActions + table={table} + rfqId={table.getSelectedRowModel().rows[0]?.original.rfqId ?? 0} + /> + </DataTableAdvancedToolbar> + </DataTable> + + {/* 댓글 시트 */} + <CommentSheet + currentUserId={1} + open={commentSheetOpen} + tbeId={selectedTbeIdForFiles ?? 0} + onOpenChange={setCommentSheetOpen} + vendorId={selectedVendorIdForComments ?? 0} + rfqId={selectedRfqIdForComments ?? 0} + isLoading={isLoadingComments} + initialComments={initialComments} + /> + + {/* 파일 업로드/다운로드 다이얼로그 */} + <TBEFileDialog + isOpen={isFileDialogOpen} + onOpenChange={setIsFileDialogOpen} + tbeId={selectedTbeIdForFiles ?? 0} + vendorId={selectedVendorIdForFiles ?? 0} + rfqId={selectedRfqIdForFiles ?? 0} + onRefresh={handleRefresh} + /> + + <TbeResultDialog + open={rowAction?.type === "tbeResult"} + onOpenChange={() => setRowAction(null)} + tbe={rowAction?.row.original ?? null} + /> + + <VendorContactsDialog + isOpen={isContactDialogOpen} + onOpenChange={setIsContactDialogOpen} + vendorId={selectedVendorId} + vendor={selectedVendor} + /> + + </> + ) +}
\ No newline at end of file |
