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:
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { X, Save, Plus, Wrench, Trash2 } from 'lucide-react';
|
||||
import { X, Save, Plus, Wrench, Trash2, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -19,10 +19,12 @@ import {
|
||||
} from '@/components/ui/select';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { RuleModal } from './RuleModal';
|
||||
import { toast } from 'sonner';
|
||||
import type { Process, ClassificationRule, ProcessType } from '@/types/process';
|
||||
import { PROCESS_TYPE_OPTIONS, MATCHING_TYPE_OPTIONS } from '@/types/process';
|
||||
import { createProcess, updateProcess } from './actions';
|
||||
|
||||
// Mock 담당부서 옵션
|
||||
// 담당부서 옵션 (추후 API 연동 가능)
|
||||
const DEPARTMENT_OPTIONS = [
|
||||
{ value: '스크린생산부서', label: '스크린생산부서' },
|
||||
{ value: '절곡생산부서', label: '절곡생산부서' },
|
||||
@@ -31,7 +33,7 @@ const DEPARTMENT_OPTIONS = [
|
||||
{ value: '포장/출하부서', label: '포장/출하부서' },
|
||||
];
|
||||
|
||||
// Mock 작업일지 양식 옵션
|
||||
// 작업일지 양식 옵션 (추후 API 연동 가능)
|
||||
const WORK_LOG_OPTIONS = [
|
||||
{ value: '스크린 작업일지', label: '스크린 작업일지' },
|
||||
{ value: '절곡 작업일지', label: '절곡 작업일지' },
|
||||
@@ -67,7 +69,8 @@ export function ProcessForm({ mode, initialData }: ProcessFormProps) {
|
||||
const [equipmentInfo, setEquipmentInfo] = useState(initialData?.equipmentInfo || '');
|
||||
const [workSteps, setWorkSteps] = useState(initialData?.workSteps?.join(', ') || '');
|
||||
const [note, setNote] = useState(initialData?.note || '');
|
||||
const [isActive, setIsActive] = useState(initialData?.status === '사용중' ?? true);
|
||||
const [isActive, setIsActive] = useState(initialData ? initialData.status === '사용중' : true);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
// 규칙 모달 상태
|
||||
const [ruleModalOpen, setRuleModalOpen] = useState(false);
|
||||
@@ -91,13 +94,13 @@ export function ProcessForm({ mode, initialData }: ProcessFormProps) {
|
||||
}, []);
|
||||
|
||||
// 제출
|
||||
const handleSubmit = () => {
|
||||
const handleSubmit = async () => {
|
||||
if (!processName.trim()) {
|
||||
alert('공정명을 입력해주세요.');
|
||||
toast.error('공정명을 입력해주세요.');
|
||||
return;
|
||||
}
|
||||
if (!department) {
|
||||
alert('담당부서를 선택해주세요.');
|
||||
toast.error('담당부서를 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -106,20 +109,46 @@ export function ProcessForm({ mode, initialData }: ProcessFormProps) {
|
||||
processType,
|
||||
department,
|
||||
workLogTemplate: workLogTemplate || undefined,
|
||||
classificationRules,
|
||||
classificationRules: classificationRules.map((rule) => ({
|
||||
registrationType: rule.registrationType,
|
||||
ruleType: rule.ruleType,
|
||||
matchingType: rule.matchingType,
|
||||
conditionValue: rule.conditionValue,
|
||||
priority: rule.priority,
|
||||
description: rule.description,
|
||||
isActive: rule.isActive,
|
||||
})),
|
||||
requiredWorkers,
|
||||
equipmentInfo: equipmentInfo.trim() || undefined,
|
||||
workSteps: workSteps
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean),
|
||||
workSteps: workSteps,
|
||||
note: note.trim() || undefined,
|
||||
isActive,
|
||||
};
|
||||
|
||||
console.log(isEdit ? '공정 수정 데이터:' : '공정 등록 데이터:', formData);
|
||||
alert(`공정이 ${isEdit ? '수정' : '등록'}되었습니다.`);
|
||||
router.push('/ko/master-data/process-management');
|
||||
setIsLoading(true);
|
||||
try {
|
||||
if (isEdit && initialData?.id) {
|
||||
const result = await updateProcess(initialData.id, formData);
|
||||
if (result.success) {
|
||||
toast.success('공정이 수정되었습니다.');
|
||||
router.push('/ko/master-data/process-management');
|
||||
} else {
|
||||
toast.error(result.error || '수정에 실패했습니다.');
|
||||
}
|
||||
} else {
|
||||
const result = await createProcess(formData);
|
||||
if (result.success) {
|
||||
toast.success('공정이 등록되었습니다.');
|
||||
router.push('/ko/master-data/process-management');
|
||||
} else {
|
||||
toast.error(result.error || '등록에 실패했습니다.');
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
toast.error('처리 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 취소
|
||||
@@ -133,12 +162,16 @@ export function ProcessForm({ mode, initialData }: ProcessFormProps) {
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-xl font-semibold">공정 {isEdit ? '수정' : '등록'}</h1>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
<Button variant="outline" onClick={handleCancel} disabled={isLoading}>
|
||||
<X className="h-4 w-4 mr-2" />
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSubmit}>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
<Button onClick={handleSubmit} disabled={isLoading}>
|
||||
{isLoading ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isEdit ? '수정' : '등록'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,76 +1,27 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { useState, useMemo, useCallback, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Wrench, Plus, Pencil, Trash2 } from 'lucide-react';
|
||||
import { Wrench, Plus, Pencil, Trash2, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { TableCell, TableRow } from '@/components/ui/table';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { IntegratedListTemplateV2, TabOption, TableColumn } from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { MobileCard } from '@/components/molecules/MobileCard';
|
||||
import type { Process, ProcessStatus } from '@/types/process';
|
||||
|
||||
// Mock 데이터
|
||||
const mockProcesses: Process[] = [
|
||||
{
|
||||
id: '1',
|
||||
processCode: 'P-004',
|
||||
processName: '재고(포밍)',
|
||||
description: '철판을 포밍하여 절곡 부품(반제품) 생산 후 재고 입고',
|
||||
processType: '생산',
|
||||
department: '포밍생산부서',
|
||||
workLogTemplate: '재고생산 작업일지',
|
||||
classificationRules: [],
|
||||
requiredWorkers: 2,
|
||||
workSteps: ['포밍', '검사', '포장'],
|
||||
status: '사용중',
|
||||
createdAt: '2025-01-01',
|
||||
updatedAt: '2025-01-15',
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
processCode: 'P-003',
|
||||
processName: '슬랫',
|
||||
description: '슬랫 코일 절단 및 성형',
|
||||
processType: '생산',
|
||||
department: '슬랫생산부서',
|
||||
classificationRules: [],
|
||||
requiredWorkers: 3,
|
||||
workSteps: ['절단', '성형', '검사'],
|
||||
status: '사용중',
|
||||
createdAt: '2025-01-01',
|
||||
updatedAt: '2025-01-10',
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
processCode: 'P-002',
|
||||
processName: '절곡',
|
||||
description: '가이드레일, 케이스, 하단마감재 제작',
|
||||
processType: '생산',
|
||||
department: '절곡생산부서',
|
||||
classificationRules: [],
|
||||
requiredWorkers: 4,
|
||||
workSteps: ['절단', '절곡', '용접', '검사'],
|
||||
status: '사용중',
|
||||
createdAt: '2025-01-01',
|
||||
updatedAt: '2025-01-08',
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
processCode: 'P-001',
|
||||
processName: '스크린',
|
||||
description: '방화스크린 원단 가공 및 조립',
|
||||
processType: '생산',
|
||||
department: '스크린생산부서',
|
||||
classificationRules: [],
|
||||
requiredWorkers: 3,
|
||||
workSteps: ['원단가공', '조립', '검사', '포장'],
|
||||
status: '사용중',
|
||||
createdAt: '2025-01-01',
|
||||
updatedAt: '2025-01-05',
|
||||
},
|
||||
];
|
||||
import { toast } from 'sonner';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import type { Process } from '@/types/process';
|
||||
import { getProcessList, deleteProcess, deleteProcesses, toggleProcessActive, getProcessStats } from './actions';
|
||||
|
||||
// 테이블 컬럼 정의
|
||||
const tableColumns: TableColumn[] = [
|
||||
@@ -85,33 +36,62 @@ const tableColumns: TableColumn[] = [
|
||||
{ key: 'actions', label: '작업', className: 'w-[100px] text-center' },
|
||||
];
|
||||
|
||||
// 탭 옵션 계산
|
||||
function getTabOptions(processes: Process[]): TabOption[] {
|
||||
const total = processes.length;
|
||||
const active = processes.filter(p => p.status === '사용중').length;
|
||||
const inactive = processes.filter(p => p.status === '미사용').length;
|
||||
|
||||
return [
|
||||
{ value: 'all', label: '전체', count: total },
|
||||
{ value: '사용중', label: '사용중', count: active },
|
||||
{ value: '미사용', label: '미사용', count: inactive },
|
||||
];
|
||||
interface ProcessListClientProps {
|
||||
initialData?: Process[];
|
||||
initialStats?: { total: number; active: number; inactive: number };
|
||||
}
|
||||
|
||||
export default function ProcessListClient() {
|
||||
export default function ProcessListClient({ initialData = [], initialStats }: ProcessListClientProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// 상태
|
||||
const [processes] = useState<Process[]>(mockProcesses);
|
||||
const [processes, setProcesses] = useState<Process[]>(initialData);
|
||||
const [stats, setStats] = useState(initialStats ?? { total: 0, active: 0, inactive: 0 });
|
||||
const [activeTab, setActiveTab] = useState('all');
|
||||
const [searchValue, setSearchValue] = useState('');
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
|
||||
const itemsPerPage = 20;
|
||||
|
||||
// 데이터 로드
|
||||
const loadData = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const [listResult, statsResult] = await Promise.all([
|
||||
getProcessList({ size: 1000 }), // 전체 조회
|
||||
getProcessStats(),
|
||||
]);
|
||||
|
||||
if (listResult.success && listResult.data) {
|
||||
setProcesses(listResult.data.items);
|
||||
}
|
||||
if (statsResult.success && statsResult.data) {
|
||||
setStats({
|
||||
total: statsResult.data.total,
|
||||
active: statsResult.data.active,
|
||||
inactive: statsResult.data.inactive,
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
toast.error('데이터 로드에 실패했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 초기 데이터가 없으면 로드
|
||||
useEffect(() => {
|
||||
if (initialData.length === 0) {
|
||||
loadData();
|
||||
}
|
||||
}, [initialData.length, loadData]);
|
||||
|
||||
// 필터링된 데이터
|
||||
const filteredProcesses = useMemo(() => {
|
||||
return processes.filter(process => {
|
||||
return processes.filter((process) => {
|
||||
// 탭 필터
|
||||
if (activeTab !== 'all' && process.status !== activeTab) {
|
||||
return false;
|
||||
@@ -137,7 +117,14 @@ export default function ProcessListClient() {
|
||||
}, [filteredProcesses, currentPage, itemsPerPage]);
|
||||
|
||||
// 탭 옵션
|
||||
const tabOptions = useMemo(() => getTabOptions(processes), [processes]);
|
||||
const tabOptions: TabOption[] = useMemo(
|
||||
() => [
|
||||
{ value: 'all', label: '전체', count: stats.total },
|
||||
{ value: '사용중', label: '사용중', count: stats.active },
|
||||
{ value: '미사용', label: '미사용', count: stats.inactive },
|
||||
],
|
||||
[stats]
|
||||
);
|
||||
|
||||
// 핸들러
|
||||
const handleTabChange = useCallback((value: string) => {
|
||||
@@ -151,7 +138,7 @@ export default function ProcessListClient() {
|
||||
}, []);
|
||||
|
||||
const handleToggleSelection = useCallback((id: string) => {
|
||||
setSelectedItems(prev => {
|
||||
setSelectedItems((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(id)) {
|
||||
newSet.delete(id);
|
||||
@@ -166,159 +153,266 @@ export default function ProcessListClient() {
|
||||
if (selectedItems.size === paginatedData.length) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(paginatedData.map(p => p.id)));
|
||||
setSelectedItems(new Set(paginatedData.map((p) => p.id)));
|
||||
}
|
||||
}, [selectedItems.size, paginatedData]);
|
||||
|
||||
const handleRowClick = useCallback((process: Process) => {
|
||||
router.push(`/ko/master-data/process-management/${process.id}`);
|
||||
}, [router]);
|
||||
const handleRowClick = useCallback(
|
||||
(process: Process) => {
|
||||
router.push(`/ko/master-data/process-management/${process.id}`);
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
const handleCreate = useCallback(() => {
|
||||
router.push('/ko/master-data/process-management/new');
|
||||
}, [router]);
|
||||
|
||||
const handleEdit = useCallback((e: React.MouseEvent, processId: string) => {
|
||||
e.stopPropagation();
|
||||
router.push(`/ko/master-data/process-management/${processId}/edit`);
|
||||
}, [router]);
|
||||
const handleEdit = useCallback(
|
||||
(e: React.MouseEvent, processId: string) => {
|
||||
e.stopPropagation();
|
||||
router.push(`/ko/master-data/process-management/${processId}/edit`);
|
||||
},
|
||||
[router]
|
||||
);
|
||||
|
||||
const handleDelete = useCallback((e: React.MouseEvent, processId: string) => {
|
||||
const handleDeleteClick = useCallback((e: React.MouseEvent, processId: string) => {
|
||||
e.stopPropagation();
|
||||
// TODO: 삭제 확인 모달 및 API 연동
|
||||
console.log('Delete process:', processId);
|
||||
setDeleteTargetId(processId);
|
||||
setDeleteDialogOpen(true);
|
||||
}, []);
|
||||
|
||||
// 테이블 행 렌더링
|
||||
const renderTableRow = useCallback((process: Process, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(process.id);
|
||||
const handleDeleteConfirm = useCallback(async () => {
|
||||
if (!deleteTargetId) return;
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
key={process.id}
|
||||
className="cursor-pointer hover:bg-muted/50"
|
||||
onClick={() => handleRowClick(process)}
|
||||
>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox
|
||||
checked={isSelected}
|
||||
onCheckedChange={() => handleToggleSelection(process.id)}
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
|
||||
<TableCell className="font-medium">{process.processCode}</TableCell>
|
||||
<TableCell>
|
||||
<div>
|
||||
<div className="font-medium">{process.processName}</div>
|
||||
{process.description && (
|
||||
<div className="text-sm text-muted-foreground">{process.description}</div>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Badge variant="secondary">{process.processType}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{process.department}</TableCell>
|
||||
<TableCell className="text-center">
|
||||
{process.classificationRules.length > 0 ? (
|
||||
<Badge variant="outline">{process.classificationRules.length}</Badge>
|
||||
) : (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-center">{process.requiredWorkers}명</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Badge variant={process.status === '사용중' ? 'default' : 'secondary'}>
|
||||
{process.status}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
{isSelected && (
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={(e) => handleEdit(e, process.id)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-destructive hover:text-destructive"
|
||||
onClick={(e) => handleDelete(e, process.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const result = await deleteProcess(deleteTargetId);
|
||||
if (result.success) {
|
||||
toast.success('공정이 삭제되었습니다.');
|
||||
setProcesses((prev) => prev.filter((p) => p.id !== deleteTargetId));
|
||||
setStats((prev) => ({
|
||||
...prev,
|
||||
total: prev.total - 1,
|
||||
active: prev.active - (processes.find((p) => p.id === deleteTargetId)?.status === '사용중' ? 1 : 0),
|
||||
inactive: prev.inactive - (processes.find((p) => p.id === deleteTargetId)?.status === '미사용' ? 1 : 0),
|
||||
}));
|
||||
setSelectedItems((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
newSet.delete(deleteTargetId);
|
||||
return newSet;
|
||||
});
|
||||
} else {
|
||||
toast.error(result.error || '삭제에 실패했습니다.');
|
||||
}
|
||||
} catch {
|
||||
toast.error('삭제 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setDeleteDialogOpen(false);
|
||||
setDeleteTargetId(null);
|
||||
}
|
||||
}, [deleteTargetId, processes]);
|
||||
|
||||
const handleBulkDelete = useCallback(async () => {
|
||||
if (selectedItems.size === 0) {
|
||||
toast.warning('삭제할 항목을 선택해주세요.');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const ids = Array.from(selectedItems);
|
||||
const result = await deleteProcesses(ids);
|
||||
if (result.success) {
|
||||
toast.success(`${result.deletedCount}개 항목이 삭제되었습니다.`);
|
||||
await loadData();
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
toast.error(result.error || '일괄 삭제에 실패했습니다.');
|
||||
}
|
||||
} catch {
|
||||
toast.error('일괄 삭제 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [selectedItems, loadData]);
|
||||
|
||||
const handleToggleStatus = useCallback(
|
||||
async (e: React.MouseEvent, processId: string) => {
|
||||
e.stopPropagation();
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const result = await toggleProcessActive(processId);
|
||||
if (result.success && result.data) {
|
||||
toast.success('상태가 변경되었습니다.');
|
||||
setProcesses((prev) => prev.map((p) => (p.id === processId ? result.data! : p)));
|
||||
// 통계 업데이트
|
||||
const oldProcess = processes.find((p) => p.id === processId);
|
||||
if (oldProcess) {
|
||||
const wasActive = oldProcess.status === '사용중';
|
||||
setStats((prev) => ({
|
||||
...prev,
|
||||
active: wasActive ? prev.active - 1 : prev.active + 1,
|
||||
inactive: wasActive ? prev.inactive + 1 : prev.inactive - 1,
|
||||
}));
|
||||
}
|
||||
} else {
|
||||
toast.error(result.error || '상태 변경에 실패했습니다.');
|
||||
}
|
||||
} catch {
|
||||
toast.error('상태 변경 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[processes]
|
||||
);
|
||||
|
||||
// 테이블 행 렌더링
|
||||
const renderTableRow = useCallback(
|
||||
(process: Process, index: number, globalIndex: number) => {
|
||||
const isSelected = selectedItems.has(process.id);
|
||||
|
||||
return (
|
||||
<TableRow key={process.id} className="cursor-pointer hover:bg-muted/50" onClick={() => handleRowClick(process)}>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Checkbox checked={isSelected} onCheckedChange={() => handleToggleSelection(process.id)} />
|
||||
</TableCell>
|
||||
<TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
|
||||
<TableCell className="font-medium">{process.processCode}</TableCell>
|
||||
<TableCell>
|
||||
<div>
|
||||
<div className="font-medium">{process.processName}</div>
|
||||
{process.description && <div className="text-sm text-muted-foreground">{process.description}</div>}
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}, [selectedItems, handleToggleSelection, handleRowClick, handleEdit, handleDelete]);
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
<Badge variant="secondary">{process.processType}</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{process.department}</TableCell>
|
||||
<TableCell className="text-center">
|
||||
{process.classificationRules.length > 0 ? (
|
||||
<Badge variant="outline">{process.classificationRules.length}</Badge>
|
||||
) : (
|
||||
<span className="text-muted-foreground">-</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-center">{process.requiredWorkers}명</TableCell>
|
||||
<TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
|
||||
<Badge
|
||||
variant={process.status === '사용중' ? 'default' : 'secondary'}
|
||||
className="cursor-pointer"
|
||||
onClick={(e) => handleToggleStatus(e, process.id)}
|
||||
>
|
||||
{process.status}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
{isSelected && (
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={(e) => handleEdit(e, process.id)}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 text-destructive hover:text-destructive"
|
||||
onClick={(e) => handleDeleteClick(e, process.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
},
|
||||
[selectedItems, handleToggleSelection, handleRowClick, handleEdit, handleDeleteClick, handleToggleStatus]
|
||||
);
|
||||
|
||||
// 모바일 카드 렌더링
|
||||
const renderMobileCard = useCallback((
|
||||
process: Process,
|
||||
index: number,
|
||||
globalIndex: number,
|
||||
isSelected: boolean,
|
||||
onToggle: () => void
|
||||
) => {
|
||||
return (
|
||||
<MobileCard
|
||||
title={process.processName}
|
||||
subtitle={process.processCode}
|
||||
description={process.description}
|
||||
badge={process.status}
|
||||
badgeVariant={process.status === '사용중' ? 'default' : 'secondary'}
|
||||
isSelected={isSelected}
|
||||
onToggle={onToggle}
|
||||
onClick={() => handleRowClick(process)}
|
||||
details={[
|
||||
{ label: '구분', value: process.processType },
|
||||
{ label: '담당부서', value: process.department },
|
||||
{ label: '인원', value: `${process.requiredWorkers}명` },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}, [handleRowClick]);
|
||||
const renderMobileCard = useCallback(
|
||||
(process: Process, index: number, globalIndex: number, isSelected: boolean, onToggle: () => void) => {
|
||||
return (
|
||||
<MobileCard
|
||||
title={process.processName}
|
||||
subtitle={process.processCode}
|
||||
description={process.description}
|
||||
badge={process.status}
|
||||
badgeVariant={process.status === '사용중' ? 'default' : 'secondary'}
|
||||
isSelected={isSelected}
|
||||
onToggle={onToggle}
|
||||
onClick={() => handleRowClick(process)}
|
||||
details={[
|
||||
{ label: '구분', value: process.processType },
|
||||
{ label: '담당부서', value: process.department },
|
||||
{ label: '인원', value: `${process.requiredWorkers}명` },
|
||||
]}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[handleRowClick]
|
||||
);
|
||||
|
||||
return (
|
||||
<IntegratedListTemplateV2
|
||||
title="공정 목록"
|
||||
icon={Wrench}
|
||||
headerActions={
|
||||
<div className="flex justify-end w-full">
|
||||
<Button onClick={handleCreate} className="gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
공정 등록
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
searchValue={searchValue}
|
||||
onSearchChange={handleSearchChange}
|
||||
searchPlaceholder="공정코드, 공정명, 담당부서 검색"
|
||||
tabs={tabOptions}
|
||||
activeTab={activeTab}
|
||||
onTabChange={handleTabChange}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
allData={filteredProcesses}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={handleToggleSelection}
|
||||
onToggleSelectAll={handleToggleSelectAll}
|
||||
getItemId={(item) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems: filteredProcesses.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
<>
|
||||
<IntegratedListTemplateV2
|
||||
title="공정 목록"
|
||||
icon={Wrench}
|
||||
headerActions={
|
||||
<div className="flex justify-end w-full gap-2">
|
||||
{selectedItems.size > 0 && (
|
||||
<Button variant="destructive" onClick={handleBulkDelete} disabled={isLoading}>
|
||||
{isLoading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Trash2 className="h-4 w-4 mr-2" />}
|
||||
선택 삭제 ({selectedItems.size})
|
||||
</Button>
|
||||
)}
|
||||
<Button onClick={handleCreate} className="gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
공정 등록
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
searchValue={searchValue}
|
||||
onSearchChange={handleSearchChange}
|
||||
searchPlaceholder="공정코드, 공정명, 담당부서 검색"
|
||||
tabs={tabOptions}
|
||||
activeTab={activeTab}
|
||||
onTabChange={handleTabChange}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
allData={filteredProcesses}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={handleToggleSelection}
|
||||
onToggleSelectAll={handleToggleSelectAll}
|
||||
getItemId={(item) => item.id}
|
||||
renderTableRow={renderTableRow}
|
||||
renderMobileCard={renderMobileCard}
|
||||
pagination={{
|
||||
currentPage,
|
||||
totalPages,
|
||||
totalItems: filteredProcesses.length,
|
||||
itemsPerPage,
|
||||
onPageChange: setCurrentPage,
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* 삭제 확인 다이얼로그 */}
|
||||
<AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>공정 삭제</AlertDialogTitle>
|
||||
<AlertDialogDescription>선택한 공정을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>취소</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleDeleteConfirm} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
|
||||
삭제
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,12 +33,12 @@ const getDocumentCode = (processName: string): string => {
|
||||
};
|
||||
|
||||
// 공정명을 부서명으로 매핑
|
||||
const getDepartmentName = (processName: string): string => {
|
||||
const getDepartmentName = (processName: string, department?: string): string => {
|
||||
if (processName.includes('스크린')) return '스크린 생산부서';
|
||||
if (processName.includes('슬랫')) return '슬랫 생산부서';
|
||||
if (processName.includes('절곡')) return '절곡 생산부서';
|
||||
if (processName.includes('포밍')) return '포밍 생산부서';
|
||||
return process?.department || '생산부서';
|
||||
return department || '생산부서';
|
||||
};
|
||||
|
||||
export function ProcessWorkLogPreviewModal({
|
||||
@@ -51,7 +51,7 @@ export function ProcessWorkLogPreviewModal({
|
||||
};
|
||||
|
||||
const documentCode = getDocumentCode(process.processName);
|
||||
const departmentName = getDepartmentName(process.processName);
|
||||
const departmentName = getDepartmentName(process.processName, process.department);
|
||||
const today = new Date().toLocaleDateString('ko-KR', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
|
||||
416
src/components/process-management/actions.ts
Normal file
416
src/components/process-management/actions.ts
Normal file
@@ -0,0 +1,416 @@
|
||||
'use server';
|
||||
|
||||
import { cookies } from 'next/headers';
|
||||
import type { Process, ProcessFormData, ClassificationRule } from '@/types/process';
|
||||
|
||||
// ============================================================================
|
||||
// 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 타입 정의
|
||||
// ============================================================================
|
||||
|
||||
interface ApiProcess {
|
||||
id: number;
|
||||
tenant_id: number;
|
||||
process_code: string;
|
||||
process_name: string;
|
||||
description: string | null;
|
||||
process_type: string;
|
||||
department: string | null;
|
||||
work_log_template: string | null;
|
||||
required_workers: number;
|
||||
equipment_info: string | null;
|
||||
work_steps: string[] | null;
|
||||
note: string | null;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
classification_rules?: ApiClassificationRule[];
|
||||
}
|
||||
|
||||
interface ApiClassificationRule {
|
||||
id: number;
|
||||
process_id: number;
|
||||
registration_type: string;
|
||||
rule_type: string;
|
||||
matching_type: string;
|
||||
condition_value: string;
|
||||
priority: number;
|
||||
description: string | null;
|
||||
is_active: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface ApiResponse<T> {
|
||||
success: boolean;
|
||||
message: string;
|
||||
data: T;
|
||||
}
|
||||
|
||||
interface PaginatedResponse<T> {
|
||||
current_page: number;
|
||||
data: T[];
|
||||
last_page: number;
|
||||
per_page: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 데이터 변환 함수
|
||||
// ============================================================================
|
||||
|
||||
function transformApiToFrontend(apiData: ApiProcess): Process {
|
||||
return {
|
||||
id: String(apiData.id),
|
||||
processCode: apiData.process_code,
|
||||
processName: apiData.process_name,
|
||||
description: apiData.description ?? undefined,
|
||||
processType: apiData.process_type as Process['processType'],
|
||||
department: apiData.department ?? '',
|
||||
workLogTemplate: apiData.work_log_template ?? undefined,
|
||||
classificationRules: (apiData.classification_rules ?? []).map(transformRuleApiToFrontend),
|
||||
requiredWorkers: apiData.required_workers,
|
||||
equipmentInfo: apiData.equipment_info ?? undefined,
|
||||
workSteps: apiData.work_steps ?? [],
|
||||
note: apiData.note ?? undefined,
|
||||
status: apiData.is_active ? '사용중' : '미사용',
|
||||
createdAt: apiData.created_at,
|
||||
updatedAt: apiData.updated_at,
|
||||
};
|
||||
}
|
||||
|
||||
function transformRuleApiToFrontend(apiRule: ApiClassificationRule): ClassificationRule {
|
||||
return {
|
||||
id: String(apiRule.id),
|
||||
registrationType: apiRule.registration_type as ClassificationRule['registrationType'],
|
||||
ruleType: apiRule.rule_type as ClassificationRule['ruleType'],
|
||||
matchingType: apiRule.matching_type as ClassificationRule['matchingType'],
|
||||
conditionValue: apiRule.condition_value,
|
||||
priority: apiRule.priority,
|
||||
description: apiRule.description ?? undefined,
|
||||
isActive: apiRule.is_active,
|
||||
createdAt: apiRule.created_at,
|
||||
};
|
||||
}
|
||||
|
||||
function transformFrontendToApi(data: ProcessFormData): Record<string, unknown> {
|
||||
return {
|
||||
process_name: data.processName,
|
||||
process_type: data.processType,
|
||||
department: data.department || null,
|
||||
work_log_template: data.workLogTemplate || null,
|
||||
required_workers: data.requiredWorkers,
|
||||
equipment_info: data.equipmentInfo || null,
|
||||
work_steps: data.workSteps ? data.workSteps.split(',').map((s) => s.trim()).filter(Boolean) : [],
|
||||
note: data.note || null,
|
||||
is_active: data.isActive,
|
||||
classification_rules: data.classificationRules.map((rule) => ({
|
||||
registration_type: rule.registrationType,
|
||||
rule_type: rule.ruleType,
|
||||
matching_type: rule.matchingType,
|
||||
condition_value: rule.conditionValue,
|
||||
priority: rule.priority,
|
||||
description: rule.description || null,
|
||||
is_active: rule.isActive,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// API 함수
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 공정 목록 조회
|
||||
*/
|
||||
export async function getProcessList(params?: {
|
||||
page?: number;
|
||||
size?: number;
|
||||
q?: string;
|
||||
status?: string;
|
||||
process_type?: string;
|
||||
}): Promise<{ success: boolean; data?: { items: Process[]; total: number; page: number; totalPages: number }; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const searchParams = new URLSearchParams();
|
||||
|
||||
if (params?.page) searchParams.set('page', String(params.page));
|
||||
if (params?.size) searchParams.set('size', String(params.size));
|
||||
if (params?.q) searchParams.set('q', params.q);
|
||||
if (params?.status) searchParams.set('status', params.status);
|
||||
if (params?.process_type) searchParams.set('process_type', params.process_type);
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.API_URL}/v1/processes?${searchParams.toString()}`,
|
||||
{ method: 'GET', headers, cache: 'no-store' }
|
||||
);
|
||||
|
||||
const result: ApiResponse<PaginatedResponse<ApiProcess>> = await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return { success: false, error: result.message || '목록 조회에 실패했습니다.' };
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
items: result.data.data.map(transformApiToFrontend),
|
||||
total: result.data.total,
|
||||
page: result.data.current_page,
|
||||
totalPages: result.data.last_page,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[getProcessList] Error:', error);
|
||||
return { success: false, error: '서버 오류가 발생했습니다.' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 공정 상세 조회
|
||||
*/
|
||||
export async function getProcessById(id: string): Promise<{ success: boolean; data?: Process; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(`${process.env.API_URL}/v1/processes/${id}`, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
const result: ApiResponse<ApiProcess> = await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return { success: false, error: result.message || '조회에 실패했습니다.' };
|
||||
}
|
||||
|
||||
return { success: true, data: transformApiToFrontend(result.data) };
|
||||
} catch (error) {
|
||||
console.error('[getProcessById] Error:', error);
|
||||
return { success: false, error: '서버 오류가 발생했습니다.' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 공정 생성
|
||||
*/
|
||||
export async function createProcess(data: ProcessFormData): Promise<{ success: boolean; data?: Process; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const apiData = transformFrontendToApi(data);
|
||||
|
||||
const response = await fetch(`${process.env.API_URL}/v1/processes`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(apiData),
|
||||
});
|
||||
|
||||
const result: ApiResponse<ApiProcess> = await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return { success: false, error: result.message || '등록에 실패했습니다.' };
|
||||
}
|
||||
|
||||
return { success: true, data: transformApiToFrontend(result.data) };
|
||||
} catch (error) {
|
||||
console.error('[createProcess] Error:', error);
|
||||
return { success: false, error: '서버 오류가 발생했습니다.' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 공정 수정
|
||||
*/
|
||||
export async function updateProcess(id: string, data: ProcessFormData): Promise<{ success: boolean; data?: Process; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const apiData = transformFrontendToApi(data);
|
||||
|
||||
const response = await fetch(`${process.env.API_URL}/v1/processes/${id}`, {
|
||||
method: 'PUT',
|
||||
headers,
|
||||
body: JSON.stringify(apiData),
|
||||
});
|
||||
|
||||
const result: ApiResponse<ApiProcess> = await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return { success: false, error: result.message || '수정에 실패했습니다.' };
|
||||
}
|
||||
|
||||
return { success: true, data: transformApiToFrontend(result.data) };
|
||||
} catch (error) {
|
||||
console.error('[updateProcess] Error:', error);
|
||||
return { success: false, error: '서버 오류가 발생했습니다.' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 공정 삭제
|
||||
*/
|
||||
export async function deleteProcess(id: string): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(`${process.env.API_URL}/v1/processes/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers,
|
||||
});
|
||||
|
||||
const result: ApiResponse<null> = await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return { success: false, error: result.message || '삭제에 실패했습니다.' };
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('[deleteProcess] Error:', error);
|
||||
return { success: false, error: '서버 오류가 발생했습니다.' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 공정 일괄 삭제
|
||||
*/
|
||||
export async function deleteProcesses(ids: string[]): Promise<{ success: boolean; deletedCount?: number; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(`${process.env.API_URL}/v1/processes`, {
|
||||
method: 'DELETE',
|
||||
headers,
|
||||
body: JSON.stringify({ ids: ids.map((id) => parseInt(id, 10)) }),
|
||||
});
|
||||
|
||||
const result: ApiResponse<{ deleted_count: number }> = await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return { success: false, error: result.message || '일괄 삭제에 실패했습니다.' };
|
||||
}
|
||||
|
||||
return { success: true, deletedCount: result.data.deleted_count };
|
||||
} catch (error) {
|
||||
console.error('[deleteProcesses] Error:', error);
|
||||
return { success: false, error: '서버 오류가 발생했습니다.' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 공정 상태 토글
|
||||
*/
|
||||
export async function toggleProcessActive(id: string): Promise<{ success: boolean; data?: Process; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(`${process.env.API_URL}/v1/processes/${id}/toggle`, {
|
||||
method: 'PATCH',
|
||||
headers,
|
||||
});
|
||||
|
||||
const result: ApiResponse<ApiProcess> = await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return { success: false, error: result.message || '상태 변경에 실패했습니다.' };
|
||||
}
|
||||
|
||||
return { success: true, data: transformApiToFrontend(result.data) };
|
||||
} catch (error) {
|
||||
console.error('[toggleProcessActive] Error:', error);
|
||||
return { success: false, error: '서버 오류가 발생했습니다.' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 공정 옵션 목록 (드롭다운용)
|
||||
*/
|
||||
export async function getProcessOptions(): Promise<{
|
||||
success: boolean;
|
||||
data?: Array<{ id: string; processCode: string; processName: string; processType: string; department: string }>;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(`${process.env.API_URL}/v1/processes/options`, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
const result: ApiResponse<Array<{ id: number; process_code: string; process_name: string; process_type: string; department: string }>> =
|
||||
await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return { success: false, error: result.message || '옵션 조회에 실패했습니다.' };
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: result.data.map((item) => ({
|
||||
id: String(item.id),
|
||||
processCode: item.process_code,
|
||||
processName: item.process_name,
|
||||
processType: item.process_type,
|
||||
department: item.department ?? '',
|
||||
})),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[getProcessOptions] Error:', error);
|
||||
return { success: false, error: '서버 오류가 발생했습니다.' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 공정 통계
|
||||
*/
|
||||
export async function getProcessStats(): Promise<{
|
||||
success: boolean;
|
||||
data?: { total: number; active: number; inactive: number; byType: Record<string, number> };
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(`${process.env.API_URL}/v1/processes/stats`, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
const result: ApiResponse<{ total: number; active: number; inactive: number; by_type: Record<string, number> }> = await response.json();
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return { success: false, error: result.message || '통계 조회에 실패했습니다.' };
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
total: result.data.total,
|
||||
active: result.data.active,
|
||||
inactive: result.data.inactive,
|
||||
byType: result.data.by_type,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[getProcessStats] Error:', error);
|
||||
return { success: false, error: '서버 오류가 발생했습니다.' };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user