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
|
'use client'
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { Textarea } from '@/components/ui/textarea';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { toast } from 'sonner';
import { Loader2, Search, FileText, Clock, User, AlertCircle, XCircle } from 'lucide-react';
// API 함수 및 타입
import { getApprovalDetail, getApprovalContent, cancelApproval } from '@/lib/knox-api/approval/approval';
import type { ApprovalDetailResponse, ApprovalContentResponse, ApprovalLine } from '@/lib/knox-api/approval/approval';
import { formatDate } from '@/lib/utils';
// 상태/역할 텍스트 매핑 (mock util 대체)
const getStatusText = (status: string) => {
const map: Record<string, string> = {
'-3': '암호화실패',
'-2': '암호화중',
'-1': '예약상신',
'0': '보류',
'1': '진행중',
'2': '완결',
'3': '반려',
'4': '상신취소',
'5': '전결',
'6': '후완결',
};
return map[status] || status;
};
const getRoleText = (role: string) => {
const map: Record<string, string> = {
'0': '기안',
'1': '결재',
'2': '합의',
'3': '후결',
'4': '병렬합의',
'7': '병렬결재',
'9': '통보',
};
return map[role] || role;
};
interface ApprovalDetailProps {
initialApInfId?: string;
}
interface ApprovalDetailData {
detail: ApprovalDetailResponse['data'];
content: ApprovalContentResponse['data'];
}
// 첨부파일 타입 (가이드에 명확히 정의되어 있지 않아 필드 일부 추정)
interface ApprovalAttachment {
fileName?: string;
fileSize?: string;
downloadUrl?: string;
fileId?: string;
[key: string]: unknown; // 기타 필드 허용
}
export default function ApprovalDetail({
initialApInfId = ''
}: ApprovalDetailProps) {
const [apInfId, setApInfId] = useState(initialApInfId);
const [approvalData, setApprovalData] = useState<ApprovalDetailData | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isCancelling, setIsCancelling] = useState(false);
const [cancelOpinion, setCancelOpinion] = useState('');
const fetchApprovalDetail = async (id: string) => {
if (!id.trim()) {
toast.error('결재 ID를 입력해주세요.');
return;
}
setIsLoading(true);
setError(null);
setApprovalData(null);
try {
const [detailResponse, contentResponse] = await Promise.all([
getApprovalDetail(id),
getApprovalContent(id)
]);
if (detailResponse.result.toLowerCase() === 'success' && contentResponse.result.toLowerCase() === 'success') {
setApprovalData({
detail: detailResponse.data,
content: contentResponse.data
});
} else {
setError('결재 정보를 가져오는데 실패했습니다.');
toast.error('결재 정보를 가져오는데 실패했습니다.');
}
} catch (err) {
console.error('결재 상세 조회 오류:', err);
setError('결재 정보를 가져오는 중 오류가 발생했습니다.');
toast.error('결재 정보를 가져오는 중 오류가 발생했습니다.');
} finally {
setIsLoading(false);
}
};
const getSecurityTypeText = (type: string) => {
const typeMap: Record<string, string> = {
'PERSONAL': '개인',
'CONFIDENTIAL': '기밀',
'CONFIDENTIAL_STRICT': '극기밀'
};
return typeMap[type] || type;
};
const getSecurityTypeBadgeVariant = (type: string) => {
switch (type) {
case 'PERSONAL':
return 'default';
case 'CONFIDENTIAL':
return 'secondary';
case 'CONFIDENTIAL_STRICT':
return 'destructive';
default:
return 'outline';
}
};
const getStatusBadgeVariant = (status: string) => {
switch (status) {
case '2': // 완결
return 'default';
case '1': // 진행중
return 'secondary';
case '3': // 반려
return 'destructive';
case '4': // 상신취소
return 'outline';
default:
return 'outline';
}
};
const canCancelApproval = (status: string) => {
// 진행중(1), 보류(0) 상태에서만 취소 가능
return ['0', '1'].includes(status);
};
const handleCancelApproval = async () => {
if (!approvalData) return;
if (!cancelOpinion.trim()) {
toast.error('상신취소 의견을 입력해주세요.');
return;
}
setIsCancelling(true);
try {
const response = await cancelApproval(approvalData.detail.apInfId, cancelOpinion);
if (response.result === 'success') {
toast.success('결재가 성공적으로 취소되었습니다.');
// 상태 업데이트
setApprovalData({
...approvalData,
detail: {
...approvalData.detail,
status: '4' // 상신취소
}
});
// 의견 초기화
setCancelOpinion('');
} else {
toast.error('결재 취소에 실패했습니다.');
}
} catch (err) {
console.error('결재 취소 오류:', err);
toast.error('결재 취소 중 오류가 발생했습니다.');
} finally {
setIsCancelling(false);
}
};
// 첨부파일 다운로드 헬퍼
const handleDownload = async (attachment: ApprovalAttachment) => {
try {
// 1) downloadUrl 이 이미 포함된 경우
if (attachment.downloadUrl) {
window.open(attachment.downloadUrl, '_blank');
return;
}
// 2) fileId + 별도 엔드포인트 조합 (가이드에 명시되지 않았으므로 best-effort 처리)
if (attachment.fileId) {
const url = `${process.env.NEXT_PUBLIC_KNOX_API_BASE_URL || ''}/approval/api/v2.0/attachments/${attachment.fileId}`;
const resp = await fetch(url, {
method: 'GET',
headers: {
'System-ID': process.env.NEXT_PUBLIC_KNOX_SYSTEM_ID || '',
},
});
if (!resp.ok) throw new Error('다운로드 실패');
// blob 생성 후 브라우저 다운로드
const blob = await resp.blob();
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = attachment.fileName || 'attachment';
link.click();
URL.revokeObjectURL(link.href);
return;
}
toast.error('다운로드 URL 정보를 찾을 수 없습니다.');
} catch (err) {
console.error('첨부파일 다운로드 오류:', err);
toast.error('첨부파일 다운로드 중 오류가 발생했습니다.');
}
};
// 초기 로딩 (initialApInfId가 있는 경우)
useEffect(() => {
if (initialApInfId) {
fetchApprovalDetail(initialApInfId);
}
}, [initialApInfId]);
return (
<Card className="w-full max-w-5xl">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<FileText className="w-5 h-5" />
결재 상세 조회
</CardTitle>
<CardDescription>
결재 ID를 입력하여 상세 정보를 조회합니다.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{/* 검색 영역 */}
<div className="flex items-center gap-3">
<div className="flex-1">
<Label htmlFor="apInfId">결재 ID</Label>
<Input
id="apInfId"
placeholder="결재 ID를 입력하세요"
value={apInfId}
onChange={(e) => setApInfId(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && fetchApprovalDetail(apInfId)}
/>
</div>
<Button
onClick={() => fetchApprovalDetail(apInfId)}
disabled={isLoading}
>
{isLoading ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
조회 중...
</>
) : (
<>
<Search className="w-4 h-4 mr-2" />
조회
</>
)}
</Button>
</div>
{/* 에러 메시지 */}
{error && (
<div className="p-4 bg-red-50 border border-red-200 rounded-lg">
<div className="flex items-center gap-2 text-red-700">
<AlertCircle className="w-4 h-4" />
<span className="font-medium">오류</span>
</div>
<p className="text-sm text-red-600 mt-1">{error}</p>
</div>
)}
{/* 결재 상세 정보 */}
{approvalData && (
<div className="space-y-6">
{/* 기본 정보 */}
<div className="space-y-4">
<h3 className="text-lg font-semibold flex items-center gap-2">
<FileText className="w-5 h-5" />
기본 정보
</h3>
<div className="grid grid-cols-2 gap-4 p-4 bg-gray-50 rounded-lg">
<div>
<Label className="text-sm font-medium text-gray-600">결재 ID</Label>
<p className="text-sm font-mono mt-1">{approvalData.detail.apInfId}</p>
</div>
<div>
<Label className="text-sm font-medium text-gray-600">시스템 ID</Label>
<p className="text-sm mt-1">{approvalData.detail.systemId}</p>
</div>
<div>
<Label className="text-sm font-medium text-gray-600">제목</Label>
<p className="text-sm mt-1 font-medium">{approvalData.detail.subject}</p>
</div>
<div>
<Label className="text-sm font-medium text-gray-600">상신일시</Label>
<p className="text-sm mt-1 flex items-center gap-2">
<Clock className="w-4 h-4" />
{formatDate(approvalData.detail.sbmDt, "kr")}
</p>
</div>
<div>
<Label className="text-sm font-medium text-gray-600">상태</Label>
<div className="mt-1">
<Badge variant={getStatusBadgeVariant(approvalData.detail.status)}>
{getStatusText(approvalData.detail.status)}
</Badge>
</div>
</div>
<div>
<Label className="text-sm font-medium text-gray-600">보안 등급</Label>
<div className="mt-1">
<Badge variant={getSecurityTypeBadgeVariant(approvalData.detail.docSecuType)}>
{getSecurityTypeText(approvalData.detail.docSecuType)}
</Badge>
</div>
</div>
<div>
<Label className="text-sm font-medium text-gray-600">긴급 여부</Label>
<div className="mt-1">
<Badge variant={approvalData.detail.urgYn === 'Y' ? 'destructive' : 'outline'}>
{approvalData.detail.urgYn === 'Y' ? '긴급' : '일반'}
</Badge>
</div>
</div>
<div>
<Label className="text-sm font-medium text-gray-600">언어</Label>
<p className="text-sm mt-1">{approvalData.detail.sbmLang}</p>
</div>
</div>
</div>
{/* 결재 취소 섹션 */}
<div className="space-y-4">
<h3 className="text-lg font-semibold flex items-center gap-2">
<XCircle className="w-5 h-5" />
결재 취소
</h3>
<div className={`p-4 rounded-lg border ${
canCancelApproval(approvalData.detail.status)
? 'bg-blue-50 border-blue-200'
: 'bg-yellow-50 border-yellow-200'
}`}>
<div className="flex items-center gap-2 mb-2">
<span className={`font-medium ${
canCancelApproval(approvalData.detail.status)
? 'text-blue-700'
: 'text-yellow-700'
}`}>
{canCancelApproval(approvalData.detail.status) ? '취소 가능' : '취소 불가'}
</span>
</div>
<p className={`text-sm ${
canCancelApproval(approvalData.detail.status)
? 'text-blue-600'
: 'text-yellow-600'
}`}>
{canCancelApproval(approvalData.detail.status)
? '이 결재는 취소할 수 있습니다.'
: '현재 상태에서는 취소할 수 없습니다.'}
</p>
</div>
{/* 취소 의견 및 버튼 */}
{canCancelApproval(approvalData.detail.status) && (
<div className="space-y-4">
<div>
<Label htmlFor="cancelOpinion" className="text-sm font-medium">
상신취소 의견 <span className="text-red-500">*</span>
</Label>
<Textarea
id="cancelOpinion"
placeholder="상신취소 사유를 입력해주세요"
value={cancelOpinion}
onChange={(e) => setCancelOpinion(e.target.value)}
className="mt-1"
rows={3}
/>
<p className="text-xs text-gray-500 mt-1">
상신취소 의견은 필수 입력 항목입니다.
</p>
</div>
<div className="flex justify-end">
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
variant="destructive"
disabled={isCancelling || !cancelOpinion.trim()}
>
{isCancelling ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
취소 중...
</>
) : (
<>
<XCircle className="w-4 h-4 mr-2" />
결재 취소
</>
)}
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>결재 취소 확인</AlertDialogTitle>
<AlertDialogDescription>
정말로 이 결재를 취소하시겠습니까?
<br />
<br />
<strong>결재 ID:</strong> {approvalData.detail.apInfId}
<br />
<strong>제목:</strong> {approvalData.detail.subject}
<br />
<strong>취소 의견:</strong> {cancelOpinion}
<br />
<br />
이 작업은 되돌릴 수 없습니다.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>취소</AlertDialogCancel>
<AlertDialogAction
onClick={handleCancelApproval}
className="bg-red-600 hover:bg-red-700"
>
결재 취소
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</div>
)}
</div>
<Separator />
{/* 결재 내용 */}
<div className="space-y-4">
<h3 className="text-lg font-semibold">결재 내용</h3>
<div className="p-4 bg-gray-50 rounded-lg">
<div className="mb-2">
<Label className="text-sm font-medium text-gray-600">내용 형식</Label>
<Badge variant="outline" className="ml-2">
{approvalData.content.contentsType}
</Badge>
</div>
<div className="mt-4 p-4 bg-white rounded border">
<pre className="whitespace-pre-wrap text-sm">
{approvalData.content.contents}
</pre>
</div>
</div>
</div>
<Separator />
{/* 결재 경로 */}
<div className="space-y-4">
<h3 className="text-lg font-semibold flex items-center gap-2">
<User className="w-5 h-5" />
결재 경로
</h3>
<div className="space-y-3">
{approvalData.detail.aplns.map((apln: ApprovalLine, index: number) => (
<div key={index} className="flex items-center gap-4 p-4 border rounded-lg">
<Badge variant="outline" className="min-w-[40px] text-center">
{apln.seq}
</Badge>
<div className="flex-1 grid grid-cols-4 gap-4">
<div>
<Label className="text-xs font-medium text-gray-600">사용자 ID</Label>
<p className="text-sm mt-1">{apln.userId || apln.epId || '-'}</p>
</div>
<div>
<Label className="text-xs font-medium text-gray-600">이메일</Label>
<p className="text-sm mt-1">{apln.emailAddress || '-'}</p>
</div>
<div>
<Label className="text-xs font-medium text-gray-600">역할</Label>
<div className="mt-1">
<Badge variant="secondary">
{getRoleText(apln.role)}
</Badge>
</div>
</div>
<div>
<Label className="text-xs font-medium text-gray-600">상태</Label>
<div className="mt-1">
<Badge variant={apln.aplnStatsCode === '1' ? 'default' :
apln.aplnStatsCode === '2' ? 'destructive' : 'outline'}>
{getStatusText(apln.aplnStatsCode)}
</Badge>
</div>
</div>
</div>
<div className="flex flex-col gap-1 text-xs">
{apln.arbPmtYn === 'Y' && (
<Badge variant="outline" className="text-xs">전결권한</Badge>
)}
{apln.contentsMdfyPmtYn === 'Y' && (
<Badge variant="outline" className="text-xs">본문수정</Badge>
)}
{apln.aplnMdfyPmtYn === 'Y' && (
<Badge variant="outline" className="text-xs">경로변경</Badge>
)}
</div>
</div>
))}
</div>
</div>
{/* 첨부파일 */}
{approvalData.detail.attachments && approvalData.detail.attachments.length > 0 && (
<>
<Separator />
<div className="space-y-4">
<h3 className="text-lg font-semibold">첨부파일</h3>
<div className="space-y-2">
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
{approvalData.detail.attachments.map((attachment: any, index: number) => (
<div key={index} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
<FileText className="w-4 h-4 text-gray-500" />
<div className="flex-1">
<p className="text-sm font-medium">{attachment.fileName || `첨부파일 ${index + 1}`}</p>
<p className="text-xs text-gray-500">{attachment.fileSize || '크기 정보 없음'}</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => handleDownload(attachment)}
>
다운로드
</Button>
</div>
))}
</div>
</div>
</>
)}
</div>
)}
</CardContent>
</Card>
);
}
|