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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
|
"use server";
/**
* SWP Vendor Actions
*
* 벤더 페이지(제출)에서 사용하는 서버 액션 모음입니다.
* - 다운로드 및 업로드는 서버액션의 데이터 직렬화 문제로, 별도의 API Route로 분리함
* - 간단한 API 호출은 서버 액션으로 관리
*
* 1. 파일 메타정보 업로드
* 2. 파일 업로드 취소
*
*/
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import db from "@/db/db";
import { vendors } from "@/db/schema/vendors";
import { contracts } from "@/db/schema/contract";
import { projects } from "@/db/schema/projects";
import { stageDocuments } from "@/db/schema/vendorDocu";
import { eq, and } from "drizzle-orm";
import {
getDocumentList,
getDocumentDetail,
cancelStandbyFile,
downloadDocumentFile,
type DocumentListItem,
type DocumentDetail,
type DownloadFileResult
} from "./document-service";
import { debugLog, debugError, debugSuccess, debugProcess, debugWarn } from "@/lib/debug-utils";
// ============================================================================
// 벤더 세션 정보 조회
// ============================================================================
interface VendorSessionInfo {
vendorId: number;
vendorCode: string;
vendorName: string;
companyId: number;
}
export async function getVendorSessionInfo(): Promise<VendorSessionInfo | null> {
debugProcess("벤더 세션 정보 조회 시작");
const session = await getServerSession(authOptions);
debugLog("세션 조회 완료", { hasSession: !!session, hasCompanyId: !!session?.user?.companyId });
if (!session?.user?.companyId) {
debugWarn("세션 또는 companyId 없음");
return null;
}
const companyId = typeof session.user.companyId === 'string'
? parseInt(session.user.companyId, 10)
: session.user.companyId as number;
debugLog("벤더 정보 조회 시작", { companyId });
// vendors 테이블에서 companyId로 벤더 정보 조회
const vendor = await db
.select({
id: vendors.id,
vendorCode: vendors.vendorCode,
vendorName: vendors.vendorName,
})
.from(vendors)
.where(eq(vendors.id, companyId))
.limit(1);
debugLog("벤더 정보 조회 완료", { found: !!vendor[0], vendorCode: vendor[0]?.vendorCode });
if (!vendor[0] || !vendor[0].vendorCode) {
debugWarn("벤더 정보 또는 벤더 코드 없음", { vendor: vendor[0] });
return null;
}
const result = {
vendorId: vendor[0].id,
vendorCode: vendor[0].vendorCode,
vendorName: vendor[0].vendorName,
companyId,
};
debugSuccess("벤더 세션 정보 조회 성공", { vendorCode: result.vendorCode });
return result;
}
// ============================================================================
// 벤더의 프로젝트 목록 조회
// ============================================================================
export async function fetchVendorProjects() {
debugProcess("벤더 프로젝트 목록 조회 시작");
try {
const vendorInfo = await getVendorSessionInfo();
if (!vendorInfo) {
debugError("벤더 정보 없음 - 프로젝트 조회 실패");
throw new Error("벤더 정보를 찾을 수 없습니다.");
}
debugLog("프로젝트 목록 DB 조회 시작", { vendorId: vendorInfo.vendorId });
// contracts 테이블에서 해당 벤더의 계약들의 프로젝트 조회
const vendorProjects = await db
.selectDistinct({
PROJ_NO: projects.code,
PROJ_NM: projects.name,
})
.from(contracts)
.innerJoin(projects, eq(contracts.projectId, projects.id))
.where(eq(contracts.vendorId, vendorInfo.vendorId))
.orderBy(projects.code);
debugSuccess("프로젝트 목록 조회 성공", { count: vendorProjects.length });
return vendorProjects;
} catch (error) {
debugError("프로젝트 목록 조회 실패", error);
console.error("[fetchVendorProjects] 오류:", error);
return [];
}
}
// ============================================================================
// 벤더 필터링된 문서 목록 조회 (Full API 기반)
// ============================================================================
export async function fetchVendorDocuments(projNo?: string): Promise<DocumentListItem[]> {
debugProcess("벤더 문서 목록 조회 시작", { projNo });
try {
const vendorInfo = await getVendorSessionInfo();
if (!vendorInfo) {
debugError("벤더 정보 없음 - 문서 조회 실패");
throw new Error("벤더 정보를 찾을 수 없습니다.");
}
if (!projNo) {
debugWarn("프로젝트 번호 없음");
return [];
}
debugLog("문서 목록 조회 시작", {
projNo,
vendorCode: vendorInfo.vendorCode
});
// document-service의 getDocumentList 사용
const documents = await getDocumentList(projNo, vendorInfo.vendorCode);
debugSuccess("문서 목록 조회 성공", { count: documents.length });
return documents;
} catch (error) {
debugError("문서 목록 조회 실패", error);
console.error("[fetchVendorDocuments] 오류:", error);
throw new Error("문서 목록 조회 실패 [SWP 담당자에게 문의하세요]");
}
}
// ============================================================================
// 문서 상세 조회 (Rev-Activity-File 트리)
// ============================================================================
export async function fetchVendorDocumentDetail(
projNo: string,
docNo: string
): Promise<DocumentDetail> {
debugProcess("벤더 문서 상세 조회 시작", { projNo, docNo });
try {
const vendorInfo = await getVendorSessionInfo();
if (!vendorInfo) {
debugError("벤더 정보 없음");
throw new Error("벤더 정보를 찾을 수 없습니다.");
}
debugLog("문서 상세 조회 시작", { projNo, docNo });
// document-service의 getDocumentDetail 사용
const detail = await getDocumentDetail(projNo, docNo);
debugSuccess("문서 상세 조회 성공", {
docNo: detail.docNo,
revisions: detail.revisions.length,
});
return detail;
} catch (error) {
debugError("문서 상세 조회 실패", error);
console.error("[fetchVendorDocumentDetail] 오류:", error);
throw new Error("문서 상세 조회 실패");
}
}
// ============================================================================
// 파일 취소
// ============================================================================
export async function cancelVendorFile(
boxSeq: string,
actvSeq: string
): Promise<void> {
debugProcess("벤더 파일 취소 시작", { boxSeq, actvSeq });
try {
const vendorInfo = await getVendorSessionInfo();
if (!vendorInfo) {
debugError("벤더 정보 없음");
throw new Error("벤더 정보를 찾을 수 없습니다.");
}
// vendorId를 문자열로 변환하여 사용
await cancelStandbyFile(boxSeq, actvSeq, String(vendorInfo.vendorId));
debugSuccess("파일 취소 완료", { boxSeq, actvSeq });
} catch (error) {
debugError("파일 취소 실패", error);
console.error("[cancelVendorFile] 오류:", error);
throw new Error("파일 취소 실패");
}
}
// ============================================================================
// 파일 다운로드
// ============================================================================
export async function downloadVendorFile(
projNo: string,
ownDocNo: string,
fileName: string
): Promise<DownloadFileResult> {
debugProcess("벤더 파일 다운로드 시작", { projNo, ownDocNo, fileName });
try {
const vendorInfo = await getVendorSessionInfo();
if (!vendorInfo) {
debugError("벤더 정보 없음");
return {
success: false,
error: "벤더 정보를 찾을 수 없습니다.",
};
}
// document-service의 downloadDocumentFile 사용
const result = await downloadDocumentFile(projNo, ownDocNo, fileName);
if (result.success) {
debugSuccess("파일 다운로드 완료", { fileName });
} else {
debugWarn("파일 다운로드 실패", { fileName, error: result.error });
}
return result;
} catch (error) {
debugError("파일 다운로드 실패", error);
console.error("[downloadVendorFile] 오류:", error);
return {
success: false,
error: error instanceof Error ? error.message : "파일 다운로드 실패",
};
}
}
// ============================================================================
// 벤더 통계 조회 (Full API 기반)
// ============================================================================
export async function fetchVendorSwpStats(projNo?: string) {
debugProcess("벤더 통계 조회 시작", { projNo });
try {
const vendorInfo = await getVendorSessionInfo();
if (!vendorInfo) {
debugError("벤더 정보 없음 - 통계 조회 실패");
throw new Error("벤더 정보를 찾을 수 없습니다.");
}
if (!projNo) {
debugWarn("프로젝트 번호 없음");
return {
total_documents: 0,
total_revisions: 0,
total_files: 0,
uploaded_files: 0,
last_sync: null,
};
}
// API에서 문서 목록 조회
const documents = await getDocumentList(projNo, vendorInfo.vendorCode);
// 통계 계산
let totalRevisions = 0;
let totalFiles = 0;
let uploadedFiles = 0;
for (const doc of documents) {
totalFiles += doc.fileCount;
// standbyFileCount가 0이 아니면 업로드된 것으로 간주
uploadedFiles += doc.fileCount - doc.standbyFileCount;
// 리비전 수 추정 (LTST_REV_NO 기반)
if (doc.LTST_REV_NO) {
const revNum = parseInt(doc.LTST_REV_NO, 10);
if (!isNaN(revNum)) {
totalRevisions += revNum + 1; // Rev 00부터 시작이므로 +1
}
}
}
const result = {
total_documents: documents.length,
total_revisions: totalRevisions,
total_files: totalFiles,
uploaded_files: uploadedFiles,
last_sync: new Date(), // API 기반이므로 항상 최신
};
debugSuccess("통계 조회 성공", {
documents: result.total_documents,
revisions: result.total_revisions,
files: result.total_files,
uploaded: result.uploaded_files,
});
return result;
} catch (error) {
debugError("통계 조회 실패", error);
console.error("[fetchVendorSwpStats] 오류:", error);
return {
total_documents: 0,
total_revisions: 0,
total_files: 0,
uploaded_files: 0,
last_sync: null,
};
}
}
// ============================================================================
// 벤더가 업로드한 파일 목록 조회 (Inbox)
//
// API 응답 파일 목록 + DB의 업로드 필요 문서 목록을 함께 반환
// - DB 조회: stageDocuments에서 buyerSystemStatus='Completed'인 문서 중
// 아직 업로드되지 않은 문서 (vendorDocNumber가 API 응답의 OWN_DOC_NO에 없는 것)
// - 목적: 벤더에게 업로드를 위한 문서번호 기준(vendorDocNumber)을 제공
// ============================================================================
export async function fetchVendorUploadedFiles(projNo: string) {
debugProcess("벤더 업로드 파일 목록 조회 시작", { projNo });
try {
const vendorInfo = await getVendorSessionInfo();
if (!vendorInfo) {
debugError("벤더 정보 없음 - 업로드 파일 조회 실패");
throw new Error("벤더 정보를 찾을 수 없습니다.");
}
if (!projNo) {
debugWarn("프로젝트 번호 없음");
return { files: [], requiredDocs: [] };
}
debugLog("업로드 파일 목록 조회 시작", {
projNo,
vendorCode: vendorInfo.vendorCode
});
// 1. API에서 업로드된 파일 목록 조회
const { fetchGetExternalInboxList } = await import("./api-client");
const files = await fetchGetExternalInboxList({
projNo,
vndrCd: vendorInfo.vendorCode,
});
debugLog("API 파일 목록 조회 완료", { count: files.length });
// 2. 프로젝트 ID 조회
const project = await db
.select({ id: projects.id })
.from(projects)
.where(eq(projects.code, projNo))
.limit(1);
if (!project[0]) {
debugWarn("프로젝트를 찾을 수 없음", { projNo });
return { files, requiredDocs: [] };
}
const projectId = project[0].id;
// 3. stageDocuments에서 buyerSystemStatus='Completed'인 문서 조회
const completedDocs = await db
.select({
vendorDocNumber: stageDocuments.vendorDocNumber,
title: stageDocuments.title,
buyerSystemComment: stageDocuments.buyerSystemComment,
})
.from(stageDocuments)
.where(
and(
eq(stageDocuments.projectId, projectId),
eq(stageDocuments.vendorId, vendorInfo.vendorId),
eq(stageDocuments.buyerSystemStatus, "Completed")
)
);
debugLog("stageDocuments 조회 완료", { count: completedDocs.length });
// 4. API 응답에 이미 존재하는 vendorDocNumber 필터링
const uploadedDocNumbers = new Set(
files.map((file) => file.OWN_DOC_NO).filter(Boolean)
);
const requiredDocs = completedDocs
.filter((doc) => doc.vendorDocNumber && !uploadedDocNumbers.has(doc.vendorDocNumber))
.map((doc) => ({
vendorDocNumber: doc.vendorDocNumber!,
title: doc.title,
buyerSystemComment: doc.buyerSystemComment || null,
}));
debugSuccess("업로드 파일 목록 조회 성공", {
filesCount: files.length,
requiredDocsCount: requiredDocs.length
});
return { files, requiredDocs };
} catch (error) {
debugError("업로드 파일 목록 조회 실패", error);
console.error("[fetchVendorUploadedFiles] 오류:", error);
throw new Error("업로드 파일 목록 조회 실패");
}
}
// ============================================================================
// 벤더가 업로드한 파일 취소 (userId 파라미터 버전)
// ============================================================================
export interface CancelVendorUploadedFileParams {
boxSeq: string;
actvSeq: string;
userId: string;
}
export async function cancelVendorUploadedFile(params: CancelVendorUploadedFileParams) {
debugProcess("벤더 업로드 파일 취소 시작", params);
try {
const vendorInfo = await getVendorSessionInfo();
if (!vendorInfo) {
debugError("벤더 정보 없음");
throw new Error("벤더 정보를 찾을 수 없습니다.");
}
// api-client의 callSaveInBoxListCancelStatus 사용
const { callSaveInBoxListCancelStatus } = await import("./api-client");
const cancelCount = await callSaveInBoxListCancelStatus({
boxSeq: params.boxSeq,
actvSeq: params.actvSeq,
chgr: `evcp${params.userId}`,
});
debugSuccess("업로드 파일 취소 완료", {
...params,
cancelCount
});
return {
success: true,
cancelCount
};
} catch (error) {
debugError("업로드 파일 취소 실패", error);
console.error("[cancelVendorUploadedFile] 오류:", error);
throw new Error("파일 취소 실패");
}
}
// ============================================================================
// 주의: 파일 업로드는 /api/swp/upload 라우트에서 처리됩니다
// ============================================================================
|