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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
|
"use server"
import db from "@/db/db"
import { and, eq, isNull, desc, sql} from "drizzle-orm";
import { revalidatePath} from "next/cache";
import { format } from "date-fns"
import { vendorInvestigations, vendorPQSubmissions, siteVisitRequests, vendorSiteVisitInfo, siteVisitRequestAttachments } from "@/db/schema/pq"
import { sendEmail } from "../mail/sendEmail";
import { decryptWithServerAction } from '@/components/drm/drmUtils'
import { vendors } from "@/db/schema/vendors";
import { saveFile, saveDRMFile } from "@/lib/file-stroage";
import { getServerSession } from "next-auth/next"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"
import { users } from "@/db/schema"
// 방문실사 요청 서버 액션
export async function createSiteVisitRequestAction(input: {
investigationId: number;
inspectionDuration: number;
requestedStartDate: Date;
requestedEndDate: Date;
shiAttendees: Record<string, boolean>;
shiAttendeeDetails?: string;
vendorRequests: Record<string, boolean>;
otherVendorRequests?: string;
additionalRequests?: string;
attachments?: Array<File>;
}) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
throw new Error("Unauthorized");
}
const investigationId = Number(input.investigationId)
// 기존 방문실사 요청이 있는지 확인
const existingRequest = await db
.select()
.from(siteVisitRequests)
.where(eq(siteVisitRequests.investigationId, investigationId))
.limit(1);
if (existingRequest.length > 0) {
return {
success: false,
error: "이미 방문실사 요청이 존재합니다. 추가 요청은 불가능합니다."
};
}
// 방문실사 요청 생성
const [siteVisitRequest] = await db
.insert(siteVisitRequests)
.values({
investigationId: investigationId,
requesterId: session.user.id,
inspectionDuration: input.inspectionDuration,
requestedStartDate: input.requestedStartDate,
requestedEndDate: input.requestedEndDate,
shiAttendees: input.shiAttendees,
vendorRequests: input.vendorRequests,
additionalRequests: input.additionalRequests,
status: "REQUESTED",
})
.returning();
// SHI 첨부파일 처리
if (input.attachments && input.attachments.length > 0) {
console.log(`📎 첨부파일 처리 시작: ${input.attachments.length}개 파일`);
const processedFiles: any[] = [];
for (const file of input.attachments) {
try {
console.log(`📁 파일 처리 중: ${file.name} (${file.size} bytes)`);
// saveDRMFile을 사용하여 파일 저장
const saveResult = await saveDRMFile(
file,
decryptWithServerAction,
`site-visit-requests/${siteVisitRequest.id}`,
session.user.id.toString()
);
if (!saveResult.success) {
console.error(`❌ 파일 저장 실패: ${file.name}`, saveResult.error);
throw new Error(`파일 저장 실패: ${file.name} - ${saveResult.error}`);
}
console.log(`✅ 파일 저장 완료: ${file.name} -> ${saveResult.fileName}`);
// DB에 첨부파일 레코드 생성
const attachmentValue = {
siteVisitRequestId: siteVisitRequest.id,
vendorSiteVisitInfoId: null, // SHI 첨부파일은 vendorSiteVisitInfoId가 null
fileName: saveResult.fileName!,
originalFileName: file.name,
filePath: saveResult.publicPath!,
fileSize: file.size,
mimeType: file.type || 'application/octet-stream',
createdAt: new Date(),
updatedAt: new Date(),
};
processedFiles.push(attachmentValue);
} catch (error) {
console.error(`❌ 첨부파일 처리 오류: ${file.name}`, error);
throw new Error(`첨부파일 처리 중 오류가 발생했습니다: ${file.name}`);
}
}
if (processedFiles.length > 0) {
await db.insert(siteVisitRequestAttachments).values(processedFiles);
console.log(`✅ 첨부파일 DB 저장 완료: ${processedFiles.length}개`);
}
}
// 이메일 발송
try {
// 실사, 협력업체, 발송자 정보 조회
const investigationResult = await db
.select()
.from(vendorInvestigations)
.where(eq(vendorInvestigations.id, siteVisitRequest.investigationId))
.limit(1);
const investigation = investigationResult[0];
if (!investigation) {
throw new Error('실사 정보를 찾을 수 없습니다.');
}
const vendorResult = await db
.select()
.from(vendors)
.where(eq(vendors.id, investigation.vendorId))
.limit(1);
const vendor = vendorResult[0];
if (!vendor) {
throw new Error('협력업체 정보를 찾을 수 없습니다.');
}
const senderResult = await db
.select()
.from(users)
.where(eq(users.id, siteVisitRequest.requesterId!))
.limit(1);
const sender = senderResult[0];
if (!sender) {
throw new Error('발송자 정보를 찾을 수 없습니다.');
}
// 마감일 계산 (발송일 + 7일)
const deadlineDate = format(new Date(), 'yyyy.MM.dd');
// SHI 참석자 정보 파싱 (새로운 구조에 맞게)
const shiAttendees = input.shiAttendees as any;
// 메일 제목
const subject = `[SHI Audit] 방문실사 시행 안내 및 실사 관련 추가정보 요청 _ ${vendor.vendorName} (${vendor.vendorCode}, 사업자번호: ${vendor.taxId})`;
// 메일 컨텍스트
const context = {
// 기본 정보
vendorName: vendor.vendorName,
vendorContactName: vendor.vendorName || '',
requesterName: sender.name,
requesterTitle: 'Procurement Manager',
requesterEmail: sender.email,
// 실사 정보
investigationMethod: investigation.investigationMethod,
// investigationMethodDescription: investigation.investigationMethodDescription,
requestedStartDate: format(siteVisitRequest.requestedStartDate!, 'yyyy.MM.dd'),
requestedEndDate: format(siteVisitRequest.requestedEndDate!, 'yyyy.MM.dd'),
inspectionDuration: siteVisitRequest.inspectionDuration,
// 마감일
deadlineDate,
// SHI 참석자 정보 (새로운 구조)
shiAttendees: Object.entries(shiAttendees)
.filter(([, value]) => value.checked)
.map(([key, value]) => {
const departmentLabels: Record<string, string> = {
technicalSales: "기술영업",
design: "설계",
procurement: "구매",
quality: "품질",
production: "생산",
commissioning: "시운전",
other: "기타"
};
const departmentName = departmentLabels[key] || key;
const details = value.details ? ` (${value.details})` : '';
return `${departmentName} ${value.count}명${details}`;
}),
shiAttendeeDetails: input.shiAttendeeDetails || null,
// 협력업체 요청 정보 (default 값으로 고정)
vendorRequests: [
' 실사공장명',
' 실사공장 주소',
' 실사공장 가는 방법',
' 실사공장 Contact Point',
' 실사공장 연락처',
' 실사공장 이메일',
' 실사 참석 예정인력',
' 공장 출입절차 및 준비물'
],
otherVendorRequests: input.otherVendorRequests,
// 추가 요청사항
additionalRequests: siteVisitRequest.additionalRequests,
// 포털 URL
portalUrl: `${process.env.NEXT_PUBLIC_BASE_URL}/ko/partners/site-visit`,
// 현재 연도
currentYear: new Date().getFullYear()
};
// 메일 발송 (벤더 이메일로 직접 발송)
await sendEmail({
to: vendor.email || '',
cc: sender.email,
subject,
template: 'site-visit-request' as string,
context,
// cc: vendor.email !== sender.email ? sender.email : undefined
});
console.log('방문실사 요청 메일 발송 완료:', {
to: vendor.email,
subject,
vendorName: vendor.vendorName
});
// 메일 발송 성공 시 상태 업데이트
await db
.update(siteVisitRequests)
.set({
status: "SENT",
sentAt: new Date()
})
.where(eq(siteVisitRequests.id, siteVisitRequest.id));
} catch (emailError) {
console.error('방문실사 요청 메일 발송 실패:', emailError);
}
revalidatePath("/evcp/pq_new");
revalidatePath("/partners/site-visit");
return {
success: true,
data: siteVisitRequest,
message: "방문실사 요청이 성공적으로 생성되었습니다."
};
} catch (error) {
console.error("방문실사 요청 생성 오류:", error);
return {
success: false,
error: "방문실사 요청 생성 중 오류가 발생했습니다."
};
}
}
// 방문실사 요청 조회 서버 액션
export async function getSiteVisitRequestAction(investigationId: number) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
throw new Error("Unauthorized");
}
const siteVisitRequest = await db
.select()
.from(siteVisitRequests)
.where(eq(siteVisitRequests.investigationId, investigationId))
.limit(1);
if (!siteVisitRequest[0]) {
return {
success: true,
data: null
};
}
// SHI 첨부파일 조회 (vendorSiteVisitInfoId가 null인 것들)
const shiAttachments = await db
.select()
.from(siteVisitRequestAttachments)
.where(
and(
eq(siteVisitRequestAttachments.siteVisitRequestId, siteVisitRequest[0].id),
isNull(siteVisitRequestAttachments.vendorSiteVisitInfoId)
)
);
return {
success: true,
data: {
...siteVisitRequest[0],
shiAttachments
}
};
} catch (error) {
console.error("방문실사 요청 조회 오류:", error);
return {
success: false,
error: "방문실사 요청 조회 중 오류가 발생했습니다."
};
}
}
// 협력업체용 방문실사 요청 조회
export async function getSiteVisitRequestsByVendorId(vendorId: number) {
try {
const result = await db
.select({
id: siteVisitRequests.id,
investigationId: siteVisitRequests.investigationId,
requesterId: siteVisitRequests.requesterId,
inspectionDuration: siteVisitRequests.inspectionDuration,
requestedStartDate: siteVisitRequests.requestedStartDate,
requestedEndDate: siteVisitRequests.requestedEndDate,
shiAttendees: siteVisitRequests.shiAttendees,
vendorRequests: siteVisitRequests.vendorRequests,
additionalRequests: siteVisitRequests.additionalRequests,
status: siteVisitRequests.status,
sentAt: siteVisitRequests.sentAt,
createdAt: siteVisitRequests.createdAt,
updatedAt: siteVisitRequests.updatedAt,
// 실사 정보
investigationMethod: vendorInvestigations.investigationMethod,
investigationAddress: vendorInvestigations.investigationAddress,
investigationNotes: vendorInvestigations.investigationNotes,
forecastedAt: vendorInvestigations.forecastedAt,
actualAt: vendorInvestigations.completedAt,
result: vendorInvestigations.evaluationResult,
resultNotes: vendorInvestigations.purchaseComment,
// PQ 정보
pqItems: vendorPQSubmissions.pqItems,
// 협력업체 정보
vendorName: vendors.vendorName,
vendorCode: vendors.vendorCode,
vendorEmail: vendors.email,
})
.from(siteVisitRequests)
.leftJoin(
vendorInvestigations,
eq(siteVisitRequests.investigationId, vendorInvestigations.id)
)
.leftJoin(
sql`users AS requester`,
eq(siteVisitRequests.requesterId, sql`requester.id`)
)
.leftJoin(
vendors,
eq(vendorInvestigations.vendorId, vendors.id)
)
.leftJoin(
vendorPQSubmissions,
eq(vendorInvestigations.pqSubmissionId, vendorPQSubmissions.id)
)
.where(eq(vendorInvestigations.vendorId, vendorId))
.orderBy(desc(siteVisitRequests.createdAt));
// 각 방문실사 요청에 대해 협력업체 정보 조회
const resultWithVendorInfo = await Promise.all(
result.map(async (item) => {
const vendorInfoResult = await db
.select({
id: vendorSiteVisitInfo.id,
siteVisitRequestId: vendorSiteVisitInfo.siteVisitRequestId,
factoryName: vendorSiteVisitInfo.factoryName,
factoryLocation: vendorSiteVisitInfo.factoryLocation,
factoryAddress: vendorSiteVisitInfo.factoryAddress,
factoryPicName: vendorSiteVisitInfo.factoryPicName,
factoryPicPhone: vendorSiteVisitInfo.factoryPicPhone,
factoryPicEmail: vendorSiteVisitInfo.factoryPicEmail,
factoryDirections: vendorSiteVisitInfo.factoryDirections,
accessProcedure: vendorSiteVisitInfo.accessProcedure,
hasAttachments: vendorSiteVisitInfo.hasAttachments,
otherInfo: vendorSiteVisitInfo.otherInfo,
submittedAt: vendorSiteVisitInfo.submittedAt,
submittedBy: vendorSiteVisitInfo.submittedBy,
createdAt: vendorSiteVisitInfo.createdAt,
updatedAt: vendorSiteVisitInfo.updatedAt,
})
.from(vendorSiteVisitInfo)
.where(eq(vendorSiteVisitInfo.siteVisitRequestId, item.id))
.limit(1);
const vendorInfo = vendorInfoResult.length > 0 ? vendorInfoResult[0] : null;
// SHI 첨부파일 조회 (vendorSiteVisitInfoId가 null인 것들)
const shiAttachments = await db
.select()
.from(siteVisitRequestAttachments)
.where(
and(
eq(siteVisitRequestAttachments.siteVisitRequestId, item.id),
isNull(siteVisitRequestAttachments.vendorSiteVisitInfoId)
)
);
return {
...item,
shiAttendees: item.shiAttendees as Record<string, unknown> | null,
vendorRequests: item.vendorRequests as Record<string, unknown> | null,
vendorInfo,
shiAttachments,
};
})
);
console.log(`📊 방문실사 요청 조회 완료 - 총 ${resultWithVendorInfo.length}개 요청`)
console.log(`🔍 실제실사일/실사결과 데이터 확인:`, resultWithVendorInfo.map(item => ({
id: item.id,
actualAt: item.actualAt,
result: item.result,
investigationId: item.investigationId
})))
return resultWithVendorInfo;
} catch (error) {
console.error("방문실사 요청 조회 오류:", error);
return [];
}
}
// 협력업체 정보 제출 서버 액션
export async function submitVendorInfoAction(input: {
siteVisitRequestId: number;
factoryName: string;
factoryLocation: string;
factoryAddress: string;
factoryPicName: string;
factoryPicPhone: string;
factoryPicEmail: string;
factoryDirections: string;
accessProcedure: string;
hasAttachments: boolean;
otherInfo?: string;
attachments?: Array<File>;
}) {
try {
const session = await getServerSession(authOptions);
if (!session?.user?.id) {
throw new Error("Unauthorized");
}
// 기존 협력업체 정보가 있는지 확인
const existingInfo = await db
.select()
.from(vendorSiteVisitInfo)
.where(eq(vendorSiteVisitInfo.siteVisitRequestId, input.siteVisitRequestId))
.limit(1);
if (existingInfo.length > 0) {
// 기존 정보 업데이트
await db
.update(vendorSiteVisitInfo)
.set({
factoryName: input.factoryName,
factoryLocation: input.factoryLocation,
factoryAddress: input.factoryAddress,
factoryPicName: input.factoryPicName,
factoryPicPhone: input.factoryPicPhone,
factoryPicEmail: input.factoryPicEmail,
factoryDirections: input.factoryDirections,
accessProcedure: input.accessProcedure,
hasAttachments: input.hasAttachments,
otherInfo: input.otherInfo,
// submittedBy: session.user.id,
submittedAt: new Date(),
})
.where(eq(vendorSiteVisitInfo.siteVisitRequestId, input.siteVisitRequestId));
} else {
// 새로운 정보 삽입
await db
.insert(vendorSiteVisitInfo)
.values({
siteVisitRequestId: input.siteVisitRequestId,
factoryName: input.factoryName,
factoryLocation: input.factoryLocation,
factoryAddress: input.factoryAddress,
factoryPicName: input.factoryPicName,
factoryPicPhone: input.factoryPicPhone,
factoryPicEmail: input.factoryPicEmail,
factoryDirections: input.factoryDirections,
accessProcedure: input.accessProcedure,
hasAttachments: input.hasAttachments,
otherInfo: input.otherInfo,
submittedBy: Number(session.user.id),
});
}
// 첨부파일 처리
if (input.attachments && input.attachments.length > 0) {
console.log(`📎 협력업체 첨부파일 처리 시작: ${input.attachments.length}개 파일`);
// 기존 첨부파일 삭제 (업데이트 시)
if (existingInfo.length > 0) {
console.log(`🗑️ 기존 첨부파일 삭제: vendorSiteVisitInfoId ${existingInfo[0].id}`);
await db
.delete(siteVisitRequestAttachments)
.where(eq(siteVisitRequestAttachments.vendorSiteVisitInfoId, existingInfo[0].id));
}
let attachmentValues: any[] = [];
for (const file of input.attachments) {
try {
console.log(`📁 협력업체 파일 처리 중: ${file.name} (${file.size} bytes)`);
// saveFile을 사용하여 파일 저장 (협력업체 첨부파일은 일반 파일로 처리)
const saveResult = await saveFile({
file,
directory: `site-visit-vendor-info/${input.siteVisitRequestId}`,
originalName: file.name,
userId: session.user.id.toString()
});
if (!saveResult.success) {
console.error(`❌ 협력업체 파일 저장 실패: ${file.name}`, saveResult.error);
throw new Error(`파일 저장 실패: ${file.name} - ${saveResult.error}`);
}
console.log(`✅ 협력업체 파일 저장 완료: ${file.name} -> ${saveResult.fileName}`);
// DB에 첨부파일 레코드 생성
const attachmentValue = {
siteVisitRequestId: input.siteVisitRequestId,
vendorSiteVisitInfoId: existingInfo.length > 0 ? existingInfo[0].id : null,
fileName: saveResult.fileName!,
originalFileName: file.name,
filePath: saveResult.publicPath!,
fileSize: file.size,
mimeType: file.type || 'application/octet-stream',
createdAt: new Date(),
updatedAt: new Date(),
};
attachmentValues.push(attachmentValue as any);
} catch (error) {
console.error(`❌ 협력업체 첨부파일 처리 오류: ${file.name}`, error);
throw new Error(`첨부파일 처리 중 오류가 발생했습니다: ${file.name}`);
}
}
if (attachmentValues.length > 0) {
await db.insert(siteVisitRequestAttachments).values(attachmentValues);
console.log(`✅ 협력업체 첨부파일 DB 저장 완료: ${attachmentValues.length}개`);
}
}
// 방문실사 요청 상태 업데이트
await db
.update(siteVisitRequests)
.set({
status: "VENDOR_SUBMITTED"
})
.where(eq(siteVisitRequests.id, input.siteVisitRequestId));
revalidatePath("/evcp/pq_new");
revalidatePath("/partners/site-visit");
return {
success: true,
message: "협력업체 정보가 성공적으로 제출되었습니다."
};
} catch (error) {
console.error("협력업체 정보 제출 오류:", error);
return {
success: false,
error: "협력업체 정보 제출 중 오류가 발생했습니다."
};
}
}
// SHI eVCP에서 협력업체 방문실사 정보 조회
export async function getVendorSiteVisitInfoAction(siteVisitRequestId: number) {
try {
// 새로운 테이블에서 협력업체 정보 조회
const vendorInfoResult = await db
.select()
.from(vendorSiteVisitInfo)
.where(eq(vendorSiteVisitInfo.siteVisitRequestId, siteVisitRequestId))
.limit(1);
const vendorInfo = vendorInfoResult.length > 0 ? vendorInfoResult[0] : null;
if (!vendorInfo) {
return {
success: false,
error: "해당 방문실사 요청에 대한 협력업체 정보가 없습니다."
};
}
// 첨부파일 조회
const attachments = await db
.select()
.from(siteVisitRequestAttachments)
.where(eq(siteVisitRequestAttachments.vendorSiteVisitInfoId, vendorInfo.id));
return {
success: true,
data: {
vendorInfo,
attachments
}
};
} catch (error) {
console.error("협력업체 방문실사 정보 조회 오류:", error);
return {
success: false,
error: "협력업체 방문실사 정보 조회 중 오류가 발생했습니다."
};
}
}
|