From 3e59693e017742d971f490eb7c58870cb745a98d Mon Sep 17 00:00:00 2001 From: joonhoekim <26rote@gmail.com> Date: Fri, 18 Jul 2025 03:58:34 +0000 Subject: (김준회) 결재 모듈 개발 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/knox/approval/ApprovalCancel.tsx | 341 +++++++++++++++++ components/knox/approval/ApprovalDetail.tsx | 362 ++++++++++++++++++ components/knox/approval/ApprovalList.tsx | 322 ++++++++++++++++ components/knox/approval/ApprovalManager.tsx | 190 ++++++++++ components/knox/approval/ApprovalSubmit.tsx | 476 ++++++++++++++++++++++++ components/knox/approval/index.ts | 23 ++ components/knox/approval/mocks/approval-mock.ts | 230 ++++++++++++ 7 files changed, 1944 insertions(+) create mode 100644 components/knox/approval/ApprovalCancel.tsx create mode 100644 components/knox/approval/ApprovalDetail.tsx create mode 100644 components/knox/approval/ApprovalList.tsx create mode 100644 components/knox/approval/ApprovalManager.tsx create mode 100644 components/knox/approval/ApprovalSubmit.tsx create mode 100644 components/knox/approval/index.ts create mode 100644 components/knox/approval/mocks/approval-mock.ts (limited to 'components/knox') diff --git a/components/knox/approval/ApprovalCancel.tsx b/components/knox/approval/ApprovalCancel.tsx new file mode 100644 index 00000000..d077bfc6 --- /dev/null +++ b/components/knox/approval/ApprovalCancel.tsx @@ -0,0 +1,341 @@ +'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 { 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'; + +// Mock 데이터 +import { mockApprovalAPI, getStatusText } from './mocks/approval-mock'; + +interface ApprovalCancelProps { + useFakeData?: boolean; + systemId?: string; + initialApInfId?: string; + onCancelSuccess?: (apInfId: string) => void; +} + +export default function ApprovalCancel({ + useFakeData = false, + systemId = 'EVCP_SYSTEM', + initialApInfId = '', + onCancelSuccess +}: ApprovalCancelProps) { + const [apInfId, setApInfId] = useState(initialApInfId); + const [approvalDetail, setApprovalDetail] = useState(null); + const [isLoading, setIsLoading] = useState(false); + const [isCancelling, setIsCancelling] = useState(false); + const [error, setError] = useState(null); + const [cancelResult, setCancelResult] = useState<{ apInfId: string } | null>(null); + + const fetchApprovalDetail = async () => { + if (!apInfId.trim()) { + toast.error('결재 ID를 입력해주세요.'); + return; + } + + setIsLoading(true); + setError(null); + setApprovalDetail(null); + setCancelResult(null); + + try { + const response = useFakeData + ? await mockApprovalAPI.getApprovalDetail(apInfId) + : await getApprovalDetail(apInfId, systemId); + + 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; + + setIsCancelling(true); + + try { + const response = useFakeData + ? await mockApprovalAPI.cancelApproval(approvalDetail.apInfId) + : await cancelApproval(approvalDetail.apInfId, systemId); + + if (response.result === 'SUCCESS') { + setCancelResult({ apInfId: response.data.apInfId }); + toast.success('결재가 성공적으로 취소되었습니다.'); + onCancelSuccess?.(response.data.apInfId); + + // 상태 업데이트 + setApprovalDetail({ + ...approvalDetail, + status: '4' // 상신취소 + }); + } else { + toast.error('결재 취소에 실패했습니다.'); + } + } catch (err) { + console.error('결재 취소 오류:', err); + toast.error('결재 취소 중 오류가 발생했습니다.'); + } finally { + setIsCancelling(false); + } + }; + + const formatDate = (dateString: string) => { + if (!dateString || dateString.length < 14) return dateString; + const year = dateString.substring(0, 4); + const month = dateString.substring(4, 6); + const day = dateString.substring(6, 8); + const hour = dateString.substring(8, 10); + const minute = dateString.substring(10, 12); + const second = dateString.substring(12, 14); + + return `${year}-${month}-${day} ${hour}:${minute}:${second}`; + }; + + 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 ( + + + + + 결재 취소 + + + 결재 ID를 입력하여 상신을 취소합니다. {useFakeData && '(테스트 모드)'} + + + + + {/* 검색 영역 */} +
+
+ + setApInfId(e.target.value)} + onKeyPress={(e) => e.key === 'Enter' && fetchApprovalDetail()} + /> +
+ +
+ + {/* 취소 완료 메시지 */} + {cancelResult && ( +
+
+ + 취소 완료 +
+

+ 결재 ID: {cancelResult.apInfId}가 성공적으로 취소되었습니다. +

+
+ )} + + {/* 에러 메시지 */} + {error && ( +
+
+ + 오류 +
+

{error}

+
+ )} + + {/* 결재 정보 */} + {approvalDetail && ( +
+
+

결재 정보

+ +
+
+ +

{approvalDetail.apInfId}

+
+
+ +

{approvalDetail.subject}

+
+
+ +

{formatDate(approvalDetail.sbmDt)}

+
+
+ +
+ + {getStatusText(approvalDetail.status)} + +
+
+
+
+ + + + {/* 취소 가능 여부 */} +
+

취소 가능 여부

+ +
+
+ {canCancelApproval(approvalDetail.status) ? ( + + ) : ( + + )} + + {canCancelApproval(approvalDetail.status) ? '취소 가능' : '취소 불가'} + +
+

+ {getCancelabilityMessage(approvalDetail.status)} +

+
+
+ + {/* 취소 버튼 */} + {canCancelApproval(approvalDetail.status) && ( + <> + + +
+ + + + + + + 결재 취소 확인 + + 정말로 이 결재를 취소하시겠습니까? +
+
+ 결재 ID: {approvalDetail.apInfId} +
+ 제목: {approvalDetail.subject} +
+
+ 이 작업은 되돌릴 수 없습니다. +
+
+ + 취소 + + 결재 취소 + + +
+
+
+ + )} +
+ )} +
+
+ ); +} \ No newline at end of file diff --git a/components/knox/approval/ApprovalDetail.tsx b/components/knox/approval/ApprovalDetail.tsx new file mode 100644 index 00000000..034bde7d --- /dev/null +++ b/components/knox/approval/ApprovalDetail.tsx @@ -0,0 +1,362 @@ +'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 { toast } from 'sonner'; +import { Loader2, Search, FileText, Clock, User, AlertCircle } from 'lucide-react'; + +// API 함수 및 타입 +import { getApprovalDetail, getApprovalContent } from '@/lib/knox-api/approval/approval'; +import type { ApprovalDetailResponse, ApprovalContentResponse, ApprovalLine } from '@/lib/knox-api/approval/approval'; + +// Mock 데이터 +import { mockApprovalAPI, getStatusText, getRoleText, getApprovalStatusText } from './mocks/approval-mock'; + +interface ApprovalDetailProps { + useFakeData?: boolean; + systemId?: string; + initialApInfId?: string; +} + +interface ApprovalDetailData { + detail: ApprovalDetailResponse['data']; + content: ApprovalContentResponse['data']; +} + +export default function ApprovalDetail({ + useFakeData = false, + systemId = 'EVCP_SYSTEM', + initialApInfId = '' +}: ApprovalDetailProps) { + const [apInfId, setApInfId] = useState(initialApInfId); + const [approvalData, setApprovalData] = useState(null); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + 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([ + useFakeData + ? mockApprovalAPI.getApprovalDetail(id) + : getApprovalDetail(id, systemId), + useFakeData + ? mockApprovalAPI.getApprovalContent(id) + : getApprovalContent(id, systemId) + ]); + + if (detailResponse.result === 'SUCCESS' && contentResponse.result === 'SUCCESS') { + setApprovalData({ + detail: detailResponse.data, + content: contentResponse.data + }); + } else { + setError('결재 정보를 가져오는데 실패했습니다.'); + toast.error('결재 정보를 가져오는데 실패했습니다.'); + } + } catch (err) { + console.error('결재 상세 조회 오류:', err); + setError('결재 정보를 가져오는 중 오류가 발생했습니다.'); + toast.error('결재 정보를 가져오는 중 오류가 발생했습니다.'); + } finally { + setIsLoading(false); + } + }; + + const formatDate = (dateString: string) => { + if (!dateString || dateString.length < 14) return dateString; + // YYYYMMDDHHMMSS 형식을 YYYY-MM-DD HH:MM:SS로 변환 + const year = dateString.substring(0, 4); + const month = dateString.substring(4, 6); + const day = dateString.substring(6, 8); + const hour = dateString.substring(8, 10); + const minute = dateString.substring(10, 12); + const second = dateString.substring(12, 14); + + return `${year}-${month}-${day} ${hour}:${minute}:${second}`; + }; + + const getSecurityTypeText = (type: string) => { + const typeMap: Record = { + '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'; + } + }; + + // 초기 로딩 (initialApInfId가 있는 경우) + useEffect(() => { + if (initialApInfId) { + fetchApprovalDetail(initialApInfId); + } + }, [initialApInfId, useFakeData, systemId]); + + return ( + + + + + 결재 상세 조회 + + + 결재 ID를 입력하여 상세 정보를 조회합니다. {useFakeData && '(테스트 모드)'} + + + + + {/* 검색 영역 */} +
+
+ + setApInfId(e.target.value)} + onKeyPress={(e) => e.key === 'Enter' && fetchApprovalDetail(apInfId)} + /> +
+ +
+ + {/* 에러 메시지 */} + {error && ( +
+
+ + 오류 +
+

{error}

+
+ )} + + {/* 결재 상세 정보 */} + {approvalData && ( +
+ {/* 기본 정보 */} +
+

+ + 기본 정보 +

+ +
+
+ +

{approvalData.detail.apInfId}

+
+
+ +

{approvalData.detail.systemId}

+
+
+ +

{approvalData.detail.subject}

+
+
+ +

+ + {formatDate(approvalData.detail.sbmDt)} +

+
+
+ +
+ + {getStatusText(approvalData.detail.status)} + +
+
+
+ +
+ + {getSecurityTypeText(approvalData.detail.docSecuType)} + +
+
+
+ +
+ + {approvalData.detail.urgYn === 'Y' ? '긴급' : '일반'} + +
+
+
+ +

{approvalData.detail.sbmLang}

+
+
+
+ + + + {/* 결재 내용 */} +
+

결재 내용

+ +
+
+ + + {approvalData.content.contentsType} + +
+ +
+
+                    {approvalData.content.contents}
+                  
+
+
+
+ + + + {/* 결재 경로 */} +
+

+ + 결재 경로 +

+ +
+ {approvalData.detail.aplns.map((apln: ApprovalLine, index: number) => ( +
+ + {apln.seq} + + +
+
+ +

{apln.userId || apln.epId || '-'}

+
+
+ +

{apln.emailAddress || '-'}

+
+
+ +
+ + {getRoleText(apln.role)} + +
+
+
+ +
+ + {getApprovalStatusText(apln.aplnStatsCode)} + +
+
+
+ +
+ {apln.arbPmtYn === 'Y' && ( + 전결권한 + )} + {apln.contentsMdfyPmtYn === 'Y' && ( + 본문수정 + )} + {apln.aplnMdfyPmtYn === 'Y' && ( + 경로변경 + )} +
+
+ ))} +
+
+ + {/* 첨부파일 */} + {approvalData.detail.attachments && approvalData.detail.attachments.length > 0 && ( + <> + +
+

첨부파일

+ +
+ {approvalData.detail.attachments.map((attachment: any, index: number) => ( +
+ +
+

{attachment.fileName || `첨부파일 ${index + 1}`}

+

{attachment.fileSize || '크기 정보 없음'}

+
+ +
+ ))} +
+
+ + )} +
+ )} +
+
+ ); +} \ No newline at end of file diff --git a/components/knox/approval/ApprovalList.tsx b/components/knox/approval/ApprovalList.tsx new file mode 100644 index 00000000..7f80e74a --- /dev/null +++ b/components/knox/approval/ApprovalList.tsx @@ -0,0 +1,322 @@ +'use client' + +import { useState, useEffect } 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 } from '@/lib/knox-api/approval/approval'; +import type { SubmissionListResponse, ApprovalHistoryResponse } from '@/lib/knox-api/approval/approval'; + +// Mock 데이터 +import { mockApprovalAPI, getStatusText } from './mocks/approval-mock'; + +interface ApprovalListProps { + useFakeData?: boolean; + systemId?: string; + type?: 'submission' | 'history'; + onItemClick?: (apInfId: string) => void; +} + +type ListItem = { + apInfId: string; + subject: string; + sbmDt: string; + status: string; + urgYn?: string; + docSecuType?: string; + actionType?: string; + actionDt?: string; + userId?: string; +}; + +export default function ApprovalList({ + useFakeData = false, + systemId = 'EVCP_SYSTEM', + type = 'submission', + onItemClick +}: ApprovalListProps) { + const [listData, setListData] = useState([]); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const fetchData = async () => { + setIsLoading(true); + setError(null); + + try { + let response: SubmissionListResponse | ApprovalHistoryResponse; + + if (type === 'submission') { + response = useFakeData + ? await mockApprovalAPI.getSubmissionList() + : await getSubmissionList(systemId); + } else { + response = useFakeData + ? await mockApprovalAPI.getApprovalHistory() + : await getApprovalHistory(systemId); + } + + if (response.result === 'SUCCESS') { + setListData(response.data); + } else { + setError('목록을 가져오는데 실패했습니다.'); + toast.error('목록을 가져오는데 실패했습니다.'); + } + } catch (err) { + console.error('목록 조회 오류:', err); + setError('목록을 가져오는 중 오류가 발생했습니다.'); + toast.error('목록을 가져오는 중 오류가 발생했습니다.'); + } finally { + setIsLoading(false); + } + }; + + const formatDate = (dateString: string) => { + if (!dateString || dateString.length < 14) return dateString; + const year = dateString.substring(0, 4); + const month = dateString.substring(4, 6); + const day = dateString.substring(6, 8); + const hour = dateString.substring(8, 10); + const minute = dateString.substring(10, 12); + + return `${year}-${month}-${day} ${hour}:${minute}`; + }; + + 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 = { + '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 = { + 'SUBMIT': '상신', + 'APPROVE': '승인', + 'REJECT': '반려', + 'CANCEL': '취소', + 'DELEGATE': '위임' + }; + return actionMap[actionType] || actionType; + }; + + const handleItemClick = (apInfId: string) => { + onItemClick?.(apInfId); + }; + + // 컴포넌트 마운트 시 데이터 로드 + useEffect(() => { + fetchData(); + }, [type, useFakeData, systemId]); + + return ( + + + + + {type === 'submission' ? '상신함' : '결재 이력'} + + + {type === 'submission' + ? '상신한 결재 목록을 확인합니다.' + : '결재 처리 이력을 확인합니다.' + } {useFakeData && '(테스트 모드)'} + + + + + {/* 새로고침 버튼 */} +
+
+ 총 {listData.length}건 +
+ +
+ + {/* 에러 메시지 */} + {error && ( +
+
+ + 오류 +
+

{error}

+
+ )} + + {/* 목록 테이블 */} +
+ + + + 결재 ID + 제목 + 상신일시 + 상태 + {type === 'submission' && ( + <> + 긴급 + 보안등급 + + )} + {type === 'history' && ( + <> + 처리일시 + 처리자 + 처리유형 + + )} + 작업 + + + + {listData.length === 0 ? ( + + + {isLoading ? '데이터를 불러오는 중...' : '데이터가 없습니다.'} + + + ) : ( + listData.map((item) => ( + + + {item.apInfId} + + + {item.subject} + + + {formatDate(item.sbmDt)} + + + + {getStatusText(item.status)} + + + + {type === 'submission' && ( + <> + + {item.urgYn === 'Y' ? ( + + 긴급 + + ) : ( + + 일반 + + )} + + + + {getSecurityTypeText(item.docSecuType || 'PERSONAL')} + + + + )} + + {type === 'history' && ( + <> + + {item.actionDt ? formatDate(item.actionDt) : '-'} + + + {item.userId || '-'} + + + {item.actionType ? ( + + {getActionTypeText(item.actionType)} + + ) : '-'} + + + )} + + + + + + )) + )} + +
+
+ + {/* 페이지네이션 영역 (향후 구현 예정) */} + {listData.length > 0 && ( +
+
+ 페이지네이션 기능은 향후 구현 예정입니다. +
+
+ )} +
+
+ ); +} \ No newline at end of file diff --git a/components/knox/approval/ApprovalManager.tsx b/components/knox/approval/ApprovalManager.tsx new file mode 100644 index 00000000..cac534c4 --- /dev/null +++ b/components/knox/approval/ApprovalManager.tsx @@ -0,0 +1,190 @@ +'use client' + +import { useState } from 'react'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; +import { Badge } from '@/components/ui/badge'; +import { Switch } from '@/components/ui/switch'; +import { Label } from '@/components/ui/label'; +import { Separator } from '@/components/ui/separator'; +import { FileText, Eye, XCircle, List, History, Settings } from 'lucide-react'; + +// 결재 컴포넌트들 +import ApprovalSubmit from './ApprovalSubmit'; +import ApprovalDetail from './ApprovalDetail'; +import ApprovalCancel from './ApprovalCancel'; +import ApprovalList from './ApprovalList'; + +interface ApprovalManagerProps { + useFakeData?: boolean; + systemId?: string; + defaultTab?: string; +} + +export default function ApprovalManager({ + useFakeData = false, + systemId = 'EVCP_SYSTEM', + defaultTab = 'submit' +}: ApprovalManagerProps) { + const [currentTab, setCurrentTab] = useState(defaultTab); + const [isTestMode, setIsTestMode] = useState(useFakeData); + const [selectedApInfId, setSelectedApInfId] = useState(''); + + const handleSubmitSuccess = (apInfId: string) => { + setSelectedApInfId(apInfId); + setCurrentTab('detail'); + }; + + const handleCancelSuccess = (apInfId: string) => { + setSelectedApInfId(apInfId); + setCurrentTab('detail'); + }; + + const handleListItemClick = (apInfId: string) => { + setSelectedApInfId(apInfId); + setCurrentTab('detail'); + }; + + const handleTestModeChange = (checked: boolean) => { + setIsTestMode(checked); + }; + + return ( +
+ {/* 헤더 */} + + + + + Knox 결재 시스템 + + + 결재 상신, 조회, 취소 등 모든 결재 업무를 관리할 수 있습니다. + + + + +
+
+
+ + +
+ {isTestMode && ( + + 테스트 모드 활성화 + + )} +
+ +
+ 시스템 ID: + {systemId} +
+
+
+
+ + {/* 메인 탭 */} + + + + + 상신 + + + + 상세조회 + + + + 취소 + + + + 상신함 + + + + 이력 + + + + {/* 결재 상신 탭 */} + + + + + {/* 결재 상세 조회 탭 */} + + + + + {/* 결재 취소 탭 */} + + + + + {/* 상신함 탭 */} + + + + + {/* 결재 이력 탭 */} + + + + + + {/* 하단 정보 */} + + +
+
+
+ + Knox API 결재 시스템 +
+ +
+ Next.js 15 + shadcn/ui + TypeScript +
+
+ +
+ 버전: + v1.0.0 +
+
+
+
+
+ ); +} \ No newline at end of file diff --git a/components/knox/approval/ApprovalSubmit.tsx b/components/knox/approval/ApprovalSubmit.tsx new file mode 100644 index 00000000..3b5aa230 --- /dev/null +++ b/components/knox/approval/ApprovalSubmit.tsx @@ -0,0 +1,476 @@ +'use client' + +import { useState } from 'react'; +import { useForm } from 'react-hook-form'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { z } from 'zod'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'; +import { Input } from '@/components/ui/input'; +import { Textarea } from '@/components/ui/textarea'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; +import { Switch } from '@/components/ui/switch'; +import { Badge } from '@/components/ui/badge'; +import { Separator } from '@/components/ui/separator'; +import { toast } from 'sonner'; +import { Loader2, Plus, Trash2, FileText, AlertCircle } from 'lucide-react'; + +// API 함수 및 타입 +import { submitApproval, createSubmitApprovalRequest, createApprovalLine } from '@/lib/knox-api/approval/approval'; +import type { ApprovalLine, SubmitApprovalRequest } from '@/lib/knox-api/approval/approval'; + +// Mock 데이터 +import { mockApprovalAPI, createMockApprovalLine, getRoleText } from './mocks/approval-mock'; + +const formSchema = z.object({ + subject: z.string().min(1, '제목은 필수입니다'), + contents: z.string().min(1, '내용은 필수입니다'), + contentsType: z.enum(['TEXT', 'HTML', 'MIME']), + docSecuType: z.enum(['PERSONAL', 'CONFIDENTIAL', 'CONFIDENTIAL_STRICT']), + urgYn: z.boolean(), + importantYn: z.boolean(), + notifyOption: z.enum(['0', '1', '2', '3']), + docMngSaveCode: z.enum(['0', '1']), + sbmLang: z.enum(['ko', 'ja', 'zh', 'en']), + timeZone: z.string().default('GMT+9'), + aplns: z.array(z.object({ + userId: z.string().min(1, '사용자 ID는 필수입니다'), + emailAddress: z.string().email('유효한 이메일 주소를 입력해주세요').optional(), + role: z.enum(['0', '1', '2', '3', '4', '7', '9']), + seq: z.string(), + opinion: z.string().optional() + })).min(1, '최소 1개의 결재 경로가 필요합니다') +}); + +type FormData = z.infer; + +interface ApprovalSubmitProps { + useFakeData?: boolean; + systemId?: string; + onSubmitSuccess?: (apInfId: string) => void; +} + +export default function ApprovalSubmit({ + useFakeData = false, + systemId = 'EVCP_SYSTEM', + onSubmitSuccess +}: ApprovalSubmitProps) { + const [isSubmitting, setIsSubmitting] = useState(false); + const [submitResult, setSubmitResult] = useState<{ apInfId: string } | null>(null); + + const form = useForm({ + resolver: zodResolver(formSchema), + defaultValues: { + subject: '', + contents: '', + contentsType: 'TEXT', + docSecuType: 'PERSONAL', + urgYn: false, + importantYn: false, + notifyOption: '0', + docMngSaveCode: '0', + sbmLang: 'ko', + timeZone: 'GMT+9', + aplns: [ + { + userId: '', + emailAddress: '', + role: '0', + seq: '1', + opinion: '' + } + ] + } + }); + + const aplns = form.watch('aplns'); + + const addApprovalLine = () => { + const newSeq = (aplns.length + 1).toString(); + form.setValue('aplns', [...aplns, { + userId: '', + emailAddress: '', + role: '1', + seq: newSeq, + opinion: '' + }]); + }; + + const removeApprovalLine = (index: number) => { + if (aplns.length > 1) { + const newAplns = aplns.filter((_, i) => i !== index); + // 순서 재정렬 + const reorderedAplns = newAplns.map((apln, i) => ({ + ...apln, + seq: (i + 1).toString() + })); + form.setValue('aplns', reorderedAplns); + } + }; + + const onSubmit = async (data: FormData) => { + setIsSubmitting(true); + setSubmitResult(null); + + try { + // 결재 경로 생성 + const approvalLines: ApprovalLine[] = await Promise.all( + data.aplns.map(async (apln) => { + if (useFakeData) { + return createMockApprovalLine({ + userId: apln.userId, + emailAddress: apln.emailAddress, + role: apln.role, + seq: apln.seq, + opinion: apln.opinion + }); + } else { + return createApprovalLine( + { userId: apln.userId, emailAddress: apln.emailAddress }, + apln.role, + apln.seq, + { opinion: apln.opinion } + ); + } + }) + ); + + // 상신 요청 생성 + const submitRequest: SubmitApprovalRequest = useFakeData + ? { + ...data, + urgYn: data.urgYn ? 'Y' : 'N', + importantYn: data.importantYn ? 'Y' : 'N', + sbmDt: new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14), + apInfId: 'test-ap-inf-id-' + Date.now(), + aplns: approvalLines + } + : await createSubmitApprovalRequest( + data.contents, + data.subject, + approvalLines, + { + contentsType: data.contentsType, + docSecuType: data.docSecuType, + urgYn: data.urgYn ? 'Y' : 'N', + importantYn: data.importantYn ? 'Y' : 'N', + notifyOption: data.notifyOption, + docMngSaveCode: data.docMngSaveCode, + sbmLang: data.sbmLang, + timeZone: data.timeZone + } + ); + + // API 호출 + const response = useFakeData + ? await mockApprovalAPI.submitApproval(submitRequest) + : await submitApproval(submitRequest, systemId); + + if (response.result === 'SUCCESS') { + setSubmitResult({ apInfId: response.data.apInfId }); + toast.success('결재가 성공적으로 상신되었습니다.'); + onSubmitSuccess?.(response.data.apInfId); + form.reset(); + } else { + toast.error('결재 상신에 실패했습니다.'); + } + } catch (error) { + console.error('결재 상신 오류:', error); + toast.error('결재 상신 중 오류가 발생했습니다.'); + } finally { + setIsSubmitting(false); + } + }; + + return ( + + + + + 결재 상신 + + + 새로운 결재를 상신합니다. {useFakeData && '(테스트 모드)'} + + + + + {submitResult && ( +
+
+ + 상신 완료 +
+

+ 결재 ID: {submitResult.apInfId} +

+
+ )} + +
+ + {/* 기본 정보 */} +
+

기본 정보

+ + ( + + 제목 * + + + + + + )} + /> + + ( + + 내용 * + +