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
|
/**
* 기술영업 RFQ 발송 결재 서버 액션
*
* DRM 파일이 있는 기술영업 RFQ를 발송할 때 결재를 거치는 서버 액션
*/
'use server';
import { ApprovalSubmissionSaga } from '@/lib/approval';
import { mapTechSalesRfqSendToTemplateVariables } from './approval-handlers';
import { revalidatePath, revalidateTag } from 'next/cache';
interface TechSalesRfqSendApprovalData {
// RFQ 기본 정보
rfqId: number;
rfqCode?: string;
rfqType: "SHIP" | "TOP" | "HULL";
// 발송 데이터
vendorIds: number[];
selectedContacts?: Array<{
vendorId: number;
contactId: number;
contactEmail: string;
contactName: string;
}>;
drmAttachmentIds: number[];
// 첨부파일 정보 (파일명, 크기 등)
drmAttachments: Array<{
fileName?: string | null;
fileSize?: number | null;
}>;
// 신청 사유
applicationReason: string;
// 결재 정보
currentUser: {
id: number;
epId: string | null;
name?: string;
email?: string;
};
approvers?: string[]; // Knox EP ID 배열
}
/**
* 기술영업 RFQ 발송 결재 상신 (초기 발송)
*
* DRM 파일이 있는 경우 결재를 거쳐 RFQ를 발송합니다.
*/
export async function requestTechSalesRfqSendWithApproval(data: TechSalesRfqSendApprovalData) {
// 1. 입력 검증
if (!data.currentUser.epId) {
throw new Error('Knox EP ID가 필요합니다. 시스템 관리자에게 문의하세요.');
}
if (!data.vendorIds || data.vendorIds.length === 0) {
throw new Error('발송할 벤더를 선택해주세요.');
}
if (!data.drmAttachmentIds || data.drmAttachmentIds.length === 0) {
throw new Error('DRM 첨부파일이 없습니다. 결재가 필요하지 않습니다.');
}
console.log('[TechSales RFQ Approval] Starting approval process for RFQ send');
console.log('[TechSales RFQ Approval] RFQ ID:', data.rfqId);
console.log('[TechSales RFQ Approval] Vendors:', data.vendorIds.length);
console.log('[TechSales RFQ Approval] DRM Attachments:', data.drmAttachmentIds.length);
try {
// 2. RFQ 상태를 "결재 진행중"으로 변경
const db = (await import('@/db/db')).default;
const { techSalesRfqs, TECH_SALES_RFQ_STATUSES } = await import('@/db/schema/techSales');
const { eq } = await import('drizzle-orm');
await db.update(techSalesRfqs)
.set({
status: TECH_SALES_RFQ_STATUSES.APPROVAL_IN_PROGRESS,
updatedAt: new Date(),
})
.where(eq(techSalesRfqs.id, data.rfqId));
console.log('[TechSales RFQ Approval] RFQ status updated to APPROVAL_IN_PROGRESS');
// 3. 벤더 이름 조회
const { getTechSalesRfqVendors } = await import('./service');
const vendorsResult = await getTechSalesRfqVendors(data.rfqId);
const vendorNames = vendorsResult.data?.filter(v => data.vendorIds.includes(v.vendorId))
.map(v => v.vendorName) || [];
// 4. 템플릿 변수 매핑
const variables = await mapTechSalesRfqSendToTemplateVariables({
attachments: data.drmAttachments,
vendorNames: vendorNames,
applicationReason: data.applicationReason,
});
// 5. Knox 상신용 첨부파일 준비
const knoxAttachments = await prepareKnoxDrmAttachments(data.drmAttachmentIds);
if (knoxAttachments.length === 0) {
throw new Error('상신할 DRM 첨부파일을 준비하지 못했습니다.');
}
// 6. 결재 상신용 payload 구성
const approvalPayload = {
rfqId: data.rfqId,
rfqCode: data.rfqCode,
vendorIds: data.vendorIds,
selectedContacts: data.selectedContacts,
drmAttachmentIds: data.drmAttachmentIds,
currentUser: {
id: data.currentUser.id,
name: data.currentUser.name,
email: data.currentUser.email,
epId: data.currentUser.epId,
},
};
// 7. Saga로 결재 상신
const saga = new ApprovalSubmissionSaga(
'tech_sales_rfq_send_with_drm', // 핸들러 키
approvalPayload, // 결재 승인 후 실행될 데이터
{
title: `암호화해제 신청 - ${data.rfqCode || 'RFQ'}`,
description: `${vendorNames.length}개 업체에 DRM 첨부파일 ${data.drmAttachmentIds.length}개를 포함한 암호화해제 신청`,
templateName: '암호화해제 신청', // DB에 있어야 함
variables,
approvers: data.approvers,
currentUser: {
id: data.currentUser.id,
epId: data.currentUser.epId,
email: data.currentUser.email,
},
attachments: knoxAttachments,
}
);
const result = await saga.execute();
console.log('[TechSales RFQ Approval] ✅ Approval submitted successfully');
console.log('[TechSales RFQ Approval] Approval ID:', result.approvalId);
console.log('[TechSales RFQ Approval] Pending Action ID:', result.pendingActionId);
revalidateTag("techSalesRfqs");
revalidateTag("techSalesVendorQuotations");
revalidateTag(`techSalesRfq-${data.rfqId}`);
revalidatePath(getTechSalesRevalidationPath(data.rfqType || "SHIP"));
return {
success: true,
...result,
message: `결재가 상신되었습니다. (결재 ID: ${result.approvalId})`,
};
} catch (error) {
console.error('[TechSales RFQ Approval] ❌ Failed to submit approval:', error);
throw new Error(
error instanceof Error
? error.message
: '기술영업 RFQ 발송 결재 상신에 실패했습니다.'
);
}
}
/**
* RFQ 타입에 따른 캐시 무효화 경로 반환
*/
function getTechSalesRevalidationPath(rfqType: "SHIP" | "TOP" | "HULL"): string {
switch (rfqType) {
case "SHIP":
return "/evcp/budgetary-tech-sales-ship";
case "TOP":
return "/evcp/budgetary-tech-sales-top";
case "HULL":
return "/evcp/budgetary-tech-sales-hull";
default:
return "/evcp/budgetary-tech-sales-ship";
}
}
/**
* Knox 상신용 DRM 첨부파일을 File 객체로 준비
*/
async function prepareKnoxDrmAttachments(attachmentIds: number[]): Promise<File[]> {
if (!attachmentIds || attachmentIds.length === 0) return [];
const db = (await import('@/db/db')).default;
const { techSalesAttachments } = await import('@/db/schema/techSales');
const { inArray } = await import('drizzle-orm');
const attachments = await db.query.techSalesAttachments.findMany({
where: inArray(techSalesAttachments.id, attachmentIds),
columns: {
id: true,
filePath: true,
originalFileName: true,
fileName: true,
fileType: true,
},
});
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || process.env.NEXT_PUBLIC_URL;
const files: File[] = [];
for (const attachment of attachments) {
if (!attachment.filePath || !baseUrl) {
console.error('[TechSales RFQ Approval] 첨부파일 경로나 BASE_URL이 없습니다.', attachment.id);
continue;
}
const fileUrl = `${baseUrl}${attachment.filePath}`;
const response = await fetch(fileUrl);
if (!response.ok) {
console.error(`[TechSales RFQ Approval] 첨부파일 다운로드 실패: ${fileUrl} (status: ${response.status})`);
continue;
}
const blob = await response.blob();
const file = new File(
[blob],
attachment.originalFileName || attachment.fileName || 'attachment',
{
type: attachment.fileType || blob.type || 'application/octet-stream',
}
);
files.push(file);
}
return files;
}
/**
* 기술영업 RFQ DRM 첨부 해제 결재 상신
*
* 이미 발송된 RFQ에 DRM 파일이 추가된 경우 DRM 해제를 위한 결재 상신
*/
export async function requestRfqResendWithDrmApproval(data: {
rfqId: number;
rfqCode?: string;
drmAttachmentIds: number[];
drmAttachments: Array<{
id: number;
fileName?: string | null;
fileSize?: number | null;
attachmentType?: string | null;
}>;
applicationReason: string;
currentUser: {
id: number;
epId: string | null;
name?: string;
email?: string;
};
approvers?: string[];
}) {
if (!data.currentUser.epId) {
throw new Error('Knox EP ID가 필요합니다.');
}
console.log('[RFQ DRM Unlock Approval] Starting DRM unlock approval process');
console.log('[RFQ DRM Unlock Approval] RFQ ID:', data.rfqId);
console.log('[RFQ DRM Unlock Approval] DRM Attachments:', data.drmAttachmentIds.length);
try {
// 템플릿 변수 매핑
const variables = await mapTechSalesRfqSendToTemplateVariables({
attachments: data.drmAttachments.map(att => ({
fileName: att.fileName,
fileSize: att.fileSize,
})),
vendorNames: [],
applicationReason: data.applicationReason,
});
// DRM 첨부파일을 Knox 상신용 File 객체로 준비
const knoxAttachments = await prepareKnoxDrmAttachments(data.drmAttachmentIds);
if (knoxAttachments.length === 0) {
throw new Error('상신할 DRM 첨부파일을 준비하지 못했습니다.');
}
// 결재 payload 구성
const approvalPayload = {
rfqId: data.rfqId,
rfqCode: data.rfqCode,
drmAttachmentIds: data.drmAttachmentIds,
currentUser: {
id: data.currentUser.id,
name: data.currentUser.name,
email: data.currentUser.email,
epId: data.currentUser.epId,
},
};
console.log('approvalPayload', approvalPayload);
// Saga로 결재 상신
const saga = new ApprovalSubmissionSaga(
'tech_sales_rfq_resend_with_drm', // 핸들러 키
approvalPayload,
{
title: `DRM 파일 해제 결재 - ${data.rfqCode || 'RFQ'}`,
description: `발송 완료된 RFQ에 추가된 DRM 첨부파일 ${data.drmAttachmentIds.length}개 해제를 요청합니다.`,
templateName: '암호화해제 신청',
variables,
approvers: data.approvers,
currentUser: {
id: data.currentUser.id,
name: data.currentUser.name,
epId: data.currentUser.epId,
email: data.currentUser.email,
},
attachments: knoxAttachments,
}
);
const result = await saga.execute();
console.log('[RFQ DRM Unlock Approval] ✅ DRM unlock approval submitted successfully');
return {
success: true,
...result,
message: `DRM 해제 결재가 상신되었습니다. (결재 ID: ${result.approvalId})`,
};
} catch (error) {
console.error('[RFQ DRM Unlock Approval] ❌ Failed to submit DRM unlock approval:', error);
throw new Error(
error instanceof Error
? error.message
: 'RFQ DRM 해제 결재 상신에 실패했습니다.'
);
}
}
|