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,11 +2,12 @@
|
||||
|
||||
/**
|
||||
* 검사 등록 페이지
|
||||
* API 연동 완료 (2025-12-26)
|
||||
*/
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ClipboardCheck, ImageIcon } from 'lucide-react';
|
||||
import { ClipboardCheck, ImageIcon, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -14,6 +15,8 @@ import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { toast } from 'sonner';
|
||||
import { createInspection } from './actions';
|
||||
import { inspectionItemsTemplate, judgeMeasurement } from './mockData';
|
||||
import type { InspectionItem, QualityCheckItem, MeasurementItem } from './types';
|
||||
|
||||
@@ -38,6 +41,9 @@ export function InspectionCreate() {
|
||||
// validation 에러 상태
|
||||
const [validationErrors, setValidationErrors] = useState<string[]>([]);
|
||||
|
||||
// 제출 상태
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
// 폼 입력 핸들러
|
||||
const handleInputChange = (field: string, value: string | number) => {
|
||||
setFormData(prev => ({ ...prev, [field]: value }));
|
||||
@@ -115,15 +121,37 @@ export function InspectionCreate() {
|
||||
};
|
||||
|
||||
// 검사완료
|
||||
const handleSubmit = () => {
|
||||
const handleSubmit = async () => {
|
||||
// validation 체크
|
||||
if (!validateForm()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: API 호출
|
||||
console.log('Submit:', { ...formData, items: inspectionItems });
|
||||
router.push('/quality/inspections');
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const result = await createInspection({
|
||||
inspectionType: 'PQC', // 기본값: 공정검사
|
||||
lotNo: formData.lotNo,
|
||||
itemName: formData.itemName,
|
||||
processName: formData.processName,
|
||||
quantity: formData.quantity,
|
||||
unit: 'EA', // 기본 단위
|
||||
remarks: formData.remarks || undefined,
|
||||
items: inspectionItems,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success('검사가 등록되었습니다.');
|
||||
router.push('/quality/inspections');
|
||||
} else {
|
||||
toast.error(result.error || '검사 등록에 실패했습니다.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[InspectionCreate] handleSubmit error:', error);
|
||||
toast.error('검사 등록 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -136,11 +164,18 @@ export function InspectionCreate() {
|
||||
<h1 className="text-xl font-semibold">검사 등록</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
<Button variant="outline" onClick={handleCancel} disabled={isSubmitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSubmit}>
|
||||
검사완료
|
||||
<Button onClick={handleSubmit} disabled={isSubmitting}>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
등록 중...
|
||||
</>
|
||||
) : (
|
||||
'검사완료'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
/**
|
||||
* 검사 상세/수정 페이지
|
||||
* API 연동 완료 (2025-12-26)
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useMemo } from 'react';
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useRouter, useSearchParams } from 'next/navigation';
|
||||
import { ClipboardCheck, Printer, Paperclip } from 'lucide-react';
|
||||
import { ClipboardCheck, Printer, Paperclip, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -24,8 +25,10 @@ import {
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { mockInspections, judgmentColorMap, judgeMeasurement } from './mockData';
|
||||
import type { InspectionItem, QualityCheckItem, MeasurementItem } from './types';
|
||||
import { toast } from 'sonner';
|
||||
import { getInspectionById, updateInspection } from './actions';
|
||||
import { judgmentColorMap, judgeMeasurement } from './mockData';
|
||||
import type { Inspection, InspectionItem, QualityCheckItem, MeasurementItem } from './types';
|
||||
|
||||
interface InspectionDetailProps {
|
||||
id: string;
|
||||
@@ -36,20 +39,42 @@ export function InspectionDetail({ id }: InspectionDetailProps) {
|
||||
const searchParams = useSearchParams();
|
||||
const isEditMode = searchParams.get('mode') === 'edit';
|
||||
|
||||
// 검사 데이터 조회 (mockData에서)
|
||||
const inspection = useMemo(() => {
|
||||
return mockInspections.find(i => i.id === id);
|
||||
}, [id]);
|
||||
// 검사 데이터 상태
|
||||
const [inspection, setInspection] = useState<Inspection | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
// 수정 폼 상태
|
||||
const [editReason, setEditReason] = useState('');
|
||||
const [inspectionItems, setInspectionItems] = useState<InspectionItem[]>(
|
||||
inspection?.items || []
|
||||
);
|
||||
const [inspectionItems, setInspectionItems] = useState<InspectionItem[]>([]);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
// validation 에러 상태
|
||||
const [validationErrors, setValidationErrors] = useState<string[]>([]);
|
||||
|
||||
// API로 검사 데이터 로드
|
||||
const loadInspection = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const result = await getInspectionById(id);
|
||||
if (result.success && result.data) {
|
||||
setInspection(result.data);
|
||||
setInspectionItems(result.data.items || []);
|
||||
} else {
|
||||
toast.error(result.error || '검사 데이터를 불러오는데 실패했습니다.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[InspectionDetail] loadInspection error:', error);
|
||||
toast.error('검사 데이터 로드 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
// 컴포넌트 마운트 시 데이터 로드
|
||||
useEffect(() => {
|
||||
loadInspection();
|
||||
}, [loadInspection]);
|
||||
|
||||
// 품질 검사 항목 결과 변경 (양호/불량)
|
||||
const handleQualityResultChange = useCallback((itemId: string, result: '양호' | '불량') => {
|
||||
setInspectionItems(prev => prev.map(item => {
|
||||
@@ -128,14 +153,31 @@ export function InspectionDetail({ id }: InspectionDetailProps) {
|
||||
};
|
||||
|
||||
// 수정 완료
|
||||
const handleSubmitEdit = () => {
|
||||
const handleSubmitEdit = async () => {
|
||||
// validation 체크
|
||||
if (!validateForm()) {
|
||||
return;
|
||||
}
|
||||
// TODO: API 호출
|
||||
console.log('Submit Edit:', { editReason, items: inspectionItems });
|
||||
router.push(`/quality/inspections/${id}`);
|
||||
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
const result = await updateInspection(id, {
|
||||
items: inspectionItems,
|
||||
remarks: editReason,
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
toast.success('검사가 수정되었습니다.');
|
||||
router.push(`/quality/inspections/${id}`);
|
||||
} else {
|
||||
toast.error(result.error || '검사 수정에 실패했습니다.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[InspectionDetail] handleSubmitEdit error:', error);
|
||||
toast.error('검사 수정 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 수정 사유 변경 핸들러
|
||||
@@ -153,6 +195,18 @@ export function InspectionDetail({ id }: InspectionDetailProps) {
|
||||
console.log('Print Report');
|
||||
};
|
||||
|
||||
// 로딩 상태
|
||||
if (isLoading) {
|
||||
return (
|
||||
<PageLayout>
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
// 데이터 없음
|
||||
if (!inspection) {
|
||||
return (
|
||||
<PageLayout>
|
||||
@@ -337,11 +391,18 @@ export function InspectionDetail({ id }: InspectionDetailProps) {
|
||||
<h1 className="text-xl font-semibold">검사 수정</h1>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" onClick={handleCancelEdit}>
|
||||
<Button variant="outline" onClick={handleCancelEdit} disabled={isSubmitting}>
|
||||
취소
|
||||
</Button>
|
||||
<Button onClick={handleSubmitEdit}>
|
||||
수정 완료
|
||||
<Button onClick={handleSubmitEdit} disabled={isSubmitting}>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
수정 중...
|
||||
</>
|
||||
) : (
|
||||
'수정 완료'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -3,11 +3,12 @@
|
||||
/**
|
||||
* 검사 목록 페이지
|
||||
* IntegratedListTemplateV2 패턴 적용
|
||||
* API 연동 완료 (2025-12-26)
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Plus, ClipboardCheck, Clock, PlayCircle, CheckCircle2, AlertTriangle } from 'lucide-react';
|
||||
import { Plus, ClipboardCheck, Clock, PlayCircle, CheckCircle2, AlertTriangle, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { TableCell, TableRow } from '@/components/ui/table';
|
||||
@@ -19,8 +20,10 @@ import {
|
||||
StatCard,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import { mockInspections, mockStats, statusColorMap, inspectionTypeLabels } from './mockData';
|
||||
import type { Inspection, InspectionStatus } from './types';
|
||||
import { toast } from 'sonner';
|
||||
import { getInspections, getInspectionStats } from './actions';
|
||||
import { statusColorMap, inspectionTypeLabels } from './mockData';
|
||||
import type { Inspection, InspectionStatus, InspectionStats } from './types';
|
||||
|
||||
// 탭 필터 정의
|
||||
type TabFilter = '전체' | InspectionStatus;
|
||||
@@ -30,54 +33,94 @@ const ITEMS_PER_PAGE = 20;
|
||||
|
||||
export function InspectionList() {
|
||||
const router = useRouter();
|
||||
|
||||
// ===== 상태 관리 =====
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [activeTab, setActiveTab] = useState<TabFilter>('전체');
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [inspections, setInspections] = useState<Inspection[]>([]);
|
||||
const [totalItems, setTotalItems] = useState(0);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [statsData, setStatsData] = useState<InspectionStats>({
|
||||
waitingCount: 0,
|
||||
inProgressCount: 0,
|
||||
completedCount: 0,
|
||||
defectRate: 0,
|
||||
});
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
// 탭별 카운트 계산
|
||||
const tabCounts = useMemo(() => {
|
||||
return {
|
||||
전체: mockInspections.length,
|
||||
대기: mockInspections.filter((i) => i.status === '대기').length,
|
||||
진행중: mockInspections.filter((i) => i.status === '진행중').length,
|
||||
완료: mockInspections.filter((i) => i.status === '완료').length,
|
||||
};
|
||||
}, []);
|
||||
// ===== 데이터 로드 =====
|
||||
const loadData = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
// 병렬로 목록 + 통계 조회
|
||||
const [listResult, statsResult] = await Promise.all([
|
||||
getInspections({
|
||||
page: currentPage,
|
||||
size: ITEMS_PER_PAGE,
|
||||
q: searchTerm || undefined,
|
||||
status: activeTab !== '전체' ? activeTab : undefined,
|
||||
}),
|
||||
getInspectionStats(),
|
||||
]);
|
||||
|
||||
// 탭 옵션
|
||||
if (listResult.success) {
|
||||
setInspections(listResult.data);
|
||||
setTotalItems(listResult.pagination.total);
|
||||
setTotalPages(listResult.pagination.lastPage);
|
||||
} else {
|
||||
toast.error(listResult.error || '검사 목록 조회에 실패했습니다.');
|
||||
}
|
||||
|
||||
if (statsResult.success && statsResult.data) {
|
||||
setStatsData(statsResult.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[InspectionList] loadData error:', error);
|
||||
toast.error('데이터 로드 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [currentPage, searchTerm, activeTab]);
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
// 탭 옵션 (통계 기반)
|
||||
const tabs: TabOption[] = [
|
||||
{ value: '전체', label: '전체', count: tabCounts.전체 },
|
||||
{ value: '대기', label: '대기', count: tabCounts.대기, color: 'gray' },
|
||||
{ value: '진행중', label: '진행중', count: tabCounts.진행중, color: 'blue' },
|
||||
{ value: '완료', label: '완료', count: tabCounts.완료, color: 'green' },
|
||||
{ value: '전체', label: '전체', count: totalItems },
|
||||
{ value: '대기', label: '대기', count: statsData.waitingCount, color: 'gray' },
|
||||
{ value: '진행중', label: '진행중', count: statsData.inProgressCount, color: 'blue' },
|
||||
{ value: '완료', label: '완료', count: statsData.completedCount, color: 'green' },
|
||||
];
|
||||
|
||||
// 통계 카드
|
||||
const stats: StatCard[] = [
|
||||
{
|
||||
label: '금일 대기 건수',
|
||||
value: `${mockStats.waitingCount}건`,
|
||||
value: `${statsData.waitingCount}건`,
|
||||
icon: Clock,
|
||||
iconColor: 'text-gray-600',
|
||||
},
|
||||
{
|
||||
label: '진행 중 검사',
|
||||
value: `${mockStats.inProgressCount}건`,
|
||||
value: `${statsData.inProgressCount}건`,
|
||||
icon: PlayCircle,
|
||||
iconColor: 'text-blue-600',
|
||||
},
|
||||
{
|
||||
label: '금일 완료 건수',
|
||||
value: `${mockStats.completedCount}건`,
|
||||
value: `${statsData.completedCount}건`,
|
||||
icon: CheckCircle2,
|
||||
iconColor: 'text-green-600',
|
||||
},
|
||||
{
|
||||
label: '불량 발생률',
|
||||
value: `${mockStats.defectRate}%`,
|
||||
value: `${statsData.defectRate.toFixed(1)}%`,
|
||||
icon: AlertTriangle,
|
||||
iconColor: mockStats.defectRate > 0 ? 'text-red-600' : 'text-gray-400',
|
||||
iconColor: statsData.defectRate > 0 ? 'text-red-600' : 'text-gray-400',
|
||||
},
|
||||
];
|
||||
|
||||
@@ -92,40 +135,11 @@ export function InspectionList() {
|
||||
{ key: 'inspector', label: '담당자', className: 'w-[80px]' },
|
||||
];
|
||||
|
||||
// 필터링된 데이터
|
||||
const filteredInspections = useMemo(() => {
|
||||
let result = [...mockInspections];
|
||||
|
||||
// 탭 필터
|
||||
if (activeTab !== '전체') {
|
||||
result = result.filter((i) => i.status === activeTab);
|
||||
}
|
||||
|
||||
// 검색 필터
|
||||
if (searchTerm) {
|
||||
const term = searchTerm.toLowerCase();
|
||||
result = result.filter(
|
||||
(i) =>
|
||||
i.lotNo.toLowerCase().includes(term) ||
|
||||
i.itemName.toLowerCase().includes(term) ||
|
||||
i.processName.toLowerCase().includes(term)
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [activeTab, searchTerm]);
|
||||
|
||||
// 페이지네이션 데이터
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
|
||||
return filteredInspections.slice(startIndex, startIndex + ITEMS_PER_PAGE);
|
||||
}, [filteredInspections, currentPage]);
|
||||
|
||||
// 페이지네이션 설정
|
||||
// 페이지네이션 설정 (API 기반)
|
||||
const pagination = {
|
||||
currentPage,
|
||||
totalPages: Math.ceil(filteredInspections.length / ITEMS_PER_PAGE),
|
||||
totalItems: filteredInspections.length,
|
||||
totalPages,
|
||||
totalItems,
|
||||
itemsPerPage: ITEMS_PER_PAGE,
|
||||
onPageChange: setCurrentPage,
|
||||
};
|
||||
@@ -144,12 +158,12 @@ export function InspectionList() {
|
||||
}, []);
|
||||
|
||||
const handleToggleSelectAll = useCallback(() => {
|
||||
if (selectedItems.size === paginatedData.length) {
|
||||
if (selectedItems.size === inspections.length) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(paginatedData.map((i) => i.id)));
|
||||
setSelectedItems(new Set(inspections.map((i) => i.id)));
|
||||
}
|
||||
}, [paginatedData, selectedItems.size]);
|
||||
}, [inspections, selectedItems.size]);
|
||||
|
||||
// 상세 페이지 이동
|
||||
const handleView = useCallback((id: string) => {
|
||||
@@ -257,6 +271,15 @@ export function InspectionList() {
|
||||
</Button>
|
||||
);
|
||||
|
||||
// 로딩 상태
|
||||
if (isLoading && inspections.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-16">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<IntegratedListTemplateV2<Inspection>
|
||||
title="검사 목록"
|
||||
@@ -271,9 +294,9 @@ export function InspectionList() {
|
||||
activeTab={activeTab}
|
||||
onTabChange={handleTabChange}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
totalCount={filteredInspections.length}
|
||||
allData={filteredInspections}
|
||||
data={inspections}
|
||||
totalCount={totalItems}
|
||||
allData={inspections}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={handleToggleSelection}
|
||||
onToggleSelectAll={handleToggleSelectAll}
|
||||
|
||||
626
src/components/quality/InspectionManagement/actions.ts
Normal file
626
src/components/quality/InspectionManagement/actions.ts
Normal file
@@ -0,0 +1,626 @@
|
||||
'use server';
|
||||
|
||||
/**
|
||||
* 검사 관리 Server Actions
|
||||
* API 연동 완료 (2025-12-26)
|
||||
*
|
||||
* API Endpoints:
|
||||
* - GET /api/v1/inspections - 목록 조회
|
||||
* - GET /api/v1/inspections/stats - 통계 조회
|
||||
* - GET /api/v1/inspections/{id} - 상세 조회
|
||||
* - POST /api/v1/inspections - 등록
|
||||
* - PUT /api/v1/inspections/{id} - 수정
|
||||
* - DELETE /api/v1/inspections/{id} - 삭제
|
||||
* - PATCH /api/v1/inspections/{id}/complete - 검사 완료 처리
|
||||
*/
|
||||
|
||||
import { cookies } from 'next/headers';
|
||||
import type {
|
||||
Inspection,
|
||||
InspectionStats,
|
||||
InspectionType,
|
||||
InspectionStatus,
|
||||
InspectionItem,
|
||||
} from './types';
|
||||
|
||||
// ===== 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 InspectionApiItem {
|
||||
id: number;
|
||||
inspection_no: string;
|
||||
inspection_type: 'IQC' | 'PQC' | 'FQC';
|
||||
request_date: string;
|
||||
inspection_date?: string;
|
||||
item_name: string;
|
||||
lot_no: string;
|
||||
process_name: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
status: 'waiting' | 'in_progress' | 'completed';
|
||||
result?: 'pass' | 'fail';
|
||||
inspector_id?: number;
|
||||
inspector?: { id: number; name: string };
|
||||
items?: Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
type: 'quality' | 'measurement';
|
||||
spec: string;
|
||||
unit?: string;
|
||||
result?: string;
|
||||
measured_value?: number;
|
||||
judgment?: 'pass' | 'fail';
|
||||
}>;
|
||||
remarks?: string;
|
||||
opinion?: string;
|
||||
attachments?: Array<{
|
||||
id: string;
|
||||
file_name: string;
|
||||
file_url: string;
|
||||
file_type: string;
|
||||
uploaded_at: string;
|
||||
}>;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface InspectionApiPaginatedResponse {
|
||||
data: InspectionApiItem[];
|
||||
current_page: number;
|
||||
last_page: number;
|
||||
per_page: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface InspectionStatsApi {
|
||||
waiting_count: number;
|
||||
in_progress_count: number;
|
||||
completed_count: number;
|
||||
defect_rate: number;
|
||||
}
|
||||
|
||||
// ===== 페이지네이션 타입 =====
|
||||
interface PaginationMeta {
|
||||
currentPage: number;
|
||||
lastPage: number;
|
||||
perPage: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
// ===== 상태 변환 =====
|
||||
function mapApiStatus(status: InspectionApiItem['status']): InspectionStatus {
|
||||
switch (status) {
|
||||
case 'waiting':
|
||||
return '대기';
|
||||
case 'in_progress':
|
||||
return '진행중';
|
||||
case 'completed':
|
||||
return '완료';
|
||||
default:
|
||||
return '대기';
|
||||
}
|
||||
}
|
||||
|
||||
function mapFrontendStatus(status: InspectionStatus): string {
|
||||
switch (status) {
|
||||
case '대기':
|
||||
return 'waiting';
|
||||
case '진행중':
|
||||
return 'in_progress';
|
||||
case '완료':
|
||||
return 'completed';
|
||||
default:
|
||||
return 'waiting';
|
||||
}
|
||||
}
|
||||
|
||||
// ===== API → Frontend 변환 =====
|
||||
function transformApiToFrontend(api: InspectionApiItem): Inspection {
|
||||
const items: InspectionItem[] = (api.items || []).map((item) => {
|
||||
if (item.type === 'measurement') {
|
||||
return {
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
type: 'measurement' as const,
|
||||
spec: item.spec,
|
||||
unit: item.unit || '',
|
||||
measuredValue: item.measured_value,
|
||||
judgment: item.judgment === 'pass' ? '적합' : item.judgment === 'fail' ? '부적합' : undefined,
|
||||
};
|
||||
}
|
||||
return {
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
type: 'quality' as const,
|
||||
spec: item.spec,
|
||||
result: item.result === 'good' ? '양호' : item.result === 'bad' ? '불량' : undefined,
|
||||
judgment: item.judgment === 'pass' ? '적합' : item.judgment === 'fail' ? '부적합' : undefined,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
id: String(api.id),
|
||||
inspectionNo: api.inspection_no,
|
||||
inspectionType: api.inspection_type,
|
||||
requestDate: api.request_date,
|
||||
inspectionDate: api.inspection_date,
|
||||
itemName: api.item_name,
|
||||
lotNo: api.lot_no,
|
||||
processName: api.process_name,
|
||||
quantity: api.quantity,
|
||||
unit: api.unit,
|
||||
status: mapApiStatus(api.status),
|
||||
result: api.result === 'pass' ? '합격' : api.result === 'fail' ? '불합격' : undefined,
|
||||
inspector: api.inspector?.name,
|
||||
items,
|
||||
remarks: api.remarks,
|
||||
opinion: api.opinion,
|
||||
attachments: api.attachments?.map((att) => ({
|
||||
id: att.id,
|
||||
fileName: att.file_name,
|
||||
fileUrl: att.file_url,
|
||||
fileType: att.file_type,
|
||||
uploadedAt: att.uploaded_at,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
// ===== 검사 목록 조회 =====
|
||||
export async function getInspections(params?: {
|
||||
page?: number;
|
||||
size?: number;
|
||||
q?: string;
|
||||
status?: InspectionStatus | '전체';
|
||||
inspectionType?: InspectionType;
|
||||
dateFrom?: string;
|
||||
dateTo?: string;
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
data: Inspection[];
|
||||
pagination: PaginationMeta;
|
||||
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('per_page', String(params.size));
|
||||
if (params?.q) searchParams.set('q', params.q);
|
||||
if (params?.status && params.status !== '전체') {
|
||||
searchParams.set('status', mapFrontendStatus(params.status));
|
||||
}
|
||||
if (params?.inspectionType) {
|
||||
searchParams.set('inspection_type', params.inspectionType);
|
||||
}
|
||||
if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
|
||||
if (params?.dateTo) searchParams.set('date_to', params.dateTo);
|
||||
|
||||
const queryString = searchParams.toString();
|
||||
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/inspections${queryString ? `?${queryString}` : ''}`;
|
||||
|
||||
console.log('[InspectionActions] GET inspections:', url);
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn('[InspectionActions] GET inspections error:', response.status);
|
||||
return {
|
||||
success: false,
|
||||
data: [],
|
||||
pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
|
||||
error: `API 오류: ${response.status}`,
|
||||
};
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (!result.success) {
|
||||
return {
|
||||
success: false,
|
||||
data: [],
|
||||
pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
|
||||
error: result.message || '검사 목록 조회에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
const paginatedData: InspectionApiPaginatedResponse = result.data || {
|
||||
data: [],
|
||||
current_page: 1,
|
||||
last_page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
};
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: paginatedData.data.map(transformApiToFrontend),
|
||||
pagination: {
|
||||
currentPage: paginatedData.current_page,
|
||||
lastPage: paginatedData.last_page,
|
||||
perPage: paginatedData.per_page,
|
||||
total: paginatedData.total,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[InspectionActions] getInspections error:', error);
|
||||
return {
|
||||
success: false,
|
||||
data: [],
|
||||
pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 검사 통계 조회 =====
|
||||
export async function getInspectionStats(params?: {
|
||||
dateFrom?: string;
|
||||
dateTo?: string;
|
||||
inspectionType?: InspectionType;
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
data?: InspectionStats;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const searchParams = new URLSearchParams();
|
||||
|
||||
if (params?.dateFrom) searchParams.set('date_from', params.dateFrom);
|
||||
if (params?.dateTo) searchParams.set('date_to', params.dateTo);
|
||||
if (params?.inspectionType) {
|
||||
searchParams.set('inspection_type', params.inspectionType);
|
||||
}
|
||||
|
||||
const queryString = searchParams.toString();
|
||||
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/inspections/stats${queryString ? `?${queryString}` : ''}`;
|
||||
|
||||
console.log('[InspectionActions] GET stats:', url);
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn('[InspectionActions] GET stats error:', response.status);
|
||||
return {
|
||||
success: false,
|
||||
error: `API 오류: ${response.status}`,
|
||||
};
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (!result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '통계 조회에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
const statsApi: InspectionStatsApi = result.data;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
waitingCount: statsApi.waiting_count,
|
||||
inProgressCount: statsApi.in_progress_count,
|
||||
completedCount: statsApi.completed_count,
|
||||
defectRate: statsApi.defect_rate,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[InspectionActions] getInspectionStats error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 검사 상세 조회 =====
|
||||
export async function getInspectionById(id: string): Promise<{
|
||||
success: boolean;
|
||||
data?: Inspection;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/inspections/${id}`;
|
||||
|
||||
console.log('[InspectionActions] GET inspection:', url);
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('[InspectionActions] GET inspection error:', response.status);
|
||||
return {
|
||||
success: false,
|
||||
error: `API 오류: ${response.status}`,
|
||||
};
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (!result.success || !result.data) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '검사 조회에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: transformApiToFrontend(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[InspectionActions] getInspectionById error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 검사 등록 =====
|
||||
export async function createInspection(data: {
|
||||
inspectionType: InspectionType;
|
||||
lotNo: string;
|
||||
itemName: string;
|
||||
processName: string;
|
||||
quantity: number;
|
||||
unit: string;
|
||||
inspectorId?: number;
|
||||
remarks?: string;
|
||||
items?: InspectionItem[];
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
data?: Inspection;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const apiData: Record<string, unknown> = {
|
||||
inspection_type: data.inspectionType,
|
||||
lot_no: data.lotNo,
|
||||
item_name: data.itemName,
|
||||
process_name: data.processName,
|
||||
quantity: data.quantity,
|
||||
unit: data.unit,
|
||||
};
|
||||
|
||||
if (data.inspectorId) apiData.inspector_id = data.inspectorId;
|
||||
if (data.remarks) apiData.remarks = data.remarks;
|
||||
if (data.items && data.items.length > 0) {
|
||||
apiData.items = data.items.map((item) => ({
|
||||
name: item.name,
|
||||
type: item.type,
|
||||
spec: item.spec,
|
||||
unit: item.type === 'measurement' ? (item as { unit?: string }).unit : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
console.log('[InspectionActions] POST inspection request:', apiData);
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/inspections`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(apiData),
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[InspectionActions] POST inspection response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '검사 등록에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: transformApiToFrontend(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[InspectionActions] createInspection error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 검사 수정 =====
|
||||
export async function updateInspection(
|
||||
id: string,
|
||||
data: {
|
||||
items?: InspectionItem[];
|
||||
result?: '합격' | '불합격';
|
||||
remarks?: string;
|
||||
opinion?: string;
|
||||
}
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
data?: Inspection;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const apiData: Record<string, unknown> = {};
|
||||
|
||||
if (data.items) {
|
||||
apiData.items = data.items.map((item) => {
|
||||
if (item.type === 'measurement') {
|
||||
const measurementItem = item as { measuredValue?: number; judgment?: string };
|
||||
return {
|
||||
id: item.id,
|
||||
measured_value: measurementItem.measuredValue,
|
||||
judgment: measurementItem.judgment === '적합' ? 'pass' : 'fail',
|
||||
};
|
||||
}
|
||||
const qualityItem = item as { result?: string; judgment?: string };
|
||||
return {
|
||||
id: item.id,
|
||||
result: qualityItem.result === '양호' ? 'good' : 'bad',
|
||||
judgment: qualityItem.judgment === '적합' ? 'pass' : 'fail',
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
if (data.result) {
|
||||
apiData.result = data.result === '합격' ? 'pass' : 'fail';
|
||||
}
|
||||
if (data.remarks !== undefined) apiData.remarks = data.remarks;
|
||||
if (data.opinion !== undefined) apiData.opinion = data.opinion;
|
||||
|
||||
console.log('[InspectionActions] PUT inspection request:', apiData);
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/inspections/${id}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
headers,
|
||||
body: JSON.stringify(apiData),
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[InspectionActions] PUT inspection response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '검사 수정에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: transformApiToFrontend(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[InspectionActions] updateInspection error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 검사 삭제 =====
|
||||
export async function deleteInspection(id: string): Promise<{
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/inspections/${id}`,
|
||||
{
|
||||
method: 'DELETE',
|
||||
headers,
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[InspectionActions] DELETE inspection response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '검사 삭제에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('[InspectionActions] deleteInspection error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 검사 완료 처리 =====
|
||||
export async function completeInspection(
|
||||
id: string,
|
||||
data: {
|
||||
result: '합격' | '불합격';
|
||||
opinion?: string;
|
||||
}
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
data?: Inspection;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const apiData = {
|
||||
result: data.result === '합격' ? 'pass' : 'fail',
|
||||
opinion: data.opinion,
|
||||
};
|
||||
|
||||
console.log('[InspectionActions] PATCH complete request:', apiData);
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/inspections/${id}/complete`,
|
||||
{
|
||||
method: 'PATCH',
|
||||
headers,
|
||||
body: JSON.stringify(apiData),
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[InspectionActions] PATCH complete response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '검사 완료 처리에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: transformApiToFrontend(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[InspectionActions] completeInspection error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,22 @@
|
||||
// 검사관리 컴포넌트 및 타입 export
|
||||
/**
|
||||
* 검사관리 컴포넌트 및 타입 export
|
||||
* API 연동 완료 (2025-12-26)
|
||||
*/
|
||||
|
||||
export * from './types';
|
||||
// Note: mockData.ts는 statusColorMap, inspectionTypeLabels 등 상수만 사용 중 (삭제 시 분리 필요)
|
||||
export * from './mockData';
|
||||
export { InspectionList } from './InspectionList';
|
||||
export { InspectionCreate } from './InspectionCreate';
|
||||
export { InspectionDetail } from './InspectionDetail';
|
||||
export { InspectionDetail } from './InspectionDetail';
|
||||
|
||||
// Server Actions (API 연동)
|
||||
export {
|
||||
getInspections,
|
||||
getInspectionStats,
|
||||
getInspectionById,
|
||||
createInspection,
|
||||
updateInspection,
|
||||
deleteInspection,
|
||||
completeInspection,
|
||||
} from './actions';
|
||||
Reference in New Issue
Block a user