From 75249e6fa46864f49d4eb91bd755171b6b65eaae Mon Sep 17 00:00:00 2001 From: joonhoekim <26rote@gmail.com> Date: Mon, 28 Jul 2025 12:10:39 +0000 Subject: (김준회) 공통모듈 - Knox 결재 모듈 구현, 유저 선택기 구현, 상신 결재 저장을 위한 DB 스키마 및 서비스 추가, spreadjs 라이센스 환경변수 통일, 유저 테이블에 epId 컬럼 추가 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.development | 4 +- .env.production | 4 +- app/[lng]/admin/approval-test/page.tsx | 10 +- app/[lng]/admin/approval-test/page.tsx.bak | 32 - app/[lng]/admin/mdg/page.tsx.bak | 277 ------ app/api/auth/[...nextauth]/route.ts | 1 + components/common/user/user-selector.tsx | 447 ++++++++++ components/knox/approval/ApprovalCancel.tsx | 34 +- components/knox/approval/ApprovalDetail.tsx | 58 +- components/knox/approval/ApprovalList.tsx | 38 +- components/knox/approval/ApprovalManager.tsx | 92 +- components/knox/approval/ApprovalSubmit.tsx | 1063 +++++++++++++++++------ components/knox/approval/index.ts | 3 - components/knox/approval/mocks/approval-mock.ts | 230 ----- components/qna/tiptap-editor.tsx | 16 - components/rich-text-editor/RichTextEditor.tsx | 998 +++++++++++++++++++++ components/spread-js/dataBinding.tsx | 4 +- components/spread-js/testSheet.tsx | 4 +- db/schema/index.ts | 9 +- db/schema/knox/approvals.ts | 16 + db/schema/users.ts | 1 + lib/knox-api/approval/approval.ts | 74 +- lib/knox-api/approval/service.ts | 140 +++ lib/knox-api/common.ts | 1 + lib/knox-sync/employee-sync-service.ts | 3 + lib/knox-sync/master-sync-service.ts | 2 +- lib/users/service.ts | 95 +- 27 files changed, 2708 insertions(+), 948 deletions(-) delete mode 100644 app/[lng]/admin/approval-test/page.tsx.bak delete mode 100644 app/[lng]/admin/mdg/page.tsx.bak create mode 100644 components/common/user/user-selector.tsx delete mode 100644 components/knox/approval/mocks/approval-mock.ts create mode 100644 components/rich-text-editor/RichTextEditor.tsx create mode 100644 db/schema/knox/approvals.ts create mode 100644 lib/knox-api/approval/service.ts diff --git a/.env.development b/.env.development index 6b74e5de..2ea1c4b0 100644 --- a/.env.development +++ b/.env.development @@ -117,7 +117,7 @@ MDG_SOAP_USERNAME=P2038_01 # 개발/품질/운영 공통 # MDG_SOAP_PASSWORD=STG4857602 # 개발 MDG_SOAP_PASSWORD=SEW2765890 # 품질 # MDG_SOAP_PASSWORD=POI9807861 # 운영 -SOAP_LOG_MAX_RECORDS=500 +SOAP_LOG_MAX_RECORDS=5000 # === SOAP 인터페이스 설정 === # === KNOX API 사용을 위한 설정 === @@ -128,7 +128,7 @@ KNOX_SYSTEM_ID="KCD60REST00046" KNOX_API_BEARER="5a84ab62-d523-3602-ad3d-e3421893ae0c" # 운영 # 동기화 설정 KNOX_API_FORCE_LIMIT=false # 주간대량호출 강제 제한 여부 -KNOX_API_HOURLY_LIMIT=90 # 시간당 API 호출횟수 제한 +KNOX_API_HOURLY_LIMIT=400 # 시간당 API 호출횟수 제한 # KNOX_API_CALL_DELAY_MS # API 배치 처리간 딜레이 수동 설정이며, 자동 산출값보다 높아야 적용 KNOX_MASTER_SYNC_CRON="0 2 * * *" # cron 스케줄, 새벽 2시에 적용되며, 직급-조직도-임직원 순으로 적용. KNOX_MASTER_SYNC_FIRST_RUN="false" # 앱 시작시 동기화 시작 여부 diff --git a/.env.production b/.env.production index 0efe9996..17dbaa42 100644 --- a/.env.production +++ b/.env.production @@ -118,7 +118,7 @@ MDG_SOAP_USERNAME=P2038_01 # 개발/품질/운영 공통 # MDG_SOAP_PASSWORD=STG4857602 # 개발 MDG_SOAP_PASSWORD=SEW2765890 # 품질 # MDG_SOAP_PASSWORD=POI9807861 # 운영 -SOAP_LOG_MAX_RECORDS=500 +SOAP_LOG_MAX_RECORDS=5000 # === SOAP 인터페이스 설정 === # === KNOX API 사용을 위한 설정 === @@ -129,7 +129,7 @@ KNOX_SYSTEM_ID="KCD60REST00046" KNOX_API_BEARER="5a84ab62-d523-3602-ad3d-e3421893ae0c" # 운영 # 동기화 설정 KNOX_API_FORCE_LIMIT=false # 주간대량호출 강제 제한 여부 -KNOX_API_HOURLY_LIMIT=90 # 시간당 API 호출횟수 제한 +KNOX_API_HOURLY_LIMIT=400 # 시간당 API 호출횟수 제한 # KNOX_API_CALL_DELAY_MS # API 배치 처리간 딜레이 수동 설정이며, 자동 산출값보다 높아야 적용 KNOX_MASTER_SYNC_CRON="0 2 * * *" # cron 스케줄, 새벽 2시에 적용되며, 직급-조직도-임직원 순으로 적용. KNOX_MASTER_SYNC_FIRST_RUN="false" # 앱 시작시 동기화 시작 여부 diff --git a/app/[lng]/admin/approval-test/page.tsx b/app/[lng]/admin/approval-test/page.tsx index f044d87d..ab5654f3 100644 --- a/app/[lng]/admin/approval-test/page.tsx +++ b/app/[lng]/admin/approval-test/page.tsx @@ -2,8 +2,8 @@ import { Metadata } from 'next'; import ApprovalManager from '@/components/knox/approval/ApprovalManager'; export const metadata: Metadata = { - title: 'Knox 결재 시스템 테스트 | Admin', - description: 'Knox API를 사용한 결재 시스템 기능 테스트용', + title: 'Knox 결재 시스템 | Admin', + description: 'Knox API를 사용한 결재 시스템', }; export default function ApprovalTestPage() { @@ -12,18 +12,14 @@ export default function ApprovalTestPage() {
{/* 페이지 헤더 */}
-

Knox 결재 시스템 테스트

+

Knox 결재 시스템

Knox API를 사용한 결재 시스템 컴포넌트입니다. -
- 테스트 모드가 기본적으로 활성화되어 있으며, 테스트 모드에서는 실제 API 대신 모킹 데이터를 사용

{/* 결재 관리자 컴포넌트 */}
diff --git a/app/[lng]/admin/approval-test/page.tsx.bak b/app/[lng]/admin/approval-test/page.tsx.bak deleted file mode 100644 index de0e2b5a..00000000 --- a/app/[lng]/admin/approval-test/page.tsx.bak +++ /dev/null @@ -1,32 +0,0 @@ -import { Metadata } from 'next'; -import ApprovalManager from '@/components/knox/approval/ApprovalManager'; - -export const metadata: Metadata = { - title: 'Knox 결재 시스템 테스트 | Admin', - description: 'Knox API를 사용한 결재 시스템의 모든 기능을 테스트할 수 있는 페이지입니다.', -}; - -export default function ApprovalTestPage() { - return ( -
-
- {/* 페이지 헤더 */} -
-

Knox 결재 시스템 테스트

-

- Knox API를 사용한 결재 시스템의 모든 기능을 테스트할 수 있습니다. -
- 테스트 모드가 기본적으로 활성화되어 있으며, 실제 API 대신 가짜 데이터를 사용합니다. -

-
- - {/* 결재 관리자 컴포넌트 */} - -
-
- ); -} diff --git a/app/[lng]/admin/mdg/page.tsx.bak b/app/[lng]/admin/mdg/page.tsx.bak deleted file mode 100644 index e2926deb..00000000 --- a/app/[lng]/admin/mdg/page.tsx.bak +++ /dev/null @@ -1,277 +0,0 @@ -'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 { toast } from 'sonner' -import { Loader2, Send, RefreshCw } from 'lucide-react' - -// CSV 필드를 정의할 타입 -interface VendorFieldDef { - table: string; - name: string; - mandatory: boolean; - description: string; -} - -// CSV 파싱 함수 (간단 파서) -const parseCSV = (csv: string): VendorFieldDef[] => { - const lines = csv.trim().split('\n'); - // 첫 번째 라인은 헤더이므로 제거 - return lines.slice(1).map((line) => { - const parts = line.split(','); - const table = parts[1]?.trim(); - const name = parts[2]?.trim(); - const mandatory = parts[3]?.trim() === 'M'; - const description = parts.slice(6).join(',').trim(); - return { table, name, mandatory, description } as VendorFieldDef; - }); -}; - -// 기존 샘플 기본값 (필요 시 확장) -const sampleDefaults: Record = { - BP_HEADER: 'TEST001', - ZZSRMCD: 'EVCP', - TITLE: 'TEST', - BU_SORT1: 'TEST VENDOR', - NAME_ORG1: '테스트 벤더 회사', - KTOKK: 'Z001', - VEN_KFBUS: '제조업', - VEN_KFIND: 'IT', - MASTERFLAG: 'X', - IBND_TYPE: 'U', - ZZREQID: 'TESTUSER01', - ADDRNO: '0001', - AD_NATION: '1', - COUNTRY: 'KR', - LANGU_COM: 'K', - POST_COD1: '06292', - CITY1: '서울시', - DISTRICT: '강남구', - REGION: '11', - MC_STREET: '테헤란로 123', - T_COUNTRY: 'KR', - T_NUMBER: '02-1234-5678', - F_COUNTRY: 'KR', - F_NUMBER: '02-1234-5679', - U_ADDRESS: 'https://test.vendor.com', - E_ADDRESS: 'contact@test.vendor.com', - BP_TX_TYP: 'KR2', - TAXNUM: '123-45-67890', - AD_CONSNO: '1', -}; - -// XML escape helper -const escapeXml = (unsafe: string) => unsafe.replace(/[<>&'"']/g, (c) => { - switch (c) { - case '<': return '<'; - case '>': return '>'; - case '&': return '&'; - case '"': return '"'; - case "'": return '''; - default: return c; - } -}); - -export default function MDGTestPage() { - const [formData, setFormData] = useState>({}); - const [fieldDefs, setFieldDefs] = useState([]); - const [resultXml, setResultXml] = useState(''); - const [isLoading, setIsLoading] = useState(false); - - // CSV 로딩 및 초기 데이터 셋업 - useEffect(() => { - const load = async () => { - const res = await fetch('/wsdl/P2MD3007_AO.csv'); - const csvText = await res.text(); - const defs = parseCSV(csvText); - setFieldDefs(defs); - - const init: Record = {}; - defs.forEach((d) => { - init[d.name] = sampleDefaults[d.name] ?? ''; - }); - setFormData(init); - }; - - load(); - }, []); - - // XML 생성 유틸리티 (폼 데이터 -> SOAP Envelope) - const buildEnvelopeXml = (currentForm: Record, defs: VendorFieldDef[]) => { - if (defs.length === 0) return ''; - const bodyContent = defs.map((f) => { - const val = currentForm[f.name] ?? ''; - return `<${f.name}>${escapeXml(val)}`; - }).join('\n '); - - const supplierXml = `\n ${bodyContent}\n `; - - return `\n\n \n \n \n \n ${supplierXml}\n \n \n \n`; - }; - - // 폼 데이터 변경 시 실시간 XML 생성 - useEffect(() => { - const xml = buildEnvelopeXml(formData, fieldDefs); - setResultXml(xml); - }, [formData, fieldDefs]); - - // 폼 데이터 업데이트 - const updateField = (field: string, value: string) => { - setFormData(prev => ({ ...prev, [field]: value })); - }; - - // 기본값으로 리셋 - const resetForm = () => { - const reset: Record = {}; - fieldDefs.forEach((d) => { - reset[d.name] = sampleDefaults[d.name] ?? ''; - }); - setFormData(reset); - toast.success('폼이 기본값으로 리셋되었습니다.'); - }; - - // 테스트 송신 실행 (실제 서버 호출) - const handleTestSend = async () => { - try { - setIsLoading(true); - - // 필수 필드 검증 - const requiredFields = fieldDefs.filter(d => d.mandatory).map(d => d.name); - const missingFields = requiredFields.filter(field => !formData[field]?.trim()); - - if (missingFields.length > 0) { - toast.error(`필수 필드가 누락되었습니다: ${missingFields.join(', ')}`); - setIsLoading(false); - return; - } - - // 서버 API 호출해 송신 - const res = await fetch('/api/mdg/send-vendor-xml', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ envelope: resultXml }), - }); - - const json = await res.json(); - - if (!res.ok || !json.success) { - // 상세 오류 메시지 추출 (vendorCode 기반 또는 직접 오류 메시지) - const detailMsg = json?.results?.[0]?.error ?? json?.message ?? json?.responseText ?? '송신 실패'; - toast.error(`송신 실패: ${detailMsg}`); - setIsLoading(false); - return; - } - - toast.success('MDG 송신이 완료되었습니다.'); - - } catch (error) { - console.error('테스트 송신 실패:', error); - toast.error('테스트 송신 중 오류가 발생했습니다.'); - } finally { - setIsLoading(false); - } - }; - - return ( -
-
-
-

MDG VENDOR 마스터 테스트

-

- VENDOR 마스터 데이터를 MDG 시스템으로 테스트 송신합니다 -

-
-
- - -
-
- - {/* 동적 필드 렌더링 */} - {fieldDefs.length === 0 ? ( -

CSV 로딩 중...

- ) : ( -
- {Object.entries( - fieldDefs.reduce((acc: Record, cur) => { - acc[cur.table] = acc[cur.table] ? [...acc[cur.table], cur] : [cur]; - return acc; - }, {}) - ).map(([table, fields]) => ( - - - - {table} - {fields.some(f => f.mandatory) && ( - 필수 포함 - )} - - {table} 테이블 입력 - - - {fields.filter((f, idx, arr) => arr.findIndex(x => x.name === f.name) === idx).map((field) => ( -
- - updateField(field.name, e.target.value)} - /> - {field.description && ( -

{field.description}

- )} -
- ))} -
-
- ))} -
- )} - - {/* 송신 결과 영역 */} - - - 송신 결과 - - MDG 시스템으로의 송신 결과가 여기에 표시됩니다 - - - - {resultXml ? ( -
-              {resultXml}
-            
- ) : ( -
-

- 테스트 송신 버튼을 클릭하면 결과가 표시됩니다. -

-
- )} -
-
-
- ); -} - diff --git a/app/api/auth/[...nextauth]/route.ts b/app/api/auth/[...nextauth]/route.ts index fe93906d..5896fb90 100644 --- a/app/api/auth/[...nextauth]/route.ts +++ b/app/api/auth/[...nextauth]/route.ts @@ -235,6 +235,7 @@ export const authOptions: NextAuthOptions = { authMethod: tempAuth.authMethod as AuthMethod, dbSessionId: dbSession.id, roles: userRoles, // ✅ roles 배열 추가 + epId: user.epId, // Knox 계정인 경우, epId 추가 (Knox API 사용하는 경우 필요) } } catch (error) { diff --git a/components/common/user/user-selector.tsx b/components/common/user/user-selector.tsx new file mode 100644 index 00000000..4a43fa5e --- /dev/null +++ b/components/common/user/user-selector.tsx @@ -0,0 +1,447 @@ +"use client" + +import * as React from "react" +import { Search, X, Users, ChevronLeft, ChevronRight } from "lucide-react" +import { Button } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Badge } from "@/components/ui/badge" +import { useDebounce } from "@/hooks/use-debounce" +import { cn } from "@/lib/utils" +// import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar" +import { Skeleton } from "@/components/ui/skeleton" +import { searchUsersForSelector } from "@/lib/users/service" + +// User 타입 정의 +export interface UserSelectItem { + id: number + name: string + email: string + epId?: string | null + deptCode?: string | null + deptName?: string | null + imageUrl?: string | null + domain?: string + companyName?: string | null +} + +// Domain 필터 타입 +export type UserDomainFilter = + | { type: "exclude"; domains: string[] } // partners가 아닌 경우 + | { type: "include"; domains: string[] } // 특정 domain인 경우 + | null // 필터 없음 + +// 페이지네이션 정보 타입 +interface PaginationInfo { + page: number + perPage: number + total: number + pageCount: number + hasNextPage: boolean + hasPrevPage: boolean +} + +export interface UserSelectorProps { + /** 선택된 사용자들 */ + selectedUsers?: UserSelectItem[] + /** 사용자 선택 변경 콜백 */ + onUsersChange?: (users: UserSelectItem[]) => void + /** 단일 선택 모드 여부 */ + singleSelect?: boolean + /** domain 필터 */ + domainFilter?: UserDomainFilter + /** placeholder 텍스트 */ + placeholder?: string + /** 입력 없이 focus 시 표시할 placeholder */ + noValuePlaceHolder?: string + /** 비활성화 여부 */ + disabled?: boolean + /** 최대 선택 가능 사용자 수 */ + maxSelections?: number + /** 조직도 선택 다이얼로그 오픈 콜백 (추후 구현) */ + onOpenOrgChart?: () => void + /** 컴포넌트 클래스명 */ + className?: string + /** 사용자 선택 후 팝오버 닫기 여부 */ + closeOnSelect?: boolean +} + +export function UserSelector({ + selectedUsers = [], + onUsersChange, + singleSelect = false, + domainFilter, + placeholder = "사용자를 검색하세요...", + noValuePlaceHolder = "사용자를 검색하거나 조직도에서 찾아보세요", + disabled = false, + maxSelections, + onOpenOrgChart, + className, + closeOnSelect = true // 기본값으로 선택 후 닫기 +}: UserSelectorProps) { + const [searchQuery, setSearchQuery] = React.useState("") + const [isSearching, setIsSearching] = React.useState(false) + const [searchResults, setSearchResults] = React.useState([]) + const [isPopoverOpen, setIsPopoverOpen] = React.useState(false) + const [currentPage, setCurrentPage] = React.useState(1) + const [pagination, setPagination] = React.useState({ + page: 1, + perPage: 10, + total: 0, + pageCount: 0, + hasNextPage: false, + hasPrevPage: false, + }) + const [searchError, setSearchError] = React.useState(null) + + const inputRef = React.useRef(null) + + // Debounce 적용된 검색어 + const debouncedSearchQuery = useDebounce(searchQuery, 300) + + // 검색 실행 - useCallback으로 메모이제이션 + const performSearch = React.useCallback(async (query: string, page: number = 1) => { + setIsSearching(true) + setSearchError(null) + + try { + const result = await searchUsersForSelector(query, page, 10, domainFilter) + + if (result.success) { + setSearchResults(result.data) + setPagination(result.pagination) + setCurrentPage(page) + } else { + setSearchResults([]) + setSearchError("검색 중 오류가 발생했습니다.") + setPagination({ + page: 1, + perPage: 10, + total: 0, + pageCount: 0, + hasNextPage: false, + hasPrevPage: false, + }) + } + } catch (err) { + console.error("사용자 검색 실패:", err) + setSearchResults([]) + setSearchError("검색 중 오류가 발생했습니다.") + setPagination({ + page: 1, + perPage: 10, + total: 0, + pageCount: 0, + hasNextPage: false, + hasPrevPage: false, + }) + } finally { + setIsSearching(false) + } + }, [domainFilter]) + + // Debounced 검색어 변경 시 검색 실행 + React.useEffect(() => { + setCurrentPage(1) + performSearch(debouncedSearchQuery, 1) + }, [debouncedSearchQuery, performSearch]) + + // 페이지 변경 처리 - useCallback으로 메모이제이션 + const handlePageChange = React.useCallback((newPage: number) => { + if (newPage >= 1 && newPage <= pagination.pageCount) { + performSearch(debouncedSearchQuery, newPage) + } + }, [pagination.pageCount, performSearch, debouncedSearchQuery]) + + // 사용자 선택 처리 - useCallback으로 메모이제이션 + const handleUserSelect = React.useCallback((user: UserSelectItem) => { + if (disabled) return + + const isSelected = selectedUsers.some(u => u.id === user.id) + let newSelection: UserSelectItem[] + + if (singleSelect) { + newSelection = isSelected ? [] : [user] + } else { + if (isSelected) { + newSelection = selectedUsers.filter(u => u.id !== user.id) + } else { + if (maxSelections && selectedUsers.length >= maxSelections) { + return // 최대 선택 수 도달 + } + newSelection = [...selectedUsers, user] + } + } + + onUsersChange?.(newSelection) + + // 선택 후 팝오버 닫기 (closeOnSelect가 true이거나 단일 선택 모드일 때) + if ((closeOnSelect || singleSelect) && !isSelected) { + setIsPopoverOpen(false) + setSearchQuery("") + } + }, [disabled, selectedUsers, singleSelect, maxSelections, onUsersChange, closeOnSelect]) + + // 선택된 사용자 제거 - useCallback으로 메모이제이션 + const handleRemoveUser = React.useCallback((userId: number) => { + if (disabled) return + const newSelection = selectedUsers.filter(u => u.id !== userId) + onUsersChange?.(newSelection) + }, [disabled, selectedUsers, onUsersChange]) + + // 사용자 이니셜 생성 - useMemo로 메모이제이션 + const getUserInitials = React.useCallback((name: string) => { + const names = name.split(' ') + return names.length > 1 + ? `${names[0][0]}${names[1][0]}` + : name.slice(0, 2) + }, []) + + // Input 이벤트 핸들러들 + const handleInputFocus = React.useCallback(() => { + setIsPopoverOpen(true) + }, []) + + const handleInputChange = React.useCallback((e: React.ChangeEvent) => { + setSearchQuery(e.target.value) + if (!isPopoverOpen) { + setIsPopoverOpen(true) + } + }, [isPopoverOpen]) + + const handleClosePopover = React.useCallback(() => { + setIsPopoverOpen(false) + }, []) + + // 계산된 값들 - useMemo로 메모이제이션 + const shouldShowResults = React.useMemo(() => + searchQuery.trim() || isSearching, [searchQuery, isSearching]) + + const hasResults = React.useMemo(() => + searchResults.length > 0, [searchResults.length]) + + // 검색 결과 렌더링 - 컴포넌트 분리로 가독성 향상 + const renderSearchResults = React.useMemo(() => { + if (!shouldShowResults) { + return ( +
+ {noValuePlaceHolder} +
+ ) + } + + if (isSearching) { + return ( +
+ {Array.from({ length: 3 }).map((_, i) => ( +
+
+ ? +
+
+ +
+
+ ))} +
+ ) + } + + if (searchError) { + return ( +
+ {searchError} +
+ ) + } + + if (!hasResults) { + return ( +
+ 검색 결과가 없습니다. +
+ ) + } + + return ( + <> +
+ {searchResults.map((user) => { + const isSelected = selectedUsers.some(u => u.id === user.id) + const canSelect = !maxSelections || selectedUsers.length < maxSelections || isSelected + + return ( +
handleUserSelect(user)} + className={cn( + "flex items-center space-x-3 p-2 rounded-md cursor-pointer hover:bg-accent", + !canSelect && !isSelected && "opacity-50 cursor-not-allowed" + )} + > +
+ {getUserInitials(user.name)} +
+
+
+ {user.name} + · + {user.email} + {user.deptName && ( + <> + · + {user.deptName} + + )} + {isSelected &&
} +
+
+
+ ) + })} +
+ + {/* 페이지네이션 */} + {pagination.pageCount > 1 && ( +
+
+ {pagination.total}명 중 {((pagination.page - 1) * pagination.perPage) + 1}-{Math.min(pagination.page * pagination.perPage, pagination.total)}명 +
+
+ + + {pagination.page} / {pagination.pageCount} + + +
+
+ )} + + ) + }, [ + shouldShowResults, + noValuePlaceHolder, + isSearching, + searchError, + hasResults, + searchResults, + selectedUsers, + maxSelections, + handleUserSelect, + getUserInitials, + pagination, + currentPage, + handlePageChange + ]) + + return ( +
+ {/* 검색 입력 영역 */} +
+
+
+ + +
+ + {/* 검색 결과 팝오버 */} + {isPopoverOpen && ( +
+ {/* 팝오버 헤더 */} +
+ 사용자 선택 + +
+ + {/* 검색 결과 영역 */} +
+ {renderSearchResults} +
+
+ )} +
+ + {/* 조직도 찾기 버튼 */} + {onOpenOrgChart && ( + + )} +
+ + {/* 선택된 사용자들 표시 */} + {selectedUsers.length > 0 && ( +
+ {selectedUsers.map((user) => ( + +
+ {getUserInitials(user.name)} +
+ {user.name} + {user.deptName && ( + ({user.deptName}) + )} + {!disabled && ( + + )} +
+ ))} +
+ )} + + {/* 선택 제한 안내 */} + {maxSelections && selectedUsers.length >= maxSelections && ( +
+ 최대 {maxSelections}명까지 선택할 수 있습니다. +
+ )} +
+ ) +} diff --git a/components/knox/approval/ApprovalCancel.tsx b/components/knox/approval/ApprovalCancel.tsx index d077bfc6..b40b43df 100644 --- a/components/knox/approval/ApprovalCancel.tsx +++ b/components/knox/approval/ApprovalCancel.tsx @@ -15,19 +15,29 @@ import { Loader2, XCircle, AlertTriangle, CheckCircle } from 'lucide-react'; 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'; +// 상태 코드 텍스트 매핑 (mock util 대체) +const getStatusText = (status: string) => { + const map: Record = { + '-3': '암호화실패', + '-2': '암호화중', + '-1': '예약상신', + '0': '보류', + '1': '진행중', + '2': '완결', + '3': '반려', + '4': '상신취소', + '5': '전결', + '6': '후완결', + }; + return map[status] || '알 수 없음'; +}; interface ApprovalCancelProps { - useFakeData?: boolean; - systemId?: string; initialApInfId?: string; onCancelSuccess?: (apInfId: string) => void; } export default function ApprovalCancel({ - useFakeData = false, - systemId = 'EVCP_SYSTEM', initialApInfId = '', onCancelSuccess }: ApprovalCancelProps) { @@ -50,9 +60,7 @@ export default function ApprovalCancel({ setCancelResult(null); try { - const response = useFakeData - ? await mockApprovalAPI.getApprovalDetail(apInfId) - : await getApprovalDetail(apInfId, systemId); + const response = await getApprovalDetail(apInfId); if (response.result === 'SUCCESS') { setApprovalDetail(response.data); @@ -75,9 +83,7 @@ export default function ApprovalCancel({ setIsCancelling(true); try { - const response = useFakeData - ? await mockApprovalAPI.cancelApproval(approvalDetail.apInfId) - : await cancelApproval(approvalDetail.apInfId, systemId); + const response = await cancelApproval(approvalDetail.apInfId); if (response.result === 'SUCCESS') { setCancelResult({ apInfId: response.data.apInfId }); @@ -154,14 +160,14 @@ export default function ApprovalCancel({ }; return ( - + 결재 취소 - 결재 ID를 입력하여 상신을 취소합니다. {useFakeData && '(테스트 모드)'} + 상신한 결재를 취소합니다. diff --git a/components/knox/approval/ApprovalDetail.tsx b/components/knox/approval/ApprovalDetail.tsx index 6db43cbe..d6c883cb 100644 --- a/components/knox/approval/ApprovalDetail.tsx +++ b/components/knox/approval/ApprovalDetail.tsx @@ -14,12 +14,37 @@ import { Loader2, Search, FileText, Clock, User, AlertCircle } from 'lucide-reac 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'; +// 상태/역할 텍스트 매핑 (mock util 대체) +const getStatusText = (status: string) => { + const map: Record = { + '-3': '암호화실패', + '-2': '암호화중', + '-1': '예약상신', + '0': '보류', + '1': '진행중', + '2': '완결', + '3': '반려', + '4': '상신취소', + '5': '전결', + '6': '후완결', + }; + return map[status] || status; +}; + +const getRoleText = (role: string) => { + const map: Record = { + '0': '기안', + '1': '결재', + '2': '합의', + '3': '후결', + '4': '병렬합의', + '7': '병렬결재', + '9': '통보', + }; + return map[role] || role; +}; interface ApprovalDetailProps { - useFakeData?: boolean; - systemId?: string; initialApInfId?: string; } @@ -38,8 +63,6 @@ interface ApprovalAttachment { } export default function ApprovalDetail({ - useFakeData = false, - systemId = 'EVCP_SYSTEM', initialApInfId = '' }: ApprovalDetailProps) { const [apInfId, setApInfId] = useState(initialApInfId); @@ -59,12 +82,8 @@ export default function ApprovalDetail({ try { const [detailResponse, contentResponse] = await Promise.all([ - useFakeData - ? mockApprovalAPI.getApprovalDetail(id) - : getApprovalDetail(id, systemId), - useFakeData - ? mockApprovalAPI.getApprovalContent(id) - : getApprovalContent(id, systemId) + getApprovalDetail(id), + getApprovalContent(id) ]); if (detailResponse.result === 'SUCCESS' && contentResponse.result === 'SUCCESS') { @@ -146,11 +165,11 @@ export default function ApprovalDetail({ // 2) fileId + 별도 엔드포인트 조합 (가이드에 명시되지 않았으므로 best-effort 처리) if (attachment.fileId) { - const url = `${process.env.KNOX_API_BASE_URL}/approval/api/v2.0/attachments/${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': systemId, + 'System-ID': process.env.NEXT_PUBLIC_KNOX_SYSTEM_ID || '', }, }); if (!resp.ok) throw new Error('다운로드 실패'); @@ -177,17 +196,17 @@ export default function ApprovalDetail({ if (initialApInfId) { fetchApprovalDetail(initialApInfId); } - }, [initialApInfId, useFakeData, systemId]); + }, [initialApInfId]); return ( - + 결재 상세 조회 - 결재 ID를 입력하여 상세 정보를 조회합니다. {useFakeData && '(테스트 모드)'} + 결재 ID를 입력하여 상세 정보를 조회합니다. @@ -354,7 +373,7 @@ export default function ApprovalDetail({
- {getApprovalStatusText(apln.aplnStatsCode)} + {getStatusText(apln.aplnStatsCode)}
@@ -384,7 +403,8 @@ export default function ApprovalDetail({

첨부파일

- {approvalData.detail.attachments.map((attachment: ApprovalAttachment, index: number) => ( + {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */} + {approvalData.detail.attachments.map((attachment: any, index: number) => (
diff --git a/components/knox/approval/ApprovalList.tsx b/components/knox/approval/ApprovalList.tsx index 7f80e74a..3a766901 100644 --- a/components/knox/approval/ApprovalList.tsx +++ b/components/knox/approval/ApprovalList.tsx @@ -12,12 +12,24 @@ import { Loader2, List, Eye, RefreshCw, AlertCircle } from 'lucide-react'; 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'; +// 상태 텍스트 매핑 (mock util 대체) +const getStatusText = (status: string) => { + const map: Record = { + '-3': '암호화실패', + '-2': '암호화중', + '-1': '예약상신', + '0': '보류', + '1': '진행중', + '2': '완결', + '3': '반려', + '4': '상신취소', + '5': '전결', + '6': '후완결', + }; + return map[status] || '알 수 없음'; +}; interface ApprovalListProps { - useFakeData?: boolean; - systemId?: string; type?: 'submission' | 'history'; onItemClick?: (apInfId: string) => void; } @@ -35,8 +47,6 @@ type ListItem = { }; export default function ApprovalList({ - useFakeData = false, - systemId = 'EVCP_SYSTEM', type = 'submission', onItemClick }: ApprovalListProps) { @@ -52,17 +62,13 @@ export default function ApprovalList({ let response: SubmissionListResponse | ApprovalHistoryResponse; if (type === 'submission') { - response = useFakeData - ? await mockApprovalAPI.getSubmissionList() - : await getSubmissionList(systemId); + response = await getSubmissionList(); } else { - response = useFakeData - ? await mockApprovalAPI.getApprovalHistory() - : await getApprovalHistory(systemId); + response = await getApprovalHistory(); } if (response.result === 'SUCCESS') { - setListData(response.data); + setListData(response.data as unknown as ListItem[]); } else { setError('목록을 가져오는데 실패했습니다.'); toast.error('목록을 가져오는데 실패했습니다.'); @@ -142,10 +148,10 @@ export default function ApprovalList({ // 컴포넌트 마운트 시 데이터 로드 useEffect(() => { fetchData(); - }, [type, useFakeData, systemId]); + }, [type]); return ( - + @@ -155,7 +161,7 @@ export default function ApprovalList({ {type === 'submission' ? '상신한 결재 목록을 확인합니다.' : '결재 처리 이력을 확인합니다.' - } {useFakeData && '(테스트 모드)'} + } diff --git a/components/knox/approval/ApprovalManager.tsx b/components/knox/approval/ApprovalManager.tsx index cac534c4..89450445 100644 --- a/components/knox/approval/ApprovalManager.tsx +++ b/components/knox/approval/ApprovalManager.tsx @@ -4,8 +4,6 @@ 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'; @@ -16,18 +14,13 @@ 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) => { @@ -45,12 +38,8 @@ export default function ApprovalManager({ setCurrentTab('detail'); }; - const handleTestModeChange = (checked: boolean) => { - setIsTestMode(checked); - }; - return ( -
+
{/* 헤더 */} @@ -65,26 +54,15 @@ export default function ApprovalManager({
-
-
- - -
- {isTestMode && ( - - 테스트 모드 활성화 - - )} -
+ {/* 좌측 영역 - 현재는 테스트 모드 UI 제거로 여백 유지 */} +
-
- 시스템 ID: - {systemId} -
+ {process.env.NEXT_PUBLIC_KNOX_SYSTEM_ID && ( +
+ 시스템 ID: + {process.env.NEXT_PUBLIC_KNOX_SYSTEM_ID} +
+ )}
@@ -116,50 +94,46 @@ export default function ApprovalManager({ {/* 결재 상신 탭 */} - +
+ +
{/* 결재 상세 조회 탭 */} - +
+ +
{/* 결재 취소 탭 */} - +
+ +
{/* 상신함 탭 */} - +
+ +
{/* 결재 이력 탭 */} - +
+ +
diff --git a/components/knox/approval/ApprovalSubmit.tsx b/components/knox/approval/ApprovalSubmit.tsx index 526a87f3..f3c1fa3d 100644 --- a/components/knox/approval/ApprovalSubmit.tsx +++ b/components/knox/approval/ApprovalSubmit.tsx @@ -1,6 +1,6 @@ 'use client' -import { useState } from 'react'; +import { useState, useEffect } from 'react'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; @@ -8,25 +8,93 @@ 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 { Checkbox } from '@/components/ui/checkbox'; +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'; import { toast } from 'sonner'; -import { Loader2, Plus, Trash2, FileText, AlertCircle } from 'lucide-react'; +import { Loader2, Trash2, FileText, AlertCircle, GripVertical } from 'lucide-react'; + +// dnd-kit imports for drag and drop +import { + DndContext, + closestCenter, + KeyboardSensor, + PointerSensor, + useSensor, + useSensors, + type DragEndEvent, +} from '@dnd-kit/core'; + +// 드래그 이동을 수직 축으로 제한하고, 리스트 영역 밖으로 벗어나지 않도록 하는 modifier +import { + restrictToVerticalAxis, + restrictToParentElement, +} from '@dnd-kit/modifiers'; +import { + arrayMove, + SortableContext, + sortableKeyboardCoordinates, + verticalListSortingStrategy, + useSortable, +} from '@dnd-kit/sortable'; +import { + CSS, +} from '@dnd-kit/utilities'; // API 함수 및 타입 import { submitApproval, submitSecurityApproval, 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'; +// 역할 텍스트 매핑 (기존 mock util 대체) +const getRoleText = (role: string) => { + const map: Record = { + '0': '기안', + '1': '결재', + '2': '합의', + '3': '후결', + '4': '병렬합의', + '7': '병렬결재', + '9': '통보', + }; + return map[role] || role; +}; + +// TiptapEditor 컴포넌트 +import RichTextEditor from '@/components/rich-text-editor/RichTextEditor'; + +// UserSelector 컴포넌트 +import { UserSelector, type UserSelectItem } from '@/components/common/user/user-selector'; +import { useSession } from 'next-auth/react'; + +// UserSelector에서 반환되는 사용자에 epId가 포함될 수 있으므로 확장 타입 정의 +interface ExtendedUserSelectItem extends UserSelectItem { + epId?: string; +} + +// 역할 코드 타입 정의 +type ApprovalRole = '0' | '1' | '2' | '3' | '4' | '7' | '9'; + +// 결재 라인 아이템 타입 정의 (고유 ID 포함) +interface ApprovalLineItem { + id: string; // 내부 고유 식별자 + epId?: string; // Knox 고유 ID (전사 고유) + userId?: string; // DB User PK + emailAddress?: string; + name?: string; // 사용자 이름 + deptName?: string; // 부서명 + role: ApprovalRole; + seq: string; + opinion?: string; +} const formSchema = z.object({ subject: z.string().min(1, '제목은 필수입니다'), contents: z.string().min(1, '내용은 필수입니다'), - contentsType: z.enum(['TEXT', 'HTML', 'MIME']), + contentsType: z.literal('HTML'), docSecuType: z.enum(['PERSONAL', 'CONFIDENTIAL', 'CONFIDENTIAL_STRICT']), urgYn: z.boolean(), importantYn: z.boolean(), @@ -35,8 +103,12 @@ const formSchema = z.object({ sbmLang: z.enum(['ko', 'ja', 'zh', 'en']), timeZone: z.string().default('GMT+9'), aplns: z.array(z.object({ - userId: z.string().min(1, '사용자 ID는 필수입니다'), + id: z.string(), // 고유 식별자 + epId: z.string().optional(), + userId: z.string().optional(), emailAddress: z.string().email('유효한 이메일 주소를 입력해주세요').optional(), + name: z.string().optional(), + deptName: z.string().optional(), role: z.enum(['0', '1', '2', '3', '4', '7', '9']), seq: z.string(), opinion: z.string().optional() @@ -48,25 +120,344 @@ const formSchema = z.object({ 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) { +// Sortable한 결재 라인 컴포넌트 +interface SortableApprovalLineProps { + apln: ApprovalLineItem; + index: number; + form: ReturnType>; + onRemove: () => void; + canRemove: boolean; + selected: boolean; + onSelect: () => void; +} + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +function SortableApprovalLine({ apln, index, form, onRemove, canRemove, selected, onSelect }: SortableApprovalLineProps) { + const { + attributes, + listeners, + setNodeRef, + transform, + transition, + isDragging, + } = useSortable({ id: apln.id }); // 고유 ID 사용 + + const style = { + transform: CSS.Transform.toString(transform), + transition, + opacity: isDragging ? 0.5 : 1, // 드래그 중일 때 투명도 조절 + }; + + + return ( +
+ {/* 드래그 핸들 */} +
+ +
+ + {/* 선택 체크박스 (상신자는 제외하지만 공간은 확보) */} + {index !== 0 ? ( + onSelect()} + onClick={(e) => e.stopPropagation()} + /> + ) : ( +
// 기안자용 빈 공간 (체크박스가 없으므로) + )} + + {/* 실제 seq 기준 표시 */} + {parseInt(apln.seq) + 1} + +
+ {/* 사용자 정보 표시 */} +
+
+
+ {(apln.name || 'Knox 이름 없음')}{apln.deptName ? ` / ${apln.deptName}` : ''} +
+
+ ( + + + + + + + )} + /> + ( + + + + + + + )} + /> + ( + + + + + + + )} + /> + ( + + + + + + + )} + /> +
+ + {/* 역할 선택 */} + {index === 0 ? ( + // 상신자는 역할 선택 대신 고정 표시 +
+ 기안 +
+ ) : ( + { + // 병렬 여부 판단 + const isParallel = field.value === '4' || field.value === '7'; + + // 병렬, 후결 값을 제외한 기본 역할 + const baseRole: ApprovalRole = field.value === '7' ? '1' : field.value === '4' ? '2' : field.value === '3' ? '1' : field.value as ApprovalRole; + + // 기본 역할 변경 핸들러 + const handleBaseRoleChange = (val: string) => { + if (!val) return; + let newRole = val; + if (isParallel) { + if (val === '1') newRole = '7'; + else if (val === '2') newRole = '4'; + } + field.onChange(newRole); + }; + + // 병렬인 경우 한 개 버튼으로 표시 + if (isParallel) { + return ( + + + {getRoleText(field.value)} + + + ); + } + + return ( + +
+ + 결재 + 합의 + 통보 + +
+ +
+ ); + }} + /> + )} + + {/* 의견 입력란 제거됨 */} + + {/* 역할 표시 */} +
+ + {getRoleText(apln.role)} + + + {canRemove && ( + + )} +
+
+
+ ); +} + +// Sortable Approval Group (seq 단위 카드) +interface SortableApprovalGroupProps { + group: ApprovalLineItem[]; // 동일 seq 항목들 + index: number; + form: ReturnType>; + onRemoveGroup: () => void; + canRemove: boolean; + selected: boolean; + onSelect: () => void; +} + +function SortableApprovalGroup({ group, index, form, onRemoveGroup, canRemove, selected, onSelect }: SortableApprovalGroupProps) { + const seq = group[0].seq; + const role = group[0].role; + // 그룹을 식별할 안정적인 고유 키(첫 구성원의 id 활용) + const groupKey = group[0].id; + + const { + attributes, + listeners, + setNodeRef, + transform, + transition, + isDragging, + } = useSortable({ id: groupKey }); + + const style = { + transform: CSS.Transform.toString(transform), + transition, + opacity: isDragging ? 0.5 : 1, + }; + + return ( +
+ {/* 드래그 핸들 */} +
+ +
+ + {/* 그룹 선택 체크박스 (상신자 제외하지만 공간은 확보) */} + {index !== 0 ? ( + e.stopPropagation()} + /> + ) : ( +
// 기안자용 빈 공간 + )} + + {/* seq 표시 */} + {parseInt(seq) + 1} + + {/* 그룹 상세 정보 */} +
+ {/* 사용자 목록 */} +
+ {group.map((u) => ( +
+ {(u.name || 'Knox 이름 없음')}{u.deptName ? ` / ${u.deptName}` : ''} +
+ ))} +
+ + {/* 역할 */} +
+ {seq === '0' ? ( + + 기안 + + ) : role === '7' || role === '4' ? ( + + {getRoleText(role)} + + ) : ( + // 단일일 때는 기존 토글 재사용 (첫 항목 기준) + a.id === group[0].id)}.role`} + render={({ field }) => ( + + 결재 + 합의 + 통보 + + )} + /> + )} +
+ + {/* 삭제 버튼 */} +
+ {canRemove && ( + + )} +
+
+
+ ); +} + +export default function ApprovalSubmit({ onSubmitSuccess }: ApprovalSubmitProps) { + const { data: session } = useSession(); const [isSubmitting, setIsSubmitting] = useState(false); const [submitResult, setSubmitResult] = useState<{ apInfId: string } | null>(null); + const [selectedSeqs, setSelectedSeqs] = useState([]); + + // 그룹 단위 선택/해제 + const toggleSelectGroup = (seq: string) => { + setSelectedSeqs((prev) => + prev.includes(seq) ? prev.filter((s) => s !== seq) : [...prev, seq] + ); + }; + const clearSelection = () => setSelectedSeqs([]); + const form = useForm({ resolver: zodResolver(formSchema), defaultValues: { subject: '', contents: '', - contentsType: 'TEXT', + contentsType: 'HTML', docSecuType: 'PERSONAL', urgYn: false, importantYn: false, @@ -74,109 +465,342 @@ export default function ApprovalSubmit({ docMngSaveCode: '0', sbmLang: 'ko', timeZone: 'GMT+9', - aplns: [ - { - userId: '', - emailAddress: '', - role: '0', - seq: '1', - opinion: '' - } - ], + aplns: [], attachments: undefined } }); 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 applyParallel = () => { + if (selectedSeqs.length < 2) { + toast.error('두 명 이상 선택해야 병렬 지정이 가능합니다.'); + return; + } + + const current = form.getValues('aplns'); + const selectedAplns = current.filter((a) => selectedSeqs.includes(a.seq)); + + const roles = Array.from(new Set(selectedAplns.map((a) => a.role))); + if (roles.length !== 1) { + toast.error('선택된 항목의 역할이 동일해야 합니다.'); + return; + } + + const role = roles[0]; + let newRole: ApprovalRole; + if (role === '1') { + newRole = '7'; // 병렬 결재 + } else if (role === '2') { + newRole = '4'; // 병렬 합의 + } else if (role === '9') { + newRole = '9'; // 병렬 통보(역할 코드 유지) + } else { + toast.error('결재, 합의 또는 통보만 병렬 지정 가능합니다.'); + return; + } + + const minSeq = Math.min(...selectedAplns.map((a) => parseInt(a.seq))); + + const updated = current.map((a) => { + if (selectedSeqs.includes(a.seq)) { + return { ...a, role: newRole as ApprovalRole, seq: minSeq.toString() }; + } + return a; + }); + + form.setValue('aplns', reorderBySeq(updated), { shouldDirty: true }); + clearSelection(); + }; + + // 후결 전환 핸들러 + const applyAfter = () => { + if (selectedSeqs.length !== 1) { + toast.error('후결은 한 명만 지정할 수 있습니다.'); + return; + } + + const targetSeq = selectedSeqs[0]; + + // 병렬 그룹(결재:7, 합의:4)은 후결 전환 불가 + const targetRole = form.getValues('aplns').find((a) => a.seq === targetSeq)?.role; + if (targetRole === '7' || targetRole === '4') { + toast.error('병렬 그룹은 후결로 전환할 수 없습니다.'); + return; + } + + const updated = form.getValues('aplns').map((a) => { + if (a.seq === targetSeq) { + return { ...a, role: (a.role === '3' ? '1' : '3') as ApprovalRole }; + } + return a; + }); + + form.setValue('aplns', reorderBySeq(updated), { shouldDirty: true }); + clearSelection(); + }; + + // 병렬 해제 핸들러 + const ungroupParallel = () => { + if (selectedSeqs.length === 0) { + toast.error('해제할 결재선을 선택하세요.'); + return; + } + + let newSeqCounter = 1; // 0은 상신자 유지 + const updated = form.getValues('aplns').map((a) => { + if (selectedSeqs.includes(a.seq)) { + let newRole: ApprovalRole = a.role; + if (a.role === '7') newRole = '1'; + if (a.role === '4') newRole = '2'; + + return { ...a, role: newRole, seq: '' }; // seq 임시 비움 + } + return { ...a }; + }); + + // seq 재할당 (상신자 제외하고 순차) + const reassigned = updated + .sort((x, y) => parseInt(x.seq || '0') - parseInt(y.seq || '0')) + .map((a) => { + if (a.seq === '0') return a; // 상신자 + const newItem = { ...a, seq: newSeqCounter.toString() }; + newSeqCounter += 1; + return newItem; + }); + + form.setValue('aplns', reassigned as FormData['aplns'], { shouldDirty: true }); + clearSelection(); + }; + + // seq 기준 정렬 및 재번호 부여 (병렬 그룹은 동일 seq 유지) + const reorderBySeq = (list: FormData['aplns']): FormData['aplns'] => { + const sorted = [...list].sort((a, b) => parseInt(a.seq) - parseInt(b.seq)); + + // 기존 seq -> 새 seq 매핑. 병렬 그룹(동일 seq)은 동일한 새 seq 를 갖도록 처리 + const seqMap = new Map(); + let nextSeq = 0; + + return sorted.map((apln) => { + if (!seqMap.has(apln.seq)) { + seqMap.set(apln.seq, nextSeq.toString()); + nextSeq += 1; + } + return { ...apln, seq: seqMap.get(apln.seq)! }; + }); + }; + + // 로그인 사용자를 첫 번째 결재자로 보장하는 effect + useEffect(() => { + if (!session?.user) return; + + const currentEmail = session.user.email ?? ''; + const currentEpId = (session.user as { epId?: string }).epId; + const currentUserId = session.user.id ?? undefined; + + let currentAplns = form.getValues('aplns'); + + // 이미 포함되어 있는지 확인 (epId 또는 email 기준) + const selfIndex = currentAplns.findIndex( + (a) => (currentEpId && a.epId === currentEpId) || a.emailAddress === currentEmail + ); + + if (selfIndex === -1) { + // 맨 앞에 상신자 추가 + const newSelf: FormData['aplns'][number] = { + id: generateUniqueId(), + epId: currentEpId, + userId: currentUserId ? currentUserId.toString() : undefined, + emailAddress: currentEmail, + name: session.user.name ?? undefined, + role: '0', // 기안 + seq: '0', + opinion: '' + }; + + currentAplns = [newSelf, ...currentAplns]; + } + + // seq 재정렬 보장 + currentAplns = currentAplns.map((apln, idx) => ({ ...apln, seq: idx.toString() })); + + form.setValue('aplns', currentAplns, { shouldValidate: false, shouldDirty: true }); + }, [session, form]); + + // dnd-kit sensors + const sensors = useSensors( + useSensor(PointerSensor, { + activationConstraint: { + distance: 8, + }, + }), + useSensor(KeyboardSensor, { + coordinateGetter: sortableKeyboardCoordinates, + }) + ); + + // 고유 ID 생성 함수 + const generateUniqueId = () => { + return `apln-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; + }; + + // 결재자 추가 (UserSelector를 통해) + const addApprovalUsers = (users: UserSelectItem[]) => { + const newAplns = [...aplns]; + + users.forEach((user) => { + // 이미 추가된 사용자인지 확인 + const existingIndex = newAplns.findIndex(apln => apln.userId === user.id.toString()); + if (existingIndex === -1) { + // 새 사용자 추가 + const newSeq = (newAplns.length).toString(); // 0은 상신자 + const newApln: FormData['aplns'][number] = { + id: generateUniqueId(), // 고유 ID 생성 + epId: (user as ExtendedUserSelectItem).epId, // epId가 전달되면 사용 + userId: user.id.toString(), + emailAddress: user.email, + name: user.name, + deptName: (user as ExtendedUserSelectItem).deptName ?? undefined, + role: '1', // 기본값: 결재 + seq: newSeq, + opinion: '' + }; + newAplns.push(newApln); + } + }); + + form.setValue('aplns', newAplns); + }; + + // 그룹 삭제 (seq 기반) + const removeApprovalGroup = (seq: string) => { + if (seq === '0') return; // 상신자 삭제 불가 + + const remaining = aplns.filter((a) => a.seq !== seq); + + // seq 재정렬 (병렬 그룹 유지) + const reordered = reorderBySeq(remaining); + form.setValue('aplns', reordered); }; + // 기존 단일 삭제 로직은 더 이상 사용하지 않음 (호환 위해 남겨둠) + // eslint-disable-next-line @typescript-eslint/no-unused-vars const removeApprovalLine = (index: number) => { + // 첫 번째(상신자)는 삭제 불가 + if (index === 0) return; + if (aplns.length > 1) { - const newAplns = aplns.filter((_, i) => i !== index); - // 순서 재정렬 - const reorderedAplns = newAplns.map((apln, i) => ({ + const newAplns = aplns.filter((_: FormData['aplns'][number], i: number) => i !== index); + // 순서 재정렬 (ID는 유지) + const reorderedAplns = newAplns.map((apln: FormData['aplns'][number], i: number) => ({ ...apln, - seq: (i + 1).toString() + seq: (i).toString() })); form.setValue('aplns', reorderedAplns); } }; + // 드래그앤드롭 핸들러 (그룹 이동 지원) + const handleDragEnd = (event: DragEndEvent) => { + const { active, over } = event; + + if (!over || active.id === over.id) return; + + // 현재 id는 그룹의 고유 key(첫 라인 id) + const activeKey = active.id as string; + const overKey = over.id as string; + + // key → seq 매핑 생성 + const idToSeq = new Map(); + aplns.forEach((a) => { + // 같은 seq 내 첫 번째 id만 매핑하면 충분하지만, 안전하게 모두 매핑 + idToSeq.set(a.id, a.seq); + }); + + const activeSeq = idToSeq.get(activeKey); + const overSeq = idToSeq.get(overKey); + + if (!activeSeq || !overSeq) return; + + if (activeSeq === '0' || overSeq === '0') return; // 상신자는 이동 불가 + + // 현재 그룹 순서를 key 기반으로 계산 + const seqOrder = Array.from(new Set(aplns.map((a) => a.seq))); + const keyOrder = seqOrder.map((seq) => { + return aplns.find((a) => a.seq === seq)!.id; + }); + + const oldIndex = keyOrder.indexOf(activeKey); + const newIndex = keyOrder.indexOf(overKey); + + const newKeyOrder = arrayMove(keyOrder, oldIndex, newIndex); + + // key → 새 seq 매핑 + const keyToNewSeq = new Map(); + newKeyOrder.forEach((k, idx) => { + keyToNewSeq.set(k, idx.toString()); + }); + + // aplns 재구성 + seq 재할당 + const updatedAplns: FormData['aplns'] = []; + newKeyOrder.forEach((k) => { + const oldSeq = idToSeq.get(k)!; + const groupItems = aplns.filter((a) => a.seq === oldSeq); + groupItems.forEach((item) => { + updatedAplns.push({ ...item, seq: keyToNewSeq.get(k)! }); + }); + }); + + form.setValue('aplns', updatedAplns, { shouldValidate: false, shouldDirty: true }); + }; + const onSubmit = async (data: FormData) => { setIsSubmitting(true); setSubmitResult(null); try { - // 결재 경로 생성 + // 결재 경로 생성 (ID 제거하고 API 호출) 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 } - ); - } - }) + data.aplns.map((apln) => + createApprovalLine( + // userId: apln.userId 는 불필요하므로 제거 + { epId: apln.epId, emailAddress: apln.emailAddress }, + apln.role, + apln.seq, + { opinion: apln.opinion } + ) + ) ); // 상신 요청 생성 const attachmentsArray = data.attachments ? Array.from(data.attachments as FileList) : undefined; - 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, - attachments: attachmentsArray - } - : 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, - attachments: attachmentsArray - } - ); + const submitRequest: SubmitApprovalRequest = await createSubmitApprovalRequest( + data.contents, + data.subject, + approvalLines, + { + contentsType: 'HTML', + 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, + attachments: attachmentsArray + } + ); // API 호출 (보안 등급에 따라 분기) const isSecure = data.docSecuType === 'CONFIDENTIAL' || data.docSecuType === 'CONFIDENTIAL_STRICT'; - const response = useFakeData - ? await mockApprovalAPI.submitApproval(submitRequest) - : isSecure - ? await submitSecurityApproval(submitRequest, systemId) - : await submitApproval(submitRequest, systemId); + console.log(submitRequest); + + const response = isSecure + ? await submitSecurityApproval(submitRequest) + : await submitApproval(submitRequest); if (response.result === 'SUCCESS') { setSubmitResult({ apInfId: response.data.apInfId }); @@ -195,14 +819,14 @@ export default function ApprovalSubmit({ }; return ( - + 결재 상신 - 새로운 결재를 상신합니다. {useFakeData && '(테스트 모드)'} + 새로운 결재를 상신합니다. @@ -223,7 +847,80 @@ export default function ApprovalSubmit({
{/* 기본 정보 */}
-

기본 정보

+ + + + {/* 결재 경로 */} +
+

결재 경로

+ + {/* 상단 제어 버튼 */} +
+ + + +
+ + {/* 결재자 추가 섹션 */} +
+
+ +

사용자를 검색하여 결재 라인에 추가하세요

+
+ +
+ + {/* 그룹 기반 렌더링 */} + {aplns.length > 0 && ( + (() => { + const groups = Object.values( + aplns.reduce>((acc, apln) => { + acc[apln.seq] = acc[apln.seq] ? [...acc[apln.seq], apln] : [apln]; + return acc; + }, {}) + ).sort((a, b) => parseInt(a[0].seq) - parseInt(b[0].seq)); + + return ( + + g[0].id)} strategy={verticalListSortingStrategy}> +
+ {groups.map((group, idx) => ( + removeApprovalGroup(group[0].seq)} + canRemove={idx !== 0 && aplns.length > 1} + selected={selectedSeqs.includes(group[0].seq)} + onSelect={() => toggleSelectGroup(group[0].seq)} + /> + ))} +
+
+
+ ); + })() + )} + + {aplns.length === 0 && ( +
+ +

결재자를 추가해주세요

+
+ )} +
내용 * -