1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
|
"use client"
import * as React from "react"
import { useRouter } from "next/navigation"
import { useSession } from "next-auth/react"
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 "./vendors-table-columns"
import { vendors } from "@/db/schema/vendors"
import { VendorsTableToolbarActions } from "./vendors-table-toolbar-actions"
import { fetchRfqAttachmentsbyCommentId, getMatchedVendors } from "../service"
import { InviteVendorsDialog } from "./invite-vendors-dialog"
import { CommentSheet } from "./comments-sheet"
import { RfqShipVendorRow } from "@/config/vendorRfqShipColumnsConfig"
import { RfqType } from "../validations"
import { toast } from "sonner"
// CommentSheet와 호환되는 코멘트 타입 정의
interface RfqShipComment {
id: number;
commentText: string;
vendorId?: number;
createdAt: Date;
commentedBy?: number;
attachments?: {
id: number;
fileName: string;
filePath: string;
}[];
}
interface VendorsTableProps {
promises: Promise<[Awaited<ReturnType<typeof getMatchedVendors>>]>
rfqId: number
rfqType: RfqType
}
export function MatchedVendorsTable({ promises, rfqId, rfqType }: VendorsTableProps) {
const { data: session } = useSession()
// 1) Suspense로 받아온 데이터
const [{ data, pageCount }] = React.use(promises)
// 2) Row 액션 상태
const [rowAction, setRowAction] = React.useState<
DataTableRowAction<RfqShipVendorRow> | null
>(null)
// router 획득
const router = useRouter()
// 3) CommentSheet 에 넣을 상태
const [initialComments, setInitialComments] = React.useState<
RfqShipComment[]
>([])
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: RfqShipComment[] = await Promise.all(
comments.map(async (c) => {
const attachments = await fetchRfqAttachmentsbyCommentId(c.id)
return {
...c,
createdAt: c.createdAt || new Date(),
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,
}),
[router]
)
// 7) 필터 정의
const filterFields: DataTableFilterField<RfqShipVendorRow>[] = []
const advancedFilterFields: DataTableAdvancedFilterField<RfqShipVendorRow>[] = [
{ id: "vendorName", label: "Vendor Name", type: "text" },
{ id: "vendorCode", label: "Vendor Code", type: "text" },
{ id: "projectCode", label: "Project Code", type: "text" },
{ id: "projectName", label: "Project Name", type: "text" },
{
id: "vendorStatus",
label: "Vendor Status",
type: "multi-select",
options: vendors.status.enumValues.map((status) => ({
label: toSentenceCase(status),
value: status,
})),
},
{
id: "commercialResponseStatus",
label: "Response Status",
type: "multi-select",
options: ["DRAFT", "SUBMITTED", "REJECTED", "APPROVED"].map((s) => ({
label: s,
value: s,
})),
},
{ id: "respondedAt", label: "Response Date", type: "date" },
]
// 8) 테이블 생성
const { table } = useDataTable({
data: data as unknown as RfqShipVendorRow[], // 타입 변환
columns,
pageCount,
filterFields,
enablePinning: true,
enableAdvancedFilter: true,
initialState: {
sorting: [{ id: "respondedAt", 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
return (
<>
<DataTable
table={table}
>
<DataTableAdvancedToolbar
table={table}
filterFields={advancedFilterFields}
shallow={false}
>
<VendorsTableToolbarActions
table={table as any}
rfqId={rfqId}
rfqType={rfqType}
/>
</DataTableAdvancedToolbar>
</DataTable>
{/* CBE 요청 다이얼로그 */}
<InviteVendorsDialog
vendors={rowAction?.row.original ? [rowAction?.row.original as any] : []}
onOpenChange={() => setRowAction(null)}
rfqId={rfqId}
rfqType={rfqType}
open={rowAction?.type === "invite"}
showTrigger={false}
currentUser={session?.user}
directCbe={true}
/>
{/* 댓글 시트 */}
<CommentSheet
open={commentSheetOpen}
onOpenChange={setCommentSheetOpen}
initialComments={initialComments as any}
rfqId={rfqId}
vendorId={selectedVendorIdForComments ?? 0}
currentUserId={currentUserId}
isLoading={isLoadingComments}
onCommentsUpdated={(updatedComments: any) => {
// Row 의 comments 필드도 업데이트
if (!rowAction?.row) return
rowAction.row.original.comments = updatedComments
}}
/>
</>
)
}
|