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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
|
// app/lib/shi-buyer-system-api.ts
import db from '@/db/db'
import {
stageDocuments,
stageIssueStages,
contracts,
vendors,
projects,
stageSubmissions,
stageSubmissionAttachments,
} from '@/db/schema'
import { eq, and, sql, ne, or, isNull, inArray } from 'drizzle-orm'
import fs from 'fs/promises'
import path from 'path'
interface ShiDocumentInfo {
PROJ_NO: string
SHI_DOC_NO: string
CATEGORY: string | null
RESPONSIBLE_CD: string
RESPONSIBLE: string
VNDR_CD: string
VNDR_NM: string
DSN_SKL: string | null
MIFP_CD: string
MIFP_NM: string
CG_EMPNO1: string
CG_EMPNM1: string
OWN_DOC_NO: string
DSC: string
DOC_CLASS: string
COMMENT: string
STATUS: string
CRTER: string
CRTE_DTM: string
CHGR: string
CHG_DTM: string
}
interface ShiScheduleInfo {
PROJ_NO: string
SHI_DOC_NO: string
DDPKIND: string
SCHEDULE_TYPE: string
BASELINE1: string | null
REVISED1: string | null
FORECAST1: string | null
ACTUAL1: string | null
BASELINE2: string | null
REVISED2: string | null
FORECAST2: string | null
ACTUAL2: string | null
CRTER: string
CRTE_DTM: string
CHGR: string
CHG_DTM: string
}
// SHI API 응답 타입
interface ShiDocumentResponse {
PROJ_NO: string
SHI_DOC_NO: string
STATUS: string
COMMENT: string | null
CATEGORY?: string
RESPONSIBLE_CD?: string
RESPONSIBLE?: string
VNDR_CD?: string
VNDR_NM?: string
DSN_SKL?: string
MIFP_CD?: string
MIFP_NM?: string
CG_EMPNO1?: string
CG_EMPNM1?: string
OWN_DOC_NO?: string
DSC?: string
DOC_CLASS?: string
CRTER?: string
CRTE_DTM?: string
CHGR?: string
CHG_DTM?: string
}
interface ShiApiResponse {
GetDwgInfoResult: ShiDocumentResponse[]
}
// InBox 파일 정보 인터페이스 (SaveInBoxList API 요청 형식)
interface InBoxFileInfo {
CPY_CD: string // 회사 코드 (항상 "C00001" 고정, VNDR_CD와는 별개)
FILE_NM: string // 파일명: [OWNDOCNO]_[REVNO]_[STAGE].[extension]
OFDC_NO: string | null // null 가능
PROJ_NO: string // 프로젝트 번호
OWN_DOC_NO: string // 자사 문서번호
REV_NO: string // 리비전 번호
STAGE: string // 스테이지 (예: IFA, IFB 등)
STAT: string // 상태코드 (예: SCW03 - Completed)
FILE_SZ: string // 파일 크기 (byte, 문자열)
FLD_PATH: string // 폴더 경로: [ProjNo][CpyCd][YYYYMMDDHHMMSS]
}
// 파일 저장용 확장 인터페이스
interface FileInfoWithBuffer extends InBoxFileInfo {
fileBuffer: Buffer;
attachment: {
id: number;
fileName: string;
mimeType: string | null;
storagePath: string | null;
storageUrl: string | null;
[key: string]: any;
};
// 네트워크 경로 생성을 위한 추가 정보
_timestamp: string;
_extension: string;
}
// SaveInBoxList API 응답 인터페이스
interface SaveInBoxListResponse {
SaveInBoxListResult: {
success: boolean
message: string
processedCount?: number
files?: Array<{
fileName: string
networkPath: string
status: string
}>
}
}
// SaveInBoxList API 요청 인터페이스
interface SaveInBoxListRequest {
externalInboxLists: InBoxFileInfo[]
}
// 내부 문서 타입 (getDocumentsToSend 반환 타입)
interface DocumentWithStages {
documentId: number
docNumber: string
vendorDocNumber: string | null
title: string
status: string
buyerSystemComment: string | null
projectCode: string
vendorCode: string
vendorName: string
docClass?: string | null
stages: Array<{
id: number
documentId: number
stageName: string
stageOrder: number | null
planDate: Date | string | null
actualDate: Date | string | null
[key: string]: any
}>
}
// 제출 정보 타입 (getSubmissionFullInfo 반환 타입)
interface SubmissionFullInfo {
submission: {
id: number
revisionNumber: number
submittedBy: string
[key: string]: any
}
stage: {
id: number
stageName: string
[key: string]: any
}
document: {
id: number
docNumber: string
vendorDocNumber: string | null
[key: string]: any
}
project: {
id: number
code: string
[key: string]: any
}
vendor: {
id: number
vendorCode: string | null
vendorName: string
[key: string]: any
} | null
attachments: Array<{
id: number
fileName: string
mimeType: string | null
storagePath: string | null
storageUrl: string | null
[key: string]: any
}>
}
export class ShiBuyerSystemAPI {
private baseUrl = process.env.SWP_BASE_URL || 'http://60.100.99.217/DDP/Services/VNDRService.svc'
private ddcUrl = process.env.DDC_BASE_URL || 'http://60.100.99.217/DDC/Services/WebService.svc'
private localStoragePath = process.env.NAS_PATH || './uploads'
// SMB로 마운트한 SWP 업로드 경로 (/mnt/swp-smb-dir/ 경로이며, 네트워크 경로로는 \\60.100.91.61\SBox 경로임)
private swpMountDir = process.env.SWP_MONUT_DIR || '/mnt/swp-smb-dir/';
/**
* 타임스탬프를 YYYYMMDDhhmmss 형식으로 생성
*/
private getTimestamp(): string {
const now = new Date();
return (
now.getFullYear().toString() +
(now.getMonth() + 1).toString().padStart(2, '0') +
now.getDate().toString().padStart(2, '0') +
now.getHours().toString().padStart(2, '0') +
now.getMinutes().toString().padStart(2, '0') +
now.getSeconds().toString().padStart(2, '0')
);
}
/**
* 파일명에서 이름과 확장자를 분리
*/
private parseFileName(fileName: string): { name: string; extension: string } {
const lastDotIndex = fileName.lastIndexOf('.');
if (lastDotIndex === -1) {
return { name: fileName, extension: '' };
}
return {
name: fileName.substring(0, lastDotIndex),
extension: fileName.substring(lastDotIndex + 1),
};
}
/**
* SMB 마운트 경로에 맞는 파일 경로 생성 (레거시 경로 규칙)
* /mnt/swp-smb-dir/{PROJ_NO}/{CPY_CD}/{YYYYMMDDHHmmSS}/[OWN_DOC_NO]_[REV_NO]_[STAGE]_[YYYYMMDD].확장자
*/
private generateMountPath(
projNo: string,
cpyCode: string,
timestamp: string,
ownDocNo: string,
revNo: string,
stage: string,
extension: string
): string {
const dateOnly = timestamp.substring(0, 8); // YYYYMMDD만 추출
// 파일명 생성: [OWN_DOC_NO]_[REV_NO]_[STAGE]_[YYYYMMDD].확장자
const fileName = extension
? `[${ownDocNo}]_${revNo}_${stage}_${dateOnly}.${extension}`
: `[${ownDocNo}]_${revNo}_${stage}_${dateOnly}`;
// 전체 경로 생성
return path.join(this.swpMountDir, projNo, cpyCode, timestamp, fileName);
}
/**
* 네트워크 경로 생성 (SHI 시스템에서 접근 가능한 경로)
* \\60.100.91.61\SBox\{PROJ_NO}\{CPY_CD}\{YYYYMMDDHHmmSS}\[OWN_DOC_NO]_[REV_NO]_[STAGE]_[YYYYMMDD].확장자
*/
private generateNetworkPath(
projNo: string,
cpyCode: string,
timestamp: string,
ownDocNo: string,
revNo: string,
stage: string,
extension: string
): string {
const dateOnly = timestamp.substring(0, 8); // YYYYMMDD만 추출
// 파일명 생성: [OWN_DOC_NO]_[REV_NO]_[STAGE]_[YYYYMMDD].확장자
const fileName = extension
? `[${ownDocNo}]_${revNo}_${stage}_${dateOnly}.${extension}`
: `[${ownDocNo}]_${revNo}_${stage}_${dateOnly}`;
// 네트워크 경로 생성
return `\\\\60.100.91.61\\SBox\\${projNo}\\${cpyCode}\\${timestamp}\\${fileName}`;
}
async sendToSHI(contractId: number) {
try {
// 1. 전송할 문서 조회
const documents = await this.getDocumentsToSend(contractId)
if (documents.length === 0) {
return { success: false, message: "전송할 문서가 없습니다." }
}
// 2. 도서 정보 전송
await this.sendDocumentInfo(documents)
// 3. 스케줄 정보 전송
await this.sendScheduleInfo(documents)
// 4. 동기화 상태 업데이트
await this.updateSyncStatus(documents.map(d => d.documentId))
return {
success: true,
message: `${documents.length}개 문서가 성공적으로 전송되었습니다.`,
count: documents.length
}
} catch (error) {
console.error("SHI 전송 오류:", error)
// 에러 시 동기화 상태 업데이트
await this.updateSyncError(
contractId,
error instanceof Error ? error.message : "알 수 없는 오류"
)
throw error
}
}
private async getDocumentsToSend(contractId: number): Promise<DocumentWithStages[]> {
// 1. 먼저 문서 목록을 가져옴
const documents = await db
.select({
documentId: stageDocuments.id,
docNumber: stageDocuments.docNumber,
vendorDocNumber: stageDocuments.vendorDocNumber,
title: stageDocuments.title,
status: stageDocuments.status,
buyerSystemComment: stageDocuments.buyerSystemComment, // 코멘트 필드 추가
docClass: stageDocuments.docClass, // DOC_CLASS 필드 추가
projectCode: sql<string>`(SELECT code FROM projects WHERE id = ${stageDocuments.projectId})`,
vendorCode: sql<string>`(SELECT vendor_code FROM vendors WHERE id = ${stageDocuments.vendorId})`,
vendorName: sql<string>`(SELECT vendor_name FROM vendors WHERE id = ${stageDocuments.vendorId})`,
})
.from(stageDocuments)
.where(
and(
eq(stageDocuments.contractId, contractId),
eq(stageDocuments.status, 'ACTIVE'),
// ne는 null을 포함하지 않음
or(
isNull(stageDocuments.buyerSystemStatus),
ne(stageDocuments.buyerSystemStatus, "승인(DC)")
)
)
)
// 2. 각 문서에 대해 스테이지 정보를 별도로 조회
const documentsWithStages = await Promise.all(
documents.map(async (doc) => {
const stages = await db
.select()
.from(stageIssueStages)
.where(eq(stageIssueStages.documentId, doc.documentId))
.orderBy(stageIssueStages.stageOrder)
return {
...doc,
stages: stages || []
} as DocumentWithStages
})
)
return documentsWithStages
}
private async sendDocumentInfo(documents: DocumentWithStages[]) {
const shiDocuments: ShiDocumentInfo[] = documents.map((doc) => {
const docInfo: ShiDocumentInfo = {
PROJ_NO: doc.projectCode,
SHI_DOC_NO: doc.docNumber,
CATEGORY: null, // SHI 설계자가 직접 입력함
// 김준식 프로 요청으로 RESPONSIBLE_CD / RESPONSIBLE 값 변경 (251002,김준회)
RESPONSIBLE_CD: 'C00001', // 고정
RESPONSIBLE: 'SHI', // 고정
VNDR_CD: doc.vendorCode || '',
VNDR_NM: doc.vendorName || '',
DSN_SKL: null, // SHI 설계자가 직접 입력함
MIFP_CD: '',
MIFP_NM: '',
CG_EMPNO1: '',
CG_EMPNM1: '',
OWN_DOC_NO: doc.vendorDocNumber || doc.docNumber,
DSC: doc.title,
DOC_CLASS: doc.docClass || '', // 선택한 DOC_CLASS 사용
COMMENT: doc.buyerSystemComment || '', // 실제 코멘트 전송
// 조민정 프로 요청으로 'ACTIVE' --> '생성요청' 값으로 변경 (251002,김준회)
STATUS: '생성요청', // 고정
CRTER: 'EVCP_SYSTEM', // 고정
CRTE_DTM: new Date().toISOString(),
CHGR: 'EVCP_SYSTEM', // 고정
CHG_DTM: new Date().toISOString(),
};
// DOC_CLASS 값 로깅 (디버깅용)
console.log(`[SHI API] 문서 ${doc.docNumber} - DOC_CLASS: "${doc.docClass}" -> 전송값: "${docInfo.DOC_CLASS}"`);
return docInfo;
});
// 전송 데이터 로깅 (디버깅용)
console.log('[SHI API] SetDwgInfo 요청 데이터:', JSON.stringify(shiDocuments, null, 2))
const response = await fetch(`${this.baseUrl}/SetDwgInfo`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(shiDocuments)
})
if (!response.ok) {
const errorText = await response.text()
throw new Error(`도서 정보 전송 실패: ${response.statusText} - ${errorText}`)
}
return response.json()
}
private async sendScheduleInfo(documents: DocumentWithStages[]) {
const schedules: ShiScheduleInfo[] = []
for (const doc of documents) {
for (const stage of doc.stages) {
// 날짜에서 1은 Issue, 2는 Receipt
if (stage.planDate) {
schedules.push({
PROJ_NO: doc.projectCode,
SHI_DOC_NO: doc.docNumber,
DDPKIND: "V",
SCHEDULE_TYPE: stage.stageName,
BASELINE1: stage.planDate ? new Date(stage.planDate).toISOString() : null,
REVISED1: null,
FORECAST1: null,
ACTUAL1: stage.actualDate ? new Date(stage.actualDate).toISOString() : null,
BASELINE2: null,
REVISED2: null,
FORECAST2: null,
ACTUAL2: null,
CRTER: "EVCP_SYSTEM",
CRTE_DTM: new Date().toISOString(),
CHGR: "EVCP_SYSTEM",
CHG_DTM: new Date().toISOString()
})
}
}
}
if (schedules.length === 0) {
console.log("전송할 스케줄 정보가 없습니다.")
return
}
const response = await fetch(`${this.baseUrl}/SetScheduleInfo`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(schedules)
})
if (!response.ok) {
const errorText = await response.text()
throw new Error(`스케줄 정보 전송 실패: ${response.statusText} - ${errorText}`)
}
return response.json()
}
private async updateSyncStatus(documentIds: number[]) {
if (documentIds.length === 0) return
await db
.update(stageDocuments)
.set({
syncStatus: 'synced',
lastSyncedAt: new Date(),
syncError: null,
syncVersion: sql`sync_version + 1`,
lastModifiedBy: 'EVCP'
})
.where(inArray(stageDocuments.id, documentIds))
}
private async updateSyncError(contractId: number, errorMessage: string) {
await db
.update(stageDocuments)
.set({
syncStatus: 'error',
syncError: errorMessage,
lastModifiedBy: 'EVCP'
})
.where(
and(
eq(stageDocuments.contractId, contractId),
eq(stageDocuments.status, 'ACTIVE')
)
)
}
async pullDocumentStatus(contractId: number) {
try {
const contract = await db.query.contracts.findFirst({
where: eq(contracts.id, contractId),
});
if (!contract || !contract.projectId || !contract.vendorId) {
throw new Error(`계약 정보가 올바르지 않습니다: ${contractId}`)
}
const project = await db.query.projects.findFirst({
where: eq(projects.id, contract.projectId),
});
if (!project || !project.code) {
throw new Error(`프로젝트를 찾을 수 없습니다: ${contract.projectId}`)
}
const vendor = await db.query.vendors.findFirst({
where: eq(vendors.id, contract.vendorId),
});
if (!vendor || !vendor.vendorCode) {
throw new Error(`벤더를 찾을 수 없습니다: ${contract.vendorId}`)
}
const shiDocuments = await this.fetchDocumentsFromSHI(project.code, {
VNDR_CD: vendor.vendorCode ?? undefined
})
if (!shiDocuments || shiDocuments.length === 0) {
return {
success: true,
message: "동기화할 문서가 없습니다.",
updatedCount: 0,
documents: []
}
}
const updateResults = await this.updateLocalDocuments(project.code, shiDocuments)
return {
success: true,
message: `${updateResults.updatedCount}개 문서의 상태가 업데이트되었습니다.`,
updatedCount: updateResults.updatedCount,
newCount: updateResults.newCount,
documents: updateResults.documents
}
} catch (error) {
console.error("문서 상태 풀링 오류:", error)
throw error
}
}
private async fetchDocumentsFromSHI(
projectCode: string,
filters?: {
SHI_DOC_NO?: string
CATEGORY?: string
VNDR_CD?: string
RESPONSIBLE_CD?: string
STATUS?: string
DOC_CLASS?: string
CRTE_DTM_FROM?: string
CRTE_DTM_TO?: string
CHG_DTM_FROM?: string
CHG_DTM_TO?: string
}
): Promise<ShiDocumentResponse[]> {
const params = new URLSearchParams({ PROJ_NO: projectCode })
if (filters) {
Object.entries(filters).forEach(([key, value]) => {
if (value) params.append(key, value)
})
}
const url = `${this.baseUrl}/GetDwgInfo?${params.toString()}`
const response = await fetch(url, {
method: 'GET',
headers: {
'Accept': 'application/json'
}
})
if (!response.ok) {
throw new Error(`문서 조회 실패: ${response.statusText}`)
}
const data: ShiApiResponse = await response.json()
return data.GetDwgInfoResult || []
}
private async updateLocalDocuments(
projectCode: string,
shiDocuments: ShiDocumentResponse[]
) {
let updatedCount = 0
let newCount = 0
const updatedDocuments: Array<{
docNumber: string
title: string
status: string | null | undefined
comment: string | null | undefined
action: string
}> = []
const project = await db.query.projects.findFirst({
where: eq(projects.code, projectCode)
})
if (!project) {
throw new Error(`프로젝트를 찾을 수 없습니다: ${projectCode}`)
}
for (const shiDoc of shiDocuments) {
const localDoc = await db.query.stageDocuments.findFirst({
where: and(
eq(stageDocuments.projectId, project.id),
eq(stageDocuments.docNumber, shiDoc.SHI_DOC_NO)
)
})
if (localDoc) {
if (
localDoc.buyerSystemStatus !== shiDoc.STATUS ||
localDoc.buyerSystemComment !== shiDoc.COMMENT
) {
await db
.update(stageDocuments)
.set({
buyerSystemStatus: shiDoc.STATUS,
buyerSystemComment: shiDoc.COMMENT,
lastSyncedAt: new Date(),
syncStatus: 'synced',
syncError: null,
lastModifiedBy: 'BUYER_SYSTEM',
syncVersion: sql`sync_version + 1`
})
.where(eq(stageDocuments.id, localDoc.id))
updatedCount++
updatedDocuments.push({
docNumber: shiDoc.SHI_DOC_NO,
title: shiDoc.DSC || localDoc.title,
status: shiDoc.STATUS,
comment: shiDoc.COMMENT,
action: 'updated'
})
}
} else {
console.log(`SHI에만 존재하는 문서: ${shiDoc.SHI_DOC_NO}`)
newCount++
updatedDocuments.push({
docNumber: shiDoc.SHI_DOC_NO,
title: shiDoc.DSC || 'N/A',
status: shiDoc.STATUS,
comment: shiDoc.COMMENT,
action: 'new_in_shi'
})
}
}
return {
updatedCount,
newCount,
documents: updatedDocuments
}
}
async getSyncStatus(contractId: number) {
const documents = await db
.select({
docNumber: stageDocuments.docNumber,
title: stageDocuments.title,
syncStatus: stageDocuments.syncStatus,
lastSyncedAt: stageDocuments.lastSyncedAt,
syncError: stageDocuments.syncError,
buyerSystemStatus: stageDocuments.buyerSystemStatus,
buyerSystemComment: stageDocuments.buyerSystemComment
})
.from(stageDocuments)
.where(eq(stageDocuments.contractId, contractId))
return documents
}
/**
* 스테이지 제출 건들의 파일을 SHI 구매자 시스템으로 동기화
* @param submissionIds 제출 ID 배열
*/
async syncSubmissionsToSHI(submissionIds: number[]) {
const results = {
totalCount: submissionIds.length,
successCount: 0,
failedCount: 0,
details: [] as Array<{
submissionId: number
success: boolean
message?: string
syncedFiles?: number
error?: string
}>
}
for (const submissionId of submissionIds) {
try {
const result = await this.syncSingleSubmission(submissionId)
if (result.success) {
results.successCount++
} else {
results.failedCount++
}
results.details.push(result)
} catch (error) {
results.failedCount++
results.details.push({
submissionId,
success: false,
error: error instanceof Error ? error.message : "Unknown error"
})
}
}
return results
}
/**
* 단일 제출 건 동기화
*/
private async syncSingleSubmission(submissionId: number) {
try {
// 1. 제출 정보 조회 (프로젝트, 문서, 스테이지, 파일 정보 포함)
const submissionInfo = await this.getSubmissionFullInfo(submissionId)
if (!submissionInfo) {
throw new Error(`제출 정보를 찾을 수 없습니다: ${submissionId}`)
}
// 2. 동기화 시작 상태 업데이트
await this.updateSubmissionSyncStatus(submissionId, 'syncing')
// 3. 첨부파일들과 실제 파일 내용을 준비
const filesWithContent = await this.prepareFilesWithContent(submissionInfo)
if (filesWithContent.length === 0) {
await this.updateSubmissionSyncStatus(submissionId, 'synced', '전송할 파일이 없습니다')
return {
submissionId,
success: true,
message: "전송할 파일이 없습니다"
}
}
// 4. SaveInBoxList API 호출하여 네트워크 경로 받기
const response = await this.sendToInBox(filesWithContent)
// 5. SMB 마운트 경로에 파일 저장
if (
response.SaveInBoxListResult.success &&
response.SaveInBoxListResult.files
) {
await this.saveFilesToNetworkPaths(filesWithContent)
// 6. 동기화 결과 업데이트
await this.updateSubmissionSyncStatus(submissionId, 'synced', null, {
syncedFilesCount: filesWithContent.length,
buyerSystemStatus: 'SYNCED'
})
// 개별 파일 상태 업데이트
await this.updateAttachmentsSyncStatus(
submissionInfo.attachments.map(a => a.id),
'synced'
)
return {
submissionId,
success: true,
message: response.SaveInBoxListResult.message,
syncedFiles: filesWithContent.length
}
} else {
throw new Error(response.SaveInBoxListResult.message)
}
} catch (error) {
await this.updateSubmissionSyncStatus(
submissionId,
'failed',
error instanceof Error ? error.message : '알 수 없는 오류'
)
throw error
}
}
/**
* 제출 정보 조회 (관련 정보 포함)
*/
private async getSubmissionFullInfo(submissionId: number): Promise<SubmissionFullInfo | null> {
const result = await db
.select({
submission: stageSubmissions,
stage: stageIssueStages,
document: stageDocuments,
project: projects,
vendor: vendors
})
.from(stageSubmissions)
.innerJoin(stageIssueStages, eq(stageSubmissions.stageId, stageIssueStages.id))
.innerJoin(stageDocuments, eq(stageSubmissions.documentId, stageDocuments.id))
.innerJoin(projects, eq(stageDocuments.projectId, projects.id))
.leftJoin(vendors, eq(stageDocuments.vendorId, vendors.id))
.where(eq(stageSubmissions.id, submissionId))
.limit(1)
if (result.length === 0) return null
// 첨부파일 조회 - 파일 경로 포함
const attachments = await db
.select()
.from(stageSubmissionAttachments)
.where(
and(
eq(stageSubmissionAttachments.submissionId, submissionId),
eq(stageSubmissionAttachments.status, 'ACTIVE')
)
)
return {
...result[0],
attachments
} as SubmissionFullInfo
}
/**
* 파일 내용과 함께 InBox 파일 정보 준비
*/
private async prepareFilesWithContent(
submissionInfo: SubmissionFullInfo
): Promise<FileInfoWithBuffer[]> {
const filesWithContent: FileInfoWithBuffer[] = [];
const timestamp = this.getTimestamp(); // 모든 파일에 동일한 타임스탬프 사용
const cpyCode = 'C00001'; // CPY_CD는 항상 C00001 고정 (레거시 시스템 협의사항)
for (const attachment of submissionInfo.attachments) {
try {
// 파일 경로 결정 (storagePath 또는 storageUrl 사용)
const filePath = attachment.storagePath || attachment.storageUrl;
if (!filePath) {
console.warn(`첨부파일 ${attachment.id}의 경로를 찾을 수 없습니다.`);
continue;
}
// 전체 경로 생성
const fullPath = path.isAbsolute(filePath)
? filePath
: path.join(this.localStoragePath, filePath);
// 파일 읽기
const fileBuffer = await fs.readFile(fullPath);
// 파일명 파싱
const { extension } = this.parseFileName(attachment.fileName);
// OWN_DOC_NO 결정 (vendorDocNumber가 있으면 사용, 없으면 docNumber 사용)
const ownDocNo = submissionInfo.document.vendorDocNumber || submissionInfo.document.docNumber;
// 리비전 번호 (2자리로 패딩)
const revNo = String(submissionInfo.submission.revisionNumber).padStart(2, '0');
// 파일명 생성: [OWNDOCNO]_[REVNO]_[STAGE]_[YYYYMMDDhhmmss].[extension]
const fileName = extension
? `${ownDocNo}_${revNo}_${submissionInfo.stage.stageName}_${timestamp}.${extension}`
: `${ownDocNo}_${revNo}_${submissionInfo.stage.stageName}_${timestamp}`;
// 폴더 경로 생성: \\projNo\\cpyCd\\[OFDC_NO]\\YYYYMMDD
// OFDC_NO가 없으면 빈 문자열 (\\\\로 표시됨)
const dateOnly = timestamp.substring(0, 8); // YYYYMMDD만 추출
const ofdcNo = ''; // OFDC_NO는 현재 null이므로 빈 문자열
const fldPath = `\\\\${submissionInfo.project.code}\\\\${cpyCode}\\\\${ofdcNo}\\\\${dateOnly}`;
// 파일 정보 생성 (새로운 API 형식)
const fileInfo: FileInfoWithBuffer = {
CPY_CD: cpyCode,
FILE_NM: fileName,
OFDC_NO: null,
PROJ_NO: submissionInfo.project.code,
OWN_DOC_NO: ownDocNo,
REV_NO: revNo,
STAGE: submissionInfo.stage.stageName,
STAT: 'SCW03', // Completed 상태
FILE_SZ: String(fileBuffer.length),
FLD_PATH: fldPath,
fileBuffer: fileBuffer,
attachment: {
id: attachment.id,
fileName: attachment.fileName,
mimeType: attachment.mimeType,
storagePath: attachment.storagePath,
storageUrl: attachment.storageUrl,
},
// 네트워크 경로 생성을 위한 추가 정보
_timestamp: timestamp,
_extension: extension,
};
filesWithContent.push(fileInfo);
} catch (error) {
console.error(`파일 읽기 실패: ${attachment.fileName}`, error);
// 파일 읽기 실패 시 계속 진행
continue;
}
}
return filesWithContent;
}
/**
* SaveInBoxList API 호출 (파일 메타데이터만 전송)
*/
private async sendToInBox(
files: FileInfoWithBuffer[]
): Promise<SaveInBoxListResponse> {
// fileBuffer, attachment, _timestamp, _extension을 제외한 메타데이터만 전송
const fileMetadata = files.map((file) => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { fileBuffer, attachment, _timestamp, _extension, ...metadata } = file;
return metadata as InBoxFileInfo;
});
// 새로운 API 형식에 맞게 요청 생성
const request: SaveInBoxListRequest = {
externalInboxLists: fileMetadata
};
console.log('SaveInBoxList 요청:', JSON.stringify(request, null, 2));
const response = await fetch(`${this.ddcUrl}/SaveInBoxList`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify(request),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`InBox 전송 실패: ${response.statusText} - ${errorText}`);
}
const data = await response.json();
console.log('SaveInBoxList 응답:', JSON.stringify(data, null, 2));
// 응답 구조 확인 및 처리
if (!data.SaveInBoxListResult) {
return {
SaveInBoxListResult: {
success: true,
message: '전송 완료',
processedCount: files.length,
files: files.map((f) => {
// 레거시 네트워크 경로 생성
const networkPath = this.generateNetworkPath(
f.PROJ_NO,
f.CPY_CD,
f._timestamp,
f.OWN_DOC_NO,
f.REV_NO,
f.STAGE,
f._extension
);
return {
fileName: f.FILE_NM,
networkPath: networkPath,
status: 'READY',
};
}),
},
};
}
return data;
}
/**
* SMB 마운트 경로에 파일 저장 (레거시 경로 규칙 적용)
*/
private async saveFilesToNetworkPaths(
filesWithContent: FileInfoWithBuffer[]
) {
for (const fileInfo of filesWithContent) {
try {
// 레거시 경로 규칙에 따라 마운트 경로 생성
const targetPath = this.generateMountPath(
fileInfo.PROJ_NO,
fileInfo.CPY_CD,
fileInfo._timestamp,
fileInfo.OWN_DOC_NO,
fileInfo.REV_NO,
fileInfo.STAGE,
fileInfo._extension
);
// 디렉토리 생성 (없는 경우)
const targetDir = path.dirname(targetPath);
await fs.mkdir(targetDir, { recursive: true });
// 파일 저장
await fs.writeFile(targetPath, fileInfo.fileBuffer);
console.log(`파일 저장 완료: ${fileInfo.FILE_NM} -> ${targetPath}`);
console.log(
`생성된 경로 구조: ${fileInfo.PROJ_NO}/${fileInfo.CPY_CD}/${fileInfo._timestamp}/[${fileInfo.OWN_DOC_NO}]_${fileInfo.REV_NO}_${fileInfo.STAGE}_${fileInfo._timestamp.substring(0, 8)}.${fileInfo._extension}`
);
// 네트워크 경로 생성 (레거시 형식)
const networkPath = this.generateNetworkPath(
fileInfo.PROJ_NO,
fileInfo.CPY_CD,
fileInfo._timestamp,
fileInfo.OWN_DOC_NO,
fileInfo.REV_NO,
fileInfo.STAGE,
fileInfo._extension
);
console.log(`네트워크 경로: ${networkPath}`);
console.log(`FLD_PATH (API 전송용): ${fileInfo.FLD_PATH}`);
// DB에 경로 정보 업데이트
await db
.update(stageSubmissionAttachments)
.set({
buyerSystemUrl: networkPath, // 네트워크 경로 저장 (SHI 시스템에서 접근 가능한 경로)
buyerSystemStatus: 'UPLOADED',
lastModifiedBy: 'EVCP'
})
.where(eq(stageSubmissionAttachments.id, fileInfo.attachment.id))
} catch (error) {
console.error(`파일 저장 실패: ${fileInfo.FILE_NM}`, error)
// 개별 파일 실패는 전체 프로세스를 중단하지 않음
}
}
}
/**
* 제출 동기화 상태 업데이트
*/
private async updateSubmissionSyncStatus(
submissionId: number,
status: string,
error?: string | null,
additionalData?: Record<string, string | number | Date | null>
) {
const updateData: any = {
syncStatus: status,
lastSyncedAt: new Date(),
syncError: error ?? null,
lastModifiedBy: 'EVCP',
...additionalData
}
if (status === 'failed') {
updateData.syncRetryCount = sql`sync_retry_count + 1`
updateData.nextRetryAt = new Date(Date.now() + 30 * 60 * 1000) // 30분 후 재시도
}
await db
.update(stageSubmissions)
.set(updateData)
.where(eq(stageSubmissions.id, submissionId))
}
/**
* 첨부파일 동기화 상태 업데이트
*/
private async updateAttachmentsSyncStatus(
attachmentIds: number[],
status: string
) {
if (attachmentIds.length === 0) return
await db
.update(stageSubmissionAttachments)
.set({
syncStatus: status,
syncCompletedAt: status === 'synced' ? new Date() : null,
buyerSystemStatus: status === 'synced' ? 'UPLOADED' : 'PENDING',
lastModifiedBy: 'EVCP'
})
.where(inArray(stageSubmissionAttachments.id, attachmentIds))
}
/**
* 동기화 재시도 (실패한 건들)
*/
async retrySyncFailedSubmissions(contractId?: number) {
const conditions = [
eq(stageSubmissions.syncStatus, 'failed'),
sql`next_retry_at <= NOW()`
]
if (contractId) {
const documentIds = await db
.select({ id: stageDocuments.id })
.from(stageDocuments)
.where(eq(stageDocuments.contractId, contractId))
if (documentIds.length > 0) {
conditions.push(
inArray(
stageSubmissions.documentId,
documentIds.map((d) => d.id)
)
)
}
}
const failedSubmissions = await db
.select({ id: stageSubmissions.id })
.from(stageSubmissions)
.where(and(...conditions))
.limit(10) // 한 번에 최대 10개씩 재시도
if (failedSubmissions.length === 0) {
return {
success: true,
message: "재시도할 제출 건이 없습니다.",
retryCount: 0
}
}
const submissionIds = failedSubmissions.map(s => s.id)
const results = await this.syncSubmissionsToSHI(submissionIds)
return {
success: true,
message: `${results.successCount}/${results.totalCount}개 제출 건 재시도 완료`,
...results
}
}
}
|