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
|
# 결재 워크플로우 시스템 (Approval Workflow)
Knox 결재 시스템과 연동된 **Saga 패턴 기반** 자동화 결재 워크플로우 모듈입니다.
> **최신 업데이트:** Saga Orchestrator 패턴으로 전면 리팩터링 완료 (2024-11)
> - 기존 래퍼 함수 제거, Saga 클래스로 완전 전환
> - 비즈니스 프로세스가 명시적으로 표현됨
> - 상세 내용: [SAGA_PATTERN.md](./SAGA_PATTERN.md)
## 📋 목차
- [빠른 시작](#-빠른-시작)
- [Saga 패턴 아키텍처](#-saga-패턴-아키텍처)
- [주요 기능](#-주요-기능)
- [사용 방법](#-사용-방법)
- [API 레퍼런스](#-api-레퍼런스)
- [파일 구조](#-파일-구조)
- [개발 가이드](#-개발-가이드)
- [트러블슈팅](#-트러블슈팅)
---
## 🚀 빠른 시작
### 1. 핸들러 등록 (앱 초기화 시 1회)
```typescript
// instrumentation.ts
import { registerActionHandler } from '@/lib/approval';
export async function register() {
const { initializeApprovalHandlers } = await import('@/lib/approval/handlers-registry');
await initializeApprovalHandlers();
}
```
### 2. 결재 상신
```typescript
'use server';
import { ApprovalSubmissionSaga } from '@/lib/approval';
export async function requestWithApproval(data: RequestData) {
// 1. 템플릿 변수 준비
const variables = await mapToTemplateVariables(data);
// 2. Saga로 결재 상신
const saga = new ApprovalSubmissionSaga(
'my_action_type', // 핸들러 등록 시 사용한 키
{ id: data.id }, // 결재 승인 후 실행될 payload
{
title: '결재 요청',
templateName: '결재 템플릿',
variables,
approvers: ['EP001', 'EP002'],
currentUser: {
id: user.id,
epId: user.epId,
email: user.email,
}
}
);
return await saga.execute();
// → { pendingActionId: 1, approvalId: 'AP-2024-001', status: 'pending_approval' }
}
```
### 3. 자동 실행 (폴링 서비스가 처리)
결재 승인 시 등록된 핸들러가 자동으로 실행됩니다. 별도 작업 불필요!
---
## 🏗️ Saga 패턴 아키텍처
### 전체 흐름
```
┌─────────────────────────────────────────────────────────┐
│ 1. 결재 상신 (UI) │
│ ApprovalSubmissionSaga.execute() │
└──────────────────────┬──────────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ 7단계 Orchestration: │
│ 1. 핸들러 초기화 │
│ 2. 템플릿 준비 │
│ 3. 결재선 생성 │
│ 4. 결재 요청 생성 │
│ 5. ⚠️ DB 저장 (Saga 핵심) │
│ 6. Knox 상신 │
│ 7. 캐시 무효화 │
└──────────────┬──────────────────────┘
│
성공 ▼ ▼ 실패
┌──────────┐ ┌─────────────┐
│ 반환 │ │ 보상 트랜잭션 │
└──────────┘ │ status→failed│
└─────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ 2. Knox 결재 시스템 │
│ (결재자들이 승인/반려 처리) │
└──────────────────────┬──────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────┐
│ 3. 폴링 서비스 (1분마다 자동 실행) │
│ checkPendingApprovals() │
│ - Knox API로 상태 일괄 조회 (최대 1000건) │
│ - 상태 변경 감지 │
└──────────────────────┬──────────────────────────────────┘
│
승인 시 ▼
┌─────────────────────────────────────────────────────────┐
│ 4. 액션 자동 실행 (백그라운드) │
│ ApprovalExecutionSaga.execute() │
│ - 등록된 핸들러 호출 │
│ - 비즈니스 로직 실행 │
│ - 상태 업데이트 (executed) │
└─────────────────────────────────────────────────────────┘
```
### Saga 패턴의 핵심: 분산 트랜잭션 관리
Knox는 외부 시스템이므로 DB 트랜잭션으로 롤백할 수 없습니다.
**Saga 패턴**으로 데이터 정합성을 보장합니다.
```typescript
// ApprovalSubmissionSaga 내부
async execute() {
try {
// 1~4단계: 준비 작업
await this.initializeHandlers();
await this.prepareApprovalTemplate();
await this.createApprovalLines();
await this.createSubmitRequest();
// 5단계: ⚠️ DB에 먼저 저장 (Knox 상신 전)
await this.savePendingAction();
// 6단계: Knox 상신 (외부 API, 롤백 불가)
await this.submitToKnox();
// 7단계: 캐시 무효화
await this.invalidateCache();
return { pendingActionId, approvalId, status: 'pending_approval' };
} catch (error) {
// 실패 시 보상 트랜잭션 (Compensating Transaction)
await this.compensate(error);
throw error;
}
}
```
**장점:**
- Knox 상신 전 DB 저장 실패 → 전체 실패 (정상)
- Knox 상신 실패 → DB에 실패 기록 남음 (추적 가능)
- Knox 상신 성공 후 DB 업데이트 실패 위험 제거
---
## 🎯 주요 기능
### 1. Saga Orchestrator (핵심)
세 가지 Saga 클래스로 결재 프로세스를 명시적으로 관리:
| Saga 클래스 | 역할 | 단계 수 |
|------------|------|--------|
| `ApprovalSubmissionSaga` | 결재 상신 | 7단계 |
| `ApprovalExecutionSaga` | 결재 승인 후 액션 실행 | 7단계 |
| `ApprovalRejectionSaga` | 결재 반려 처리 | 4단계 |
### 2. 템플릿 시스템
DB에 저장된 HTML 템플릿으로 결재 문서 생성:
```typescript
// 템플릿에 변수 삽입
const variables = {
'업체명': 'ABC 협력업체',
'담당자': '홍길동',
'요청일': '2024-11-05'
};
const saga = new ApprovalSubmissionSaga(
'vendor_registration',
payload,
{
templateName: '정규업체 등록', // DB에서 조회
variables, // 변수 치환
// ...
}
);
```
**HTML 변환 유틸리티:**
```typescript
import {
htmlTableConverter,
htmlListConverter,
htmlDescriptionList
} from '@/lib/approval';
// 테이블 생성
const table = await htmlTableConverter(data, [
{ key: 'name', label: '이름' },
{ key: 'email', label: '이메일' }
]);
// 리스트 생성
const list = await htmlListConverter(['항목1', '항목2']);
// Description List
const dl = await htmlDescriptionList({
'제목': '내용',
'담당자': '홍길동'
});
```
### 3. 자동 폴링 서비스
1분마다 Knox API를 호출하여 결재 상태 자동 확인:
```typescript
// instrumentation.ts
import { startApprovalPollingScheduler } from '@/lib/approval';
export async function register() {
// 1분마다 자동 실행
await startApprovalPollingScheduler();
}
```
**배치 처리 최적화:**
- 최대 1000건씩 일괄 조회
- Knox API 부하 최소화
- 에러 격리 (일부 실패해도 계속 진행)
### 4. 캐시 관리
Next.js의 `revalidatePath`를 활용한 실시간 UI 업데이트:
```typescript
import { revalidateApprovalLogs } from '@/lib/approval';
// 결재 상신/승인/반려 시 자동 호출됨
await revalidateApprovalLogs();
```
**자동 무효화 시점:**
- ✅ 결재 상신 시
- ✅ 결재 승인/반려 시
- ✅ 액션 실행 완료 시
자세한 내용: [README_CACHE.md](./README_CACHE.md)
---
## 💻 사용 방법
### Step 1: 비즈니스 핸들러 작성
```typescript
// lib/my-feature/handlers.ts
'use server';
export async function myBusinessLogicInternal(payload: {
id: number;
reason: string;
}) {
// 결재 승인 후 실행될 실제 비즈니스 로직
const result = await db.insert(myTable).values({
id: payload.id,
reason: payload.reason,
status: 'approved',
});
return result;
}
// 템플릿 변수 매핑
export async function mapToTemplateVariables(data: MyData) {
return {
'요청자': data.requesterName,
'요청일': formatDate(new Date()),
'사유': data.reason,
};
}
```
### Step 2: 핸들러 등록
```typescript
// lib/approval/handlers-registry.ts
import { registerActionHandler } from './approval-workflow';
export async function initializeApprovalHandlers() {
console.log('[Approval Handlers] Registering all handlers...');
// 1. 내 기능 핸들러 등록
const { myBusinessLogicInternal } = await import('@/lib/my-feature/handlers');
registerActionHandler('my_action_type', myBusinessLogicInternal);
// 2. 다른 핸들러들...
console.log('[Approval Handlers] All handlers registered');
}
```
### Step 3: 결재 서버 액션 작성
```typescript
// lib/my-feature/approval-actions.ts
'use server';
import { ApprovalSubmissionSaga } from '@/lib/approval';
import { mapToTemplateVariables } from './handlers';
export async function requestMyActionWithApproval(data: {
id: number;
reason: string;
currentUser: { id: number; epId: string | null; email?: string };
approvers?: string[];
}) {
// 1. 입력 검증
if (!data.currentUser.epId) {
throw new Error('Knox EP ID가 필요합니다');
}
// 2. 템플릿 변수 매핑
const variables = await mapToTemplateVariables(data);
// 3. Saga로 결재 상신
const saga = new ApprovalSubmissionSaga(
'my_action_type', // 핸들러 등록 시 사용한 키
{
id: data.id,
reason: data.reason,
},
{
title: `내 기능 요청 - ${data.id}`,
description: `ID ${data.id}에 대한 승인 요청`,
templateName: '내 기능 템플릿',
variables,
approvers: data.approvers,
currentUser: data.currentUser,
}
);
return await saga.execute();
}
```
### Step 4: UI에서 호출 (미리보기 다이얼로그 사용)
**⚠️ 중요: 모든 결재 상신은 반드시 미리보기 다이얼로그를 거쳐야 합니다.**
사용자가 결재 문서 내용을 확인하고 결재선을 직접 설정하는 과정이 필수입니다.
```typescript
// components/my-feature/my-dialog-with-preview.tsx
'use client';
import { useState } from 'react';
import { ApprovalPreviewDialog } from '@/lib/approval/client'; // ⚠️ /client에서 import
import { requestMyActionWithApproval } from '@/lib/my-feature/approval-actions';
import { useSession } from 'next-auth/react';
export function MyDialogWithPreview() {
const { data: session } = useSession();
const [showPreview, setShowPreview] = useState(false);
const [previewData, setPreviewData] = useState(null);
const handleApproveClick = async (formData) => {
// 1. 템플릿 변수 준비
const variables = await prepareTemplateVariables(formData);
// 2. 미리보기 데이터 설정
setPreviewData({
variables,
title: `내 기능 요청 - ${formData.id}`,
description: `ID ${formData.id}에 대한 승인 요청`,
formData, // 나중에 사용할 데이터 저장
});
// 3. 미리보기 다이얼로그 열기
setShowPreview(true);
};
const handlePreviewConfirm = async (approvalData: {
approvers: string[];
title: string;
description?: string;
}) => {
try {
const result = await requestMyActionWithApproval({
...previewData.formData,
currentUser: {
id: Number(session?.user?.id),
epId: session?.user?.epId || null,
email: session?.user?.email || undefined,
},
approvers: approvalData.approvers, // 미리보기에서 설정한 결재선
});
if (result.status === 'pending_approval') {
toast.success(`결재가 상신되었습니다. (ID: ${result.approvalId})`);
}
} catch (error) {
toast.error('결재 상신 실패');
}
};
return (
<>
<Button onClick={handleApproveClick}>결재 요청</Button>
{/* 결재 미리보기 다이얼로그 */}
{previewData && session?.user?.epId && (
<ApprovalPreviewDialog
open={showPreview}
onOpenChange={setShowPreview}
templateName="내 기능 템플릿"
variables={previewData.variables}
title={previewData.title}
description={previewData.description}
currentUser={{
id: Number(session.user.id),
epId: session.user.epId,
name: session.user.name || undefined,
email: session.user.email || undefined,
}}
onConfirm={handlePreviewConfirm}
/>
)}
</>
);
}
```
**미리보기 다이얼로그가 필수인 이유:**
- ✅ 결재 문서 내용 최종 확인 (데이터 정확성 검증)
- ✅ 결재선(결재자) 직접 선택 (올바른 결재 경로 설정)
- ✅ 결재 제목/설명 커스터마이징 (명확한 의사소통)
- ✅ 사용자가 결재 내용을 인지하고 책임감 있게 상신
- ✅ 반응형 UI (Desktop: Dialog, Mobile: Drawer)
---
## 📚 API 레퍼런스
### Saga 클래스
#### ApprovalSubmissionSaga
결재를 Knox 시스템에 상신합니다.
```typescript
constructor(
actionType: string, // 핸들러 등록 시 사용한 키
actionPayload: T, // 결재 승인 후 실행될 데이터
approvalConfig: ApprovalConfig
)
async execute(): Promise<ApprovalResult>
// → { pendingActionId, approvalId, status: 'pending_approval' }
```
**ApprovalConfig:**
```typescript
interface ApprovalConfig {
title: string; // 결재 제목
description?: string; // 결재 설명
templateName: string; // DB에 저장된 템플릿명
variables: Record<string, string>; // 템플릿 변수
approvers?: string[]; // Knox EP ID 배열
currentUser: {
id: number;
epId: string | null;
email?: string;
};
}
```
#### ApprovalExecutionSaga
결재 승인 후 액션을 실행합니다. (폴링 서비스가 자동 호출)
```typescript
constructor(apInfId: string) // Knox 결재 ID
async execute(): Promise<any>
// → 핸들러 실행 결과
```
#### ApprovalRejectionSaga
결재 반려를 처리합니다. (폴링 서비스가 자동 호출)
```typescript
constructor(apInfId: string, reason?: string)
async execute(): Promise<void>
```
### 핸들러 레지스트리
```typescript
// 핸들러 등록
function registerActionHandler(
actionType: string,
handler: (payload: any) => Promise<any>
): void
// 등록된 핸들러 조회 (디버깅용)
function getRegisteredHandlers(): string[]
```
### 폴링 서비스
```typescript
// 폴링 스케줄러 시작 (instrumentation.ts에서 호출)
async function startApprovalPollingScheduler(): Promise<cron.ScheduledTask>
// 수동으로 pending 결재 확인
async function checkPendingApprovals(): Promise<{
success: boolean;
checked: number;
updated: number;
executed: number;
}>
// 특정 결재 상태 확인 (UI에서 "새로고침" 버튼)
async function checkSingleApprovalStatus(apInfId: string): Promise<{
success: boolean;
oldStatus: string;
newStatus: string;
updated: boolean;
executed: boolean;
}>
```
### 템플릿 유틸리티
```typescript
// HTML 테이블 생성
async function htmlTableConverter(
data: any[],
columns: Array<{ key: string; label: string }>
): Promise<string>
// HTML 리스트 생성
async function htmlListConverter(items: string[]): Promise<string>
// HTML Description List 생성
async function htmlDescriptionList(
items: Record<string, string>
): Promise<string>
// 템플릿 조회
async function getApprovalTemplateByName(
name: string
): Promise<Template | null>
// 템플릿 변수 치환
async function replaceTemplateVariables(
content: string,
variables: Record<string, string>
): Promise<string>
```
### UI 컴포넌트
#### ApprovalPreviewDialog
결재 문서 미리보기 및 결재선 설정 다이얼로그 컴포넌트입니다.
**위치:** `lib/approval/approval-preview-dialog.tsx`
**Import:**
```typescript
// ⚠️ 클라이언트 컴포넌트는 반드시 /client에서 import
import { ApprovalPreviewDialog } from '@/lib/approval/client';
```
#### Props 인터페이스
```typescript
interface ApprovalPreviewDialogProps {
// 기본 제어
open: boolean;
onOpenChange: (open: boolean) => void;
// 템플릿 설정
templateName: string; // DB에서 조회할 템플릿 이름
variables: Record<string, string>; // 템플릿 변수 ({{변수명}} 형태로 치환)
title: string; // 결재 제목 (초기값)
// 사용자 정보
currentUser: {
id: number; // 사용자 DB ID
epId: string; // Knox EP ID (필수)
name?: string; // 사용자 이름
email?: string; // 이메일
deptName?: string; // 부서명
};
// 결재선 설정
defaultApprovers?: string[]; // 초기 결재선 (EP ID 배열)
// 콜백
onConfirm: (data: {
approvers: string[]; // 선택된 결재자 EP ID 배열
title: string; // (수정 가능한) 결재 제목
attachments?: File[]; // 첨부파일 (enableAttachments가 true일 때)
}) => Promise<void>;
// 옵션
allowTitleEdit?: boolean; // 제목 수정 허용 (기본: true)
// 첨부파일 (선택적 기능)
enableAttachments?: boolean; // 첨부파일 UI 활성화 (기본: false)
maxAttachments?: number; // 최대 첨부파일 개수 (기본: 10)
maxFileSize?: number; // 최대 파일 크기 bytes (기본: 100MB)
}
```
#### 주요 기능
- ✅ 템플릿 실시간 미리보기 (변수 자동 치환)
- ✅ 결재선 선택 UI (ApprovalLineSelector 통합)
- ✅ 결재 제목 수정 가능
- ✅ **선택적 첨부파일 업로드** (드래그 앤 드롭)
- ✅ 반응형 디자인 (Desktop: Dialog, Mobile: Drawer)
- ✅ 로딩 상태 자동 처리
- ✅ 유효성 검사 및 에러 핸들링
#### 사용 예시 1: 기본 사용 (첨부파일 없이)
```typescript
'use client';
import { useState } from 'react';
import { ApprovalPreviewDialog } from '@/lib/approval/client';
import { useSession } from 'next-auth/react';
import { toast } from 'sonner';
export function VendorApprovalButton({ vendorData }) {
const { data: session } = useSession();
const [showPreview, setShowPreview] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const handleOpenPreview = async () => {
// 1. 템플릿 변수 준비
const variables = {
'업체명': vendorData.companyName,
'사업자번호': vendorData.businessNumber,
'담당자': vendorData.contactPerson,
'요청일': new Date().toLocaleDateString('ko-KR'),
'요청사유': vendorData.reason,
};
// 2. 미리보기 열기
setShowPreview(true);
};
const handleConfirm = async ({ approvers, title, attachments }) => {
try {
setIsSubmitting(true);
// 3. 실제 결재 상신 API 호출
const result = await fetch('/api/vendor/approval', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
vendorId: vendorData.id,
approvers,
title,
}),
});
if (result.ok) {
toast.success('결재가 성공적으로 상신되었습니다.');
setShowPreview(false);
}
} catch (error) {
toast.error('결재 상신에 실패했습니다.');
} finally {
setIsSubmitting(false);
}
};
// EP ID 없으면 버튼 비활성화
if (!session?.user?.epId) {
return (
<Button disabled>
결재 요청 (Knox EP ID 필요)
</Button>
);
}
return (
<>
<Button onClick={handleOpenPreview}>
정규업체 등록 결재 요청
</Button>
{showPreview && (
<ApprovalPreviewDialog
open={showPreview}
onOpenChange={setShowPreview}
templateName="정규업체 등록"
variables={{
'업체명': vendorData.companyName,
'사업자번호': vendorData.businessNumber,
'담당자': vendorData.contactPerson,
'요청일': new Date().toLocaleDateString('ko-KR'),
}}
title={`정규업체 등록 - ${vendorData.companyName}`}
currentUser={{
id: Number(session.user.id),
epId: session.user.epId,
name: session.user.name || undefined,
email: session.user.email || undefined,
}}
onConfirm={handleConfirm}
/>
)}
</>
);
}
```
#### 사용 예시 2: 첨부파일 포함
```typescript
'use client';
import { useState } from 'react';
import { ApprovalPreviewDialog } from '@/lib/approval/client';
import { submitApproval } from '@/lib/knox-api/approval/approval';
export function ContractApprovalButton({ contractData }) {
const { data: session } = useSession();
const [showPreview, setShowPreview] = useState(false);
const handleConfirm = async ({ approvers, title, attachments }) => {
console.log('결재자:', approvers.length, '명');
console.log('첨부파일:', attachments?.length || 0, '개');
// Knox API로 결재 상신 (첨부파일 포함)
const approvalData = {
// 기본 정보
subject: title,
contents: `<div>계약서 검토를 요청합니다.</div>`,
contentsType: 'HTML',
// 결재선 설정
aplns: approvers.map((epId, index) => ({
epId: epId, // Knox EP ID
seq: index.toString(), // 결재 순서 (0부터 시작)
role: '1', // 역할: 0=기안, 1=결재, 2=합의, 3=참조
aplnStatsCode: '0', // 결재 상태: 0=대기
arbPmtYn: 'Y', // 임의승인 허용
contentsMdfyPmtYn: 'Y', // 내용수정 허용
aplnMdfyPmtYn: 'Y', // 결재선수정 허용
opinion: '', // 의견
})),
// 첨부파일
attachments: attachments || [], // File[] 배열
// 문서 설정
docSecuType: 'PERSONAL', // 보안등급: PERSONAL, COMPANY, SECRET
notifyOption: '0', // 알림옵션: 0=전체, 1=결재완료, 2=없음
urgYn: 'N', // 긴급여부
docMngSaveCode: '0', // 문서관리저장코드
sbmLang: 'ko', // 언어
};
// Knox API 호출
const result = await submitApproval(approvalData, {
userId: session.user.id.toString(),
epId: session.user.epId!,
emailAddress: session.user.email || '',
});
if (result.success) {
toast.success(`결재가 상신되었습니다. (ID: ${result.approvalId})`);
}
};
if (!session?.user?.epId) return null;
return (
<>
<Button onClick={() => setShowPreview(true)}>
계약서 검토 결재 요청
</Button>
<ApprovalPreviewDialog
open={showPreview}
onOpenChange={setShowPreview}
templateName="계약서 검토"
variables={{
'계약명': contractData.title,
'계약일': contractData.date,
'계약업체': contractData.vendor,
'계약금액': contractData.amount.toLocaleString(),
}}
title={`계약서 검토 - ${contractData.title}`}
currentUser={{
id: Number(session.user.id),
epId: session.user.epId,
name: session.user.name || undefined,
email: session.user.email || undefined,
}}
onConfirm={handleConfirm}
// 첨부파일 기능 활성화
enableAttachments={true}
maxAttachments={5}
maxFileSize={50 * 1024 * 1024} // 50MB
/>
</>
);
}
```
#### Knox API 연동: approvalData 객체 상세
Knox 결재 API (`submitApproval`)에 전달하는 전체 객체 구조:
```typescript
interface KnoxApprovalData {
// ===== 기본 정보 =====
subject: string; // 결재 제목 (필수)
contents: string; // 결재 내용 HTML (필수)
contentsType: 'HTML' | 'TEXT'; // 내용 타입 (기본: 'HTML')
// ===== 결재선 설정 =====
aplns: Array<{
epId: string; // Knox EP ID (필수)
seq: string; // 결재 순서 "0", "1", "2"... (필수)
role: string; // 역할 (필수)
// "0" = 기안자
// "1" = 결재자
// "2" = 합의자
// "3" = 참조자
aplnStatsCode: string; // 결재 상태 (필수)
// "0" = 대기
// "1" = 진행중
// "2" = 승인
// "3" = 반려
arbPmtYn: 'Y' | 'N'; // 임의승인 허용 (기본: 'Y')
contentsMdfyPmtYn: 'Y' | 'N'; // 내용수정 허용 (기본: 'Y')
aplnMdfyPmtYn: 'Y' | 'N'; // 결재선수정 허용 (기본: 'Y')
opinion?: string; // 결재 의견 (선택)
}>;
// ===== 첨부파일 =====
attachments?: File[]; // File 객체 배열 (선택)
// ===== 문서 설정 =====
docSecuType?: string; // 보안등급 (기본: 'PERSONAL')
// 'PERSONAL' = 개인
// 'COMPANY' = 회사
// 'SECRET' = 비밀
notifyOption?: string; // 알림옵션 (기본: '0')
// '0' = 전체 알림
// '1' = 결재완료 알림
// '2' = 알림 없음
urgYn?: 'Y' | 'N'; // 긴급여부 (기본: 'N')
docMngSaveCode?: string; // 문서관리저장코드 (기본: '0')
// '0' = 개인문서함
// '1' = 부서문서함
sbmLang?: 'ko' | 'en'; // 언어 (기본: 'ko')
// ===== 추가 옵션 =====
comment?: string; // 기안 의견 (선택)
refLineYn?: 'Y' | 'N'; // 참조선 사용여부 (기본: 'N')
agreementLineYn?: 'Y' | 'N'; // 합의선 사용여부 (기본: 'N')
}
// 사용자 정보
interface KnoxUserInfo {
userId: string; // 사용자 ID (필수)
epId: string; // Knox EP ID (필수)
emailAddress: string; // 이메일 (필수)
}
```
#### 전체 연동 예시 (Server Action)
```typescript
// app/api/vendor/approval/route.ts
'use server';
import { ApprovalSubmissionSaga } from '@/lib/approval';
import { mapVendorToTemplateVariables } from '@/lib/vendors/handlers';
export async function submitVendorApproval(data: {
vendorId: number;
approvers: string[];
title: string;
attachments?: File[];
}) {
// 1. 템플릿 변수 매핑
const vendor = await getVendorById(data.vendorId);
const variables = await mapVendorToTemplateVariables(vendor);
// 2. Saga로 결재 상신
const saga = new ApprovalSubmissionSaga(
'vendor_registration', // 핸들러 타입
{
vendorId: data.vendorId,
// 필요한 payload 데이터
},
{
title: data.title,
templateName: '정규업체 등록',
variables,
approvers: data.approvers, // EP ID 배열
currentUser: {
id: user.id,
epId: user.epId,
email: user.email,
},
}
);
return await saga.execute();
}
```
#### 첨부파일 처리
첨부파일은 Knox API 내부에서 자동으로 FormData로 변환되어 전송됩니다:
```typescript
// lib/knox-api/approval/approval.ts 내부 (참고용)
export async function submitApproval(
approvalData: KnoxApprovalData,
userInfo: KnoxUserInfo
) {
const formData = new FormData();
// 기본 데이터를 JSON으로 직렬화
formData.append('data', JSON.stringify({
subject: approvalData.subject,
contents: approvalData.contents,
aplns: approvalData.aplns,
// ... 기타 필드
}));
// 첨부파일 추가
if (approvalData.attachments) {
approvalData.attachments.forEach((file, index) => {
formData.append(`attachment_${index}`, file);
});
}
// Knox API 호출
const response = await fetch(KNOX_APPROVAL_API_URL, {
method: 'POST',
headers: {
'X-User-Id': userInfo.userId,
'X-EP-Id': userInfo.epId,
},
body: formData,
});
return response.json();
}
```
#### 주의사항
1. **EP ID 필수 체크**
```typescript
if (!session?.user?.epId) {
return <Button disabled>Knox EP ID 필요</Button>;
}
```
2. **onConfirm 에러 핸들링**
```typescript
const handleConfirm = async ({ approvers, title, attachments }) => {
try {
await submitApproval(...);
toast.success('성공');
} catch (error) {
toast.error('실패');
// ⚠️ throw하지 않으면 다이얼로그가 자동으로 닫힘
// 에러 시 다이얼로그를 열어두려면 throw 필요
throw error;
}
};
```
3. **첨부파일 제한**
- 기본값: 최대 10개, 파일당 100MB
- `maxAttachments`, `maxFileSize`로 커스터마이징 가능
- 중복 파일 자동 필터링
4. **반응형 UI**
- Desktop (≥768px): Dialog 형태
- Mobile (<768px): Drawer 형태
- 자동으로 화면 크기에 맞게 렌더링
### 캐시 관리
```typescript
// 결재 로그 캐시 무효화
async function revalidateApprovalLogs(): Promise<void>
// Pending Actions 캐시 무효화
async function revalidatePendingActions(): Promise<void>
// 특정 결재 상세 캐시 무효화
async function revalidateApprovalDetail(apInfId: string): Promise<void>
// 모든 결재 관련 캐시 무효화
async function revalidateAllApprovalCaches(): Promise<void>
```
---
## 📁 파일 구조
```
lib/approval/
├── approval-saga.ts # Saga 클래스 (메인 로직) [서버]
│ ├── ApprovalSubmissionSaga # 결재 상신 (7단계)
│ ├── ApprovalExecutionSaga # 액션 실행 (7단계)
│ └── ApprovalRejectionSaga # 반려 처리 (4단계)
│
├── approval-workflow.ts # 핸들러 레지스트리 [서버]
│ ├── registerActionHandler()
│ ├── getRegisteredHandlers()
│ └── ensureHandlersInitialized()
│
├── approval-polling-service.ts # 폴링 서비스 [서버]
│ ├── startApprovalPollingScheduler()
│ ├── checkPendingApprovals()
│ └── checkSingleApprovalStatus()
│
├── handlers-registry.ts # 핸들러 중앙 등록소 [서버]
│ └── initializeApprovalHandlers()
│
├── template-utils.ts # 템플릿 유틸리티 [서버]
│ ├── getApprovalTemplateByName()
│ ├── replaceTemplateVariables()
│ ├── htmlTableConverter()
│ ├── htmlListConverter()
│ └── htmlDescriptionList()
│
├── approval-preview-dialog.tsx # 결재 미리보기 다이얼로그 [클라이언트]
│ └── ApprovalPreviewDialog # 템플릿 미리보기 + 결재선 설정 + 첨부파일
│
├── cache-utils.ts # 캐시 관리 [서버]
│ ├── revalidateApprovalLogs()
│ ├── revalidatePendingActions()
│ └── revalidateApprovalDetail()
│
├── types.ts # 타입 정의
│ ├── ApprovalConfig
│ ├── ApprovalResult
│ └── TemplateVariables
│
├── index.ts # 서버 전용 API Export
├── client.ts # 클라이언트 컴포넌트 Export ⚠️
│ └── ApprovalPreviewDialog # ← 클라이언트에서는 이 파일에서 import
│
├── README.md # 이 문서 (전체 시스템 가이드)
├── SAGA_PATTERN.md # Saga 패턴 상세 설명
├── CRONJOB_CONTEXT_FIX.md # Request Context 문제 해결 가이드
├── USAGE_PATTERN_ANALYSIS.md # 실제 사용 패턴 분석
└── ARCHITECTURE_REVIEW.md # 아키텍처 평가
```
### Import 경로 가이드
**⚠️ 중요: 서버/클라이언트 코드는 반드시 분리해서 import 해야 합니다.**
```typescript
// ✅ 서버 액션 또는 서버 컴포넌트에서
import {
ApprovalSubmissionSaga,
getApprovalTemplateByName,
htmlTableConverter
} from '@/lib/approval';
// ✅ 클라이언트 컴포넌트에서
import { ApprovalPreviewDialog } from '@/lib/approval/client';
// ❌ 잘못된 사용 (서버 코드가 클라이언트 번들에 포함됨)
import { ApprovalPreviewDialog } from '@/lib/approval';
```
---
## 🛠️ 개발 가이드
### 새로운 결재 타입 추가하기
**1. 비즈니스 로직 작성**
```typescript
// lib/my-new-feature/handlers.ts
export async function myNewFeatureInternal(payload: MyPayload) {
// 실제 DB 작업
return await db.insert(...);
}
```
**2. 핸들러 등록**
```typescript
// lib/approval/handlers-registry.ts
export async function initializeApprovalHandlers() {
// 기존 핸들러들...
// 새 핸들러 추가
const { myNewFeatureInternal } = await import('@/lib/my-new-feature/handlers');
registerActionHandler('my_new_feature', myNewFeatureInternal);
}
```
**3. 결재 서버 액션 작성**
```typescript
// lib/my-new-feature/approval-actions.ts
export async function requestMyNewFeatureWithApproval(data) {
const saga = new ApprovalSubmissionSaga('my_new_feature', payload, config);
return await saga.execute();
}
```
**4. 템플릿 생성 (DB)**
```sql
INSERT INTO approval_templates (name, content, description) VALUES (
'내 새 기능',
'<div>... {{변수명}} ...</div>',
'내 새 기능 결재 템플릿'
);
```
끝! 폴링 서비스가 자동으로 처리합니다.
### ⚠️ Request Context 주의사항 (필수)
**핵심: 결재 핸들러는 Cronjob 환경에서 실행됩니다!**
결재 승인 후 실행되는 핸들러는 **폴링 서비스(Cronjob)**에 의해 호출됩니다.
이 환경에서는 **Request Context가 존재하지 않으므로** 다음 함수들을 **절대 사용할 수 없습니다**:
```typescript
// ❌ Cronjob 환경에서 사용 불가
import { headers } from 'next/headers';
import { getServerSession } from 'next-auth';
export async function myHandler(payload) {
const headersList = headers(); // ❌ Error: headers() called outside request scope
const session = await getServerSession(); // ❌ Error: cannot access request
revalidatePath('/some-path'); // ❌ Error: revalidatePath outside request scope
}
```
#### 올바른 해결 방법
**1. 유저 정보가 필요한 경우 → Payload에 포함**
```typescript
// ✅ 결재 상신 시 currentUser를 payload에 포함
export async function requestWithApproval(data: RequestData) {
const saga = new ApprovalSubmissionSaga(
'my_action',
{
id: data.id,
currentUser: { // ⚠️ 핸들러에서 필요한 유저 정보 포함
id: session.user.id,
name: session.user.name,
email: session.user.email,
epId: session.user.epId,
},
},
{ ... }
);
}
// ✅ 핸들러에서 payload의 currentUser 사용
export async function myHandlerInternal(payload: {
id: number;
currentUser: {
id: string | number;
name?: string | null;
email?: string | null;
epId?: string | null;
};
}) {
// payload에서 유저 정보 사용
const userId = payload.currentUser.id;
// DB 작업
await db.insert(myTable).values({
createdBy: userId,
...
});
}
```
**2. Session/Payload 분기 처리 (기존 함수 호환)**
기존 함수를 cronjob과 일반 환경에서 모두 사용하려면 분기 처리:
```typescript
// ✅ Session/Payload 분기 처리
export async function myServiceFunction({
id,
currentUser: providedUser // 선택적 파라미터
}: {
id: number;
currentUser?: {
id: string | number;
name?: string | null;
email?: string | null;
};
}) {
let currentUser;
if (providedUser) {
// ✅ Cronjob 환경: payload에서 받은 유저 정보 사용
currentUser = providedUser;
} else {
// ✅ 일반 환경: session에서 유저 정보 가져오기
const session = await getServerSession(authOptions);
if (!session?.user) {
throw new Error("인증이 필요합니다.");
}
currentUser = session.user;
}
// 이제 currentUser 안전하게 사용 가능
await db.insert(...).values({
createdBy: currentUser.id,
...
});
}
```
**3. Revalidate는 API 경로 사용**
```typescript
// ❌ 직접 호출 불가
revalidatePath('/my-path');
// ✅ API 경로를 통해 호출
await fetch('/api/revalidate/my-resource', {
method: 'POST',
});
```
#### 실제 사례: RFQ 발송
```typescript
// lib/rfq-last/service.ts
export interface SendRfqParams {
rfqId: number;
vendors: VendorForSend[];
attachmentIds: number[];
currentUser?: { // ⚠️ Cronjob 환경을 위한 선택적 파라미터
id: string | number;
name?: string | null;
email?: string | null;
epId?: string | null;
};
}
export async function sendRfqToVendors({
rfqId,
vendors,
attachmentIds,
currentUser: providedUser
}: SendRfqParams) {
let currentUser;
if (providedUser) {
// ✅ Cronjob 환경: payload에서 받은 유저 정보 사용
currentUser = providedUser;
} else {
// ✅ 일반 환경: session에서 유저 정보 가져오기
const session = await getServerSession(authOptions);
if (!session?.user) {
throw new Error("인증이 필요합니다.");
}
currentUser = session.user;
}
// ... 나머지 로직
}
// lib/rfq-last/approval-handlers.ts
export async function sendRfqWithApprovalInternal(payload: {
rfqId: number;
vendors: any[];
attachmentIds: number[];
currentUser: { // ⚠️ 필수 정보
id: string | number;
name?: string | null;
email?: string | null;
epId?: string | null;
};
}) {
// ✅ payload의 currentUser를 서비스 함수에 전달
const result = await sendRfqToVendors({
rfqId: payload.rfqId,
vendors: payload.vendors,
attachmentIds: payload.attachmentIds,
currentUser: payload.currentUser, // ⚠️ 전달
});
return result;
}
// lib/rfq-last/approval-actions.ts
export async function requestRfqSendWithApproval(data: RfqSendApprovalData) {
const saga = new ApprovalSubmissionSaga(
'rfq_send_with_attachments',
{
rfqId: data.rfqId,
vendors: data.vendors,
attachmentIds: data.attachmentIds,
currentUser: { // ⚠️ payload에 포함
id: data.currentUser.id,
name: data.currentUser.name,
email: data.currentUser.email,
epId: data.currentUser.epId,
},
},
{ ... }
);
}
```
#### 체크리스트
새로운 결재 핸들러를 작성할 때 다음을 확인하세요:
- [ ] 핸들러 함수에서 `headers()` 사용하지 않음
- [ ] 핸들러 함수에서 `getServerSession()` 직접 호출하지 않음
- [ ] 핸들러 함수에서 `revalidatePath()` 직접 호출하지 않음
- [ ] 유저 정보가 필요하면 payload에 `currentUser` 포함
- [ ] 기존 서비스 함수는 session/payload 분기 처리
- [ ] 캐시 무효화는 API 경로 사용
#### 참고 문서
- [CRONJOB_CONTEXT_FIX.md](./CRONJOB_CONTEXT_FIX.md) - Request Context 문제 상세 해결 가이드
- [Next.js Dynamic API Error](https://nextjs.org/docs/messages/next-dynamic-api-wrong-context)
### 테스트하기
```typescript
import { ApprovalSubmissionSaga } from '@/lib/approval';
describe('ApprovalSubmissionSaga', () => {
it('should submit approval successfully', async () => {
const saga = new ApprovalSubmissionSaga(
'test_action',
{ id: 123 },
{
title: 'Test',
templateName: 'Test Template',
variables: {},
currentUser: { id: 1, epId: 'EP001' }
}
);
const result = await saga.execute();
expect(result.status).toBe('pending_approval');
expect(result.approvalId).toBeDefined();
});
it('should compensate on Knox failure', async () => {
// Knox API를 모킹하여 실패 시뮬레이션
mockKnoxAPI.submitApproval.mockRejectedValue(new Error('Knox Error'));
const saga = new ApprovalSubmissionSaga(...);
await expect(saga.execute()).rejects.toThrow('Knox Error');
// pendingAction이 'failed' 상태인지 확인
const pendingAction = await db.query.pendingActions.findFirst(...);
expect(pendingAction.status).toBe('failed');
});
});
```
### 디버깅
**1. 로그 확인**
```typescript
// 각 Saga 단계마다 상세 로그 출력
[ApprovalSaga] Starting approval saga for vendor_registration
[ApprovalSaga] Step 1: Initializing handlers
[ApprovalSaga] ✓ Handlers initialized
[ApprovalSaga] Step 2: Preparing approval template
...
[ApprovalSaga] ✅ Saga completed successfully
```
**2. 등록된 핸들러 확인**
```typescript
import { getRegisteredHandlers } from '@/lib/approval';
console.log(getRegisteredHandlers());
// → ['pq_investigation_request', 'vendor_regular_registration', ...]
```
**3. Pending Actions 상태 확인**
```sql
SELECT * FROM pending_actions
WHERE status = 'pending'
ORDER BY created_at DESC;
```
**4. 폴링 서비스 로그**
```typescript
[Approval Polling] Found 5 pending approvals to check
[Approval Polling] Status changed: AP-2024-001 (1 → 2)
[Approval Polling] ✅ Executed approved action: AP-2024-001
```
### 성능 최적화
**1. 배치 크기 조정**
```typescript
// approval-polling-service.ts
const batchSize = 1000; // Knox API 호출 시 배치 크기
```
**2. 폴링 간격 조정**
```typescript
// approval-polling-service.ts
cron.schedule(
'* * * * *', // 1분마다 (필요시 조정)
async () => { ... }
);
```
**3. 캐시 전략**
```typescript
// 특정 결재만 무효화 (더 효율적)
await revalidateApprovalDetail(apInfId);
// vs 전체 무효화 (부담)
await revalidateAllApprovalCaches();
```
---
## 🔧 트러블슈팅
### 1. Knox EP ID가 없음
**증상:**
```
Error: Knox EP ID가 필요합니다
```
**원인:** 사용자의 `epId`가 `null`
**해결:**
```typescript
// UI에서 미리 체크
if (!session?.user?.epId) {
toast.error('Knox EP ID가 없습니다. 시스템 관리자에게 문의하세요.');
return;
}
// 또는 버튼 비활성화
<Button disabled={!session?.user?.epId}>
결재 요청
</Button>
```
### 2. 핸들러를 찾을 수 없음
**증상:**
```
Error: Handler not found for action type: my_action
```
**원인:** 핸들러가 등록되지 않음
**해결:**
```typescript
// 1. handlers-registry.ts에서 등록 확인
registerActionHandler('my_action', myActionInternal);
// 2. instrumentation.ts에서 초기화 확인
await initializeApprovalHandlers();
// 3. 등록된 핸들러 목록 확인
console.log(getRegisteredHandlers());
```
### 3. 템플릿을 찾을 수 없음
**증상:**
```
Warning: Template not found: 내 템플릿
```
**원인:** DB에 템플릿이 없음
**해결:**
```sql
-- DB에 템플릿 확인
SELECT * FROM approval_templates WHERE name = '내 템플릿';
-- 없으면 생성
INSERT INTO approval_templates (name, content, description) VALUES (...);
```
### 4. 폴링 서비스가 동작하지 않음
**증상:** 결재 승인했는데 액션이 실행되지 않음
**확인:**
```typescript
// 1. instrumentation.ts에서 시작 확인
export async function register() {
await startApprovalPollingScheduler(); // ✅ 이 줄 있나?
}
// 2. 로그 확인
[Approval Polling] Starting approval polling scheduler...
[Approval Polling] Scheduler started - running every minute
// 3. pending_actions 테이블 확인
SELECT * FROM pending_actions WHERE status = 'pending';
```
### 5. 캐시가 갱신되지 않음
**증상:** UI에 최신 결재 상태가 반영되지 않음
**해결:**
```typescript
// 1. 수동으로 캐시 무효화
import { revalidateApprovalLogs } from '@/lib/approval';
await revalidateApprovalLogs();
// 2. API 경로 확인 (app/api/revalidate/approval/route.ts)
// POST /api/revalidate/approval 호출
```
자세한 내용: [README_CACHE.md](./README_CACHE.md)
### 6. Knox 상신 실패
**증상:**
```
Error: Knox 상신 실패: Network error
```
**확인:**
```typescript
// 1. Knox API 설정 확인
// lib/knox-api/approval/approval.ts
// 2. 네트워크 연결 확인
// 3. pending_actions 상태 확인
SELECT * FROM pending_actions
WHERE status = 'failed'
ORDER BY created_at DESC;
```
**복구:**
```typescript
// Saga 패턴 덕분에 DB에 실패 기록이 남아있음
// 문제 해결 후 재시도 가능
const saga = new ApprovalSubmissionSaga(...);
await saga.execute();
```
### 7. Request Context 오류 (headers/session) ⚠️
**증상:**
```
Error: `headers` was called outside a request scope
Error: Cannot access request in cronjob context
```
**원인:** 결재 핸들러는 Cronjob 환경에서 실행되므로 Request Context가 없음
**해결:**
```typescript
// ❌ 잘못된 코드
export async function myHandler(payload) {
const session = await getServerSession(authOptions); // ❌ Error!
const userId = session.user.id;
}
// ✅ 올바른 코드 - payload에서 유저 정보 사용
export async function myHandler(payload: {
id: number;
currentUser: {
id: string | number;
name?: string | null;
email?: string | null;
};
}) {
const userId = payload.currentUser.id; // ✅ OK
}
// ✅ 결재 상신 시 currentUser 포함
const saga = new ApprovalSubmissionSaga(
'my_action',
{
id: data.id,
currentUser: { // ⚠️ 필수
id: session.user.id,
name: session.user.name,
email: session.user.email,
epId: session.user.epId,
},
},
{ ... }
);
```
**기존 서비스 함수 호환:**
```typescript
// ✅ Session/Payload 분기 처리
export async function myServiceFunction({
id,
currentUser: providedUser
}: {
id: number;
currentUser?: { id: string | number; ... };
}) {
let currentUser;
if (providedUser) {
// Cronjob 환경
currentUser = providedUser;
} else {
// 일반 환경
const session = await getServerSession(authOptions);
currentUser = session.user;
}
// 안전하게 사용
await db.insert(...).values({ createdBy: currentUser.id });
}
```
**자세한 내용:** [Request Context 주의사항](#️-request-context-주의사항-필수) 섹션 참조
---
## 📖 추가 문서
- **[CRONJOB_CONTEXT_FIX.md](./CRONJOB_CONTEXT_FIX.md)** - Request Context 문제 상세 해결 가이드 ⚠️
- **[SAGA_PATTERN.md](./SAGA_PATTERN.md)** - Saga 패턴 상세 설명 및 리팩터링 과정
- **[README_CACHE.md](./README_CACHE.md)** - 캐시 전략 및 관리 방법
- **[USAGE_PATTERN_ANALYSIS.md](./USAGE_PATTERN_ANALYSIS.md)** - 실제 사용 패턴 분석 및 개선 제안
- **[ARCHITECTURE_REVIEW.md](./ARCHITECTURE_REVIEW.md)** - 아키텍처 평가 및 베스트 프랙티스
---
## 🎯 핵심 요약
### 언제 사용하는가?
- ✅ 비즈니스 액션에 결재 승인이 필요한 경우
- ✅ Knox 결재 시스템과 자동 연동이 필요한 경우
- ✅ 결재 승인 후 자동으로 액션을 실행하고 싶은 경우
- ✅ **모든 결재는 미리보기 다이얼로그를 통해 상신해야 함 (필수)**
### 왜 Saga 패턴인가?
- ✅ Knox는 외부 시스템 → 일반 트랜잭션 불가
- ✅ DB 저장 → Knox 상신 순서로 데이터 정합성 보장
- ✅ 실패 시 보상 트랜잭션으로 일관성 유지
### 어떻게 사용하는가?
1. **핸들러 작성 및 등록** (1회)
2. **UI에서 미리보기 다이얼로그 열기** (필수)
3. **사용자가 결재선 설정 후 상신**
4. **폴링이 자동 실행** (설정만 하면 끝)
### 코드 요약
```typescript
// 1. 핸들러 등록 (서버 시작 시 1회)
registerActionHandler('my_action', myActionHandler);
// 2. UI에서 미리보기 다이얼로그 열기
const { variables } = await prepareTemplateVariables(data);
setShowPreview(true);
// 3. 사용자가 확인 후 결재 상신
<ApprovalPreviewDialog
templateName="내 템플릿"
variables={variables}
onConfirm={async ({ approvers }) => {
await submitApproval(approvers);
}}
/>
// 4. 끝! (폴링이 자동 실행)
```
---
## 📝 변경 이력
### 2024-11-07 - ApprovalPreviewDialog 컴포넌트 통합 및 첨부파일 기능 추가
- ✅ 중복 컴포넌트 통합: `components/approval/ApprovalPreviewDialog.tsx` → `lib/approval/approval-preview-dialog.tsx`로 일원화
- ✅ 선택적 첨부파일 업로드 기능 추가 (`enableAttachments`, `maxAttachments`, `maxFileSize` props)
- ✅ 파일 드래그 앤 드롭 UI 구현 (Dropzone, FileList 컴포넌트 활용)
- ✅ 첨부파일 유효성 검사 (크기 제한, 개수 제한, 중복 파일 필터링)
- ✅ API 인터페이스 개선: `onSubmit` → `onConfirm`으로 변경
- ✅ 콜백 시그니처 변경: `(approvers: ApprovalLineItem[])` → `({ approvers: string[], title: string, attachments?: File[] })`
- ✅ Knox API 연동 상세 가이드 추가 (approvalData 객체 전체 필드 문서화)
- ✅ 기존 사용처 업데이트 (vendor-regular-registrations, pq-review-table-new)
- ✅ README 상세화: 사용 예시, Props 인터페이스, 주의사항 등 보완
### 2024-11-06 - Request Context 호환성 개선 (RFQ 발송)
- ✅ Cronjob 환경에서 Request Context 오류 해결
- ✅ `headers()`, `getServerSession()` 호출 문제 수정
- ✅ Session/Payload 분기 처리 패턴 도입
- ✅ `currentUser`를 payload에 포함하는 표준 패턴 확립
- ✅ 기존 서비스 함수 호환성 유지 (선택적 `currentUser` 파라미터)
- ✅ RFQ 발송 핸들러에 적용 및 검증
- ✅ README에 "Request Context 주의사항" 섹션 추가
- ✅ 트러블슈팅 가이드 업데이트
### 2024-11-06 - 결재 미리보기 다이얼로그 도입
- ✅ `ApprovalPreviewDialog` 공통 컴포넌트 추가
- ✅ 모든 결재 상신은 미리보기를 거치도록 프로세스 변경
- ✅ 사용자가 결재 문서와 결재선을 확인하는 필수 단계 추가
- ✅ 템플릿 실시간 미리보기 및 변수 치환 기능
- ✅ 결재선 선택 UI 통합 (ApprovalLineSelector)
- ✅ 반응형 디자인 (Desktop: Dialog, Mobile: Drawer)
- ✅ 서버/클라이언트 코드 분리 (`index.ts` / `client.ts`)
### 2024-11-05 - Saga 패턴 전면 리팩터링
- ✅ 기존 래퍼 함수 제거
- ✅ Saga Orchestrator 클래스 도입
- ✅ 비즈니스 프로세스 명시화 (7단계)
- ✅ 보상 트랜잭션 명확화
- ✅ 코드 가독성 및 유지보수성 향상
### 이전
- 템플릿 시스템 구현
- 폴링 서비스 최적화 (배치 처리)
- 캐시 무효화 전략 개선
- 핸들러 레지스트리 패턴 도입
---
**문의 및 이슈:** 개발팀에 문의하세요.
|