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
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
|
// lib/vendor-document-list/import-service.ts - DOLCE API 연동 버전 (파일 다운로드 포함)
import db from "@/db/db"
import { documents, issueStages, contracts, projects, vendors, revisions, documentAttachments } from "@/db/schema"
import { eq, and, sql } from "drizzle-orm"
import { writeFile, mkdir } from "fs/promises"
import { join } from "path"
import { v4 as uuidv4 } from "uuid"
import { extname } from "path"
import * as crypto from "crypto"
import { debugError, debugWarn, debugSuccess, debugProcess } from "@/lib/debug-utils"
import { getServerSession } from "next-auth/next"
import { authOptions } from "@/app/api/auth/[...nextauth]/route"
export interface ImportResult {
success: boolean
newCount: number
updatedCount: number
skippedCount: number
newRevisionsCount: number
updatedRevisionsCount: number
newAttachmentsCount: number
updatedAttachmentsCount: number
downloadedFilesCount: number
errors?: string[]
message?: string
}
export interface ImportStatus {
lastImportAt?: string
availableDocuments: number
newDocuments: number
updatedDocuments: number
availableRevisions: number
newRevisions: number
updatedRevisions: number
availableAttachments: number
newAttachments: number
updatedAttachments: number
importEnabled: boolean
error?: string
}
interface DOLCEDocument {
CGbn?: string
CreateDt: string
CreateUserENM: string
CreateUserId: string
CreateUserNo: string
DGbn?: string
DegreeGbn?: string
DeptGbn?: string
Discipline: string
DrawingKind: string // B3, B4, B5
DrawingMoveGbn: string
DrawingName: string
DrawingNo: string
GTTInput_PlanDate?: string
GTTInput_ResultDate?: string
AppDwg_PlanDate?: string
AppDwg_ResultDate?: string
WorDwg_PlanDate?: string
WorDwg_ResultDate?: string
GTTPreDwg_PlanDate?: string
GTTPreDwg_ResultDate?: string
GTTWorkingDwg_PlanDate?: string
GTTWorkingDwg_ResultDate?: string
FMEAFirst_PlanDate?: string
FMEAFirst_ResultDate?: string
FMEASecond_PlanDate?: string
FMEASecond_ResultDate?: string
JGbn?: string
Manager: string
ManagerENM: string
ManagerNo: string
ProjectNo: string
RegisterGroup: number
RegisterGroupId: number
SGbn?: string
SHIDrawingNo?: string
}
interface DOLCEDetailDocument {
Status: string
Category: string // TS, FS
CategoryNM: string
CategoryENM: string
RegisterId: string
ProjectNo: string
DrawingNo: string
RegisterGroupId: number
RegisterGroup: number
DrawingName: string
RegisterSerialNoMax: number
RegisterSerialNo: number
DrawingUsage: string
DrawingUsageNM: string
DrawingUsageENM: string
RegisterKind: string
RegisterKindNM: string
RegisterKindENM: string
DrawingRevNo: string
RegisterDesc: string
UploadId: string
ManagerNM: string
Manager: string
UseYn: string
RegCompanyCode: string
RegCompanyNM: string
RegCompanyENM: string
CreateUserENM: string
CreateUserNM: string
CreateUserId: string
CreateDt: string
ModifyUserId: string
ModifyDt: string
Discipline: string
DrawingKind: string
DrawingMoveGbn: string
SHIDrawingNo: string
Receiver: string
SHINote: string
}
interface DOLCEFileInfo {
FileId: string
UploadId: string
FileSeq: number
FileServerId: string
FileTitle: string
FileDescription: string
FileName: string
FileRelativePath: string
FileSize: number
FileCreateDT: string
FileWriteDT: string
OwnerUserId: string
UseYn: string
}
class ImportService {
private readonly DES_KEY = Buffer.from("4fkkdijg", "ascii")
/**
* DOLCE 시스템에서 문서 목록 가져오기
*/
async importFromExternalSystem(
projectId: number,
sourceSystem: string = 'DOLCE'
): Promise<ImportResult> {
try {
debugProcess(`DOLCE 가져오기 시작`, { projectId, sourceSystem })
// 1. 계약 정보를 통해 프로젝트 코드와 벤더 코드 조회
const contractInfo = await this.getContractInfoById(projectId)
if (!contractInfo?.projectCode || !contractInfo?.vendorCode) {
debugError(`프로젝트 코드 또는 벤더 코드 없음`, { projectId })
throw new Error(`Project code or vendor code not found for contract ${projectId}`)
}
// debugLog(`계약 정보 조회 완료`, {
// projectId,
// projectCode: contractInfo.projectCode,
// vendorCode: contractInfo.vendorCode
// })
// 2. 각 drawingKind별로 데이터 조회
const allDocuments: DOLCEDocument[] = []
const drawingKinds = ['B3', 'B4', 'B5']
for (const drawingKind of drawingKinds) {
try {
const documents = await this.fetchFromDOLCE(
contractInfo.projectCode,
contractInfo.vendorCode,
drawingKind
)
allDocuments.push(...documents)
debugSuccess(`${drawingKind} 문서 조회 완료`, {
drawingKind,
documentCount: documents.length
})
} catch (error) {
debugWarn(`${drawingKind} 문서 조회 실패`, { drawingKind, error })
// 개별 drawingKind 실패는 전체 실패로 처리하지 않음
}
}
if (allDocuments.length === 0) {
debugProcess(`가져올 문서 없음`, { projectId })
return {
success: true,
newCount: 0,
updatedCount: 0,
skippedCount: 0,
newRevisionsCount: 0,
updatedRevisionsCount: 0,
newAttachmentsCount: 0,
updatedAttachmentsCount: 0,
downloadedFilesCount: 0,
message: '가져올 새로운 데이터가 없습니다.'
}
}
debugProcess(`전체 문서 수`, {
projectId,
totalDocuments: allDocuments.length,
byDrawingKind: {
B3: allDocuments.filter(d => d.DrawingKind === 'B3').length,
B4: allDocuments.filter(d => d.DrawingKind === 'B4').length,
B5: allDocuments.filter(d => d.DrawingKind === 'B5').length
}
})
let newCount = 0
let updatedCount = 0
let skippedCount = 0
let newRevisionsCount = 0
let updatedRevisionsCount = 0
let newAttachmentsCount = 0
let updatedAttachmentsCount = 0
let downloadedFilesCount = 0
const errors: string[] = []
// 3. 각 문서 동기화 처리
for (const dolceDoc of allDocuments) {
try {
debugProcess(`문서 동기화 시작`, {
drawingNo: dolceDoc.DrawingNo,
drawingKind: dolceDoc.DrawingKind
})
const result = await this.syncSingleDocument(projectId, dolceDoc, sourceSystem)
if (result === 'NEW') {
newCount++
// B4 문서의 경우 이슈 스테이지 자동 생성
if (dolceDoc.DrawingKind === 'B4') {
await this.createIssueStagesForB4Document(dolceDoc.DrawingNo, projectId, dolceDoc)
}
if (dolceDoc.DrawingKind === 'B3') {
await this.createIssueStagesForB3Document(dolceDoc.DrawingNo, projectId, dolceDoc)
}
if (dolceDoc.DrawingKind === 'B5') {
await this.createIssueStagesForB5Document(dolceDoc.DrawingNo, projectId, dolceDoc)
}
} else if (result === 'UPDATED') {
updatedCount++
} else {
skippedCount++
}
// 4. revisions 동기화 처리
try {
const revisionResult = await this.syncDocumentRevisions(
projectId,
dolceDoc,
sourceSystem
)
newRevisionsCount += revisionResult.newCount
updatedRevisionsCount += revisionResult.updatedCount
// 5. 파일 첨부 동기화 처리 (Category가 FS인 것만)
const attachmentResult = await this.syncDocumentAttachments(
dolceDoc,
sourceSystem
)
newAttachmentsCount += attachmentResult.newCount
updatedAttachmentsCount += attachmentResult.updatedCount
downloadedFilesCount += attachmentResult.downloadedCount
} catch (revisionError) {
debugWarn(`리비전 동기화 실패`, {
drawingNo: dolceDoc.DrawingNo,
error: revisionError
})
// revisions 동기화 실패는 에러 로그만 남기고 계속 진행
}
} catch (error) {
debugError(`문서 동기화 실패`, {
drawingNo: dolceDoc.DrawingNo,
error
})
errors.push(`Document ${dolceDoc.DrawingNo}: ${error instanceof Error ? error.message : 'Unknown error'}`)
skippedCount++
}
}
debugSuccess(`DOLCE 가져오기 완료`, {
projectId,
newCount,
updatedCount,
skippedCount,
newRevisionsCount,
updatedRevisionsCount,
newAttachmentsCount,
updatedAttachmentsCount,
downloadedFilesCount,
errorCount: errors.length
})
return {
success: errors.length === 0,
newCount,
updatedCount,
skippedCount,
newRevisionsCount,
updatedRevisionsCount,
newAttachmentsCount,
updatedAttachmentsCount,
downloadedFilesCount,
errors: errors.length > 0 ? errors : undefined,
message: `가져오기 완료: 신규 ${newCount}건, 업데이트 ${updatedCount}건, 리비전 신규 ${newRevisionsCount}건, 리비전 업데이트 ${updatedRevisionsCount}건, 파일 다운로드 ${downloadedFilesCount}건`
}
} catch (error) {
debugError(`DOLCE 가져오기 실패`, { projectId, error })
throw error
}
}
/**
* 계약 ID로 프로젝트 코드와 벤더 코드 조회
*/
private async getContractInfoById(projectId: number): Promise<{
projectCode: string;
vendorCode: string;
} | null> {
const session = await getServerSession(authOptions)
if (!session?.user?.companyId) {
throw new Error("인증이 필요합니다.")
}
const [result] = await db
.select({
projectCode: projects.code,
vendorCode: vendors.vendorCode
})
.from(contracts)
.innerJoin(projects, eq(contracts.projectId, projects.id))
.innerJoin(vendors, eq(contracts.vendorId, vendors.id))
.where(and(eq(contracts.projectId, projectId),eq(contracts.vendorId, Number(session.user.companyId))))
.limit(1)
return result?.projectCode && result?.vendorCode
? { projectCode: result.projectCode, vendorCode: result.vendorCode }
: null
}
/**
* DOLCE API에서 문서 목록 데이터 조회
*/
private async fetchFromDOLCE(
projectCode: string,
vendorCode: string,
drawingKind: string
): Promise<DOLCEDocument[]> {
const endpoint = process.env.DOLCE_DOC_LIST_API_URL || 'http://60.100.99.217:1111/Services/VDCSWebService.svc/DwgReceiptMgmt'
const requestBody = {
project: projectCode,
drawingKind: drawingKind, // B3, B4, B5
drawingMoveGbn: "",
drawingNo: "",
drawingName: "",
drawingVendor: vendorCode
}
console.log(`Fetching from DOLCE: ${projectCode} - ${drawingKind} = ${vendorCode}`)
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody)
})
if (!response.ok) {
const errorText = await response.text()
throw new Error(`DOLCE API failed: HTTP ${response.status} - ${errorText}`)
}
const data = await response.json()
// DOLCE API 응답 구조에 맞게 처리
if (data.DwgReceiptMgmtResult) {
const result = data.DwgReceiptMgmtResult
// drawingKind에 따라 적절한 배열에서 데이터 추출
let documents: DOLCEDocument[] = []
switch (drawingKind) {
case 'B3':
documents = result.VendorDwgList || []
break
case 'B4':
documents = result.GTTDwgList || []
break
case 'B5':
documents = result.FMEADwgList || []
break
default:
console.warn(`Unknown drawingKind: ${drawingKind}`)
documents = []
}
console.log(`Found ${documents.length} documents for ${drawingKind}`)
return documents as DOLCEDocument[]
} else {
console.warn(`Unexpected DOLCE response structure:`, data)
return []
}
} catch (error) {
console.error(`DOLCE API call failed for ${projectCode}/${drawingKind}:`, error)
throw error
}
}
/**
* DOLCE API에서 문서 상세 정보 조회 (revisions 데이터)
*/
private async fetchDetailFromDOLCE(
projectCode: string,
drawingNo: string,
discipline: string,
drawingKind: string
): Promise<DOLCEDetailDocument[]> {
const endpoint = process.env.DOLCE_DOC_DETAIL_API_URL || 'http://60.100.99.217:1111/Services/VDCSWebService.svc/DetailDwgReceiptMgmt'
const requestBody = {
project: projectCode,
drawingNo: drawingNo,
discipline: discipline,
drawingKind: drawingKind
}
console.log(`Fetching detail from DOLCE: ${projectCode} - ${drawingNo}`)
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody)
})
if (!response.ok) {
const errorText = await response.text()
throw new Error(`DOLCE Detail API failed: HTTP ${response.status} - ${errorText}`)
}
const data = await response.json()
// DOLCE Detail API 응답 구조에 맞게 처리
if (data.DetailDwgReceiptMgmtResult) {
const documents = data.DetailDwgReceiptMgmtResult as DOLCEDetailDocument[]
console.log(`Found ${documents.length} detail records for ${drawingNo}`)
return documents
} else {
console.warn(`Unexpected DOLCE Detail response structure:`, data)
return []
}
} catch (error) {
console.error(`DOLCE Detail API call failed for ${drawingNo}:`, error)
throw error
}
}
/**
* DOLCE API에서 파일 정보 조회
*/
private async fetchFileInfoFromDOLCE(uploadId: string): Promise<DOLCEFileInfo[]> {
const endpoint = process.env.DOLCE_FILE_INFO_API_URL || 'http://60.100.99.217:1111/Services/VDCSWebService.svc/FileInfoList'
const requestBody = {
uploadId: uploadId
}
debugProcess(`DOLCE 파일 정보 조회 시작`, { uploadId, endpoint })
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody)
})
if (!response.ok) {
const errorText = await response.text()
debugError(`DOLCE FileInfo API 실패`, { uploadId, status: response.status, error: errorText })
throw new Error(`DOLCE FileInfo API failed: HTTP ${response.status} - ${errorText}`)
}
const data = await response.json()
// DOLCE FileInfo API 응답 구조에 맞게 처리
if (data.FileInfoListResult) {
const files = data.FileInfoListResult as DOLCEFileInfo[]
const activeFiles = files.filter(f => f.UseYn === 'True')
debugSuccess(`DOLCE 파일 정보 조회 완료`, {
uploadId,
totalFiles: files.length,
activeFiles: activeFiles.length
})
return files
} else {
debugWarn(`예상치 못한 DOLCE FileInfo 응답 구조`, { uploadId, data })
return []
}
} catch (error) {
debugError(`DOLCE FileInfo API 호출 실패`, { uploadId, error })
throw error
}
}
/**
* DES 암호화 (C# DESCryptoServiceProvider 호환)
*/
private encryptDES(text: string): string {
try {
const cipher = crypto.createCipheriv('des-ecb', this.DES_KEY, '')
cipher.setAutoPadding(true)
let encrypted = cipher.update(text, 'utf8', 'base64')
encrypted += cipher.final('base64')
// + 문자를 |||로 치환
return encrypted.replace(/\+/g, '|||')
} catch (error) {
console.error('DES encryption failed:', error)
throw error
}
}
/**
* DOLCE에서 파일 다운로드
*/
private async downloadFileFromDOLCE(
fileId: string,
userId: string,
fileName: string
): Promise<Buffer> {
try {
// 암호화 문자열 생성: FileId↔UserId↔FileName
const encryptString = `${fileId}↔${userId}↔${fileName}`
const encryptedKey = this.encryptDES(encryptString)
const downloadUrl = `${process.env.DOLCE_DOWNLOAD_URL}?key=${encryptedKey}` ||`http://60.100.99.217:1111/Download.aspx?key=${encryptedKey}`
debugProcess(`DOLCE 파일 다운로드 시작`, {
fileName,
fileId,
userId,
encryptedKey,
downloadUrl
})
const response = await fetch(downloadUrl, {
method: 'GET',
headers: {
'User-Agent': 'DOLCE-Integration-Service'
}
})
if (!response.ok) {
debugError(`DOLCE 다운로드 실패`, {
fileName,
status: response.status,
url: downloadUrl
})
throw new Error(`File download failed: HTTP ${response.status}`)
}
const buffer = Buffer.from(await response.arrayBuffer())
debugSuccess(`DOLCE 파일 다운로드 완료`, {
fileName,
fileSize: buffer.length,
fileId
})
return buffer
} catch (error) {
debugError(`DOLCE 파일 다운로드 실패`, { fileName, fileId, error })
throw error
}
}
/**
* 로컬 파일 시스템에 파일 저장
*/
private async saveFileToLocal(
buffer: Buffer,
originalFileName: string
): Promise<{ fileName: string; filePath: string; fileSize: number }> {
try {
const baseDir = join(process.cwd(), "public", "documents")
// 디렉토리가 없으면 생성
await mkdir(baseDir, { recursive: true })
const ext = extname(originalFileName)
const fileName = uuidv4() + ext
const fullPath = join(baseDir, fileName)
const relativePath = "/documents/" + fileName
await writeFile(fullPath, buffer)
debugSuccess(`로컬 파일 저장 완료`, {
originalFileName,
savedFileName: fileName,
filePath: relativePath,
fileSize: buffer.length
})
return {
fileName: originalFileName,
filePath: relativePath,
fileSize: buffer.length
}
} catch (error) {
debugError(`로컬 파일 저장 실패`, { originalFileName, error })
throw error
}
}
/**
* 단일 문서 동기화
*/
private async syncSingleDocument(
projectId: number,
dolceDoc: DOLCEDocument,
sourceSystem: string
): Promise<'NEW' | 'UPDATED' | 'SKIPPED'> {
const session = await getServerSession(authOptions)
if (!session?.user?.companyId) {
throw new Error("인증이 필요합니다.")
}
const vendorId = Number(session.user.companyId)
// 기존 문서 조회 (문서 번호로)
const existingDoc = await db
.select()
.from(documents)
.where(and(
eq(documents.projectId, projectId),
eq(documents.docNumber, dolceDoc.DrawingNo),
eq(documents.discipline, dolceDoc.Discipline)
))
.limit(1)
// DOLCE 문서를 DB 스키마에 맞게 변환
const documentData = {
projectId,
vendorId,
docNumber: dolceDoc.DrawingNo,
title: dolceDoc.DrawingName,
status: 'ACTIVE',
// DOLCE 전용 필드들
drawingKind: dolceDoc.DrawingKind,
drawingMoveGbn: dolceDoc.DrawingMoveGbn,
discipline: dolceDoc.Discipline,
// 외부 시스템 정보
externalDocumentId: dolceDoc.DrawingNo, // DOLCE에서는 DrawingNo가 ID 역할
externalSystemType: sourceSystem,
externalSyncedAt: new Date(),
// B4 전용 필드들
cGbn: dolceDoc.CGbn,
dGbn: dolceDoc.DGbn,
degreeGbn: dolceDoc.DegreeGbn,
deptGbn: dolceDoc.DeptGbn,
jGbn: dolceDoc.JGbn,
sGbn: dolceDoc.SGbn,
// 추가 정보
shiDrawingNo: dolceDoc.SHIDrawingNo,
manager: dolceDoc.Manager,
managerENM: dolceDoc.ManagerENM,
managerNo: dolceDoc.ManagerNo,
registerGroup: dolceDoc.RegisterGroup,
registerGroupId: dolceDoc.RegisterGroupId,
// 생성자 정보
createUserNo: dolceDoc.CreateUserNo,
createUserId: dolceDoc.CreateUserId,
createUserENM: dolceDoc.CreateUserENM,
updatedAt: new Date()
}
if (existingDoc.length > 0) {
// 업데이트 필요 여부 확인
const existing = existingDoc[0]
const hasChanges =
existing.title !== documentData.title ||
existing.drawingMoveGbn !== documentData.drawingMoveGbn ||
existing.manager !== documentData.manager
if (hasChanges) {
await db
.update(documents)
.set(documentData)
.where(eq(documents.id, existing.id))
console.log(`Updated document: ${dolceDoc.DrawingNo}`)
return 'UPDATED'
} else {
return 'SKIPPED'
}
} else {
// 새 문서 생성
const [newDoc] = await db
.insert(documents)
.values({
...documentData,
createdAt: new Date()
})
.returning({ id: documents.id })
console.log(`Created new document: ${dolceDoc.DrawingNo}`)
return 'NEW'
}
}
/**
* 문서의 revisions 동기화
*/
private async syncDocumentRevisions(
projectId: number,
dolceDoc: DOLCEDocument,
sourceSystem: string
): Promise<{ newCount: number; updatedCount: number }> {
try {
// 1. 상세 정보 조회
const detailDocs = await this.fetchDetailFromDOLCE(
dolceDoc.ProjectNo,
dolceDoc.DrawingNo,
dolceDoc.Discipline,
dolceDoc.DrawingKind
)
if (detailDocs.length === 0) {
console.log(`No detail data found for ${dolceDoc.DrawingNo}`)
return { newCount: 0, updatedCount: 0 }
}
// 2. 해당 문서의 issueStages 조회
const documentRecord = await db
.select({ id: documents.id })
.from(documents)
.where(and(
eq(documents.projectId, projectId),
eq(documents.docNumber, dolceDoc.DrawingNo),
eq(documents.discipline, dolceDoc.Discipline),
))
.limit(1)
if (documentRecord.length === 0) {
throw new Error(`Document not found: ${dolceDoc.DrawingNo}`)
}
const documentId = documentRecord[0].id
const issueStagesList = await db
.select()
.from(issueStages)
.where(eq(issueStages.documentId, documentId))
let newCount = 0
let updatedCount = 0
// 3. 각 상세 데이터에 대해 revision 동기화
for (const detailDoc of detailDocs) {
try {
// RegisterGroupId로 해당하는 issueStage 찾기
const matchingStage = issueStagesList.find(stage => {
// RegisterGroupId와 매칭하는 로직 (추후 개선 필요)
return stage.id // 임시로 첫 번째 stage 사용
})
if (!matchingStage) {
console.warn(`No matching issue stage found for RegisterGroupId: ${detailDoc.RegisterGroupId}`)
continue
}
const result = await this.syncSingleRevision(matchingStage.id, detailDoc, sourceSystem)
if (result === 'NEW') {
newCount++
} else if (result === 'UPDATED') {
updatedCount++
}
} catch (error) {
console.error(`Failed to sync revision ${detailDoc.RegisterId}:`, error)
}
}
return { newCount, updatedCount }
} catch (error) {
console.error(`Failed to sync revisions for ${dolceDoc.DrawingNo}:`, error)
throw error
}
}
/**
* 문서의 첨부파일 동기화 (Category가 FS인 것만)
*/
private async syncDocumentAttachments(
dolceDoc: DOLCEDocument,
sourceSystem: string
): Promise<{ newCount: number; updatedCount: number; downloadedCount: number }> {
try {
debugProcess(`문서 첨부파일 동기화 시작`, {
drawingNo: dolceDoc.DrawingNo,
drawingKind: dolceDoc.DrawingKind,
discipline: dolceDoc.Discipline
})
// 1. 상세 정보 조회
const detailDocs = await this.fetchDetailFromDOLCE(
dolceDoc.ProjectNo,
dolceDoc.DrawingNo,
dolceDoc.Discipline,
dolceDoc.DrawingKind
)
// 2. Category가 'FS'인 것만 필터링
const fsDetailDocs = detailDocs.filter(doc => doc.Category === 'FS')
if (fsDetailDocs.length === 0) {
debugProcess(`FS 카테고리 문서 없음`, { drawingNo: dolceDoc.DrawingNo })
return { newCount: 0, updatedCount: 0, downloadedCount: 0 }
}
debugProcess(`FS 문서 발견`, {
drawingNo: dolceDoc.DrawingNo,
totalDetails: detailDocs.length,
fsDetails: fsDetailDocs.length
})
let newCount = 0
let updatedCount = 0
let downloadedCount = 0
// 3. 각 FS 문서에 대해 파일 첨부 동기화
for (const detailDoc of fsDetailDocs) {
try {
if (!detailDoc.UploadId || detailDoc.UploadId.trim() === '') {
debugProcess(`UploadId 없음`, { registerId: detailDoc.RegisterId })
continue
}
// 4. 해당 revision 조회
const revisionRecord = await db
.select({ id: revisions.id })
.from(revisions)
.where(eq(revisions.registerId, detailDoc.RegisterId))
.limit(1)
if (revisionRecord.length === 0) {
debugWarn(`Revision 없음`, { registerId: detailDoc.RegisterId })
continue
}
const revisionId = revisionRecord[0].id
// 5. 파일 정보 조회
const fileInfos = await this.fetchFileInfoFromDOLCE(detailDoc.UploadId)
for (const fileInfo of fileInfos) {
if (fileInfo.UseYn !== 'True') {
debugProcess(`비활성 파일 스킵`, { fileName: fileInfo.FileName })
continue
}
const result = await this.syncSingleAttachment(
revisionId,
fileInfo,
detailDoc.CreateUserId,
sourceSystem
)
if (result === 'NEW') {
newCount++
downloadedCount++
} else if (result === 'UPDATED') {
updatedCount++
}
}
} catch (error) {
debugError(`첨부파일 동기화 실패`, { registerId: detailDoc.RegisterId, error })
}
}
debugSuccess(`문서 첨부파일 동기화 완료`, {
drawingNo: dolceDoc.DrawingNo,
newCount,
updatedCount,
downloadedCount
})
return { newCount, updatedCount, downloadedCount }
} catch (error) {
debugError(`문서 첨부파일 동기화 실패`, { drawingNo: dolceDoc.DrawingNo, error })
throw error
}
}
/**
* 단일 첨부파일 동기화
*/
private async syncSingleAttachment(
revisionId: number,
fileInfo: DOLCEFileInfo,
userId: string,
sourceSystem: string
): Promise<'NEW' | 'UPDATED' | 'SKIPPED'> {
try {
debugProcess(`단일 첨부파일 동기화 시작`, {
fileName: fileInfo.FileName,
fileId: fileInfo.FileId,
revisionId,
userId
})
// 기존 첨부파일 조회 (FileId로)
const existingAttachment = await db
.select()
.from(documentAttachments)
.where(and(
eq(documentAttachments.revisionId, revisionId),
eq(documentAttachments.fileId, fileInfo.FileId)
))
.limit(1)
if (existingAttachment.length > 0) {
// 이미 존재하는 파일인 경우, 필요시 업데이트 로직 추가
debugProcess(`파일 이미 존재`, { fileName: fileInfo.FileName, fileId: fileInfo.FileId })
return 'SKIPPED'
}
// 파일 다운로드
debugProcess(`파일 다운로드 시작`, { fileName: fileInfo.FileName, fileId: fileInfo.FileId })
const fileBuffer = await this.downloadFileFromDOLCE(
fileInfo.FileId,
userId,
fileInfo.FileName
)
// 로컬 파일 시스템에 저장
const savedFile = await this.saveFileToLocal(fileBuffer, fileInfo.FileName)
// DB에 첨부파일 정보 저장
const attachmentData = {
revisionId,
fileName: fileInfo.FileName,
filePath: savedFile.filePath,
fileType: extname(fileInfo.FileName).slice(1).toLowerCase() || undefined,
fileSize: fileInfo.FileSize,
uploadId: fileInfo.UploadId,
fileId: fileInfo.FileId,
uploadedBy: userId,
dolceFilePath: fileInfo.FileRelativePath,
uploadedAt: this.convertDolceDateToDate(fileInfo.FileCreateDT),
createdAt: new Date(),
updatedAt: new Date()
}
await db
.insert(documentAttachments)
.values(attachmentData)
debugSuccess(`새 첨부파일 생성 완료`, {
fileName: fileInfo.FileName,
fileId: fileInfo.FileId,
filePath: savedFile.filePath,
fileSize: savedFile.fileSize
})
return 'NEW'
} catch (error) {
debugError(`단일 첨부파일 동기화 실패`, {
fileName: fileInfo.FileName,
fileId: fileInfo.FileId,
error
})
throw error
}
}
/**
* 단일 revision 동기화
*/
private async syncSingleRevision(
issueStageId: number,
detailDoc: DOLCEDetailDocument,
sourceSystem: string
): Promise<'NEW' | 'UPDATED' | 'SKIPPED'> {
console.log(detailDoc,"detailDoc")
// 🆕 여러 조건으로 기존 revision 조회
type RevisionRecord = {
id: number
issueStageId: number
revision: string
uploaderType: string
uploaderId: number | null
uploaderName: string | null
usage: string | null
usageType: string | null
revisionStatus: string
comment: string | null
externalUploadId: string | null
registerId: string | null
serialNo: string | null
registerSerialNoMax: string | null
createdAt: Date
updatedAt: Date
}
let existingRevision: RevisionRecord | null = null
// 1차: registerId로 조회 (가장 정확한 매칭)
if (detailDoc.RegisterId) {
const results = await db
.select()
.from(revisions)
.where(and(
eq(revisions.issueStageId, issueStageId),
eq(revisions.registerId, detailDoc.RegisterId)
))
.limit(1)
if (results.length > 0) {
existingRevision = results[0]
console.log(`✅ Found revision by registerId: ${detailDoc.RegisterId} → local ID: ${existingRevision.id}`)
} else {
console.log(`❌ NOT found by registerId: ${detailDoc.RegisterId}`)
}
}
// 2차: externalUploadId로 조회 (업로드했던 revision 매칭)
if (!existingRevision && detailDoc.UploadId) {
const results = await db
.select()
.from(revisions)
.where(and(
eq(revisions.issueStageId, issueStageId),
eq(revisions.externalUploadId, detailDoc.UploadId)
))
.limit(1)
if (results.length > 0) {
existingRevision = results[0]
console.log(`✅ Found revision by externalUploadId: ${detailDoc.UploadId} → local ID: ${existingRevision.id}`)
} else {
console.log(`❌ NOT found by externalUploadId: ${detailDoc.UploadId}`)
}
}
// 3차: DrawingRevNo + serialNo로 조회 (같은 issueStage 내에서 정확한 매칭)
if (!existingRevision && detailDoc.DrawingRevNo && detailDoc.RegisterSerialNo) {
const results = await db
.select()
.from(revisions)
.where(and(
eq(revisions.issueStageId, issueStageId),
eq(revisions.revision, detailDoc.DrawingRevNo),
eq(revisions.serialNo, String(detailDoc.RegisterSerialNo))
))
.limit(1)
if (results.length > 0) {
existingRevision = results[0]
console.log(`✅ Found revision by DrawingRevNo+serialNo: ${detailDoc.DrawingRevNo}/${detailDoc.RegisterSerialNo} → local ID: ${existingRevision.id}`)
} else {
console.log(`❌ NOT found by DrawingRevNo+serialNo: ${detailDoc.DrawingRevNo}/${detailDoc.RegisterSerialNo}`)
}
}
// 최종 결과 로그
if (!existingRevision) {
console.log(`🆕 Will CREATE NEW revision for RegisterId: ${detailDoc.RegisterId} (${detailDoc.DrawingRevNo}/${detailDoc.RegisterSerialNo})`)
}
// Category에 따른 uploaderType 매핑
const uploaderType = this.mapCategoryToUploaderType(detailDoc.Category)
// RegisterKind에 따른 usage, usageType 매핑
const { usage, usageType } = this.mapRegisterKindToUsage(detailDoc.RegisterKind)
// DOLCE 상세 데이터를 revisions 스키마에 맞게 변환
const revisionData = {
serialNo:detailDoc.RegisterSerialNo ,
issueStageId,
revision: detailDoc.DrawingRevNo,
uploaderType,
registerSerialNoMax:detailDoc.RegisterSerialNoMax,
// uploaderName: detailDoc.CreateUserNM,
usage,
usageType,
revisionStatus: detailDoc.Status,
externalUploadId: detailDoc.UploadId,
registerId: detailDoc.RegisterId, // 🆕 항상 최신 registerId로 업데이트
comment: detailDoc.SHINote,
submittedDate: this.convertDolceDateToDate(detailDoc.CreateDt),
updatedAt: new Date()
}
if (existingRevision) {
// 업데이트 필요 여부 확인 - getImportStatus와 동일한 필드 체크
const hasChanges =
existingRevision.comment !== revisionData.comment ||
existingRevision.revisionStatus !== revisionData.revisionStatus
if (hasChanges) {
await db
.update(revisions)
.set(revisionData)
.where(eq(revisions.id, existingRevision.id))
console.log(`Updated revision: ${detailDoc.RegisterId} (local ID: ${existingRevision.id})`)
return 'UPDATED'
} else {
return 'SKIPPED'
}
} else {
// 새 revision 생성
await db
.insert(revisions)
.values({
...revisionData,
createdAt: new Date()
})
console.log(`Created new revision: ${detailDoc.RegisterId}`)
return 'NEW'
}
}
/**
* Category를 uploaderType으로 매핑
*/
private mapCategoryToUploaderType(category: string): string {
switch (category) {
case 'TS':
return 'vendor'
case 'FS':
return 'shi'
default:
return 'vendor' // 기본값
}
}
/**
* RegisterKind를 usage/usageType으로 매핑
*/
private mapRegisterKindToUsage(registerKind: string): { usage: string; usageType: string | null } {
if (!registerKind) {
return {
usage: 'DEFAULT',
usageType: 'DEFAULT'
}
}
switch (registerKind.toUpperCase()) {
case 'APPR':
return {
usage: 'APPROVAL',
usageType: 'Full'
}
case 'APPR-P':
return {
usage: 'APPROVAL',
usageType: 'Partial'
}
case 'WORK':
return {
usage: 'WORKING',
usageType: 'Full'
}
case 'WORK-P':
return {
usage: 'WORKING',
usageType: 'Partial'
}
case 'FMEA-1':
return {
usage: 'The 1st',
usageType: null
}
case 'FMEA-2':
return {
usage: 'The 2nd',
usageType: null
}
case 'RECP':
return {
usage: 'Pre',
usageType: null
}
case 'RECW':
return {
usage: 'Working',
usageType: null
}
case 'CMTM':
return {
usage: 'Mark-Up',
usageType: null
}
// SUB(제출용) - 도면제출 SHI >> GTT
case 'GSUB':
return {
usage: 'SUB',
usageType: null
}
default:
console.warn(`Unknown RegisterKind: ${registerKind}`)
return {
usage: registerKind,
usageType: 'DEFAULT'
}
}
}
/**
* Status를 revisionStatus로 매핑
*/
private mapStatusToRevisionStatus(status: string): string {
// TODO: DOLCE의 Status 값에 맞게 매핑 로직 구현
// 현재는 기본 매핑만 제공
switch (status?.toUpperCase()) {
case 'SUBMITTED':
return 'SUBMITTED'
case 'APPROVED':
return 'APPROVED'
case 'REJECTED':
return 'REJECTED'
default:
return 'SUBMITTED' // 기본값
}
}
private convertDolceDateToDate(dolceDate: string | undefined | null): Date | null {
if (!dolceDate || dolceDate.trim() === '') {
return null
}
// "20250204" 형태의 문자열을 "2025-02-04" 형태로 변환
if (dolceDate.length === 8 && /^\d{8}$/.test(dolceDate)) {
const year = dolceDate.substring(0, 4)
const month = dolceDate.substring(4, 6)
const day = dolceDate.substring(6, 8)
try {
const date = new Date(`${year}-${month}-${day}`)
// 유효한 날짜인지 확인
if (isNaN(date.getTime())) {
console.warn(`Invalid date format: ${dolceDate}`)
return null
}
return date
} catch (error) {
console.warn(`Failed to parse date: ${dolceDate}`, error)
return null
}
}
console.warn(`Unexpected date format: ${dolceDate}`)
return null
}
/**
* B4 문서용 이슈 스테이지 자동 생성
*/
private async createIssueStagesForB4Document(
drawingNo: string,
projectId: number,
dolceDoc: DOLCEDocument
): Promise<void> {
try {
// 문서 ID 조회
const [document] = await db
.select({ id: documents.id })
.from(documents)
.where(and(
eq(documents.projectId, projectId),
eq(documents.docNumber, drawingNo),
eq(documents.discipline, dolceDoc.Discipline)
))
.limit(1)
if (!document) {
throw new Error(`Document not found: ${drawingNo}`)
}
const documentId = document.id
// 기존 이슈 스테이지 확인
const existingStages = await db
.select()
.from(issueStages)
.where(eq(issueStages.documentId, documentId))
const existingStageNames = existingStages.map(stage => stage.stageName)
// For Pre 스테이지 생성 (GTTPreDwg)
if (!existingStageNames.includes('For Pre')) {
await db.insert(issueStages).values({
documentId: documentId,
stageName: 'GTT → SHI (For Pre.DWG)',
planDate: this.convertDolceDateToDate(dolceDoc.GTTPreDwg_PlanDate),
actualDate: this.convertDolceDateToDate(dolceDoc.GTTPreDwg_ResultDate),
stageStatus: 'PLANNED',
stageOrder: 1,
priority: 'MEDIUM',
reminderDays: 3,
description: 'GTT 예비 도면 단계'
})
}
// For Working 스테이지 생성 (GTTWorkingDwg)
if (!existingStageNames.includes('For Work')) {
await db.insert(issueStages).values({
documentId: documentId,
stageName: 'GTT → SHI (For Work.DWG)',
planDate: this.convertDolceDateToDate(dolceDoc.GTTWorkingDwg_PlanDate),
actualDate: this.convertDolceDateToDate(dolceDoc.GTTWorkingDwg_ResultDate),
stageStatus: 'PLANNED',
stageOrder: 2,
description: 'GTT 작업 도면 단계'
})
}
console.log(`Created issue stages for B4 document: ${drawingNo}`)
} catch (error) {
console.error(`Failed to create issue stages for ${drawingNo}:`, error)
}
}
private async createIssueStagesForB3Document(
drawingNo: string,
projectId: number,
dolceDoc: DOLCEDocument
): Promise<void> {
try {
// 문서 ID 조회
const [document] = await db
.select({ id: documents.id })
.from(documents)
.where(and(
eq(documents.projectId, projectId),
eq(documents.docNumber, drawingNo),
eq(documents.discipline, dolceDoc.Discipline)
))
.limit(1)
if (!document) {
throw new Error(`Document not found: ${drawingNo}`)
}
const documentId = document.id
// 기존 이슈 스테이지 확인
const existingStages = await db
.select()
.from(issueStages)
.where(eq(issueStages.documentId, documentId))
const existingStageNames = existingStages.map(stage => stage.stageName)
// Approval 스테이지 생성
if (!existingStageNames.includes('Approval')) {
await db.insert(issueStages).values({
documentId: documentId,
stageName: 'Vendor → SHI (For Approval)',
planDate: this.convertDolceDateToDate(dolceDoc.AppDwg_PlanDate),
actualDate: this.convertDolceDateToDate(dolceDoc.AppDwg_ResultDate),
stageStatus: 'PLANNED',
stageOrder: 1,
description: 'Vendor 승인 도면 단계'
})
}
// Working 스테이지 생성
if (!existingStageNames.includes('Working')) {
await db.insert(issueStages).values({
documentId: documentId,
stageName: 'Vendor → SHI (For Working)',
planDate: this.convertDolceDateToDate(dolceDoc.WorDwg_PlanDate),
actualDate: this.convertDolceDateToDate(dolceDoc.WorDwg_ResultDate),
stageStatus: 'PLANNED',
stageOrder: 2,
description: 'Vendor 작업 도면 단계'
})
}
console.log(`Created issue stages for B3 document: ${drawingNo}`)
} catch (error) {
console.error(`Failed to create issue stages for ${drawingNo}:`, error)
}
}
private async createIssueStagesForB5Document(
drawingNo: string,
projectId: number,
dolceDoc: DOLCEDocument
): Promise<void> {
try {
// 문서 ID 조회
const [document] = await db
.select({ id: documents.id })
.from(documents)
.where(and(
eq(documents.projectId, projectId),
eq(documents.docNumber, drawingNo),
eq(documents.discipline, dolceDoc.Discipline)
))
.limit(1)
if (!document) {
throw new Error(`Document not found: ${drawingNo}`)
}
const documentId = document.id
// 기존 이슈 스테이지 확인
const existingStages = await db
.select()
.from(issueStages)
.where(eq(issueStages.documentId, documentId))
const existingStageNames = existingStages.map(stage => stage.stageName)
// Approval 스테이지 생성
if (!existingStageNames.includes('Approval')) {
await db.insert(issueStages).values({
documentId: documentId,
stageName: 'Vendor → SHI (For Approval)',
planDate: this.convertDolceDateToDate(dolceDoc.FMEAFirst_PlanDate),
actualDate: this.convertDolceDateToDate(dolceDoc.FMEAFirst_ResultDate),
stageStatus: 'PLANNED',
stageOrder: 1,
description: 'FMEA 예비 도면 단계'
})
}
// Working 스테이지 생성
if (!existingStageNames.includes('Working')) {
await db.insert(issueStages).values({
documentId: documentId,
stageName: 'Vendor → SHI (For Working)',
planDate: this.convertDolceDateToDate(dolceDoc.FMEASecond_PlanDate),
actualDate: this.convertDolceDateToDate(dolceDoc.FMEASecond_ResultDate),
stageStatus: 'PLANNED',
stageOrder: 2,
description: 'FMEA 작업 도면 단계'
})
}
console.log(`Created issue stages for B5 document: ${drawingNo}`)
} catch (error) {
console.error(`Failed to create issue stages for ${drawingNo}:`, error)
}
}
/**
* 가져오기 상태 조회
*/
/**
* 가져오기 상태 조회 - 에러 시 안전한 기본값 반환
*/
async getImportStatus(
projectId: number,
sourceSystem: string = 'DOLCE'
): Promise<ImportStatus> {
try {
// 마지막 가져오기 시간 조회
const [lastImport] = await db
.select({
lastSynced: sql<string>`MAX(${documents.externalSyncedAt})`
})
.from(documents)
.where(and(
eq(documents.projectId, projectId),
eq(documents.externalSystemType, sourceSystem)
))
// 프로젝트 코드와 벤더 코드 조회
const contractInfo = await this.getContractInfoById(projectId)
// 🔥 계약 정보가 없으면 기본 상태 반환 (에러 throw 하지 않음)
if (!contractInfo?.projectCode || !contractInfo?.vendorCode) {
console.warn(`Project code or vendor code not found for contract ${projectId}`)
return {
lastImportAt: lastImport?.lastSynced ? new Date(lastImport.lastSynced).toISOString() : undefined,
availableDocuments: 0,
newDocuments: 0,
updatedDocuments: 0,
availableRevisions: 0,
newRevisions: 0,
updatedRevisions: 0,
availableAttachments: 0,
newAttachments: 0,
updatedAttachments: 0,
importEnabled: false, // 🔥 계약 정보가 없으면 import 비활성화
error: `Contract ${projectId}에 대한 프로젝트 코드 또는 벤더 코드를 찾을 수 없습니다.` // 🔥 에러 메시지 추가
}
}
let availableDocuments = 0
let newDocuments = 0
let updatedDocuments = 0
let availableRevisions = 0
let newRevisions = 0
let updatedRevisions = 0
let availableAttachments = 0
let newAttachments = 0
let updatedAttachments = 0
try {
// 각 drawingKind별로 확인
const drawingKinds = ['B3', 'B4', 'B5']
for (const drawingKind of drawingKinds) {
try {
const externalDocs = await this.fetchFromDOLCE(
contractInfo.projectCode,
contractInfo.vendorCode,
drawingKind
)
availableDocuments += externalDocs.length
// 신규/업데이트 문서 수 계산
for (const externalDoc of externalDocs) {
const existing = await db
.select({ id: documents.id, updatedAt: documents.updatedAt })
.from(documents)
.where(and(
eq(documents.projectId, projectId),
eq(documents.docNumber, externalDoc.DrawingNo),
eq(documents.discipline, externalDoc.Discipline)
))
.limit(1)
if (existing.length === 0) {
newDocuments++
} else {
// DOLCE의 CreateDt와 로컬 updatedAt 비교
if (externalDoc.CreateDt && existing[0].updatedAt) {
const externalModified = new Date(externalDoc.CreateDt)
const localModified = new Date(existing[0].updatedAt)
if (externalModified > localModified) {
updatedDocuments++
}
}
}
// revisions 및 attachments 상태도 확인
try {
const detailDocs = await this.fetchDetailFromDOLCE(
externalDoc.ProjectNo,
externalDoc.DrawingNo,
externalDoc.Discipline,
externalDoc.DrawingKind
)
availableRevisions += detailDocs.length
for (const detailDoc of detailDocs) {
// 1. syncSingleRevision과 동일한 방식으로 revision 찾기
let existingRevision: { id: number; comment: string | null; revisionStatus: string } | null = null
// 1차: registerId로 조회 (가장 정확한 매칭)
if (detailDoc.RegisterId) {
const results = await db
.select({
id: revisions.id,
comment: revisions.comment,
revisionStatus: revisions.revisionStatus
})
.from(revisions)
.where(eq(revisions.registerId, detailDoc.RegisterId))
.limit(1)
if (results.length > 0) {
existingRevision = results[0]
}
}
// 2차: externalUploadId로 조회 (registerId가 없거나 못 찾은 경우)
if (!existingRevision && detailDoc.UploadId) {
const results = await db
.select({
id: revisions.id,
comment: revisions.comment,
revisionStatus: revisions.revisionStatus
})
.from(revisions)
.innerJoin(issueStages, eq(issueStages.id, revisions.issueStageId))
.innerJoin(documents, eq(documents.id, issueStages.documentId))
.where(
and(
eq(documents.projectId, projectId),
eq(documents.docNumber, detailDoc.DrawingNo),
eq(revisions.externalUploadId, detailDoc.UploadId)
)
)
.limit(1)
if (results.length > 0) {
existingRevision = results[0]
}
}
// 3차: DrawingRevNo + serialNo로 조회 (최후 수단)
if (!existingRevision && detailDoc.DrawingRevNo) {
const results = await db
.select({
id: revisions.id,
comment: revisions.comment,
revisionStatus: revisions.revisionStatus
})
.from(revisions)
.innerJoin(issueStages, eq(issueStages.id, revisions.issueStageId))
.innerJoin(documents, eq(documents.id, issueStages.documentId))
.where(
and(
eq(documents.projectId, projectId),
eq(documents.docNumber, detailDoc.DrawingNo),
eq(revisions.revision, detailDoc.DrawingRevNo),
eq(revisions.serialNo, String(detailDoc.RegisterSerialNo))
)
)
.limit(1)
if (results.length > 0) {
existingRevision = results[0]
}
}
if (!existingRevision) {
// revision이 존재하지 않음 -> 신규
newRevisions++
} else {
// 2. revision이 존재하면 변경사항이 있는지 체크
const hasChanges =
existingRevision.comment !== detailDoc.SHINote ||
existingRevision.revisionStatus !== detailDoc.Status
if (hasChanges) {
// 변경사항이 있음 -> 업데이트 대상
updatedRevisions++
}
// 변경사항이 없으면 카운트하지 않음
}
// FS Category 문서의 첨부파일 확인
if (detailDoc.Category === 'FS' && detailDoc.UploadId) {
try {
const fileInfos = await this.fetchFileInfoFromDOLCE(detailDoc.UploadId)
availableAttachments += fileInfos.filter(f => f.UseYn === 'True').length
for (const fileInfo of fileInfos) {
if (fileInfo.UseYn !== 'True') continue
// 1. 먼저 attachment가 존재하는지 확인
const existingAttachment = await db
.select({
id: documentAttachments.id,
fileName: documentAttachments.fileName,
fileSize: documentAttachments.fileSize,
uploadedAt: documentAttachments.uploadedAt
})
.from(documentAttachments)
.where(eq(documentAttachments.fileId, fileInfo.FileId))
.limit(1)
if (existingAttachment.length === 0) {
// attachment가 존재하지 않음 -> 신규
newAttachments++
} else {
// 2. attachment가 존재하면 변경사항이 있는지 체크
const existing = existingAttachment[0]
const dolceUploadDate = this.convertDolceDateToDate(fileInfo.FileCreateDT)
const hasChanges =
existing.fileName !== fileInfo.FileName ||
existing.fileSize !== fileInfo.FileSize ||
(dolceUploadDate && existing.uploadedAt &&
dolceUploadDate.getTime() !== existing.uploadedAt.getTime())
if (hasChanges) {
// 변경사항이 있음 -> 업데이트 대상
updatedAttachments++
}
// 변경사항이 없으면 카운트하지 않음
}
}
} catch (error) {
console.warn(`Failed to check files for ${detailDoc.UploadId}:`, error)
}
}
}
} catch (error) {
console.warn(`Failed to check revisions for ${externalDoc.DrawingNo}:`, error)
}
}
} catch (error) {
console.warn(`Failed to check ${drawingKind} for status:`, error)
}
}
} catch (error) {
console.warn(`Failed to fetch external data for status: ${error}`)
// 🔥 외부 API 호출 실패 시에도 기본값 반환
}
return {
lastImportAt: lastImport?.lastSynced ? new Date(lastImport.lastSynced).toISOString() : undefined,
availableDocuments,
newDocuments,
updatedDocuments,
availableRevisions,
newRevisions,
updatedRevisions,
availableAttachments,
newAttachments,
updatedAttachments,
importEnabled: this.isImportEnabled(sourceSystem)
}
} catch (error) {
// 🔥 최종적으로 모든 에러를 catch하여 안전한 기본값 반환
console.error('Failed to get import status:', error)
return {
lastImportAt: undefined,
availableDocuments: 0,
newDocuments: 0,
updatedDocuments: 0,
availableRevisions: 0,
newRevisions: 0,
updatedRevisions: 0,
availableAttachments: 0,
newAttachments: 0,
updatedAttachments: 0,
importEnabled: false,
error: error instanceof Error ? error.message : 'Unknown error occurred'
}
}
}
/**
* 가져오기 활성화 여부 확인
*/
private isImportEnabled(sourceSystem: string): boolean {
const upperSystem = sourceSystem.toUpperCase()
const enabled = process.env[`IMPORT_${upperSystem}_ENABLED`]
return enabled === 'true' || enabled === '1'
}
/**
* DOLCE 업로드 확인 테스트 (업로드 후 파일이 DOLCE에 존재하는지 확인)
*/
async testDOLCEFileDownload(
fileId: string,
userId: string,
fileName: string
): Promise<{ success: boolean; downloadUrl?: string; error?: string }> {
try {
// 암호화 문자열 생성: FileId↔UserId↔FileName
const encryptString = `${fileId}↔${userId}↔${fileName}`
const encryptedKey = this.encryptDES(encryptString)
const downloadUrl = `${process.env.DOLCE_DOWNLOAD_URL}?key=${encryptedKey}` || `http://60.100.99.217:1111/Download.aspx?key=${encryptedKey}`
console.log(`🧪 DOLCE 파일 다운로드 테스트:`)
console.log(` 파일명: ${fileName}`)
console.log(` FileId: ${fileId}`)
console.log(` UserId: ${userId}`)
console.log(` 암호화 키: ${encryptedKey}`)
console.log(` 다운로드 URL: ${downloadUrl}`)
const response = await fetch(downloadUrl, {
method: 'GET',
headers: {
'User-Agent': 'DOLCE-Integration-Service'
}
})
if (!response.ok) {
console.error(`❌ DOLCE 파일 다운로드 테스트 실패: HTTP ${response.status}`)
return {
success: false,
downloadUrl,
error: `HTTP ${response.status}`
}
}
const buffer = Buffer.from(await response.arrayBuffer())
console.log(`✅ DOLCE 파일 다운로드 테스트 성공: ${fileName} (${buffer.length} bytes)`)
return {
success: true,
downloadUrl
}
} catch (error) {
console.error(`❌ DOLCE 파일 다운로드 테스트 실패: ${fileName}`, error)
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
}
}
}
}
export const importService = new ImportService()
|