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
|
"use server";
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 { eq } 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("문서 목록 조회 실패 [담당자에게 문의하세요]");
}
}
// ============================================================================
// 문서 상세 조회 (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,
};
}
}
// ============================================================================
// 주의: 파일 업로드는 /api/swp/upload 라우트에서 처리됩니다
// ============================================================================
|