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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
|
// lib/tbe-last/service.ts
'use server'
import { unstable_cache } from "next/cache";
import db from "@/db/db";
import { and, desc, asc, eq, sql, or, isNull, isNotNull, ne, inArray } from "drizzle-orm";
import { tbeLastView, tbeDocumentsView } from "@/db/schema";
import { rfqPrItems } from "@/db/schema/rfqLast";
import { rfqLastTbeDocumentReviews, rfqLastTbePdftronComments, rfqLastTbeVendorDocuments,rfqLastTbeSessions } from "@/db/schema";
import { filterColumns } from "@/lib/filter-columns";
import { GetTBELastSchema } from "./validations";
import { getServerSession } from "next-auth"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"
// ==========================================
// 1. TBE 세션 목록 조회
// ==========================================
export async function getAllTBELast(input: GetTBELastSchema) {
return unstable_cache(
async () => {
// 페이징
const offset = ((input.page ?? 1) - 1) * (input.perPage ?? 10);
const limit = input.perPage ?? 10;
// 고급 필터
const advancedWhere = filterColumns({
table: tbeLastView,
filters: input.filters ?? [],
joinOperator: input.joinOperator ?? "and",
});
// 글로벌 검색
let globalWhere;
if (input.search) {
const s = `%${input.search}%`;
globalWhere = or(
sql`${tbeLastView.sessionCode} ILIKE ${s}`,
sql`${tbeLastView.rfqCode} ILIKE ${s}`,
sql`${tbeLastView.vendorName} ILIKE ${s}`,
sql`${tbeLastView.vendorCode} ILIKE ${s}`,
sql`${tbeLastView.projectCode} ILIKE ${s}`,
sql`${tbeLastView.projectName} ILIKE ${s}`,
sql`${tbeLastView.packageNo} ILIKE ${s}`,
sql`${tbeLastView.packageName} ILIKE ${s}`
);
}
// 최종 WHERE
const finalWhere = and(advancedWhere, globalWhere);
// 정렬
const orderBy = input.sort?.length
? input.sort.map((s) => {
const col = (tbeLastView as any)[s.id];
return s.desc ? desc(col) : asc(col);
})
: [desc(tbeLastView.createdAt)];
// 메인 SELECT
const [rows, total] = await db.transaction(async (tx) => {
const data = await tx
.select()
.from(tbeLastView)
.where(finalWhere)
.orderBy(...orderBy)
.offset(offset)
.limit(limit);
const [{ count }] = await tx
.select({ count: sql<number>`count(*)`.as("count") })
.from(tbeLastView)
.where(finalWhere);
return [data, Number(count)];
});
const pageCount = Math.ceil(total / limit);
return { data: rows, pageCount };
},
[JSON.stringify(input)],
{
revalidate: 60,
tags: ["tbe-last-sessions"],
}
)();
}
// ==========================================
// 2. TBE 세션 상세 조회
// ==========================================
export async function getTBESessionDetail(sessionId: number) {
// return unstable_cache(
// async () => {
// 세션 기본 정보
const [session] = await db
.select()
.from(tbeLastView)
.where(eq(tbeLastView.tbeSessionId, sessionId))
.limit(1);
if (!session) {
return null;
}
// PR 아이템 목록
const prItems = await db
.select()
.from(rfqPrItems)
.where(eq(rfqPrItems.rfqsLastId, session.rfqId))
.orderBy(desc(rfqPrItems.majorYn), asc(rfqPrItems.prItem));
// 문서 목록 (구매자 + 벤더)
const documents = await db
.select()
.from(tbeDocumentsView)
.where(eq(tbeDocumentsView.tbeSessionId, sessionId))
.orderBy(
sql`CASE document_source WHEN 'buyer' THEN 0 ELSE 1 END`,
asc(tbeDocumentsView.documentName)
);
// PDFTron 코멘트 통계
const comments = await db
.select({
documentReviewId: rfqLastTbePdftronComments.documentReviewId,
totalCount: sql<number>`count(*)`.as("total_count"),
openCount: sql<number>`sum(case when status = 'open' then 1 else 0 end)`.as("open_count"),
})
.from(rfqLastTbePdftronComments)
.innerJoin(
rfqLastTbeDocumentReviews,
eq(rfqLastTbePdftronComments.documentReviewId, rfqLastTbeDocumentReviews.id)
)
.where(eq(rfqLastTbeDocumentReviews.tbeSessionId, sessionId))
.groupBy(rfqLastTbePdftronComments.documentReviewId);
// 문서별 코멘트 수 매핑
const commentsByDocumentId = new Map(
comments.map(c => [c.documentReviewId, {
totalCount: c.totalCount,
openCount: c.openCount
}])
);
// 문서에 코멘트 정보 추가
const documentsWithComments = documents.map(doc => ({
...doc,
comments: doc.documentReviewId
? commentsByDocumentId.get(doc.documentReviewId) || { totalCount: 0, openCount: 0 }
: { totalCount: 0, openCount: 0 }
}));
return {
session,
prItems,
documents: documentsWithComments,
};
// },
// [`tbe-session-${sessionId}`],
// {
// revalidate: 60,
// tags: [`tbe-session-${sessionId}`],
// }
// )();
}
// ==========================================
// 3. 문서별 PDFTron 코멘트 조회
// ==========================================
export async function getDocumentComments(documentReviewId: number) {
const comments = await db
.select({
id: rfqLastTbePdftronComments.id,
pdftronAnnotationId: rfqLastTbePdftronComments.pdftronAnnotationId,
pageNumber: rfqLastTbePdftronComments.pageNumber,
commentText: rfqLastTbePdftronComments.commentText,
commentCategory: rfqLastTbePdftronComments.commentCategory,
severity: rfqLastTbePdftronComments.severity,
status: rfqLastTbePdftronComments.status,
createdBy: rfqLastTbePdftronComments.createdBy,
createdByType: rfqLastTbePdftronComments.createdByType,
createdAt: rfqLastTbePdftronComments.createdAt,
resolvedBy: rfqLastTbePdftronComments.resolvedBy,
resolvedAt: rfqLastTbePdftronComments.resolvedAt,
resolutionNote: rfqLastTbePdftronComments.resolutionNote,
replies: rfqLastTbePdftronComments.replies,
})
.from(rfqLastTbePdftronComments)
.where(eq(rfqLastTbePdftronComments.documentReviewId, documentReviewId))
.orderBy(asc(rfqLastTbePdftronComments.pageNumber), desc(rfqLastTbePdftronComments.createdAt));
return comments;
}
// ==========================================
// 5. 벤더 문서 업로드
// ==========================================
export async function uploadVendorDocument(
sessionId: number,
file: {
fileName: string;
originalFileName: string;
filePath: string;
fileSize: number;
fileType: string;
documentType: string;
description?: string;
}
) {
const [document] = await db
.insert(rfqLastTbeVendorDocuments)
.values({
tbeSessionId: sessionId,
documentType: file.documentType as any,
fileName: file.fileName,
originalFileName: file.originalFileName,
filePath: file.filePath,
fileSize: file.fileSize,
fileType: file.fileType,
description: file.description,
reviewRequired: true,
reviewStatus: "pending",
submittedBy: 1, // TODO: 실제 사용자 ID
submittedAt: new Date(),
})
.returning();
return document;
}
interface UpdateEvaluationData {
evaluationResult?: "Acceptable" | "Acceptable with Comment" | "Not Acceptable"
conditionalRequirements?: string
conditionsFulfilled?: boolean
technicalSummary?: string
commercialSummary?: string
overallRemarks?: string
approvalRemarks?: string
status?: "준비중" | "진행중" | "검토중" | "보류" | "완료" | "취소"
}
export async function updateTbeEvaluation(
tbeSessionId: number,
data: UpdateEvaluationData
) {
try {
const session = await getServerSession(authOptions)
if (!session?.user) {
return { success: false, error: "인증이 필요합니다" }
}
const userId = typeof session.user.id === 'string' ? parseInt(session.user.id) : session.user.id
// 현재 TBE 세션 조회
const [currentTbeSession] = await db
.select()
.from(rfqLastTbeSessions)
.where(eq(rfqLastTbeSessions.id, tbeSessionId))
.limit(1)
if (!currentTbeSession) {
return { success: false, error: "TBE 세션을 찾을 수 없습니다" }
}
// 업데이트 데이터 준비
const updateData: any = {
updatedBy: userId,
updatedAt: new Date()
}
// 평가 결과 관련 필드
if (data.evaluationResult !== undefined) {
updateData.evaluationResult = data.evaluationResult
}
// 조건부 승인 관련 (Acceptable with Comment인 경우)
if (data.evaluationResult === "Acceptable with Comment") {
if (data.conditionalRequirements !== undefined) {
updateData.conditionalRequirements = data.conditionalRequirements
}
if (data.conditionsFulfilled !== undefined) {
updateData.conditionsFulfilled = data.conditionsFulfilled
}
} else if (data.evaluationResult === "Acceptable") {
// Acceptable인 경우 조건부 필드 초기화
updateData.conditionalRequirements = null
updateData.conditionsFulfilled = true
} else if (data.evaluationResult === "Not Acceptable") {
// Not Acceptable인 경우 조건부 필드 초기화
updateData.conditionalRequirements = null
updateData.conditionsFulfilled = false
}
// 평가 요약 필드
if (data.technicalSummary !== undefined) {
updateData.technicalSummary = data.technicalSummary
}
if (data.commercialSummary !== undefined) {
updateData.commercialSummary = data.commercialSummary
}
if (data.overallRemarks !== undefined) {
updateData.overallRemarks = data.overallRemarks
}
// 승인 관련 필드
if (data.approvalRemarks !== undefined) {
updateData.approvalRemarks = data.approvalRemarks
updateData.approvedBy = userId
updateData.approvedAt = new Date()
}
// 상태 업데이트
if (data.status !== undefined) {
updateData.status = data.status
// 완료 상태로 변경 시 종료일 설정
if (data.status === "완료") {
updateData.actualEndDate = new Date()
}
}
// TBE 세션 업데이트
const [updated] = await db
.update(rfqLastTbeSessions)
.set(updateData)
.where(eq(rfqLastTbeSessions.id, tbeSessionId))
.returning()
// 캐시 초기화
revalidateTag(`tbe-session-${tbeSessionId}`)
revalidateTag(`tbe-sessions`)
// RFQ 관련 캐시도 초기화
if (currentTbeSession.rfqsLastId) {
revalidateTag(`rfq-${currentTbeSession.rfqsLastId}`)
}
return {
success: true,
data: updated,
message: "평가가 성공적으로 저장되었습니다"
}
} catch (error) {
console.error("Failed to update TBE evaluation:", error)
return {
success: false,
error: error instanceof Error ? error.message : "평가 저장에 실패했습니다"
}
}
}
export async function getTbeVendorDocuments(tbeSessionId: number) {
try {
const documents = await db
.select({
id: rfqLastTbeVendorDocuments.id,
documentName: rfqLastTbeVendorDocuments.originalFileName,
documentType: rfqLastTbeVendorDocuments.documentType,
fileName: rfqLastTbeVendorDocuments.fileName,
fileSize: rfqLastTbeVendorDocuments.fileSize,
fileType: rfqLastTbeVendorDocuments.fileType,
documentNo: rfqLastTbeVendorDocuments.documentNo,
revisionNo: rfqLastTbeVendorDocuments.revisionNo,
issueDate: rfqLastTbeVendorDocuments.issueDate,
description: rfqLastTbeVendorDocuments.description,
submittedAt: rfqLastTbeVendorDocuments.submittedAt,
// 검토 정보는 rfqLastTbeDocumentReviews에서 가져옴
reviewStatus: rfqLastTbeDocumentReviews.reviewStatus,
reviewComments: rfqLastTbeDocumentReviews.reviewComments,
reviewedAt: rfqLastTbeDocumentReviews.reviewedAt,
requiresRevision: rfqLastTbeDocumentReviews.requiresRevision,
technicalCompliance: rfqLastTbeDocumentReviews.technicalCompliance,
qualityAcceptable: rfqLastTbeDocumentReviews.qualityAcceptable,
})
.from(rfqLastTbeVendorDocuments)
.leftJoin(
rfqLastTbeDocumentReviews,
and(
eq(rfqLastTbeDocumentReviews.vendorAttachmentId, rfqLastTbeVendorDocuments.id),
eq(rfqLastTbeDocumentReviews.documentSource, "vendor")
)
)
.where(eq(rfqLastTbeVendorDocuments.tbeSessionId, tbeSessionId))
.orderBy(rfqLastTbeVendorDocuments.submittedAt)
// 문서 정보 매핑 (reviewStatus는 이미 한글로 저장되어 있음)
const mappedDocuments = documents.map(doc => ({
...doc,
reviewStatus: doc.reviewStatus || "미검토", // null인 경우 기본값
reviewRequired: doc.requiresRevision || false, // UI 호환성을 위해 필드명 매핑
}))
return {
success: true,
documents: mappedDocuments,
}
} catch (error) {
console.error("Failed to fetch vendor documents:", error)
return {
success: false,
error: "벤더 문서를 불러오는데 실패했습니다",
documents: [],
}
}
}
// 리뷰 상태 매핑 함수
function mapReviewStatus(status: string | null): string {
const statusMap: Record<string, string> = {
"pending": "미검토",
"reviewing": "검토중",
"approved": "승인",
"rejected": "반려",
}
return status ? (statusMap[status] || status) : "미검토"
}
|