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/ApprovalDetail.tsx | 362 ++++++++++++++++++++++++++++
 1 file changed, 362 insertions(+)
 create mode 100644 components/knox/approval/ApprovalDetail.tsx

(limited to 'components/knox/approval/ApprovalDetail.tsx')

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<ApprovalDetailData | null>(null);
+  const [isLoading, setIsLoading] = useState(false);
+  const [error, setError] = useState<string | null>(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<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';
+    }
+  };
+
+  // 초기 로딩 (initialApInfId가 있는 경우)
+  useEffect(() => {
+    if (initialApInfId) {
+      fetchApprovalDetail(initialApInfId);
+    }
+  }, [initialApInfId, useFakeData, systemId]);
+
+  return (
+    <Card className="w-full max-w-6xl">
+      <CardHeader>
+        <CardTitle className="flex items-center gap-2">
+          <FileText className="w-5 h-5" />
+          결재 상세 조회
+        </CardTitle>
+        <CardDescription>
+          결재 ID를 입력하여 상세 정보를 조회합니다. {useFakeData && '(테스트 모드)'}
+        </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)}
+                  </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>
+
+            <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'}>
+                            {getApprovalStatusText(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">
+                    {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">
+                          다운로드
+                        </Button>
+                      </div>
+                    ))}
+                  </div>
+                </div>
+              </>
+            )}
+          </div>
+        )}
+      </CardContent>
+    </Card>
+  );
+} 
\ No newline at end of file
-- 
cgit v1.2.3


From 5cb225e9cd6b0ba2f52572a3afa0de6e5b2a2ece Mon Sep 17 00:00:00 2001
From: joonhoekim <26rote@gmail.com>
Date: Fri, 18 Jul 2025 16:32:22 +0900
Subject: 파일첨부 API 처리, 텍스트 변경
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 app/[lng]/admin/approval-test/page.tsx      |  6 ++--
 components/knox/approval/ApprovalDetail.tsx | 54 +++++++++++++++++++++++++++--
 components/knox/approval/ApprovalSubmit.tsx | 46 ++++++++++++++++++++----
 3 files changed, 94 insertions(+), 12 deletions(-)

(limited to 'components/knox/approval/ApprovalDetail.tsx')

diff --git a/app/[lng]/admin/approval-test/page.tsx b/app/[lng]/admin/approval-test/page.tsx
index de0e2b5a..f044d87d 100644
--- a/app/[lng]/admin/approval-test/page.tsx
+++ b/app/[lng]/admin/approval-test/page.tsx
@@ -3,7 +3,7 @@ import ApprovalManager from '@/components/knox/approval/ApprovalManager';
 
 export const metadata: Metadata = {
   title: 'Knox 결재 시스템 테스트 | Admin',
-  description: 'Knox API를 사용한 결재 시스템의 모든 기능을 테스트할 수 있는 페이지입니다.',
+  description: 'Knox API를 사용한 결재 시스템 기능 테스트용',
 };
 
 export default function ApprovalTestPage() {
@@ -14,9 +14,9 @@ export default function ApprovalTestPage() {
         <div className="space-y-2">
           <h1 className="text-3xl font-bold tracking-tight">Knox 결재 시스템 테스트</h1>
           <p className="text-muted-foreground">
-            Knox API를 사용한 결재 시스템의 모든 기능을 테스트할 수 있습니다.
+            Knox API를 사용한 결재 시스템 컴포넌트입니다.
             <br />
-            테스트 모드가 기본적으로 활성화되어 있으며, 실제 API 대신 가짜 데이터를 사용합니다.
+            테스트 모드가 기본적으로 활성화되어 있으며, 테스트 모드에서는 실제 API 대신 모킹 데이터를 사용
           </p>
         </div>
 
diff --git a/components/knox/approval/ApprovalDetail.tsx b/components/knox/approval/ApprovalDetail.tsx
index 034bde7d..6db43cbe 100644
--- a/components/knox/approval/ApprovalDetail.tsx
+++ b/components/knox/approval/ApprovalDetail.tsx
@@ -28,6 +28,15 @@ interface ApprovalDetailData {
   content: ApprovalContentResponse['data'];
 }
 
+// 첨부파일 타입 (가이드에 명확히 정의되어 있지 않아 필드 일부 추정)
+interface ApprovalAttachment {
+  fileName?: string;
+  fileSize?: string;
+  downloadUrl?: string;
+  fileId?: string;
+  [key: string]: unknown; // 기타 필드 허용
+}
+
 export default function ApprovalDetail({ 
   useFakeData = false, 
   systemId = 'EVCP_SYSTEM',
@@ -126,6 +135,43 @@ export default function ApprovalDetail({
     }
   };
 
+  // 첨부파일 다운로드 헬퍼
+  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.KNOX_API_BASE_URL}/approval/api/v2.0/attachments/${attachment.fileId}`;
+        const resp = await fetch(url, {
+          method: 'GET',
+          headers: {
+            'System-ID': systemId,
+          },
+        });
+        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) {
@@ -338,14 +384,18 @@ export default function ApprovalDetail({
                   <h3 className="text-lg font-semibold">첨부파일</h3>
                   
                   <div className="space-y-2">
-                    {approvalData.detail.attachments.map((attachment: any, index: number) => (
+                    {approvalData.detail.attachments.map((attachment: ApprovalAttachment, 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">
+                        <Button 
+                          variant="outline" 
+                          size="sm" 
+                          onClick={() => handleDownload(attachment)}
+                        >
                           다운로드
                         </Button>
                       </div>
diff --git a/components/knox/approval/ApprovalSubmit.tsx b/components/knox/approval/ApprovalSubmit.tsx
index 37779ce3..526a87f3 100644
--- a/components/knox/approval/ApprovalSubmit.tsx
+++ b/components/knox/approval/ApprovalSubmit.tsx
@@ -17,7 +17,7 @@ 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 { submitApproval, submitSecurityApproval, createSubmitApprovalRequest, createApprovalLine } from '@/lib/knox-api/approval/approval';
 import type { ApprovalLine, SubmitApprovalRequest } from '@/lib/knox-api/approval/approval';
 
 // Mock 데이터
@@ -40,7 +40,9 @@ const formSchema = z.object({
     role: z.enum(['0', '1', '2', '3', '4', '7', '9']),
     seq: z.string(),
     opinion: z.string().optional()
-  })).min(1, '최소 1개의 결재 경로가 필요합니다')
+  })).min(1, '최소 1개의 결재 경로가 필요합니다'),
+  // 첨부파일 (선택)
+  attachments: z.any().optional()
 });
 
 type FormData = z.infer<typeof formSchema>;
@@ -80,7 +82,8 @@ export default function ApprovalSubmit({
           seq: '1',
           opinion: ''
         }
-      ]
+      ],
+      attachments: undefined
     }
   });
 
@@ -137,6 +140,8 @@ export default function ApprovalSubmit({
       );
 
       // 상신 요청 생성
+      const attachmentsArray = data.attachments ? Array.from(data.attachments as FileList) : undefined;
+
       const submitRequest: SubmitApprovalRequest = useFakeData
         ? {
             ...data,
@@ -144,7 +149,8 @@ export default function ApprovalSubmit({
             importantYn: data.importantYn ? 'Y' : 'N',
             sbmDt: new Date().toISOString().replace(/-|:|T/g, '').slice(0, 14),
             apInfId: 'test-ap-inf-id-' + Date.now(),
-            aplns: approvalLines
+            aplns: approvalLines,
+            attachments: attachmentsArray
           }
         : await createSubmitApprovalRequest(
             data.contents,
@@ -158,14 +164,19 @@ export default function ApprovalSubmit({
               notifyOption: data.notifyOption,
               docMngSaveCode: data.docMngSaveCode,
               sbmLang: data.sbmLang,
-              timeZone: data.timeZone
+              timeZone: data.timeZone,
+              attachments: attachmentsArray
             }
           );
 
-      // API 호출
+      // API 호출 (보안 등급에 따라 분기)
+      const isSecure = data.docSecuType === 'CONFIDENTIAL' || data.docSecuType === 'CONFIDENTIAL_STRICT';
+
       const response = useFakeData
         ? await mockApprovalAPI.submitApproval(submitRequest)
-        : await submitApproval(submitRequest, systemId);
+        : isSecure
+          ? await submitSecurityApproval(submitRequest, systemId)
+          : await submitApproval(submitRequest, systemId);
 
       if (response.result === 'SUCCESS') {
         setSubmitResult({ apInfId: response.data.apInfId });
@@ -333,6 +344,27 @@ export default function ApprovalSubmit({
                   )}
                 />
               </div>
+
+              {/* 첨부 파일 */}
+              <FormField
+                control={form.control}
+                name="attachments"
+                render={({ field }) => (
+                  <FormItem>
+                    <FormLabel>첨부 파일</FormLabel>
+                    <FormControl>
+                      <Input
+                        type="file"
+                        multiple
+                        onChange={(e) => field.onChange(e.target.files)}
+                      />
+                    </FormControl>
+                    <FormDescription>필요 시 파일을 선택하세요. (다중 선택 가능)</FormDescription>
+                    <FormMessage />
+                  </FormItem>
+                )}
+              />
+
             </div>
 
             <Separator />
-- 
cgit v1.2.3

