summaryrefslogtreecommitdiff
path: root/lib/rfqs/vendor-table/vendors-table.tsx
diff options
context:
space:
mode:
Diffstat (limited to 'lib/rfqs/vendor-table/vendors-table.tsx')
-rw-r--r--lib/rfqs/vendor-table/vendors-table.tsx210
1 files changed, 210 insertions, 0 deletions
diff --git a/lib/rfqs/vendor-table/vendors-table.tsx b/lib/rfqs/vendor-table/vendors-table.tsx
new file mode 100644
index 00000000..ae9cba41
--- /dev/null
+++ b/lib/rfqs/vendor-table/vendors-table.tsx
@@ -0,0 +1,210 @@
+"use client"
+
+import * as React from "react"
+import { useRouter } from "next/navigation"
+import { useSession } from "next-auth/react" // Next-auth session hook 추가
+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 { useFeatureFlags } from "./feature-flags-provider"
+import { getColumns } from "./vendors-table-columns"
+import { vendors } from "@/db/schema/vendors"
+import { VendorsTableToolbarActions } from "./vendors-table-toolbar-actions"
+import { VendorsTableFloatingBar } from "./vendors-table-floating-bar"
+import { fetchRfqAttachmentsbyCommentId, getMatchedVendors } from "../service"
+import { InviteVendorsDialog } from "./invite-vendors-dialog"
+import { CommentSheet, MatchedVendorComment } from "./comments-sheet"
+import { MatchedVendorRow } from "@/config/vendorRfbColumnsConfig"
+import { RfqType } from "@/lib/rfqs/validations"
+import { toast } from "sonner"
+
+interface VendorsTableProps {
+ promises: Promise<[Awaited<ReturnType<typeof getMatchedVendors>>]>
+ rfqId: number
+ rfqType: RfqType
+}
+
+export function MatchedVendorsTable({ promises, rfqId, rfqType }: VendorsTableProps) {
+ const { featureFlags } = useFeatureFlags()
+ const { data: session } = useSession() // 세션 정보 가져오기
+
+
+
+ // 1) Suspense로 받아온 데이터
+ const [{ data, pageCount }] = React.use(promises)
+ // data는 MatchedVendorRow[] 형태 (getMatchedVendors에서 반환)
+
+ console.log(data)
+
+ // 2) Row 액션 상태
+ const [rowAction, setRowAction] = React.useState<
+ DataTableRowAction<MatchedVendorRow> | null
+ >(null)
+
+ // **router** 획득
+ const router = useRouter()
+
+ // 3) CommentSheet 에 넣을 상태
+ // => "댓글"은 MatchedVendorComment[] 로 관리해야 함
+ const [initialComments, setInitialComments] = React.useState<
+ MatchedVendorComment[]
+ >([])
+
+ const [isLoadingComments, setIsLoadingComments] = React.useState(false)
+
+ const [commentSheetOpen, setCommentSheetOpen] = React.useState(false)
+ const [selectedVendorIdForComments, setSelectedVendorIdForComments] =
+ React.useState<number | null>(null)
+
+ // 4) rowAction이 바뀌면, type이 "comments"인지 확인 후 open
+ React.useEffect(() => {
+ if (rowAction?.type === "comments") {
+ openCommentSheet(rowAction.row.original.id)
+ }
+ }, [rowAction])
+
+ // 5) 댓글 시트 오픈 함수
+ async function openCommentSheet(vendorId: number) {
+ // Clear previous comments
+ setInitialComments([])
+
+ // Start loading
+ setIsLoadingComments(true)
+
+ // Open the sheet immediately with loading state
+ setSelectedVendorIdForComments(vendorId)
+ setCommentSheetOpen(true)
+
+ // (a) 현재 Row의 comments 불러옴
+ const comments = rowAction?.row.original.comments
+
+ try {
+ if (comments && comments.length > 0) {
+ // (b) 각 comment마다 첨부파일 fetch
+ const commentWithAttachments: MatchedVendorComment[] = await Promise.all(
+ comments.map(async (c) => {
+ const attachments = await fetchRfqAttachmentsbyCommentId(c.id)
+ return {
+ ...c,
+ attachments,
+ }
+ })
+ )
+ setInitialComments(commentWithAttachments)
+ }
+ } catch (error) {
+ console.error("Error loading comments:", error)
+ toast.error("Failed to load comments")
+ } finally {
+ // End loading regardless of success/failure
+ setIsLoadingComments(false)
+ }
+ }
+
+ // 6) 컬럼 정의 (memo)
+ const columns = React.useMemo(
+ () => getColumns({ setRowAction, router, openCommentSheet }),
+ [setRowAction, router]
+ )
+
+ // 7) 필터 정의
+ const filterFields: DataTableFilterField<MatchedVendorRow>[] = []
+
+ const advancedFilterFields: DataTableAdvancedFilterField<MatchedVendorRow>[] = [
+ { 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: "rfqVendorStatus",
+ label: "RFQ Status",
+ type: "multi-select",
+ options: ["INVITED", "ACCEPTED", "REJECTED", "QUOTED"].map((s) => ({
+ label: s,
+ value: s,
+ })),
+ },
+ { id: "rfqVendorUpdated", label: "Updated at", type: "date" },
+ ]
+
+ // 8) 테이블 생성
+ const { table } = useDataTable({
+ data, // MatchedVendorRow[]
+ columns,
+ pageCount,
+ filterFields,
+ enablePinning: true,
+ enableAdvancedFilter: true,
+ initialState: {
+ sorting: [{ id: "rfqVendorUpdated", desc: true }],
+ columnPinning: { right: ["actions"] },
+ },
+ // 행의 고유 ID
+ getRowId: (originalRow) => String(originalRow.id),
+ shallow: false,
+ clearOnDefault: true,
+ })
+
+ // 세션에서 userId 추출하고 숫자로 변환
+ const currentUserId = session?.user?.id ? parseInt(session.user.id, 10) : 0
+
+ console.log(currentUserId,"currentUserId")
+
+ return (
+ <div style={{ maxWidth: '80vw' }}>
+ <DataTable
+ table={table}
+ >
+ <DataTableAdvancedToolbar
+ table={table}
+ filterFields={advancedFilterFields}
+ shallow={false}
+ >
+ <VendorsTableToolbarActions table={table} rfqId={rfqId} />
+ </DataTableAdvancedToolbar>
+ </DataTable>
+
+ {/* 초대 다이얼로그 */}
+ <InviteVendorsDialog
+ vendors={rowAction?.row.original ? [rowAction?.row.original] : []}
+ onOpenChange={() => setRowAction(null)}
+ rfqId={rfqId}
+ open={rowAction?.type === "invite"}
+ showTrigger={false}
+ rfqType={rfqType}
+ />
+
+ {/* 댓글 시트 */}
+ <CommentSheet
+ open={commentSheetOpen}
+ onOpenChange={setCommentSheetOpen}
+ initialComments={initialComments}
+ rfqId={rfqId}
+ vendorId={selectedVendorIdForComments ?? 0}
+ currentUserId={currentUserId}
+ isLoading={isLoadingComments} // Pass the loading state
+ onCommentsUpdated={(updatedComments) => {
+ // Row 의 comments 필드도 업데이트
+ if (!rowAction?.row) return
+ rowAction.row.original.comments = updatedComments
+ }}
+ />
+ </div>
+ )
+} \ No newline at end of file