summaryrefslogtreecommitdiff
path: root/components/knox/approval/ApprovalCancel.tsx
blob: e3981cb7326c478b250ac05957915e96fdf25e70 (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
'use client'

import { useState } 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, XCircle, AlertTriangle, CheckCircle } from 'lucide-react';

// API 함수 및 타입
import { cancelApproval, getApprovalDetail } from '@/lib/knox-api/approval/approval';
import type { ApprovalDetailResponse } 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 ApprovalCancelProps {
  initialApInfId?: string;
  onCancelSuccess?: (apInfId: string) => void;
}

export default function ApprovalCancel({ 
  initialApInfId = '',
  onCancelSuccess 
}: ApprovalCancelProps) {
  const [apInfId, setApInfId] = useState(initialApInfId);
  const [approvalDetail, setApprovalDetail] = useState<ApprovalDetailResponse['data'] | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isCancelling, setIsCancelling] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [cancelResult, setCancelResult] = useState<{ apInfId: string } | null>(null);
  const [cancelOpinion, setCancelOpinion] = useState('');

  const fetchApprovalDetail = async () => {
    if (!apInfId.trim()) {
      toast.error('결재 ID를 입력해주세요.');
      return;
    }

    setIsLoading(true);
    setError(null);
    setApprovalDetail(null);
    setCancelResult(null);
    setCancelOpinion('');

    try {
      const response = await getApprovalDetail(apInfId);

      if (response.result === 'success') {
        setApprovalDetail(response.data);
      } else {
        setError('결재 정보를 가져오는데 실패했습니다.');
        toast.error('결재 정보를 가져오는데 실패했습니다.');
      }
    } catch (err) {
      console.error('결재 상세 조회 오류:', err);
      setError('결재 정보를 가져오는 중 오류가 발생했습니다.');
      toast.error('결재 정보를 가져오는 중 오류가 발생했습니다.');
    } finally {
      setIsLoading(false);
    }
  };

  const handleCancelApproval = async () => {
    if (!approvalDetail) return;

    if (!cancelOpinion.trim()) {
      toast.error('상신취소 의견을 입력해주세요.');
      return;
    }

    setIsCancelling(true);

    try {
      const response = await cancelApproval(approvalDetail.apInfId, cancelOpinion);

      if (response.result === 'success') {
        setCancelResult({ apInfId: response.data.apInfId });
        toast.success('결재가 성공적으로 취소되었습니다.');
        onCancelSuccess?.(response.data.apInfId);
        
        // 상태 업데이트
        setApprovalDetail({
          ...approvalDetail,
          status: '4' // 상신취소
        });
        
        // 의견 초기화
        setCancelOpinion('');
      } else {
        toast.error('결재 취소에 실패했습니다.');
      }
    } catch (err) {
      console.error('결재 취소 오류:', err);
      toast.error('결재 취소 중 오류가 발생했습니다.');
    } finally {
      setIsCancelling(false);
    }
  };

  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 getCancelabilityMessage = (status: string) => {
    if (canCancelApproval(status)) {
      return '이 결재는 취소할 수 있습니다.';
    }
    
    switch (status) {
      case '2':
        return '완결된 결재는 취소할 수 없습니다.';
      case '3':
        return '반려된 결재는 취소할 수 없습니다.';
      case '4':
        return '이미 취소된 결재입니다.';
      case '5':
        return '전결 처리된 결재는 취소할 수 없습니다.';
      case '6':
        return '후완결된 결재는 취소할 수 없습니다.';
      default:
        return '현재 상태에서는 취소할 수 없습니다.';
    }
  };

  return (
    <Card className="w-full max-w-5xl">
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <XCircle className="w-5 h-5" />
          결재 취소
        </CardTitle>
        <CardDescription>
          상신한 결재를 취소합니다.
        </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()}
            />
          </div>
          <Button
            onClick={fetchApprovalDetail}
            disabled={isLoading}
          >
            {isLoading ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                조회 중...
              </>
            ) : (
              '조회'
            )}
          </Button>
        </div>

        {/* 취소 완료 메시지 */}
        {cancelResult && (
          <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
            <div className="flex items-center gap-2 text-green-700">
              <CheckCircle className="w-4 h-4" />
              <span className="font-medium">취소 완료</span>
            </div>
            <p className="text-sm text-green-600 mt-1">
              결재 ID: {cancelResult.apInfId}가 성공적으로 취소되었습니다.
            </p>
          </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">
              <AlertTriangle className="w-4 h-4" />
              <span className="font-medium">오류</span>
            </div>
            <p className="text-sm text-red-600 mt-1">{error}</p>
          </div>
        )}

        {/* 결재 정보 */}
        {approvalDetail && (
          <div className="space-y-6">
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">결재 정보</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">{approvalDetail.apInfId}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-600">제목</Label>
                  <p className="text-sm mt-1 font-medium">{approvalDetail.subject}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-600">상신일시</Label>
                  <p className="text-sm mt-1">{formatDate(approvalDetail.sbmDt, "kr")}</p>
                </div>
                <div>
                  <Label className="text-sm font-medium text-gray-600">현재 상태</Label>
                  <div className="mt-1">
                    <Badge variant={getStatusBadgeVariant(approvalDetail.status)}>
                      {getStatusText(approvalDetail.status)}
                    </Badge>
                  </div>
                </div>
              </div>
            </div>

            <Separator />

            {/* 취소 가능 여부 */}
            <div className="space-y-4">
              <h3 className="text-lg font-semibold">취소 가능 여부</h3>
              
              <div className={`p-4 rounded-lg border ${
                canCancelApproval(approvalDetail.status) 
                  ? 'bg-blue-50 border-blue-200' 
                  : 'bg-yellow-50 border-yellow-200'
              }`}>
                <div className="flex items-center gap-2 mb-2">
                  {canCancelApproval(approvalDetail.status) ? (
                    <CheckCircle className="w-4 h-4 text-blue-600" />
                  ) : (
                    <AlertTriangle className="w-4 h-4 text-yellow-600" />
                  )}
                  <span className={`font-medium ${
                    canCancelApproval(approvalDetail.status) 
                      ? 'text-blue-700' 
                      : 'text-yellow-700'
                  }`}>
                    {canCancelApproval(approvalDetail.status) ? '취소 가능' : '취소 불가'}
                  </span>
                </div>
                <p className={`text-sm ${
                  canCancelApproval(approvalDetail.status) 
                    ? 'text-blue-600' 
                    : 'text-yellow-600'
                }`}>
                  {getCancelabilityMessage(approvalDetail.status)}
                </p>
              </div>
            </div>

            {/* 취소 의견 및 버튼 */}
            {canCancelApproval(approvalDetail.status) && (
              <>
                <Separator />
                
                <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> {approvalDetail.apInfId}
                            <br />
                            <strong>제목:</strong> {approvalDetail.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>
        )}
      </CardContent>
    </Card>
  );
}