summaryrefslogtreecommitdiff
path: root/components/knox/approval/ApprovalList.tsx
blob: ec47bf04151e31526448db36236d917ff3d6a900 (plain)
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
'use client'

import { useState, useEffect, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { toast } from 'sonner';
import { Loader2, List, Eye, RefreshCw, AlertCircle } from 'lucide-react';

// API 함수 및 타입
import { getSubmissionList, getApprovalHistory, getApprovalLogsAction, syncApprovalStatusAction } from '@/lib/knox-api/approval/approval';
import type { SubmissionListResponse, ApprovalHistoryResponse } 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] || '알 수 없음';
};

interface ApprovalListProps {
  type?: 'submission' | 'history' | 'database';
  onItemClick?: (apInfId: string) => void;
  userParams?: {
    epId?: string;
    userId?: string;
    emailAddress?: string;
  };
}

type ListItem = {
  apInfId: string;
  subject: string;
  sbmDt: string;
  status: string;
  urgYn?: string;
  docSecuType?: string;
  actionType?: string;
  actionDt?: string;
  userId?: string;
};

export default function ApprovalList({ 
  type = 'database',
  onItemClick,
  userParams
}: ApprovalListProps) {
  const [listData, setListData] = useState<ListItem[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isSyncing, setIsSyncing] = useState(false);

  const fetchData = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    try {
      if (type === 'database') {
        // 새로운 데이터베이스 조회 방식
        const response = await getApprovalLogsAction();
        
        if (response.success) {
          setListData(response.data as unknown as ListItem[]);
        } else {
          setError(response.message);
          toast.error(response.message);
        }
      } else {
        // 기존 Knox API 방식
        let response: SubmissionListResponse | ApprovalHistoryResponse;
        
        if (type === 'submission') {
          if (!userParams || (!userParams.epId && !userParams.userId && !userParams.emailAddress)) {
            setError('사용자 정보가 필요합니다. (epId, userId, 또는 emailAddress)');
            toast.error('사용자 정보가 필요합니다.');
            return;
          }
          response = await getSubmissionList(userParams);
        } else {
          response = await getApprovalHistory();
        }

        if (response.result === 'success') {
          setListData(response.data as unknown as ListItem[]);
        } else {
          setError('목록을 가져오는데 실패했습니다.');
          toast.error('목록을 가져오는데 실패했습니다.');
        }
      }
    } catch (err) {
      console.error('목록 조회 오류:', err);
      setError('목록을 가져오는 중 오류가 발생했습니다.');
      toast.error('목록을 가져오는 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  }, [type, userParams]);

  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 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 getActionTypeText = (actionType: string) => {
    const actionMap: Record<string, string> = {
      'SUBMIT': '상신',
      'APPROVE': '승인',
      'REJECT': '반려',
      'CANCEL': '취소',
      'DELEGATE': '위임'
    };
    return actionMap[actionType] || actionType;
  };

  const handleItemClick = (apInfId: string) => {
    onItemClick?.(apInfId);
  };

  // 결재 상황 동기화 함수
  const handleSync = async () => {
    if (type !== 'database') {
      toast.error('데이터베이스 모드에서만 동기화가 가능합니다.');
      return;
    }

    setIsSyncing(true);
    try {
      const result = await syncApprovalStatusAction();
      
      if (result.success) {
        toast.success(result.message);
        // 동기화 후 데이터 새로고침
        await fetchData();
      } else {
        toast.error(result.message);
      }
    } catch (error) {
      console.error('동기화 오류:', error);
      toast.error('동기화 중 오류가 발생했습니다.');
    } finally {
      setIsSyncing(false);
    }
  };

  // 컴포넌트 마운트 시 데이터 로드
  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return (
    <Card className="w-full max-w-5xl">
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <List className="w-5 h-5" />
          {type === 'database' 
            ? '결재 로그 (데이터베이스)' 
            : type === 'submission' 
              ? '상신함' 
              : '결재 이력'
          }
        </CardTitle>
        <CardDescription>
          {type === 'database'
            ? '데이터베이스에 저장된 결재 로그를 확인합니다.'
            : type === 'submission' 
              ? '상신한 결재 목록을 확인합니다.' 
              : '결재 처리 이력을 확인합니다.'
          }
        </CardDescription>
      </CardHeader>

      <CardContent className="space-y-4">
        {/* 제어 버튼들 */}
        <div className="flex justify-between items-center">
          <div className="text-sm text-gray-500">
            총 {listData.length}건
          </div>
          <div className="flex gap-2">
            {type === 'database' && (
              <Button
                onClick={handleSync}
                disabled={isSyncing || isLoading}
                variant="secondary"
                size="sm"
              >
                {isSyncing ? (
                  <>
                    <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                    동기화 중...
                  </>
                ) : (
                  <>
                    <RefreshCw className="w-4 h-4 mr-2" />
                    상태 동기화
                  </>
                )}
              </Button>
            )}
            <Button
              onClick={fetchData}
              disabled={isLoading || isSyncing}
              variant="outline"
              size="sm"
            >
              {isLoading ? (
                <>
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                  조회 중...
                </>
              ) : (
                <>
                  <RefreshCw className="w-4 h-4 mr-2" />
                  새로고침
                </>
              )}
            </Button>
          </div>
        </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>
        )}

        {/* 목록 테이블 */}
        <div className="border rounded-lg">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>결재 ID</TableHead>
                <TableHead>제목</TableHead>
                <TableHead>상신일시</TableHead>
                <TableHead>상태</TableHead>
                {type === 'submission' && (
                  <>
                    <TableHead>긴급</TableHead>
                    <TableHead>보안등급</TableHead>
                  </>
                )}
                {type === 'history' && (
                  <>
                    <TableHead>처리일시</TableHead>
                    <TableHead>처리자</TableHead>
                    <TableHead>처리유형</TableHead>
                  </>
                )}
                <TableHead>작업</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {listData.length === 0 ? (
                <TableRow>
                  <TableCell 
                    colSpan={type === 'submission' ? 7 : 8} 
                    className="text-center py-8 text-gray-500"
                  >
                    {isLoading ? '데이터를 불러오는 중...' : '데이터가 없습니다.'}
                  </TableCell>
                </TableRow>
              ) : (
                listData.map((item) => (
                  <TableRow key={item.apInfId} className="hover:bg-gray-50">
                    <TableCell className="font-mono text-sm">
                      {item.apInfId}
                    </TableCell>
                    <TableCell className="font-medium">
                      {item.subject}
                    </TableCell>
                    <TableCell>
                      {formatDate(item.sbmDt, "kr")}
                    </TableCell>
                    <TableCell>
                      <Badge variant={getStatusBadgeVariant(item.status)}>
                        {getStatusText(item.status)}
                      </Badge>
                    </TableCell>
                    
                    {type === 'submission' && (
                      <>
                        <TableCell>
                          {item.urgYn === 'Y' ? (
                            <Badge variant="destructive" className="text-xs">
                              긴급
                            </Badge>
                          ) : (
                            <Badge variant="outline" className="text-xs">
                              일반
                            </Badge>
                          )}
                        </TableCell>
                        <TableCell>
                          <Badge 
                            variant={getSecurityTypeBadgeVariant(item.docSecuType || 'PERSONAL')}
                            className="text-xs"
                          >
                            {getSecurityTypeText(item.docSecuType || 'PERSONAL')}
                          </Badge>
                        </TableCell>
                      </>
                    )}
                    
                    {type === 'history' && (
                      <>
                        <TableCell>
                          {item.actionDt ? formatDate(item.actionDt, "kr") : '-'}
                        </TableCell>
                        <TableCell>
                          {item.userId || '-'}
                        </TableCell>
                        <TableCell>
                          {item.actionType ? (
                            <Badge variant="outline" className="text-xs">
                              {getActionTypeText(item.actionType)}
                            </Badge>
                          ) : '-'}
                        </TableCell>
                      </>
                    )}
                    
                    <TableCell>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleItemClick(item.apInfId)}
                      >
                        <Eye className="w-4 h-4 mr-2" />
                        상세
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>

        {/* 페이지네이션 영역 (향후 구현 예정) */}
        {listData.length > 0 && (
          <div className="flex justify-center pt-4">
            <div className="text-sm text-gray-500">
              페이지네이션 기능은 향후 구현 예정입니다.
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
}