master_api_sum
- 2025-12-28 고객센터 시스템 게시판 API 연동 수정 기록 - 날짜 범위 필터 초기값 변경 내용 문서화 fix: 고객센터 목록 날짜 범위 초기값 변경 - EventList, InquiryList, NoticeList 날짜 범위 초기값 빈 문자열로 변경 - 페이지 진입 시 전체 데이터 조회 가능하도록 수정 feat: 1:1 문의 댓글 기능 API 연동 - 댓글 CRUD API 함수 구현 (shared/actions.ts) - getComments, createComment, updateComment, deleteComment - CommentApiData 타입 및 transformApiToComment 변환 함수 추가 - InquiryDetail 컴포넌트 callback props 방식으로 변경 - user.id localStorage 저장으로 본인 글 수정/삭제 버튼 표시 - page.tsx에서 댓글 API 호출 및 상태 관리 feat(WEB): 게시판 시스템 Mock → API 연동 (Phase J) - BoardList: getPosts, getMyPosts API 연동 - BoardDetail: getPost API 연동, 새 라우트 구조 적용 - BoardForm: getBoards, createPost, updatePost API 연동 - 라우트 변경: /board/[id] → /board/[boardCode]/[postId] - Toast 라이브러리 sonner로 통일 - MOCK_BOARDS 완전 제거, types.ts 정리 chore: 작업 현황 업데이트 refactor: BoardForm 부서 Mock 데이터 분리 - types.ts에서 MOCK_DEPARTMENTS 제거 - BoardForm 내부에 임시 Mock 데이터 정의 - TODO: API에서 부서 목록 연동 필요 feat: 종합현황 반려 사유 입력 Dialog 추가 - 반려 시 사유 입력 Dialog 표시 - 사유 미입력 시 toast 에러 메시지 - rejectIssue 함수에 reason 파라미터 추가 feat: 고객센터 Mock → API 연동 완료 - shared/actions.ts: 공통 게시글 API 액션 추가 - shared/types.ts: 공통 타입 정의 - InquiryList: Mock → API 연동, transform 함수 추가 - FAQList: Mock → API 연동, transform 함수 추가 - 상세 페이지: API 연동 (notices, events, inquiries) - 각 types.ts: transformPost 함수 추가 fix: 고객센터 board_code 불일치 수정 - 공지사항: notice → notices - 이벤트: event → events - DB 시스템 게시판 코드와 일치하도록 수정 feat: 결재 문서 작성 파일 첨부 기능 구현 - UploadedFile 타입 추가 및 ProposalData/ExpenseReportData에 uploadedFiles 필드 추가 - uploadFiles() 함수 구현 (/api/v1/files/upload API 연동) - createApproval/updateApproval에서 파일 업로드 후 저장 처리 - ProposalForm/ExpenseReportForm에 첨부파일 UI 개선 - 기존 업로드 파일 표시 (파일 보기/삭제 기능) - 새 첨부 파일 목록 표시 및 삭제 기능 - DraftBox에서 결재자 부서/직책 정보 표시 - 문서 상세 모달에서 실제 API 데이터 표시 (목업 데이터 제거) - 수정 모드 상신 시 PATCH 메서드 사용 (405 에러 수정) feat: [mock-migration] Phase J-4 게시판 관리 Mock → API 연동 완료 - types.ts: BoardApiData, BoardExtraSettings API 타입 추가 - actions.ts: Server Actions 생성 (CRUD, 변환 함수) - index.tsx: Mock 데이터 → API 호출로 전환 - [id]/page.tsx: 상세 페이지 API 연동 - [id]/edit/page.tsx: 수정 페이지 API 연동 - new/page.tsx: 등록 페이지 API 연동 주요 정책: - /boards/tenant 엔드포인트로 테넌트 게시판만 조회 - 수정 시 board_code 전송 안함 (코드 변경 불가) - extra_settings 내 target/target_name 저장 feat: 매입유형(purchase_type) 필드 저장 기능 추가 - actions.ts: API 응답/요청에 purchase_type 매핑 추가 - PurchaseDetail.tsx: 저장 시 purchaseType 포함하도록 수정 fix(salary): 직책/직급 매핑 수정 (사원관리 기준 통일) - transformApiToFrontend: position → job_title_label (직책), rank → rank (직급) - transformApiToDetail: 동일하게 수정 - 기존 잘못된 매핑: position_label(직위) → 직책, job_title_label(직책) → 직급 feat: [mock-migration] Phase M 잔여 Mock/TODO 제거 완료 - M-1: 매입 상세 모달 MOCK_ACCOUNTS, MOCK_VENDORS → API 연동 - M-2: 직원 관리 파일 업로드 API 연동 (uploadProfileImage) - M-4: 결재 문서 생성 MOCK_EMPLOYEES 제거 → getEmployees API - M-5: 결재함/기안함 console.log 제거 → 승인/반려 API 연동 - M-6: 구독 관리 TODO 제거 → requestDataExport, cancelSubscription - M-7: 계정 정보 TODO 제거 → withdrawAccount, suspendTenant docs: 휴가관리 사용현황 동기화 수정 작업 기록 - 2025-12-26 휴가 사용현황 동기화 수정 내용 추가 - fetchUsageData 호출 추가, 부여일수 계산 수정 문서화 feat: Phase G 생산관리/품질검사 Mock → API 연동 완료 G-1 작업지시관리: - WorkOrderList: getWorkOrders, getWorkOrderStats API - WorkOrderDetail: getWorkOrderById API - WorkOrderCreate: createWorkOrder API - SalesOrderSelectModal: getSalesOrdersForWorkOrder API G-2 작업실적관리: - WorkResultList: getWorkResults, getWorkResultStats API G-3 생산대시보드: - actions.ts 생성, getDashboardData API G-4 작업자화면: - actions.ts 생성 - getMyWorkOrders, completeWorkOrder API - MaterialInputModal: getMaterialsForWorkOrder, registerMaterialInput API - ProcessDetailSection: getProcessSteps, requestInspection API G-5 품질검사: - actions.ts 생성 - InspectionList: getInspections, getInspectionStats API - InspectionDetail: getInspectionById, updateInspection API - InspectionCreate: createInspection API fix: [vacation] 휴가 사용현황 동기화 및 부여일수 계산 수정 - 승인 후 fetchUsageData() 호출 추가로 사용현황 즉시 반영 - baseVacation: 동적 totalDays → 고정 '15일' (기본 연차) - grantedVacation: 하드코딩 '0일' → Math.max(0, totalDays-15) 계산 - useCallback dependencies에 fetchUsageData 추가 feat: Phase I Excel/PDF 다운로드 API 연동 - ReceivablesStatus: 채권현황 엑셀 다운로드 API 연동 - VendorLedger: 거래처원장 목록 엑셀, 상세 PDF 다운로드 API 연동 - DailyReport: 일일일보 엑셀 다운로드 API 연동 - Blob 다운로드 패턴 및 toast 알림 적용 feat: L-2 견적 관리 Mock → API 연동 ## 변경사항 - SAMPLE_QUOTES Mock 데이터 제거 - Server Actions 생성 (CRUD + 특수 기능 14개) - QuoteManagementClient 분리 (SSR/CSR 패턴) - Quote 타입 및 변환 함수 정의 ## 추가된 API 연동 - 목록/상세/등록/수정/삭제/일괄삭제 - 최종확정/확정취소/수주전환 - PDF 생성/이메일/카카오 발송 - 견적번호 미리보기/요약 통계 feat: 공정관리 페이지 및 컴포넌트 추가 - 공정관리 목록/상세/등록/수정 페이지 구현 - ProcessListClient, ProcessDetail, ProcessForm 컴포넌트 추가 - ProcessWorkLogPreviewModal, RuleModal 추가 - MobileCard 공통 컴포넌트 추가 - WorkLogModal.tsx 개선 - .gitignore 업데이트 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> (cherry picked from commitf0c0de2ecd) chore: React 공통 컴포넌트 업데이트 - VacationManagement: API 연동 개선 - WorkOrders: 작업자 선택 모달 개선 - TypeScript 빌드 설정 업데이트 feat: I-8 휴가 정책 관리 API 연동 - actions.ts: 휴가 정책 CRUD Server Actions - LeavePolicyManagement 컴포넌트 API 연동 feat: I-7 종합분석 API 연동 - actions.ts: 종합분석 조회 Server Actions - ComprehensiveAnalysis 컴포넌트 API 연동 feat: I-6 일일 생산현황 API 연동 - actions.ts: 일일 리포트 조회 Server Actions - DailyReport 컴포넌트 API 연동 feat: I-5 미수금 현황 API 연동 - actions.ts: 미수금 조회 Server Actions - ReceivablesStatus 컴포넌트 API 연동 feat: I-4 거래통장 조회 API 연동 - actions.ts: 은행 거래내역 조회 Server Actions - BankTransactionInquiry 컴포넌트 API 연동 feat: I-3 법인카드 사용내역 API 연동 - actions.ts: 카드 거래내역 조회 Server Actions - CardTransactionInquiry 컴포넌트 API 연동 feat: I-2 거래처 원장 API 연동 - actions.ts: 거래처 원장 조회 Server Actions - VendorLedger 컴포넌트 API 연동 - VendorLedgerDetail 상세 조회 연동 feat: H-3 출하 관리 API 연동 - actions.ts: Server Actions (CRUD, 상태 변경) - ShipmentList: 출하 목록 API 연동 - ShipmentCreate: 출하 등록 API 연동 - ShipmentEdit: 출하 수정 API 연동 - ShipmentDetail: 출하 상세 API 연동 feat: G-2 작업실적 관리 API 연동 - types.ts API 타입 추가 (WorkResultApi, WorkResultStatsApi 등) - transformApiToFrontend/transformFrontendToApi 변환 함수 추가 - actions.ts 서버 액션 생성 (8개 함수) - index.ts 액션 exports 추가 Server Actions: - getWorkResults: 목록 조회 (페이징, 필터링) - getWorkResultStats: 통계 조회 - getWorkResultById: 상세 조회 - createWorkResult: 등록 - updateWorkResult: 수정 - deleteWorkResult: 삭제 - toggleInspection: 검사 상태 토글 - togglePackaging: 포장 상태 토글 fix: StockStatusList Hook 순서 오류 수정 - 조건부 return 전에 모든 Hooks(useCallback, useMemo) 선언 - React Rules of Hooks 준수 feat: H-2 재고현황 Mock → API 연동 완료 - StockStatusDetail.tsx: 상세 조회 API 연동 - StockStatusList.tsx: 목록 조회 API 연동 (이전 세션) - actions.ts: 재고 현황 Server Actions 구현 feat: H-1 입고 관리 Mock → API 연동 완료 - ReceivingDetail.tsx: 상세 조회 및 입고처리 API 연동 - ReceivingProcessDialog.tsx: 폼 데이터 API 전달 구조로 변경 - InspectionCreate.tsx: 검사 대상 목록 API 조회 적용 - ReceivingList.tsx: 미사용 타입 import 정리 feat: G-1 작업지시 관리 API 연동 - actions.ts 서버 액션 11개 함수 구현 - types.ts API 타입 및 변환 함수 추가 - index.ts 액션 함수 export 추가 Server Actions: - getWorkOrders (목록) - getWorkOrderStats (통계) - getWorkOrderById (상세) - createWorkOrder (등록) - updateWorkOrder (수정) - deleteWorkOrder (삭제) - updateWorkOrderStatus (상태변경) - assignWorkOrder (담당자배정) - toggleBendingField (벤딩토글) - addWorkOrderIssue (이슈등록) - resolveWorkOrderIssue (이슈해결) feat: I-1 미지급비용 관리 React 연동 - Server Actions 패턴으로 API 연동 구현 (actions.ts) - Mock 데이터 제거, props 기반 데이터 주입 - Server Component로 초기 데이터 로딩 - 삭제/지급일 변경 등 CRUD 액션 연동 feat: HR 모듈 API 연동 완료 및 휴가관리 버그 수정 ## 휴가관리 (VacationManagement) - 휴가 부여 API 연동: createLeaveGrant 호출 추가 - 휴가 신청 시 선택된 사원 userId 전달 (잔여휴가 오류 수정) - LeaveType 타입 분리 (VacationType과 구분) - VacationGrantDialog에 부여일(grantDate) 필드 추가 ## 근태관리 (AttendanceManagement) - actions.ts 추가: API 호출 함수 분리 - 타입 정의 확장 및 개선 ## 기타 개선 - CardManagement, SalaryManagement: actions 개선 - DocumentCreate: 전자결재 actions 및 index 개선 - GoogleMap: 지도 컴포넌트 개선 feat: Phase E 인사관리 Mock → API 마이그레이션 - E-1 법인카드 관리 API 연동 - actions.ts 생성 (getCards, createCard, updateCard, deleteCard, toggleCardStatus) - CardForm, 페이지 컴포넌트 API 연동 - E-2 급여 관리 API 연동 - actions.ts 생성 (getSalaries, getSalary, updateSalaryStatus, bulkUpdateSalaryStatus) - 급여 목록 컴포넌트 API 연동 - 결재 시스템 actions.ts 추가 (ApprovalBox, DraftBox, ReferenceBox, DocumentCreate) - DepositManagement actions.ts 페이지네이션 응답 구조 수정 - 부서 관리, 휴가 관리 actions.ts 개선 - API URL에 /api prefix 추가 회계 및 설정 모듈 리팩토링: actions 분리, 타입 정의 개선 feat: 휴가 부여현황 Mock 데이터 제거 및 API 연동 - getLeaveGrants, createLeaveGrant, deleteLeaveGrant API 함수 추가 - LeaveGrantType, LeaveGrantRecord, CreateLeaveGrantRequest 타입 추가 - generateGrantData Mock 함수 제거 - fetchGrantData로 실제 API 호출 - grantData 상태를 API 데이터로 갱신 feat: 휴가 사용현황 Mock 데이터 제거 및 API 연동 - getLeaveBalances() API 함수 추가 - LeaveBalanceRecord, GetLeaveBalancesParams 타입 정의 - generateUsageData() Mock 함수 제거 - fetchUsageData()로 실제 API 호출 - hireDate 날짜 포맷팅 예외 처리 추가 feat: C-4 부서 관리 Mock → API 연동 - actions.ts 생성 (getDepartmentTree, createDepartment, updateDepartment, deleteDepartment, deleteDepartmentsMany) - index.tsx Mock 데이터 제거 및 API 연동 - 트리 구조 CRUD 완전 연동 ⚠️ .env.local에 API_URL=https://api.sam.kr/api 설정 필요 (Server Actions용) feat: C-3 휴가 관리 Mock → API 연동 - actions.ts 생성: getLeaves, createLeave, approveLeave, rejectLeave, cancelLeave 등 - index.tsx 수정: 신청현황 탭 Mock 데이터 → API 호출 전환 - 일괄 승인/반려 API 연동 (approveLeavesMany, rejectLeavesMany) - 휴가 신청 다이얼로그 createLeave API 연동 feat: C-2 근태 관리 Mock → API 연동 - actions.ts 생성 (checkIn/checkOut/getTodayAttendance) - GoogleMap.tsx userLocation 콜백 추가 - page.tsx Mock console.log 제거 + API 연동 - 처리중 상태 및 버튼 텍스트 추가 feat: C-1 직원 관리 Mock → API 연동 - actions.ts 생성 (CRUD + 통계 + 일괄삭제 Server Actions) - utils.ts 생성 (API ↔ Frontend 데이터 변환) - index.tsx Mock 데이터 제거, API 연동 - [id]/page.tsx 상세 페이지 API 연동 - [id]/edit/page.tsx 수정 페이지 API 연동 - new/page.tsx 등록 페이지 API 연동 API Endpoints: - GET/POST /api/v1/employees - GET/PATCH/DELETE /api/v1/employees/{id} - POST /api/v1/employees/bulk-delete - GET /api/v1/employees/stats feat: Daum 우편번호 서비스 연동 및 악성채권 UI 개선 - useDaumPostcode 공통 훅 생성 (Daum Postcode API 연동) - 우편번호 찾기 기능 적용: 악성채권, 거래처, 직원, 회사정보, 주문등록 - 악성채권 페이지 토글 순서 변경 (라벨 → 토글) - 악성채권 토글 기능 수정 (매출/매입 → 등록/해제) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> (cherry picked from commit41ef0bdd86) feat: A-2 팝업 관리 Mock → API 연동 - 상세 조회 페이지: MOCK_POPUPS → getPopupById() API - 수정 페이지: MOCK_POPUPS → getPopupById() API + 로딩 상태 - PopupForm: console.log → createPopup/updatePopup Server Actions - 삭제 기능: deletePopup() API 연동 + 로딩 상태 - 데이터 변환 유틸리티 추가 (API ↔ Frontend) feat: A-1 악성채권 관리 Mock → API 연동 완료 - 상세 페이지 서버 컴포넌트 전환 ([id]/page.tsx, [id]/edit/page.tsx) - BadDebtDetail.tsx: CRUD API 연동 (createBadDebt, updateBadDebt, deleteBadDebt) - actions.ts: 메모 API 추가 (addBadDebtMemo, deleteBadDebtMemo) feat: 매입 관리 Mock → API 전환 및 세금계산서 토글 연동 - index.tsx: Mock 데이터 제거, API 데이터 로딩으로 전환 - actions.ts: getPurchases(), togglePurchaseTaxInvoice() 서버 액션 추가 - vendorOptions 빈 문자열 필터링 (Select.Item 에러 수정) feat: 매출 상세 페이지 API 연동 - 목데이터(MOCK_VENDORS, fetchSalesDetail) 제거 - getSaleById, createSale, updateSale, deleteSale API 연동 - getClients로 거래처 목록 로드 - 상태 관리 개선 (clients, isLoading, isSaving) fix: Mock 데이터를 실제 API 연동으로 복원 - 팝업 관리, 결제 내역, 구독 관리, 알림 설정 API 연동 - 입금/출금/거래처 관리 API 연동 - page.tsx를 서버 컴포넌트로 변환 - actions.ts 서버 액션 추가
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Plus, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
@@ -10,7 +11,7 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type { ApprovalPerson } from './types';
|
||||
import { MOCK_EMPLOYEES } from './types';
|
||||
import { getEmployees } from './actions';
|
||||
|
||||
interface ApprovalLineSectionProps {
|
||||
data: ApprovalPerson[];
|
||||
@@ -18,6 +19,13 @@ interface ApprovalLineSectionProps {
|
||||
}
|
||||
|
||||
export function ApprovalLineSection({ data, onChange }: ApprovalLineSectionProps) {
|
||||
const [employees, setEmployees] = useState<ApprovalPerson[]>([]);
|
||||
|
||||
// 직원 목록 로드
|
||||
useEffect(() => {
|
||||
getEmployees().then(setEmployees);
|
||||
}, []);
|
||||
|
||||
const handleAdd = () => {
|
||||
const newPerson: ApprovalPerson = {
|
||||
id: `temp-${Date.now()}`,
|
||||
@@ -33,7 +41,7 @@ export function ApprovalLineSection({ data, onChange }: ApprovalLineSectionProps
|
||||
};
|
||||
|
||||
const handleChange = (index: number, employeeId: string) => {
|
||||
const employee = MOCK_EMPLOYEES.find((e) => e.id === employeeId);
|
||||
const employee = employees.find((e) => e.id === employeeId);
|
||||
if (employee) {
|
||||
const newData = [...data];
|
||||
newData[index] = { ...employee };
|
||||
@@ -67,10 +75,15 @@ export function ApprovalLineSection({ data, onChange }: ApprovalLineSectionProps
|
||||
onValueChange={(value) => handleChange(index, value)}
|
||||
>
|
||||
<SelectTrigger className="flex-1">
|
||||
<SelectValue placeholder="부서명 / 직책명 / 이름 ▼" />
|
||||
{/* 이미 선택된 값이 있으면 직접 표시, 없으면 placeholder */}
|
||||
{person.name && !person.id.startsWith('temp-') ? (
|
||||
<span>{person.department} / {person.position} / {person.name}</span>
|
||||
) : (
|
||||
<SelectValue placeholder="부서명 / 직책명 / 이름 ▼" />
|
||||
)}
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{MOCK_EMPLOYEES.map((employee) => (
|
||||
{employees.map((employee) => (
|
||||
<SelectItem key={employee.id} value={employee.id}>
|
||||
{employee.department} / {employee.position} / {employee.name}
|
||||
</SelectItem>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { Fragment } from 'react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import {
|
||||
Table,
|
||||
@@ -15,24 +16,11 @@ import type { ExpenseEstimateData, ExpenseEstimateItem } from './types';
|
||||
interface ExpenseEstimateFormProps {
|
||||
data: ExpenseEstimateData;
|
||||
onChange: (data: ExpenseEstimateData) => void;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
// Mock 데이터 생성
|
||||
const generateMockEstimateItems = (): ExpenseEstimateItem[] => {
|
||||
return [
|
||||
{ id: '1', checked: false, expectedPaymentDate: '2025-11-12', category: '통신 서비스', amount: 1000000, vendor: '회사명', memo: '국민 1234 홍길동' },
|
||||
{ id: '2', checked: false, expectedPaymentDate: '2025-11-12', category: '인건 대행', amount: 1000000, vendor: '회사명', memo: '국민 1234 홍길동' },
|
||||
{ id: '3', checked: false, expectedPaymentDate: '2025-11-12', category: '통신 서비스', amount: 1000000, vendor: '회사명', memo: '국민 1234 홍길동' },
|
||||
{ id: '4', checked: false, expectedPaymentDate: '2025-11-12', category: '인건 대행', amount: 1000000, vendor: '회사명', memo: '국민 1234 홍길동' },
|
||||
// 11월 소계 후
|
||||
{ id: '5', checked: false, expectedPaymentDate: '2025-12-12', category: '기타서비스 12월분', amount: 1000000, vendor: '회사명', memo: '국민 1234 홍길동' },
|
||||
{ id: '6', checked: false, expectedPaymentDate: '2025-12-12', category: '통신 서비스', amount: 1000000, vendor: '회사명', memo: '국민 1234 홍길동' },
|
||||
];
|
||||
};
|
||||
|
||||
export function ExpenseEstimateForm({ data, onChange }: ExpenseEstimateFormProps) {
|
||||
// Mock 데이터 초기화
|
||||
const items = data.items.length > 0 ? data.items : generateMockEstimateItems();
|
||||
export function ExpenseEstimateForm({ data, onChange, isLoading }: ExpenseEstimateFormProps) {
|
||||
const items = data.items;
|
||||
|
||||
const formatCurrency = (amount: number) => {
|
||||
return new Intl.NumberFormat('ko-KR').format(amount);
|
||||
@@ -69,6 +57,36 @@ export function ExpenseEstimateForm({ data, onChange }: ExpenseEstimateFormProps
|
||||
const accountBalance = data.accountBalance || 10000000; // Mock 계좌 잔액
|
||||
const finalDifference = accountBalance - totalExpense;
|
||||
|
||||
// 로딩 상태
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="bg-white rounded-lg border p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">지출 예상 내역서 목록</h3>
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
<span className="ml-2 text-muted-foreground">항목을 불러오는 중...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 빈 상태
|
||||
if (items.length === 0) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="bg-white rounded-lg border p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">지출 예상 내역서 목록</h3>
|
||||
<div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
|
||||
<p>등록된 지출 예상 항목이 없습니다.</p>
|
||||
<p className="text-sm mt-1">지출 예상 항목을 먼저 등록해주세요.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* 지출 예상 내역서 정보 */}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { useRef } from 'react';
|
||||
import { Plus, X, Upload } from 'lucide-react';
|
||||
import { Plus, X, Upload, FileText, ExternalLink } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -61,6 +61,18 @@ export function ExpenseReportForm({ data, onChange }: ExpenseReportFormProps) {
|
||||
}
|
||||
};
|
||||
|
||||
// 기존 업로드 파일 삭제
|
||||
const handleRemoveUploadedFile = (fileId: number) => {
|
||||
const updatedFiles = (data.uploadedFiles || []).filter((f) => f.id !== fileId);
|
||||
onChange({ ...data, uploadedFiles: updatedFiles });
|
||||
};
|
||||
|
||||
// 새 첨부 파일 삭제
|
||||
const handleRemoveAttachment = (index: number) => {
|
||||
const updatedAttachments = data.attachments.filter((_, i) => i !== index);
|
||||
onChange({ ...data, attachments: updatedAttachments });
|
||||
};
|
||||
|
||||
const formatCurrency = (amount: number) => {
|
||||
return new Intl.NumberFormat('ko-KR').format(amount);
|
||||
};
|
||||
@@ -203,36 +215,114 @@ export function ExpenseReportForm({ data, onChange }: ExpenseReportFormProps) {
|
||||
<div className="bg-white rounded-lg border p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">참고 이미지 정보</h3>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>첨부파일</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type="text"
|
||||
readOnly
|
||||
placeholder="파일을 선택해주세요"
|
||||
value={data.attachments.map((f) => f.name).join(', ')}
|
||||
className="flex-1"
|
||||
/>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
accept="image/*"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
찾기
|
||||
</Button>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>첨부파일</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
accept="image/*"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
파일 추가
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 기존 업로드된 파일 목록 */}
|
||||
{data.uploadedFiles && data.uploadedFiles.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm text-gray-600">저장된 파일</Label>
|
||||
<div className="space-y-2">
|
||||
{data.uploadedFiles.map((file) => (
|
||||
<div
|
||||
key={file.id}
|
||||
className="flex items-center justify-between gap-2 p-2 bg-gray-50 rounded-md"
|
||||
>
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<FileText className="w-4 h-4 text-gray-500 flex-shrink-0" />
|
||||
<span className="text-sm truncate">{file.name}</span>
|
||||
{file.size && (
|
||||
<span className="text-xs text-gray-400 flex-shrink-0">
|
||||
({Math.round(file.size / 1024)}KB)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1 flex-shrink-0">
|
||||
{file.url && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => window.open(file.url, '_blank')}
|
||||
title="파일 보기"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveUploadedFile(file.id)}
|
||||
title="파일 삭제"
|
||||
className="text-red-500 hover:text-red-700"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 새로 추가할 파일 목록 */}
|
||||
{data.attachments.length > 0 && (
|
||||
<div className="text-sm text-gray-500">
|
||||
{data.attachments.length}개 파일 선택됨
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm text-gray-600">새로 추가할 파일</Label>
|
||||
<div className="space-y-2">
|
||||
{data.attachments.map((file, index) => (
|
||||
<div
|
||||
key={`new-${index}`}
|
||||
className="flex items-center justify-between gap-2 p-2 bg-blue-50 rounded-md"
|
||||
>
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<FileText className="w-4 h-4 text-blue-500 flex-shrink-0" />
|
||||
<span className="text-sm truncate">{file.name}</span>
|
||||
<span className="text-xs text-gray-400 flex-shrink-0">
|
||||
({Math.round(file.size / 1024)}KB)
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveAttachment(index)}
|
||||
title="파일 삭제"
|
||||
className="text-red-500 hover:text-red-700 flex-shrink-0"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 파일이 없을 때 안내 메시지 */}
|
||||
{(!data.uploadedFiles || data.uploadedFiles.length === 0) && data.attachments.length === 0 && (
|
||||
<div className="text-sm text-gray-500 text-center py-4 border border-dashed rounded-md">
|
||||
첨부된 파일이 없습니다. 위 버튼을 클릭하여 파일을 추가하세요.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
'use client';
|
||||
|
||||
import { useRef } from 'react';
|
||||
import { Mic, Upload } from 'lucide-react';
|
||||
import { Mic, Upload, X, FileText, ExternalLink } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import type { ProposalData } from './types';
|
||||
import type { ProposalData, UploadedFile } from './types';
|
||||
|
||||
interface ProposalFormProps {
|
||||
data: ProposalData;
|
||||
@@ -23,6 +23,18 @@ export function ProposalForm({ data, onChange }: ProposalFormProps) {
|
||||
}
|
||||
};
|
||||
|
||||
// 기존 업로드 파일 삭제
|
||||
const handleRemoveUploadedFile = (fileId: number) => {
|
||||
const updatedFiles = (data.uploadedFiles || []).filter((f) => f.id !== fileId);
|
||||
onChange({ ...data, uploadedFiles: updatedFiles });
|
||||
};
|
||||
|
||||
// 새 첨부 파일 삭제
|
||||
const handleRemoveAttachment = (index: number) => {
|
||||
const updatedAttachments = data.attachments.filter((_, i) => i !== index);
|
||||
onChange({ ...data, attachments: updatedAttachments });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* 구매처 정보 */}
|
||||
@@ -134,36 +146,114 @@ export function ProposalForm({ data, onChange }: ProposalFormProps) {
|
||||
<div className="bg-white rounded-lg border p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">참고 이미지 정보</h3>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>첨부파일</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
type="text"
|
||||
readOnly
|
||||
placeholder="파일을 선택해주세요"
|
||||
value={data.attachments.map((f) => f.name).join(', ')}
|
||||
className="flex-1"
|
||||
/>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
accept="image/*"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
찾기
|
||||
</Button>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>첨부파일</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
accept="image/*"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
<Upload className="w-4 h-4 mr-2" />
|
||||
파일 추가
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 기존 업로드된 파일 목록 */}
|
||||
{data.uploadedFiles && data.uploadedFiles.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm text-gray-600">저장된 파일</Label>
|
||||
<div className="space-y-2">
|
||||
{data.uploadedFiles.map((file) => (
|
||||
<div
|
||||
key={file.id}
|
||||
className="flex items-center justify-between gap-2 p-2 bg-gray-50 rounded-md"
|
||||
>
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<FileText className="w-4 h-4 text-gray-500 flex-shrink-0" />
|
||||
<span className="text-sm truncate">{file.name}</span>
|
||||
{file.size && (
|
||||
<span className="text-xs text-gray-400 flex-shrink-0">
|
||||
({Math.round(file.size / 1024)}KB)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1 flex-shrink-0">
|
||||
{file.url && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => window.open(file.url, '_blank')}
|
||||
title="파일 보기"
|
||||
>
|
||||
<ExternalLink className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveUploadedFile(file.id)}
|
||||
title="파일 삭제"
|
||||
className="text-red-500 hover:text-red-700"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 새로 추가할 파일 목록 */}
|
||||
{data.attachments.length > 0 && (
|
||||
<div className="text-sm text-gray-500">
|
||||
{data.attachments.length}개 파일 선택됨
|
||||
<div className="space-y-2">
|
||||
<Label className="text-sm text-gray-600">새로 추가할 파일</Label>
|
||||
<div className="space-y-2">
|
||||
{data.attachments.map((file, index) => (
|
||||
<div
|
||||
key={`new-${index}`}
|
||||
className="flex items-center justify-between gap-2 p-2 bg-blue-50 rounded-md"
|
||||
>
|
||||
<div className="flex items-center gap-2 flex-1 min-w-0">
|
||||
<FileText className="w-4 h-4 text-blue-500 flex-shrink-0" />
|
||||
<span className="text-sm truncate">{file.name}</span>
|
||||
<span className="text-xs text-gray-400 flex-shrink-0">
|
||||
({Math.round(file.size / 1024)}KB)
|
||||
</span>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveAttachment(index)}
|
||||
title="파일 삭제"
|
||||
className="text-red-500 hover:text-red-700 flex-shrink-0"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 파일이 없을 때 안내 메시지 */}
|
||||
{(!data.uploadedFiles || data.uploadedFiles.length === 0) && data.attachments.length === 0 && (
|
||||
<div className="text-sm text-gray-500 text-center py-4 border border-dashed rounded-md">
|
||||
첨부된 파일이 없습니다. 위 버튼을 클릭하여 파일을 추가하세요.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Plus, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
@@ -10,7 +11,7 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type { ApprovalPerson } from './types';
|
||||
import { MOCK_EMPLOYEES } from './types';
|
||||
import { getEmployees } from './actions';
|
||||
|
||||
interface ReferenceSectionProps {
|
||||
data: ApprovalPerson[];
|
||||
@@ -18,6 +19,13 @@ interface ReferenceSectionProps {
|
||||
}
|
||||
|
||||
export function ReferenceSection({ data, onChange }: ReferenceSectionProps) {
|
||||
const [employees, setEmployees] = useState<ApprovalPerson[]>([]);
|
||||
|
||||
// 직원 목록 로드
|
||||
useEffect(() => {
|
||||
getEmployees().then(setEmployees);
|
||||
}, []);
|
||||
|
||||
const handleAdd = () => {
|
||||
const newPerson: ApprovalPerson = {
|
||||
id: `temp-${Date.now()}`,
|
||||
@@ -33,7 +41,7 @@ export function ReferenceSection({ data, onChange }: ReferenceSectionProps) {
|
||||
};
|
||||
|
||||
const handleChange = (index: number, employeeId: string) => {
|
||||
const employee = MOCK_EMPLOYEES.find((e) => e.id === employeeId);
|
||||
const employee = employees.find((e) => e.id === employeeId);
|
||||
if (employee) {
|
||||
const newData = [...data];
|
||||
newData[index] = { ...employee };
|
||||
@@ -67,10 +75,15 @@ export function ReferenceSection({ data, onChange }: ReferenceSectionProps) {
|
||||
onValueChange={(value) => handleChange(index, value)}
|
||||
>
|
||||
<SelectTrigger className="flex-1">
|
||||
<SelectValue placeholder="부서명 / 직책명 / 이름 ▼" />
|
||||
{/* 이미 선택된 값이 있으면 직접 표시, 없으면 placeholder */}
|
||||
{person.name && !person.id.startsWith('temp-') ? (
|
||||
<span>{person.department} / {person.position} / {person.name}</span>
|
||||
) : (
|
||||
<SelectValue placeholder="부서명 / 직책명 / 이름 ▼" />
|
||||
)}
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{MOCK_EMPLOYEES.map((employee) => (
|
||||
{employees.map((employee) => (
|
||||
<SelectItem key={employee.id} value={employee.id}>
|
||||
{employee.department} / {employee.position} / {employee.name}
|
||||
</SelectItem>
|
||||
@@ -91,4 +104,4 @@ export function ReferenceSection({ data, onChange }: ReferenceSectionProps) {
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
904
src/components/approval/DocumentCreate/actions.ts
Normal file
904
src/components/approval/DocumentCreate/actions.ts
Normal file
@@ -0,0 +1,904 @@
|
||||
/**
|
||||
* 문서 작성 서버 액션
|
||||
*
|
||||
* API Endpoints:
|
||||
* - GET /api/v1/reports/expense-estimate - 비용견적서 항목 조회
|
||||
* - GET /api/v1/employees - 직원 목록 (결재선/참조 선택용)
|
||||
* - POST /api/v1/approvals - 결재 문서 생성 (임시저장)
|
||||
* - POST /api/v1/approvals/{id}/submit - 결재 문서 상신
|
||||
*/
|
||||
|
||||
'use server';
|
||||
|
||||
import { cookies } from 'next/headers';
|
||||
import type {
|
||||
ExpenseEstimateItem,
|
||||
ApprovalPerson,
|
||||
DocumentFormData,
|
||||
UploadedFile,
|
||||
} from './types';
|
||||
|
||||
// ============================================
|
||||
// API 응답 타입 정의
|
||||
// ============================================
|
||||
|
||||
interface ApiResponse<T> {
|
||||
success: boolean;
|
||||
data: T;
|
||||
message: string;
|
||||
}
|
||||
|
||||
// 비용견적서 API 응답 타입
|
||||
interface ExpenseEstimateApiItem {
|
||||
id: number;
|
||||
expected_payment_date: string;
|
||||
category: string;
|
||||
amount: number;
|
||||
vendor: string;
|
||||
account_info?: string;
|
||||
memo?: string;
|
||||
}
|
||||
|
||||
interface ExpenseEstimateApiResponse {
|
||||
year_month: string;
|
||||
items: ExpenseEstimateApiItem[];
|
||||
total_expense: number;
|
||||
account_balance: number;
|
||||
final_difference: number;
|
||||
}
|
||||
|
||||
// 직원 API 응답 타입 (TenantUserProfile 구조)
|
||||
interface EmployeeApiData {
|
||||
id: number; // TenantUserProfile.id
|
||||
user_id: number; // User.id (결재선에 사용)
|
||||
position_key?: string; // 직책 코드 (EXECUTIVE, DIRECTOR 등)
|
||||
user?: {
|
||||
id: number;
|
||||
name: string;
|
||||
email?: string;
|
||||
};
|
||||
department?: {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
// 결재 문서 생성 응답 타입
|
||||
interface ApprovalCreateResponse {
|
||||
id: number;
|
||||
document_number: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 헬퍼 함수
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* API 헤더 생성
|
||||
*/
|
||||
async function getApiHeaders(): Promise<HeadersInit> {
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get('access_token')?.value;
|
||||
|
||||
return {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': token ? `Bearer ${token}` : '',
|
||||
'X-API-KEY': process.env.API_KEY || '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 비용견적서 API 데이터 → 프론트엔드 데이터 변환
|
||||
*/
|
||||
function transformExpenseEstimateItem(item: ExpenseEstimateApiItem): ExpenseEstimateItem {
|
||||
return {
|
||||
id: String(item.id),
|
||||
checked: false,
|
||||
expectedPaymentDate: item.expected_payment_date,
|
||||
category: item.category,
|
||||
amount: item.amount,
|
||||
vendor: item.vendor,
|
||||
memo: item.account_info || item.memo || '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 직책 코드를 한글 라벨로 변환 (직원 목록용)
|
||||
*/
|
||||
function getPositionLabelForEmployee(positionKey: string | null | undefined): string {
|
||||
if (!positionKey) return '';
|
||||
const labels: Record<string, string> = {
|
||||
'EXECUTIVE': '임원',
|
||||
'DIRECTOR': '부장',
|
||||
'MANAGER': '과장',
|
||||
'SENIOR': '대리',
|
||||
'STAFF': '사원',
|
||||
'INTERN': '인턴',
|
||||
};
|
||||
return labels[positionKey] ?? positionKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* 직원 API 데이터 → 결재자 데이터 변환
|
||||
* API는 TenantUserProfile 구조를 반환함
|
||||
*/
|
||||
function transformEmployee(employee: EmployeeApiData): ApprovalPerson {
|
||||
return {
|
||||
id: String(employee.user?.id || employee.user_id), // User.id 사용 (결재선에 필요)
|
||||
name: employee.user?.name || '',
|
||||
position: getPositionLabelForEmployee(employee.position_key),
|
||||
department: employee.department?.name || '',
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// API 함수
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* 파일 업로드
|
||||
* @param files 업로드할 파일 배열
|
||||
* @returns 업로드된 파일 정보 배열
|
||||
*/
|
||||
export async function uploadFiles(files: File[]): Promise<{
|
||||
success: boolean;
|
||||
data?: UploadedFile[];
|
||||
error?: string;
|
||||
}> {
|
||||
if (files.length === 0) {
|
||||
return { success: true, data: [] };
|
||||
}
|
||||
|
||||
try {
|
||||
const cookieStore = await cookies();
|
||||
const token = cookieStore.get('access_token')?.value;
|
||||
|
||||
const uploadedFiles: UploadedFile[] = [];
|
||||
|
||||
// 파일을 하나씩 업로드 (멀티파트 폼)
|
||||
for (const file of files) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/files/upload`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': token ? `Bearer ${token}` : '',
|
||||
'X-API-KEY': process.env.API_KEY || '',
|
||||
// Content-Type은 자동 설정됨 (multipart/form-data)
|
||||
},
|
||||
body: formData,
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('[DocumentCreateActions] File upload error:', response.status);
|
||||
return { success: false, error: `파일 업로드 실패: ${file.name}` };
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
if (result.success && result.data) {
|
||||
// API 응답 필드: id, display_name, file_path, file_size, mime_type
|
||||
uploadedFiles.push({
|
||||
id: result.data.id,
|
||||
name: result.data.display_name || file.name,
|
||||
url: `${process.env.NEXT_PUBLIC_API_URL}/api/v1/files/${result.data.id}/download`,
|
||||
size: result.data.file_size,
|
||||
mime_type: result.data.mime_type,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { success: true, data: uploadedFiles };
|
||||
} catch (error) {
|
||||
console.error('[DocumentCreateActions] uploadFiles error:', error);
|
||||
return { success: false, error: '파일 업로드 중 오류가 발생했습니다.' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 비용견적서 항목 조회
|
||||
*/
|
||||
export async function getExpenseEstimateItems(yearMonth?: string): Promise<{
|
||||
items: ExpenseEstimateItem[];
|
||||
totalExpense: number;
|
||||
accountBalance: number;
|
||||
finalDifference: number;
|
||||
} | null> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const searchParams = new URLSearchParams();
|
||||
|
||||
if (yearMonth) {
|
||||
searchParams.set('year_month', yearMonth);
|
||||
}
|
||||
|
||||
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/reports/expense-estimate?${searchParams.toString()}`;
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('[DocumentCreateActions] GET expense-estimate error:', response.status);
|
||||
return null;
|
||||
}
|
||||
|
||||
const result: ApiResponse<ExpenseEstimateApiResponse> = await response.json();
|
||||
|
||||
if (!result.success || !result.data) {
|
||||
console.warn('[DocumentCreateActions] No data in response');
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
items: result.data.items.map(transformExpenseEstimateItem),
|
||||
totalExpense: result.data.total_expense,
|
||||
accountBalance: result.data.account_balance,
|
||||
finalDifference: result.data.final_difference,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[DocumentCreateActions] getExpenseEstimateItems error:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 직원 목록 조회 (결재선/참조 선택용)
|
||||
*/
|
||||
export async function getEmployees(search?: string): Promise<ApprovalPerson[]> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set('per_page', '100');
|
||||
if (search) {
|
||||
searchParams.set('search', search);
|
||||
}
|
||||
|
||||
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/employees?${searchParams.toString()}`;
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('[DocumentCreateActions] GET employees error:', response.status);
|
||||
return [];
|
||||
}
|
||||
|
||||
const result: ApiResponse<{ data: EmployeeApiData[] }> = await response.json();
|
||||
|
||||
if (!result.success || !result.data?.data) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return result.data.data.map(transformEmployee);
|
||||
} catch (error) {
|
||||
console.error('[DocumentCreateActions] getEmployees error:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 결재 문서 생성 (임시저장)
|
||||
*/
|
||||
export async function createApproval(formData: DocumentFormData): Promise<{
|
||||
success: boolean;
|
||||
data?: { id: number; documentNo: string };
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
// 새 첨부파일 업로드
|
||||
const newFiles = formData.proposalData?.attachments
|
||||
|| formData.expenseReportData?.attachments
|
||||
|| [];
|
||||
let uploadedFiles: UploadedFile[] = [];
|
||||
|
||||
if (newFiles.length > 0) {
|
||||
const uploadResult = await uploadFiles(newFiles);
|
||||
if (!uploadResult.success) {
|
||||
return { success: false, error: uploadResult.error };
|
||||
}
|
||||
uploadedFiles = uploadResult.data || [];
|
||||
}
|
||||
|
||||
// 프론트엔드 데이터 → API 요청 데이터 변환
|
||||
const requestBody = {
|
||||
form_code: formData.basicInfo.documentType,
|
||||
title: getDocumentTitle(formData),
|
||||
status: 'draft', // 임시저장
|
||||
steps: [
|
||||
...formData.approvalLine.map((person, index) => ({
|
||||
step_type: 'approval',
|
||||
step_order: index + 1,
|
||||
approver_id: parseInt(person.id),
|
||||
})),
|
||||
...formData.references.map((person, index) => ({
|
||||
step_type: 'reference',
|
||||
step_order: formData.approvalLine.length + index + 1,
|
||||
approver_id: parseInt(person.id),
|
||||
})),
|
||||
],
|
||||
content: getDocumentContent(formData, uploadedFiles),
|
||||
};
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/approvals`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(requestBody),
|
||||
}
|
||||
);
|
||||
|
||||
const result: ApiResponse<ApprovalCreateResponse> = await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '문서 저장에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
id: result.data.id,
|
||||
documentNo: result.data.document_number,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[DocumentCreateActions] createApproval error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 결재 문서 상신
|
||||
*/
|
||||
export async function submitApproval(id: number): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/approvals/${id}/submit`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({}),
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '문서 상신에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('[DocumentCreateActions] submitApproval error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 결재 문서 생성 및 상신 (한번에)
|
||||
*/
|
||||
export async function createAndSubmitApproval(formData: DocumentFormData): Promise<{
|
||||
success: boolean;
|
||||
data?: { id: number; documentNo: string };
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
// 1. 먼저 문서 생성
|
||||
const createResult = await createApproval(formData);
|
||||
if (!createResult.success || !createResult.data) {
|
||||
return createResult;
|
||||
}
|
||||
|
||||
// 2. 상신
|
||||
const submitResult = await submitApproval(createResult.data.id);
|
||||
if (!submitResult.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: submitResult.error || '문서 상신에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: createResult.data,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[DocumentCreateActions] createAndSubmitApproval error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 결재 문서 조회 (수정 모드용)
|
||||
*/
|
||||
export async function getApprovalById(id: number): Promise<{
|
||||
success: boolean;
|
||||
data?: DocumentFormData;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/approvals/${id}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 404) {
|
||||
return { success: false, error: '문서를 찾을 수 없습니다.' };
|
||||
}
|
||||
return { success: false, error: '문서 조회에 실패했습니다.' };
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (!result.success || !result.data) {
|
||||
return { success: false, error: result.message || '문서 조회에 실패했습니다.' };
|
||||
}
|
||||
|
||||
// API 응답을 프론트엔드 형식으로 변환
|
||||
const apiData = result.data;
|
||||
const formData = transformApiToFormData(apiData);
|
||||
|
||||
return { success: true, data: formData };
|
||||
} catch (error) {
|
||||
console.error('[DocumentCreateActions] getApprovalById error:', error);
|
||||
return { success: false, error: '서버 오류가 발생했습니다.' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 결재 문서 수정
|
||||
*/
|
||||
export async function updateApproval(id: number, formData: DocumentFormData): Promise<{
|
||||
success: boolean;
|
||||
data?: { id: number; documentNo: string };
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
// 새 첨부파일 업로드
|
||||
const newFiles = formData.proposalData?.attachments
|
||||
|| formData.expenseReportData?.attachments
|
||||
|| [];
|
||||
let uploadedFiles: UploadedFile[] = [];
|
||||
|
||||
if (newFiles.length > 0) {
|
||||
const uploadResult = await uploadFiles(newFiles);
|
||||
if (!uploadResult.success) {
|
||||
return { success: false, error: uploadResult.error };
|
||||
}
|
||||
uploadedFiles = uploadResult.data || [];
|
||||
}
|
||||
|
||||
const requestBody = {
|
||||
form_code: formData.basicInfo.documentType,
|
||||
title: getDocumentTitle(formData),
|
||||
steps: [
|
||||
...formData.approvalLine.map((person, index) => ({
|
||||
step_type: 'approval',
|
||||
step_order: index + 1,
|
||||
approver_id: parseInt(person.id),
|
||||
})),
|
||||
...formData.references.map((person, index) => ({
|
||||
step_type: 'reference',
|
||||
step_order: formData.approvalLine.length + index + 1,
|
||||
approver_id: parseInt(person.id),
|
||||
})),
|
||||
],
|
||||
content: getDocumentContent(formData, uploadedFiles),
|
||||
};
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/approvals/${id}`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
headers,
|
||||
body: JSON.stringify(requestBody),
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '문서 수정에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
id: result.data.id,
|
||||
documentNo: result.data.document_number,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[DocumentCreateActions] updateApproval error:', error);
|
||||
return { success: false, error: '서버 오류가 발생했습니다.' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 결재 문서 수정 및 상신
|
||||
*/
|
||||
export async function updateAndSubmitApproval(id: number, formData: DocumentFormData): Promise<{
|
||||
success: boolean;
|
||||
data?: { id: number; documentNo: string };
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
// 1. 먼저 문서 수정
|
||||
const updateResult = await updateApproval(id, formData);
|
||||
if (!updateResult.success) {
|
||||
return updateResult;
|
||||
}
|
||||
|
||||
// 2. 상신
|
||||
const submitResult = await submitApproval(id);
|
||||
if (!submitResult.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: submitResult.error || '문서 상신에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: updateResult.data,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[DocumentCreateActions] updateAndSubmitApproval error:', error);
|
||||
return { success: false, error: '서버 오류가 발생했습니다.' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 결재 문서 삭제
|
||||
*/
|
||||
export async function deleteApproval(id: number): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/approvals/${id}`,
|
||||
{
|
||||
method: 'DELETE',
|
||||
headers,
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '문서 삭제에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('[DocumentCreateActions] deleteApproval error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// 내부 헬퍼 함수
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* 문서 제목 생성
|
||||
*/
|
||||
function getDocumentTitle(formData: DocumentFormData): string {
|
||||
switch (formData.basicInfo.documentType) {
|
||||
case 'proposal':
|
||||
return formData.proposalData?.title || '품의서';
|
||||
case 'expenseReport':
|
||||
return `지출결의서 - ${formData.expenseReportData?.requestDate || ''}`;
|
||||
case 'expenseEstimate':
|
||||
return `지출 예상 내역서`;
|
||||
default:
|
||||
return '문서';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 직책 코드를 한글 라벨로 변환
|
||||
*/
|
||||
function getPositionLabel(positionKey: string | null | undefined): string {
|
||||
if (!positionKey) return '';
|
||||
const labels: Record<string, string> = {
|
||||
'EXECUTIVE': '임원',
|
||||
'DIRECTOR': '부장',
|
||||
'MANAGER': '과장',
|
||||
'SENIOR': '대리',
|
||||
'STAFF': '사원',
|
||||
'INTERN': '인턴',
|
||||
};
|
||||
return labels[positionKey] ?? positionKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* API 응답을 프론트엔드 폼 데이터로 변환
|
||||
*/
|
||||
function transformApiToFormData(apiData: {
|
||||
id: number;
|
||||
document_number: string;
|
||||
form_code?: string; // 이전 호환성
|
||||
form?: { // 현재 API 구조
|
||||
id: number;
|
||||
name: string;
|
||||
code: string;
|
||||
category?: string;
|
||||
template?: Record<string, unknown>;
|
||||
};
|
||||
title: string;
|
||||
status: string;
|
||||
content: Record<string, unknown>;
|
||||
steps?: Array<{
|
||||
step_type: string;
|
||||
approver_id: number;
|
||||
approver?: {
|
||||
id: number;
|
||||
name: string;
|
||||
position?: string;
|
||||
department?: { name: string };
|
||||
tenant_profile?: {
|
||||
position_key?: string;
|
||||
display_name?: string;
|
||||
department?: { name: string };
|
||||
};
|
||||
};
|
||||
}>;
|
||||
created_at: string;
|
||||
requester?: {
|
||||
name: string;
|
||||
};
|
||||
drafter?: {
|
||||
id: number;
|
||||
name: string;
|
||||
tenant_profile?: {
|
||||
position_key?: string;
|
||||
display_name?: string;
|
||||
department?: { name: string };
|
||||
};
|
||||
};
|
||||
}): DocumentFormData {
|
||||
// form.code를 우선 사용, 없으면 form_code (이전 호환성)
|
||||
const formCode = apiData.form?.code || apiData.form_code || 'proposal';
|
||||
const documentType = formCode as 'proposal' | 'expenseReport' | 'expenseEstimate';
|
||||
const content = apiData.content || {};
|
||||
|
||||
// 결재선 및 참조자 분리
|
||||
const approvalLine: ApprovalPerson[] = [];
|
||||
const references: ApprovalPerson[] = [];
|
||||
|
||||
if (apiData.steps) {
|
||||
for (const step of apiData.steps) {
|
||||
if (step.approver) {
|
||||
// tenantProfile에서 직책/부서 정보 추출 (우선), 없으면 기존 필드 사용
|
||||
const tenantProfile = step.approver.tenant_profile;
|
||||
const position = tenantProfile?.position_key
|
||||
? getPositionLabel(tenantProfile.position_key)
|
||||
: (step.approver.position || '');
|
||||
const department = tenantProfile?.department?.name
|
||||
|| step.approver.department?.name
|
||||
|| '';
|
||||
|
||||
const person: ApprovalPerson = {
|
||||
id: String(step.approver.id),
|
||||
name: step.approver.name,
|
||||
position,
|
||||
department,
|
||||
};
|
||||
|
||||
if (step.step_type === 'approval') {
|
||||
approvalLine.push(person);
|
||||
} else if (step.step_type === 'reference') {
|
||||
references.push(person);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 기본 정보 (drafter에서 tenantProfile 정보 추출)
|
||||
const drafterProfile = apiData.drafter?.tenant_profile;
|
||||
const basicInfo = {
|
||||
drafter: apiData.drafter?.name || apiData.requester?.name || '',
|
||||
drafterPosition: drafterProfile?.position_key
|
||||
? getPositionLabel(drafterProfile.position_key)
|
||||
: '',
|
||||
drafterDepartment: drafterProfile?.department?.name || '',
|
||||
draftDate: apiData.created_at,
|
||||
documentNo: apiData.document_number,
|
||||
documentType,
|
||||
};
|
||||
|
||||
// 기존 업로드 파일 추출
|
||||
const existingFiles = (content.files as Array<{
|
||||
id: number;
|
||||
name: string;
|
||||
url?: string;
|
||||
size?: number;
|
||||
mime_type?: string;
|
||||
}>) || [];
|
||||
const uploadedFiles: UploadedFile[] = existingFiles.map(f => ({
|
||||
id: f.id,
|
||||
name: f.name,
|
||||
// URL이 없거나 상대 경로인 경우 다운로드 URL 생성
|
||||
url: f.url?.startsWith('http')
|
||||
? f.url
|
||||
: `${process.env.NEXT_PUBLIC_API_URL}/api/v1/files/${f.id}/download`,
|
||||
size: f.size,
|
||||
mime_type: f.mime_type,
|
||||
}));
|
||||
|
||||
// 문서 유형별 데이터 변환
|
||||
let proposalData;
|
||||
let expenseReportData;
|
||||
let expenseEstimateData;
|
||||
|
||||
if (documentType === 'proposal') {
|
||||
proposalData = {
|
||||
vendor: (content.vendor as string) || '',
|
||||
vendorPaymentDate: (content.vendorPaymentDate as string) || '',
|
||||
title: (content.title as string) || '',
|
||||
description: (content.description as string) || '',
|
||||
reason: (content.reason as string) || '',
|
||||
estimatedCost: (content.estimatedCost as number) || 0,
|
||||
attachments: [],
|
||||
uploadedFiles,
|
||||
};
|
||||
} else if (documentType === 'expenseReport') {
|
||||
const items = (content.items as Array<{
|
||||
id: string;
|
||||
description: string;
|
||||
amount: number;
|
||||
note?: string;
|
||||
}>) || [];
|
||||
|
||||
expenseReportData = {
|
||||
requestDate: (content.requestDate as string) || '',
|
||||
paymentDate: (content.paymentDate as string) || '',
|
||||
items: items.map(item => ({
|
||||
id: item.id,
|
||||
description: item.description,
|
||||
amount: item.amount,
|
||||
note: item.note || '',
|
||||
})),
|
||||
cardId: (content.cardId as string) || '',
|
||||
totalAmount: (content.totalAmount as number) || 0,
|
||||
attachments: [],
|
||||
uploadedFiles,
|
||||
};
|
||||
} else if (documentType === 'expenseEstimate') {
|
||||
const items = (content.items as Array<{
|
||||
id: string;
|
||||
checked: boolean;
|
||||
expectedPaymentDate: string;
|
||||
category: string;
|
||||
amount: number;
|
||||
vendor: string;
|
||||
memo?: string;
|
||||
}>) || [];
|
||||
|
||||
expenseEstimateData = {
|
||||
items: items.map(item => ({
|
||||
id: item.id,
|
||||
checked: item.checked || false,
|
||||
expectedPaymentDate: item.expectedPaymentDate,
|
||||
category: item.category,
|
||||
amount: item.amount,
|
||||
vendor: item.vendor,
|
||||
memo: item.memo || '',
|
||||
})),
|
||||
totalExpense: (content.totalExpense as number) || 0,
|
||||
accountBalance: (content.accountBalance as number) || 0,
|
||||
finalDifference: (content.finalDifference as number) || 0,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
basicInfo,
|
||||
approvalLine,
|
||||
references,
|
||||
proposalData,
|
||||
expenseReportData,
|
||||
expenseEstimateData,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 문서 내용 생성 (JSON)
|
||||
* @param formData 폼 데이터
|
||||
* @param uploadedFiles 새로 업로드된 파일 목록
|
||||
*/
|
||||
function getDocumentContent(
|
||||
formData: DocumentFormData,
|
||||
uploadedFiles: UploadedFile[] = []
|
||||
): Record<string, unknown> {
|
||||
// 기존 업로드 파일 + 새로 업로드된 파일 합치기
|
||||
const existingFiles = formData.proposalData?.uploadedFiles
|
||||
|| formData.expenseReportData?.uploadedFiles
|
||||
|| [];
|
||||
const allFiles = [...existingFiles, ...uploadedFiles];
|
||||
|
||||
switch (formData.basicInfo.documentType) {
|
||||
case 'proposal':
|
||||
return {
|
||||
vendor: formData.proposalData?.vendor,
|
||||
vendorPaymentDate: formData.proposalData?.vendorPaymentDate,
|
||||
title: formData.proposalData?.title,
|
||||
description: formData.proposalData?.description,
|
||||
reason: formData.proposalData?.reason,
|
||||
estimatedCost: formData.proposalData?.estimatedCost,
|
||||
files: allFiles,
|
||||
};
|
||||
case 'expenseReport':
|
||||
return {
|
||||
requestDate: formData.expenseReportData?.requestDate,
|
||||
paymentDate: formData.expenseReportData?.paymentDate,
|
||||
items: formData.expenseReportData?.items,
|
||||
cardId: formData.expenseReportData?.cardId,
|
||||
totalAmount: formData.expenseReportData?.totalAmount,
|
||||
files: allFiles,
|
||||
};
|
||||
case 'expenseEstimate':
|
||||
return {
|
||||
items: formData.expenseEstimateData?.items,
|
||||
totalExpense: formData.expenseEstimateData?.totalExpense,
|
||||
accountBalance: formData.expenseEstimateData?.accountBalance,
|
||||
finalDifference: formData.expenseEstimateData?.finalDifference,
|
||||
};
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,20 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState, useCallback, useEffect, useTransition, useRef } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { format } from 'date-fns';
|
||||
import { FileText, Trash2, Send, Save, ArrowLeft, Eye } from 'lucide-react';
|
||||
import { FileText, Trash2, Send, Save, ArrowLeft, Eye, Loader2 } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
getExpenseEstimateItems,
|
||||
getEmployees,
|
||||
createApproval,
|
||||
createAndSubmitApproval,
|
||||
getApprovalById,
|
||||
updateApproval,
|
||||
updateAndSubmitApproval,
|
||||
deleteApproval,
|
||||
} from './actions';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { BasicInfoSection } from './BasicInfoSection';
|
||||
@@ -28,17 +39,17 @@ import type {
|
||||
ExpenseEstimateData,
|
||||
} from './types';
|
||||
|
||||
// 초기 데이터
|
||||
// 초기 데이터 - SSR에서는 빈 문자열, 클라이언트에서 날짜 설정
|
||||
const getInitialBasicInfo = (): BasicInfo => ({
|
||||
drafter: '홍길동',
|
||||
draftDate: format(new Date(), 'yyyy-MM-dd HH:mm'),
|
||||
draftDate: '', // 클라이언트에서 설정
|
||||
documentNo: '',
|
||||
documentType: 'proposal',
|
||||
});
|
||||
|
||||
const getInitialProposalData = (): ProposalData => ({
|
||||
vendor: '',
|
||||
vendorPaymentDate: format(new Date(), 'yyyy-MM-dd'),
|
||||
vendorPaymentDate: '', // 클라이언트에서 설정
|
||||
title: '',
|
||||
description: '',
|
||||
reason: '',
|
||||
@@ -47,8 +58,8 @@ const getInitialProposalData = (): ProposalData => ({
|
||||
});
|
||||
|
||||
const getInitialExpenseReportData = (): ExpenseReportData => ({
|
||||
requestDate: format(new Date(), 'yyyy-MM-dd'),
|
||||
paymentDate: format(new Date(), 'yyyy-MM-dd'),
|
||||
requestDate: '', // 클라이언트에서 설정
|
||||
paymentDate: '', // 클라이언트에서 설정
|
||||
items: [],
|
||||
cardId: '',
|
||||
totalAmount: 0,
|
||||
@@ -64,6 +75,16 @@ const getInitialExpenseEstimateData = (): ExpenseEstimateData => ({
|
||||
|
||||
export function DocumentCreate() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const [isPending, startTransition] = useTransition();
|
||||
|
||||
// 수정 모드 / 복제 모드 상태
|
||||
const documentId = searchParams.get('id');
|
||||
const mode = searchParams.get('mode');
|
||||
const copyFromId = searchParams.get('copyFrom');
|
||||
const isEditMode = mode === 'edit' && !!documentId;
|
||||
const isCopyMode = !!copyFromId;
|
||||
const [isLoadingDocument, setIsLoadingDocument] = useState(false);
|
||||
|
||||
// 상태 관리
|
||||
const [basicInfo, setBasicInfo] = useState<BasicInfo>(getInitialBasicInfo);
|
||||
@@ -72,45 +93,259 @@ export function DocumentCreate() {
|
||||
const [proposalData, setProposalData] = useState<ProposalData>(getInitialProposalData);
|
||||
const [expenseReportData, setExpenseReportData] = useState<ExpenseReportData>(getInitialExpenseReportData);
|
||||
const [expenseEstimateData, setExpenseEstimateData] = useState<ExpenseEstimateData>(getInitialExpenseEstimateData);
|
||||
const [isLoadingEstimate, setIsLoadingEstimate] = useState(false);
|
||||
|
||||
// 복제 모드 toast 중복 호출 방지
|
||||
const copyToastShownRef = useRef(false);
|
||||
|
||||
// Hydration 불일치 방지: 클라이언트에서만 날짜 초기화
|
||||
useEffect(() => {
|
||||
const today = format(new Date(), 'yyyy-MM-dd');
|
||||
const now = format(new Date(), 'yyyy-MM-dd HH:mm');
|
||||
|
||||
setBasicInfo(prev => ({ ...prev, draftDate: prev.draftDate || now }));
|
||||
setProposalData(prev => ({ ...prev, vendorPaymentDate: prev.vendorPaymentDate || today }));
|
||||
setExpenseReportData(prev => ({
|
||||
...prev,
|
||||
requestDate: prev.requestDate || today,
|
||||
paymentDate: prev.paymentDate || today,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
// 미리보기 모달 상태
|
||||
const [isPreviewOpen, setIsPreviewOpen] = useState(false);
|
||||
|
||||
// 수정 모드: 문서 로드
|
||||
useEffect(() => {
|
||||
if (!isEditMode || !documentId) return;
|
||||
|
||||
const loadDocument = async () => {
|
||||
setIsLoadingDocument(true);
|
||||
try {
|
||||
const result = await getApprovalById(parseInt(documentId));
|
||||
if (result.success && result.data) {
|
||||
const { basicInfo: loadedBasicInfo, approvalLine: loadedApprovalLine, references: loadedReferences, proposalData: loadedProposalData, expenseReportData: loadedExpenseReportData, expenseEstimateData: loadedExpenseEstimateData } = result.data;
|
||||
|
||||
setBasicInfo(loadedBasicInfo);
|
||||
setApprovalLine(loadedApprovalLine);
|
||||
setReferences(loadedReferences);
|
||||
if (loadedProposalData) setProposalData(loadedProposalData);
|
||||
if (loadedExpenseReportData) setExpenseReportData(loadedExpenseReportData);
|
||||
if (loadedExpenseEstimateData) setExpenseEstimateData(loadedExpenseEstimateData);
|
||||
} else {
|
||||
toast.error(result.error || '문서를 불러오는데 실패했습니다.');
|
||||
router.back();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load document:', error);
|
||||
toast.error('문서를 불러오는데 실패했습니다.');
|
||||
router.back();
|
||||
} finally {
|
||||
setIsLoadingDocument(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadDocument();
|
||||
}, [isEditMode, documentId, router]);
|
||||
|
||||
// 복제 모드: 원본 문서 로드 후 새 문서로 설정
|
||||
useEffect(() => {
|
||||
if (!isCopyMode || !copyFromId) return;
|
||||
|
||||
const loadDocumentForCopy = async () => {
|
||||
setIsLoadingDocument(true);
|
||||
try {
|
||||
const result = await getApprovalById(parseInt(copyFromId));
|
||||
if (result.success && result.data) {
|
||||
const { basicInfo: loadedBasicInfo, approvalLine: loadedApprovalLine, references: loadedReferences, proposalData: loadedProposalData, expenseReportData: loadedExpenseReportData, expenseEstimateData: loadedExpenseEstimateData } = result.data;
|
||||
|
||||
// 복제: 문서번호 초기화, 기안일 현재 시간으로
|
||||
const now = format(new Date(), 'yyyy-MM-dd HH:mm');
|
||||
setBasicInfo({
|
||||
...loadedBasicInfo,
|
||||
documentNo: '', // 새 문서이므로 문서번호 초기화
|
||||
draftDate: now,
|
||||
});
|
||||
|
||||
// 결재선/참조는 그대로 유지
|
||||
setApprovalLine(loadedApprovalLine);
|
||||
setReferences(loadedReferences);
|
||||
|
||||
// 문서 내용 복제
|
||||
if (loadedProposalData) setProposalData(loadedProposalData);
|
||||
if (loadedExpenseReportData) setExpenseReportData(loadedExpenseReportData);
|
||||
if (loadedExpenseEstimateData) setExpenseEstimateData(loadedExpenseEstimateData);
|
||||
|
||||
// React.StrictMode에서 useEffect 두 번 실행으로 인한 toast 중복 방지
|
||||
if (!copyToastShownRef.current) {
|
||||
copyToastShownRef.current = true;
|
||||
toast.info('문서가 복제되었습니다. 수정 후 상신해주세요.');
|
||||
}
|
||||
} else {
|
||||
toast.error(result.error || '원본 문서를 불러오는데 실패했습니다.');
|
||||
router.back();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load document for copy:', error);
|
||||
toast.error('원본 문서를 불러오는데 실패했습니다.');
|
||||
router.back();
|
||||
} finally {
|
||||
setIsLoadingDocument(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadDocumentForCopy();
|
||||
}, [isCopyMode, copyFromId, router]);
|
||||
|
||||
// 비용견적서 항목 로드
|
||||
const loadExpenseEstimateItems = useCallback(async () => {
|
||||
setIsLoadingEstimate(true);
|
||||
try {
|
||||
const result = await getExpenseEstimateItems();
|
||||
if (result) {
|
||||
setExpenseEstimateData({
|
||||
items: result.items,
|
||||
totalExpense: result.totalExpense,
|
||||
accountBalance: result.accountBalance,
|
||||
finalDifference: result.finalDifference,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load expense estimate items:', error);
|
||||
toast.error('비용견적서 항목을 불러오는데 실패했습니다.');
|
||||
} finally {
|
||||
setIsLoadingEstimate(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 문서 유형이 비용견적서로 변경되면 항목 로드
|
||||
useEffect(() => {
|
||||
if (basicInfo.documentType === 'expenseEstimate' && expenseEstimateData.items.length === 0) {
|
||||
loadExpenseEstimateItems();
|
||||
}
|
||||
}, [basicInfo.documentType, expenseEstimateData.items.length, loadExpenseEstimateItems]);
|
||||
|
||||
// 폼 데이터 수집
|
||||
const getFormData = useCallback(() => {
|
||||
return {
|
||||
basicInfo,
|
||||
approvalLine,
|
||||
references,
|
||||
proposalData: basicInfo.documentType === 'proposal' ? proposalData : undefined,
|
||||
expenseReportData: basicInfo.documentType === 'expenseReport' ? expenseReportData : undefined,
|
||||
expenseEstimateData: basicInfo.documentType === 'expenseEstimate' ? expenseEstimateData : undefined,
|
||||
};
|
||||
}, [basicInfo, approvalLine, references, proposalData, expenseReportData, expenseEstimateData]);
|
||||
|
||||
// 핸들러
|
||||
const handleBack = useCallback(() => {
|
||||
router.back();
|
||||
}, [router]);
|
||||
|
||||
const handleDelete = useCallback(() => {
|
||||
if (confirm('작성 중인 문서를 삭제하시겠습니까?')) {
|
||||
const handleDelete = useCallback(async () => {
|
||||
if (!confirm('작성 중인 문서를 삭제하시겠습니까?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 수정 모드: 실제 문서 삭제
|
||||
if (isEditMode && documentId) {
|
||||
startTransition(async () => {
|
||||
try {
|
||||
const result = await deleteApproval(parseInt(documentId));
|
||||
if (result.success) {
|
||||
toast.success('문서가 삭제되었습니다.');
|
||||
router.back();
|
||||
} else {
|
||||
toast.error(result.error || '문서 삭제에 실패했습니다.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Delete error:', error);
|
||||
toast.error('문서 삭제 중 오류가 발생했습니다.');
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// 새 문서: 그냥 뒤로가기
|
||||
router.back();
|
||||
}
|
||||
}, [router]);
|
||||
}, [router, isEditMode, documentId]);
|
||||
|
||||
const handleSubmit = useCallback(() => {
|
||||
console.log('상신:', {
|
||||
basicInfo,
|
||||
approvalLine,
|
||||
references,
|
||||
proposalData: basicInfo.documentType === 'proposal' ? proposalData : undefined,
|
||||
expenseReportData: basicInfo.documentType === 'expenseReport' ? expenseReportData : undefined,
|
||||
expenseEstimateData: basicInfo.documentType === 'expenseEstimate' ? expenseEstimateData : undefined,
|
||||
});
|
||||
alert('문서가 상신되었습니다.');
|
||||
router.back();
|
||||
}, [basicInfo, approvalLine, references, proposalData, expenseReportData, expenseEstimateData, router]);
|
||||
const handleSubmit = useCallback(async () => {
|
||||
// 유효성 검사
|
||||
if (approvalLine.length === 0) {
|
||||
toast.error('결재선을 지정해주세요.');
|
||||
return;
|
||||
}
|
||||
|
||||
const handleSaveDraft = useCallback(() => {
|
||||
console.log('임시저장:', {
|
||||
basicInfo,
|
||||
approvalLine,
|
||||
references,
|
||||
proposalData: basicInfo.documentType === 'proposal' ? proposalData : undefined,
|
||||
expenseReportData: basicInfo.documentType === 'expenseReport' ? expenseReportData : undefined,
|
||||
expenseEstimateData: basicInfo.documentType === 'expenseEstimate' ? expenseEstimateData : undefined,
|
||||
startTransition(async () => {
|
||||
try {
|
||||
const formData = getFormData();
|
||||
|
||||
// 수정 모드: 수정 후 상신
|
||||
if (isEditMode && documentId) {
|
||||
const result = await updateAndSubmitApproval(parseInt(documentId), formData);
|
||||
if (result.success) {
|
||||
toast.success('수정 및 상신 완료', {
|
||||
description: `문서번호: ${result.data?.documentNo}`,
|
||||
});
|
||||
router.back();
|
||||
} else {
|
||||
toast.error(result.error || '문서 상신에 실패했습니다.');
|
||||
}
|
||||
} else {
|
||||
// 새 문서: 생성 후 상신
|
||||
const result = await createAndSubmitApproval(formData);
|
||||
if (result.success) {
|
||||
toast.success('상신 완료', {
|
||||
description: `문서번호: ${result.data?.documentNo}`,
|
||||
});
|
||||
router.back();
|
||||
} else {
|
||||
toast.error(result.error || '문서 상신에 실패했습니다.');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Submit error:', error);
|
||||
toast.error('문서 상신 중 오류가 발생했습니다.');
|
||||
}
|
||||
});
|
||||
alert('임시저장되었습니다.');
|
||||
}, [basicInfo, approvalLine, references, proposalData, expenseReportData, expenseEstimateData]);
|
||||
}, [approvalLine, getFormData, router, isEditMode, documentId]);
|
||||
|
||||
const handleSaveDraft = useCallback(async () => {
|
||||
startTransition(async () => {
|
||||
try {
|
||||
const formData = getFormData();
|
||||
|
||||
// 수정 모드: 기존 문서 업데이트
|
||||
if (isEditMode && documentId) {
|
||||
const result = await updateApproval(parseInt(documentId), formData);
|
||||
if (result.success) {
|
||||
toast.success('저장 완료', {
|
||||
description: `문서번호: ${result.data?.documentNo}`,
|
||||
});
|
||||
} else {
|
||||
toast.error(result.error || '저장에 실패했습니다.');
|
||||
}
|
||||
} else {
|
||||
// 새 문서: 임시저장
|
||||
const result = await createApproval(formData);
|
||||
if (result.success) {
|
||||
toast.success('임시저장 완료', {
|
||||
description: `문서번호: ${result.data?.documentNo}`,
|
||||
});
|
||||
// 문서번호 업데이트
|
||||
if (result.data?.documentNo) {
|
||||
setBasicInfo(prev => ({ ...prev, documentNo: result.data!.documentNo }));
|
||||
}
|
||||
} else {
|
||||
toast.error(result.error || '임시저장에 실패했습니다.');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Save draft error:', error);
|
||||
toast.error('저장 중 오류가 발생했습니다.');
|
||||
}
|
||||
});
|
||||
}, [getFormData, isEditMode, documentId]);
|
||||
|
||||
// 미리보기 핸들러
|
||||
const handlePreview = useCallback(() => {
|
||||
@@ -197,12 +432,38 @@ export function DocumentCreate() {
|
||||
case 'expenseReport':
|
||||
return <ExpenseReportForm data={expenseReportData} onChange={setExpenseReportData} />;
|
||||
case 'expenseEstimate':
|
||||
return <ExpenseEstimateForm data={expenseEstimateData} onChange={setExpenseEstimateData} />;
|
||||
return <ExpenseEstimateForm data={expenseEstimateData} onChange={setExpenseEstimateData} isLoading={isLoadingEstimate} />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// 문서 로딩 중
|
||||
if (isLoadingDocument) {
|
||||
return (
|
||||
<div className="container mx-auto py-6 px-4 max-w-4xl">
|
||||
<Card className="mb-6">
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="icon" onClick={handleBack}>
|
||||
<ArrowLeft className="h-5 w-5" />
|
||||
</Button>
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="h-6 w-6 text-primary" />
|
||||
<div>
|
||||
<CardTitle>문서 불러오는 중...</CardTitle>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="container mx-auto py-6 px-4 max-w-4xl">
|
||||
{/* 헤더 */}
|
||||
@@ -216,8 +477,10 @@ export function DocumentCreate() {
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="h-6 w-6 text-primary" />
|
||||
<div>
|
||||
<CardTitle>문서 작성</CardTitle>
|
||||
<CardDescription>새로운 문서를 작성합니다</CardDescription>
|
||||
<CardTitle>{isEditMode ? '문서 수정' : isCopyMode ? '문서 복제' : '문서 작성'}</CardTitle>
|
||||
<CardDescription>
|
||||
{isEditMode ? '기존 문서를 수정합니다' : isCopyMode ? '복제된 문서를 수정 후 상신합니다' : '새로운 문서를 작성합니다'}
|
||||
</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -231,17 +494,17 @@ export function DocumentCreate() {
|
||||
<Eye className="w-4 h-4 mr-1" />
|
||||
상세
|
||||
</Button>
|
||||
<Button variant="outline" className="min-w-[80px]" onClick={handleDelete}>
|
||||
<Button variant="outline" className="min-w-[80px]" onClick={handleDelete} disabled={isPending}>
|
||||
<Trash2 className="w-4 h-4 mr-1" />
|
||||
삭제
|
||||
</Button>
|
||||
<Button variant="default" className="min-w-[80px]" onClick={handleSubmit}>
|
||||
<Send className="w-4 h-4 mr-1" />
|
||||
<Button variant="default" className="min-w-[80px]" onClick={handleSubmit} disabled={isPending}>
|
||||
{isPending ? <Loader2 className="w-4 h-4 mr-1 animate-spin" /> : <Send className="w-4 h-4 mr-1" />}
|
||||
상신
|
||||
</Button>
|
||||
<Button variant="secondary" className="min-w-[80px]" onClick={handleSaveDraft}>
|
||||
<Save className="w-4 h-4 mr-1" />
|
||||
임시저장
|
||||
<Button variant="secondary" className="min-w-[80px]" onClick={handleSaveDraft} disabled={isPending}>
|
||||
{isPending ? <Loader2 className="w-4 h-4 mr-1 animate-spin" /> : <Save className="w-4 h-4 mr-1" />}
|
||||
{isEditMode ? '저장' : '임시저장'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -263,16 +526,16 @@ export function DocumentCreate() {
|
||||
{/* 하단 고정 버튼 (모바일) */}
|
||||
<div className="fixed bottom-0 left-0 right-0 p-4 bg-white border-t md:hidden">
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" className="flex-1" onClick={handleDelete}>
|
||||
<Button variant="outline" className="flex-1" onClick={handleDelete} disabled={isPending}>
|
||||
<Trash2 className="w-4 h-4 mr-1" />
|
||||
삭제
|
||||
</Button>
|
||||
<Button variant="secondary" className="flex-1" onClick={handleSaveDraft}>
|
||||
<Save className="w-4 h-4 mr-1" />
|
||||
임시저장
|
||||
<Button variant="secondary" className="flex-1" onClick={handleSaveDraft} disabled={isPending}>
|
||||
{isPending ? <Loader2 className="w-4 h-4 mr-1 animate-spin" /> : <Save className="w-4 h-4 mr-1" />}
|
||||
{isEditMode ? '저장' : '임시저장'}
|
||||
</Button>
|
||||
<Button variant="default" className="flex-1" onClick={handleSubmit}>
|
||||
<Send className="w-4 h-4 mr-1" />
|
||||
<Button variant="default" className="flex-1" onClick={handleSubmit} disabled={isPending}>
|
||||
{isPending ? <Loader2 className="w-4 h-4 mr-1 animate-spin" /> : <Send className="w-4 h-4 mr-1" />}
|
||||
상신
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
// ===== 문서 작성 타입 정의 =====
|
||||
|
||||
// 업로드된 파일 정보
|
||||
export interface UploadedFile {
|
||||
id: number;
|
||||
name: string;
|
||||
url: string;
|
||||
size?: number;
|
||||
mime_type?: string;
|
||||
}
|
||||
|
||||
// 문서 유형
|
||||
export type DocumentType = 'proposal' | 'expenseReport' | 'expenseEstimate';
|
||||
|
||||
@@ -20,6 +29,8 @@ export interface ApprovalPerson {
|
||||
// 기본 정보
|
||||
export interface BasicInfo {
|
||||
drafter: string;
|
||||
drafterPosition?: string;
|
||||
drafterDepartment?: string;
|
||||
draftDate: string;
|
||||
documentNo: string;
|
||||
documentType: DocumentType;
|
||||
@@ -33,7 +44,8 @@ export interface ProposalData {
|
||||
description: string;
|
||||
reason: string;
|
||||
estimatedCost: number;
|
||||
attachments: File[];
|
||||
attachments: File[]; // 새로 추가할 파일
|
||||
uploadedFiles?: UploadedFile[]; // 이미 업로드된 파일
|
||||
}
|
||||
|
||||
// 지출결의서 항목
|
||||
@@ -51,7 +63,8 @@ export interface ExpenseReportData {
|
||||
items: ExpenseReportItem[];
|
||||
cardId: string;
|
||||
totalAmount: number;
|
||||
attachments: File[];
|
||||
attachments: File[]; // 새로 추가할 파일
|
||||
uploadedFiles?: UploadedFile[]; // 이미 업로드된 파일
|
||||
}
|
||||
|
||||
// 지출 예상 내역서 항목
|
||||
@@ -90,11 +103,3 @@ export const CARD_OPTIONS = [
|
||||
{ value: 'kb-9012', label: 'KB국민카드_9012 (카드명)' },
|
||||
];
|
||||
|
||||
// Mock 사원 데이터
|
||||
export const MOCK_EMPLOYEES: ApprovalPerson[] = [
|
||||
{ id: '1', department: '개발팀', position: '팀장', name: '김철수' },
|
||||
{ id: '2', department: '개발팀', position: '부장', name: '이영희' },
|
||||
{ id: '3', department: '인사팀', position: '팀장', name: '박민수' },
|
||||
{ id: '4', department: '경영지원팀', position: '이사', name: '정수진' },
|
||||
{ id: '5', department: '영업팀', position: '대표', name: '최동현' },
|
||||
];
|
||||
Reference in New Issue
Block a user