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
|
# 결재 워크플로우 시스템 (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.tsx
'use client';
import { requestMyActionWithApproval } from '@/lib/my-feature/approval-actions';
import { useSession } from 'next-auth/react';
export function MyDialog() {
const { data: session } = useSession();
const handleSubmit = async (formData) => {
try {
const result = await requestMyActionWithApproval({
id: formData.id,
reason: formData.reason,
currentUser: {
id: Number(session?.user?.id),
epId: session?.user?.epId || null,
email: session?.user?.email || undefined,
},
approvers: selectedApprovers,
});
if (result.status === 'pending_approval') {
toast.success(`결재가 상신되었습니다. (ID: ${result.approvalId})`);
}
} catch (error) {
toast.error('결재 상신 실패');
}
};
return <form onSubmit={handleSubmit}>...</form>;
}
```
---
## 📚 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>
```
### 캐시 관리
```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 # 결재 상신
│ ├── ApprovalExecutionSaga # 액션 실행
│ └── ApprovalRejectionSaga # 반려 처리
│
├── 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()
│
├── cache-utils.ts # 캐시 관리
│ ├── revalidateApprovalLogs()
│ ├── revalidatePendingActions()
│ └── revalidateApprovalDetail()
│
├── types.ts # 타입 정의
│ ├── ApprovalConfig
│ ├── ApprovalResult
│ └── TemplateVariables
│
├── index.ts # 공개 API Export
│
└── README.md # 이 문서
```
---
## 🛠️ 개발 가이드
### 새로운 결재 타입 추가하기
**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>',
'내 새 기능 결재 템플릿'
);
```
끝! 폴링 서비스가 자동으로 처리합니다.
### 테스트하기
```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();
```
---
## 📖 추가 문서
- **[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. **Saga로 결재 상신** (필요할 때마다)
3. **폴링이 자동 실행** (설정만 하면 끝)
### 코드 3줄 요약
```typescript
// 1. 핸들러 등록
registerActionHandler('my_action', myActionHandler);
// 2. 결재 상신
const saga = new ApprovalSubmissionSaga('my_action', payload, config);
const result = await saga.execute();
// 3. 끝! (폴링이 자동 실행)
```
---
## 📝 변경 이력
### 2024-11 - Saga 패턴 전면 리팩터링
- ✅ 기존 래퍼 함수 제거
- ✅ Saga Orchestrator 클래스 도입
- ✅ 비즈니스 프로세스 명시화 (7단계)
- ✅ 보상 트랜잭션 명확화
- ✅ 코드 가독성 및 유지보수성 향상
### 이전
- 템플릿 시스템 구현
- 폴링 서비스 최적화 (배치 처리)
- 캐시 무효화 전략 개선
- 핸들러 레지스트리 패턴 도입
---
**문의 및 이슈:** 개발팀에 문의하세요.
|