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:
@@ -8,9 +8,9 @@
|
||||
* - 종합 의견
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useMemo } from 'react';
|
||||
import { useState, useCallback, useMemo, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ClipboardCheck, Calendar } from 'lucide-react';
|
||||
import { ClipboardCheck, Calendar, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -24,10 +24,28 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { mockInspectionTargets, defaultInspectionItems, generateLotNo } from './mockData';
|
||||
import type { InspectionCheckItem } from './types';
|
||||
import { getReceivings } from './actions';
|
||||
import type { InspectionCheckItem, ReceivingItem } from './types';
|
||||
import { SuccessDialog } from './SuccessDialog';
|
||||
|
||||
// LOT 번호 생성 함수 (YYMMDD-NN 형식)
|
||||
function generateLotNo(): string {
|
||||
const now = new Date();
|
||||
const yy = String(now.getFullYear()).slice(-2);
|
||||
const mm = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const dd = String(now.getDate()).padStart(2, '0');
|
||||
const random = String(Math.floor(Math.random() * 100)).padStart(2, '0');
|
||||
return `${yy}${mm}${dd}-${random}`;
|
||||
}
|
||||
|
||||
// 기본 검사 항목
|
||||
const defaultInspectionItems: InspectionCheckItem[] = [
|
||||
{ id: '1', name: '겉모양', specification: '외관 이상 없음', method: '육안', judgment: null, remark: '' },
|
||||
{ id: '2', name: '두께', specification: 't 1.0', method: '계측', judgment: null, remark: '' },
|
||||
{ id: '3', name: '폭', specification: 'W 1,000mm', method: '계측', judgment: null, remark: '' },
|
||||
{ id: '4', name: '길이', specification: 'L 2,000mm', method: '계측', judgment: null, remark: '' },
|
||||
];
|
||||
|
||||
interface Props {
|
||||
id?: string; // 특정 발주건으로 바로 진입하는 경우
|
||||
}
|
||||
@@ -35,10 +53,12 @@ interface Props {
|
||||
export function InspectionCreate({ id }: Props) {
|
||||
const router = useRouter();
|
||||
|
||||
// 검사 대상 목록 (API에서 조회)
|
||||
const [inspectionTargets, setInspectionTargets] = useState<ReceivingItem[]>([]);
|
||||
const [isLoadingTargets, setIsLoadingTargets] = useState(true);
|
||||
|
||||
// 선택된 검사 대상
|
||||
const [selectedTargetId, setSelectedTargetId] = useState<string>(
|
||||
id || mockInspectionTargets[2]?.id || ''
|
||||
);
|
||||
const [selectedTargetId, setSelectedTargetId] = useState<string>(id || '');
|
||||
|
||||
// 검사 정보
|
||||
const [inspectionDate, setInspectionDate] = useState(() => {
|
||||
@@ -62,10 +82,32 @@ export function InspectionCreate({ id }: Props) {
|
||||
// 성공 다이얼로그
|
||||
const [showSuccess, setShowSuccess] = useState(false);
|
||||
|
||||
// 선택된 대상 정보
|
||||
const selectedTarget = useMemo(() => {
|
||||
return mockInspectionTargets.find((t) => t.id === selectedTargetId);
|
||||
}, [selectedTargetId]);
|
||||
// 검사 대상 목록 로드 (inspection_pending 상태인 입고 건)
|
||||
useEffect(() => {
|
||||
const loadTargets = async () => {
|
||||
setIsLoadingTargets(true);
|
||||
try {
|
||||
const result = await getReceivings({ status: 'inspection_pending', perPage: 100 });
|
||||
if (result.success) {
|
||||
setInspectionTargets(result.data);
|
||||
// 초기 선택: id가 있으면 해당 건, 없으면 첫 번째 항목
|
||||
if (!selectedTargetId && result.data.length > 0) {
|
||||
setSelectedTargetId(result.data[0].id);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[InspectionCreate] loadTargets error:', err);
|
||||
} finally {
|
||||
setIsLoadingTargets(false);
|
||||
}
|
||||
};
|
||||
loadTargets();
|
||||
}, []);
|
||||
|
||||
// 선택된 대상 정보 (나중에 검사 저장 시 사용)
|
||||
const _selectedTarget = useMemo(() => {
|
||||
return inspectionTargets.find((t) => t.id === selectedTargetId);
|
||||
}, [inspectionTargets, selectedTargetId]);
|
||||
|
||||
// 대상 선택 핸들러
|
||||
const handleTargetSelect = useCallback((targetId: string) => {
|
||||
@@ -162,23 +204,33 @@ export function InspectionCreate({ id }: Props) {
|
||||
{/* 좌측: 검사 대상 선택 */}
|
||||
<div className="lg:col-span-1 space-y-2">
|
||||
<Label className="text-sm font-medium">검사 대상 선택</Label>
|
||||
<div className="space-y-2 border rounded-lg p-2 bg-white">
|
||||
{mockInspectionTargets.map((target) => (
|
||||
<div
|
||||
key={target.id}
|
||||
onClick={() => handleTargetSelect(target.id)}
|
||||
className={`p-3 rounded-lg cursor-pointer border transition-colors ${
|
||||
selectedTargetId === target.id
|
||||
? 'bg-blue-50 border-blue-300'
|
||||
: 'bg-white border-gray-200 hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
<p className="font-medium text-sm">{target.orderNo}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{target.supplier} · {target.qty}
|
||||
</p>
|
||||
<div className="space-y-2 border rounded-lg p-2 bg-white min-h-[200px]">
|
||||
{isLoadingTargets ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-primary" />
|
||||
</div>
|
||||
))}
|
||||
) : inspectionTargets.length === 0 ? (
|
||||
<div className="text-center py-8 text-muted-foreground text-sm">
|
||||
검사 대기 중인 입고 건이 없습니다.
|
||||
</div>
|
||||
) : (
|
||||
inspectionTargets.map((target) => (
|
||||
<div
|
||||
key={target.id}
|
||||
onClick={() => handleTargetSelect(target.id)}
|
||||
className={`p-3 rounded-lg cursor-pointer border transition-colors ${
|
||||
selectedTargetId === target.id
|
||||
? 'bg-blue-50 border-blue-300'
|
||||
: 'bg-white border-gray-200 hover:bg-gray-50'
|
||||
}`}
|
||||
>
|
||||
<p className="font-medium text-sm">{target.orderNo}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{target.supplier} · {target.qty} {target.unit}
|
||||
</p>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -9,16 +9,16 @@
|
||||
* - 입고완료: 입고증, 목록 버튼
|
||||
*/
|
||||
|
||||
import { useState, useCallback, useMemo } from 'react';
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Package, FileText, List, ClipboardCheck, Download } from 'lucide-react';
|
||||
import { Package, FileText, List, ClipboardCheck, Download, Loader2, AlertCircle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { mockReceivingItems, mockReceivingDetails } from './mockData';
|
||||
import { getReceivingById, processReceiving } from './actions';
|
||||
import { RECEIVING_STATUS_LABELS, RECEIVING_STATUS_STYLES } from './types';
|
||||
import type { ReceivingDetail as ReceivingDetailType } from './types';
|
||||
import type { ReceivingDetail as ReceivingDetailType, ReceivingProcessFormData } from './types';
|
||||
import { ReceivingProcessDialog } from './ReceivingProcessDialog';
|
||||
import { ReceivingReceiptDialog } from './ReceivingReceiptDialog';
|
||||
import { SuccessDialog } from './SuccessDialog';
|
||||
@@ -37,38 +37,37 @@ export function ReceivingDetail({ id }: Props) {
|
||||
lotNo?: string;
|
||||
}>({ open: false, type: 'receiving' });
|
||||
|
||||
// 데이터 가져오기
|
||||
const detail: ReceivingDetailType | undefined = useMemo(() => {
|
||||
// 먼저 상세 데이터에서 찾기
|
||||
if (mockReceivingDetails[id]) {
|
||||
return mockReceivingDetails[id];
|
||||
// API 데이터 상태
|
||||
const [detail, setDetail] = useState<ReceivingDetailType | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// API 데이터 로드
|
||||
const loadData = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await getReceivingById(id);
|
||||
|
||||
if (result.success && result.data) {
|
||||
setDetail(result.data);
|
||||
} else {
|
||||
setError(result.error || '입고 정보를 찾을 수 없습니다.');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[ReceivingDetail] loadData error:', err);
|
||||
setError('데이터를 불러오는 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
// 없으면 목록에서 변환
|
||||
const item = mockReceivingItems.find((i) => i.id === id);
|
||||
if (item) {
|
||||
return {
|
||||
id: item.id,
|
||||
orderNo: item.orderNo,
|
||||
orderDate: undefined,
|
||||
supplier: item.supplier,
|
||||
itemCode: item.itemCode,
|
||||
itemName: item.itemName,
|
||||
specification: undefined,
|
||||
orderQty: item.orderQty,
|
||||
orderUnit: item.orderUnit,
|
||||
dueDate: undefined,
|
||||
status: item.status,
|
||||
receivingDate: undefined,
|
||||
receivingQty: item.receivingQty,
|
||||
receivingLot: item.lotNo,
|
||||
supplierLot: undefined,
|
||||
receivingLocation: undefined,
|
||||
receivingManager: undefined,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}, [id]);
|
||||
|
||||
// 데이터 로드
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
// 목록으로 돌아가기
|
||||
const handleGoBack = useCallback(() => {
|
||||
router.push('/ko/material/receiving-management');
|
||||
@@ -89,11 +88,22 @@ export function ReceivingDetail({ id }: Props) {
|
||||
setIsReceivingProcessDialogOpen(true);
|
||||
}, []);
|
||||
|
||||
// 입고 완료 처리
|
||||
const handleReceivingComplete = useCallback((lotNo: string) => {
|
||||
setIsReceivingProcessDialogOpen(false);
|
||||
setSuccessDialog({ open: true, type: 'receiving', lotNo });
|
||||
}, []);
|
||||
// 입고 완료 처리 (API 호출)
|
||||
const handleReceivingComplete = useCallback(async (formData: ReceivingProcessFormData) => {
|
||||
try {
|
||||
const result = await processReceiving(id, formData);
|
||||
|
||||
if (result.success) {
|
||||
setIsReceivingProcessDialogOpen(false);
|
||||
setSuccessDialog({ open: true, type: 'receiving', lotNo: formData.receivingLot });
|
||||
} else {
|
||||
alert(result.error || '입고처리에 실패했습니다.');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[ReceivingDetail] handleReceivingComplete error:', err);
|
||||
alert('입고처리 중 오류가 발생했습니다.');
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
// 성공 다이얼로그 닫기
|
||||
const handleSuccessDialogClose = useCallback(() => {
|
||||
@@ -101,11 +111,25 @@ export function ReceivingDetail({ id }: Props) {
|
||||
router.push('/ko/material/receiving-management');
|
||||
}, [router]);
|
||||
|
||||
if (!detail) {
|
||||
// 로딩 상태 표시
|
||||
if (isLoading) {
|
||||
return (
|
||||
<PageLayout>
|
||||
<div className="flex items-center justify-center h-64">
|
||||
<p className="text-muted-foreground">데이터를 찾을 수 없습니다.</p>
|
||||
<div className="flex items-center justify-center min-h-[400px]">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
// 에러 상태 표시
|
||||
if (error || !detail) {
|
||||
return (
|
||||
<PageLayout>
|
||||
<div className="flex flex-col items-center justify-center min-h-[400px] gap-4">
|
||||
<AlertCircle className="w-12 h-12 text-red-500" />
|
||||
<p className="text-lg text-muted-foreground">{error || '데이터를 찾을 수 없습니다.'}</p>
|
||||
<Button onClick={loadData}>다시 시도</Button>
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
/**
|
||||
* 입고 목록 페이지
|
||||
* IntegratedListTemplateV2 패턴 적용
|
||||
* API 연동 버전
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { useState, useMemo, useCallback, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import {
|
||||
Package,
|
||||
@@ -13,6 +14,7 @@ import {
|
||||
ClipboardCheck,
|
||||
Calendar,
|
||||
Eye,
|
||||
Loader2,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
@@ -25,47 +27,105 @@ import {
|
||||
StatCard,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import { mockReceivingItems, mockStats, mockFilterTabs } from './mockData';
|
||||
import { getReceivings, getReceivingStats } from './actions';
|
||||
import { RECEIVING_STATUS_LABELS, RECEIVING_STATUS_STYLES } from './types';
|
||||
import type { ReceivingItem, ReceivingStatus } from './types';
|
||||
import type { ReceivingItem, ReceivingStats } from './types';
|
||||
|
||||
// 페이지당 항목 수
|
||||
const ITEMS_PER_PAGE = 20;
|
||||
|
||||
// 필터 탭 정의
|
||||
const FILTER_TABS: { key: string; label: string; status?: string }[] = [
|
||||
{ key: 'all', label: '전체' },
|
||||
{ key: 'receiving_pending', label: '입고대기', status: 'receiving_pending' },
|
||||
{ key: 'completed', label: '입고완료', status: 'completed' },
|
||||
];
|
||||
|
||||
export function ReceivingList() {
|
||||
const router = useRouter();
|
||||
|
||||
// 상태 관리
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [activeFilter, setActiveFilter] = useState<'all' | 'receiving_pending' | 'completed'>('all');
|
||||
const [activeFilter, setActiveFilter] = useState<string>('all');
|
||||
|
||||
// API 데이터 상태
|
||||
const [items, setItems] = useState<ReceivingItem[]>([]);
|
||||
const [stats, setStats] = useState<ReceivingStats | null>(null);
|
||||
const [totalItems, setTotalItems] = useState(0);
|
||||
const [totalPages, setTotalPages] = useState(1);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// 데이터 로드
|
||||
const loadData = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// 목록 및 통계 병렬 조회
|
||||
const [listResult, statsResult] = await Promise.all([
|
||||
getReceivings({
|
||||
page: currentPage,
|
||||
perPage: ITEMS_PER_PAGE,
|
||||
status: activeFilter !== 'all' ? activeFilter : undefined,
|
||||
search: searchTerm || undefined,
|
||||
}),
|
||||
getReceivingStats(),
|
||||
]);
|
||||
|
||||
if (listResult.success) {
|
||||
setItems(listResult.data);
|
||||
setTotalItems(listResult.pagination.total);
|
||||
setTotalPages(listResult.pagination.lastPage);
|
||||
} else {
|
||||
setError(listResult.error || '목록 조회에 실패했습니다.');
|
||||
}
|
||||
|
||||
if (statsResult.success && statsResult.data) {
|
||||
setStats(statsResult.data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[ReceivingList] loadData error:', err);
|
||||
setError('데이터를 불러오는 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [currentPage, activeFilter, searchTerm]);
|
||||
|
||||
// 데이터 로드 트리거
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
// 통계 카드
|
||||
const stats: StatCard[] = [
|
||||
const statCards: StatCard[] = useMemo(() => [
|
||||
{
|
||||
label: '입고대기',
|
||||
value: `${mockStats.receivingPendingCount}건`,
|
||||
value: `${stats?.receivingPendingCount ?? 0}건`,
|
||||
icon: Package,
|
||||
iconColor: 'text-yellow-600',
|
||||
},
|
||||
{
|
||||
label: '배송중',
|
||||
value: `${mockStats.shippingCount}건`,
|
||||
value: `${stats?.shippingCount ?? 0}건`,
|
||||
icon: Truck,
|
||||
iconColor: 'text-blue-600',
|
||||
},
|
||||
{
|
||||
label: '검사대기',
|
||||
value: `${mockStats.inspectionPendingCount}건`,
|
||||
value: `${stats?.inspectionPendingCount ?? 0}건`,
|
||||
icon: ClipboardCheck,
|
||||
iconColor: 'text-orange-600',
|
||||
},
|
||||
{
|
||||
label: '금일입고',
|
||||
value: `${mockStats.todayReceivingCount}건`,
|
||||
value: `${stats?.todayReceivingCount ?? 0}건`,
|
||||
icon: Calendar,
|
||||
iconColor: 'text-green-600',
|
||||
},
|
||||
];
|
||||
], [stats]);
|
||||
|
||||
// 테이블 컬럼
|
||||
const tableColumns: TableColumn[] = [
|
||||
@@ -80,45 +140,11 @@ export function ReceivingList() {
|
||||
{ key: 'status', label: '상태', className: 'w-[100px] text-center' },
|
||||
];
|
||||
|
||||
// 필터링된 데이터
|
||||
const filteredResults = useMemo(() => {
|
||||
let result = [...mockReceivingItems];
|
||||
|
||||
// 탭 필터
|
||||
if (activeFilter === 'receiving_pending') {
|
||||
result = result.filter((item) =>
|
||||
['receiving_pending', 'inspection_pending'].includes(item.status)
|
||||
);
|
||||
} else if (activeFilter === 'completed') {
|
||||
result = result.filter((item) => item.status === 'completed');
|
||||
}
|
||||
|
||||
// 검색 필터
|
||||
if (searchTerm) {
|
||||
const term = searchTerm.toLowerCase();
|
||||
result = result.filter(
|
||||
(item) =>
|
||||
item.orderNo.toLowerCase().includes(term) ||
|
||||
item.itemCode.toLowerCase().includes(term) ||
|
||||
item.itemName.toLowerCase().includes(term) ||
|
||||
item.supplier.toLowerCase().includes(term)
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [searchTerm, activeFilter]);
|
||||
|
||||
// 페이지네이션 데이터
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
|
||||
return filteredResults.slice(startIndex, startIndex + ITEMS_PER_PAGE);
|
||||
}, [filteredResults, currentPage]);
|
||||
|
||||
// 페이지네이션 설정
|
||||
const pagination = {
|
||||
currentPage,
|
||||
totalPages: Math.ceil(filteredResults.length / ITEMS_PER_PAGE),
|
||||
totalItems: filteredResults.length,
|
||||
totalPages,
|
||||
totalItems,
|
||||
itemsPerPage: ITEMS_PER_PAGE,
|
||||
onPageChange: setCurrentPage,
|
||||
};
|
||||
@@ -137,12 +163,12 @@ export function ReceivingList() {
|
||||
}, []);
|
||||
|
||||
const handleToggleSelectAll = useCallback(() => {
|
||||
if (selectedItems.size === paginatedData.length) {
|
||||
if (selectedItems.size === items.length) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(paginatedData.map((item) => item.id)));
|
||||
setSelectedItems(new Set(items.map((item) => item.id)));
|
||||
}
|
||||
}, [paginatedData, selectedItems.size]);
|
||||
}, [items, selectedItems.size]);
|
||||
|
||||
// 검색 변경 시 페이지 리셋
|
||||
const handleSearchChange = (value: string) => {
|
||||
@@ -152,7 +178,7 @@ export function ReceivingList() {
|
||||
|
||||
// 탭 변경 시 페이지 리셋
|
||||
const handleTabChange = (value: string) => {
|
||||
setActiveFilter(value as 'all' | 'receiving_pending' | 'completed');
|
||||
setActiveFilter(value);
|
||||
setCurrentPage(1);
|
||||
setSelectedItems(new Set());
|
||||
};
|
||||
@@ -267,10 +293,14 @@ export function ReceivingList() {
|
||||
};
|
||||
|
||||
// 탭 옵션
|
||||
const tabs: TabOption[] = mockFilterTabs.map((tab) => ({
|
||||
const tabs: TabOption[] = FILTER_TABS.map((tab) => ({
|
||||
value: tab.key,
|
||||
label: tab.label,
|
||||
count: tab.count,
|
||||
count: tab.key === 'all'
|
||||
? totalItems
|
||||
: tab.key === 'receiving_pending'
|
||||
? (stats?.receivingPendingCount ?? 0)
|
||||
: (stats?.todayReceivingCount ?? 0),
|
||||
}));
|
||||
|
||||
// 하단 요약
|
||||
@@ -278,18 +308,37 @@ export function ReceivingList() {
|
||||
<TableRow className="bg-gray-50 hover:bg-gray-50">
|
||||
<TableCell colSpan={tableColumns.length + 1} className="py-3">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
총 {filteredResults.length}건 / 입고대기 {mockStats.receivingPendingCount}건 / 검사대기{' '}
|
||||
{mockStats.inspectionPendingCount}건
|
||||
총 {totalItems}건 / 입고대기 {stats?.receivingPendingCount ?? 0}건 / 검사대기{' '}
|
||||
{stats?.inspectionPendingCount ?? 0}건
|
||||
</span>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
|
||||
// 로딩 상태
|
||||
if (isLoading && items.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[400px]">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 에러 상태
|
||||
if (error && items.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-[400px] gap-4">
|
||||
<p className="text-muted-foreground">{error}</p>
|
||||
<Button onClick={loadData}>다시 시도</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<IntegratedListTemplateV2<ReceivingItem>
|
||||
title="입고 목록"
|
||||
icon={Package}
|
||||
stats={stats}
|
||||
stats={statCards}
|
||||
searchValue={searchTerm}
|
||||
onSearchChange={handleSearchChange}
|
||||
searchPlaceholder="발주번호, 품목코드, 품목명, 공급업체 검색..."
|
||||
@@ -297,9 +346,9 @@ export function ReceivingList() {
|
||||
activeTab={activeFilter}
|
||||
onTabChange={handleTabChange}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
totalCount={filteredResults.length}
|
||||
allData={filteredResults}
|
||||
data={items}
|
||||
totalCount={totalItems}
|
||||
allData={items}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={handleToggleSelection}
|
||||
onToggleSelectAll={handleToggleSelectAll}
|
||||
@@ -310,4 +359,4 @@ export function ReceivingList() {
|
||||
tableFooter={tableFooter}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
*/
|
||||
|
||||
import { useState, useCallback } from 'react';
|
||||
import { Download } from 'lucide-react';
|
||||
import { Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -20,14 +20,23 @@ import {
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { generateLotNo } from './mockData';
|
||||
import type { ReceivingDetail } from './types';
|
||||
import type { ReceivingDetail, ReceivingProcessFormData } from './types';
|
||||
|
||||
// LOT 번호 생성 함수 (YYMMDD-NN 형식)
|
||||
function generateLotNo(): string {
|
||||
const now = new Date();
|
||||
const yy = String(now.getFullYear()).slice(-2);
|
||||
const mm = String(now.getMonth() + 1).padStart(2, '0');
|
||||
const dd = String(now.getDate()).padStart(2, '0');
|
||||
const random = String(Math.floor(Math.random() * 100)).padStart(2, '0');
|
||||
return `${yy}${mm}${dd}-${random}`;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
detail: ReceivingDetail;
|
||||
onComplete: (lotNo: string) => void;
|
||||
onComplete: (formData: ReceivingProcessFormData) => void;
|
||||
}
|
||||
|
||||
export function ReceivingProcessDialog({ open, onOpenChange, detail, onComplete }: Props) {
|
||||
@@ -40,6 +49,7 @@ export function ReceivingProcessDialog({ open, onOpenChange, detail, onComplete
|
||||
|
||||
// 유효성 검사 에러
|
||||
const [validationErrors, setValidationErrors] = useState<string[]>([]);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
// 유효성 검사
|
||||
const validateForm = useCallback((): boolean => {
|
||||
@@ -62,23 +72,24 @@ export function ReceivingProcessDialog({ open, onOpenChange, detail, onComplete
|
||||
}, [receivingLot, receivingQty, receivingLocation]);
|
||||
|
||||
// 입고 처리
|
||||
const handleSubmit = useCallback(() => {
|
||||
const handleSubmit = useCallback(async () => {
|
||||
if (!validateForm()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: API 호출
|
||||
console.log('입고 처리:', {
|
||||
detailId: detail.id,
|
||||
receivingLot,
|
||||
supplierLot,
|
||||
receivingQty: Number(receivingQty),
|
||||
receivingLocation,
|
||||
remark,
|
||||
});
|
||||
setIsSubmitting(true);
|
||||
|
||||
onComplete(receivingLot);
|
||||
}, [validateForm, detail.id, receivingLot, supplierLot, receivingQty, receivingLocation, remark, onComplete]);
|
||||
const formData: ReceivingProcessFormData = {
|
||||
receivingQty: Number(receivingQty),
|
||||
receivingLot,
|
||||
supplierLot: supplierLot || undefined,
|
||||
receivingLocation,
|
||||
remark: remark || undefined,
|
||||
};
|
||||
|
||||
await onComplete(formData);
|
||||
setIsSubmitting(false);
|
||||
}, [validateForm, receivingLot, supplierLot, receivingQty, receivingLocation, remark, onComplete]);
|
||||
|
||||
// 취소
|
||||
const handleCancel = useCallback(() => {
|
||||
@@ -214,11 +225,18 @@ export function ReceivingProcessDialog({ open, onOpenChange, detail, onComplete
|
||||
|
||||
{/* 버튼 영역 */}
|
||||
<div className="flex justify-end gap-2 mt-6 pt-4 border-t">
|
||||
<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-1.5 animate-spin" />
|
||||
처리 중...
|
||||
</>
|
||||
) : (
|
||||
'입고 처리'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
|
||||
517
src/components/material/ReceivingManagement/actions.ts
Normal file
517
src/components/material/ReceivingManagement/actions.ts
Normal file
@@ -0,0 +1,517 @@
|
||||
/**
|
||||
* 입고 관리 서버 액션
|
||||
*
|
||||
* API Endpoints:
|
||||
* - GET /api/v1/receivings - 목록 조회
|
||||
* - GET /api/v1/receivings/stats - 통계 조회
|
||||
* - GET /api/v1/receivings/{id} - 상세 조회
|
||||
* - POST /api/v1/receivings - 등록
|
||||
* - PUT /api/v1/receivings/{id} - 수정
|
||||
* - DELETE /api/v1/receivings/{id} - 삭제
|
||||
* - POST /api/v1/receivings/{id}/process - 입고처리
|
||||
*/
|
||||
|
||||
'use server';
|
||||
|
||||
import { cookies } from 'next/headers';
|
||||
import type {
|
||||
ReceivingItem,
|
||||
ReceivingDetail,
|
||||
ReceivingStats,
|
||||
ReceivingStatus,
|
||||
ReceivingProcessFormData,
|
||||
} from './types';
|
||||
|
||||
// ===== API 데이터 타입 =====
|
||||
interface ReceivingApiData {
|
||||
id: number;
|
||||
receiving_number: string;
|
||||
order_no?: string;
|
||||
order_date?: string;
|
||||
item_id?: number;
|
||||
item_code: string;
|
||||
item_name: string;
|
||||
specification?: string;
|
||||
supplier: string;
|
||||
order_qty: string | number;
|
||||
order_unit: string;
|
||||
due_date?: string;
|
||||
receiving_qty?: string | number;
|
||||
receiving_date?: string;
|
||||
lot_no?: string;
|
||||
supplier_lot?: string;
|
||||
receiving_location?: string;
|
||||
receiving_manager?: string;
|
||||
status: ReceivingStatus;
|
||||
remark?: string;
|
||||
creator?: { id: number; name: string };
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
interface ReceivingApiPaginatedResponse {
|
||||
data: ReceivingApiData[];
|
||||
current_page: number;
|
||||
last_page: number;
|
||||
per_page: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface ReceivingApiStatsResponse {
|
||||
receiving_pending_count: number;
|
||||
shipping_count: number;
|
||||
inspection_pending_count: number;
|
||||
today_receiving_count: number;
|
||||
}
|
||||
|
||||
// ===== API → Frontend 변환 (목록용) =====
|
||||
function transformApiToListItem(data: ReceivingApiData): ReceivingItem {
|
||||
return {
|
||||
id: String(data.id),
|
||||
orderNo: data.order_no || data.receiving_number,
|
||||
itemCode: data.item_code,
|
||||
itemName: data.item_name,
|
||||
supplier: data.supplier,
|
||||
orderQty: parseFloat(String(data.order_qty)) || 0,
|
||||
orderUnit: data.order_unit || 'EA',
|
||||
receivingQty: data.receiving_qty ? parseFloat(String(data.receiving_qty)) : undefined,
|
||||
lotNo: data.lot_no,
|
||||
status: data.status,
|
||||
};
|
||||
}
|
||||
|
||||
// ===== API → Frontend 변환 (상세용) =====
|
||||
function transformApiToDetail(data: ReceivingApiData): ReceivingDetail {
|
||||
return {
|
||||
id: String(data.id),
|
||||
orderNo: data.order_no || data.receiving_number,
|
||||
orderDate: data.order_date,
|
||||
supplier: data.supplier,
|
||||
itemCode: data.item_code,
|
||||
itemName: data.item_name,
|
||||
specification: data.specification,
|
||||
orderQty: parseFloat(String(data.order_qty)) || 0,
|
||||
orderUnit: data.order_unit || 'EA',
|
||||
dueDate: data.due_date,
|
||||
status: data.status,
|
||||
receivingDate: data.receiving_date,
|
||||
receivingQty: data.receiving_qty ? parseFloat(String(data.receiving_qty)) : undefined,
|
||||
receivingLot: data.lot_no,
|
||||
supplierLot: data.supplier_lot,
|
||||
receivingLocation: data.receiving_location,
|
||||
receivingManager: data.receiving_manager,
|
||||
};
|
||||
}
|
||||
|
||||
// ===== API → Frontend 변환 (통계용) =====
|
||||
function transformApiToStats(data: ReceivingApiStatsResponse): ReceivingStats {
|
||||
return {
|
||||
receivingPendingCount: data.receiving_pending_count,
|
||||
shippingCount: data.shipping_count,
|
||||
inspectionPendingCount: data.inspection_pending_count,
|
||||
todayReceivingCount: data.today_receiving_count,
|
||||
};
|
||||
}
|
||||
|
||||
// ===== Frontend → API 변환 (등록/수정용) =====
|
||||
function transformFrontendToApi(
|
||||
data: Partial<ReceivingDetail>
|
||||
): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = {};
|
||||
|
||||
if (data.orderNo !== undefined) result.order_no = data.orderNo;
|
||||
if (data.orderDate !== undefined) result.order_date = data.orderDate;
|
||||
if (data.itemCode !== undefined) result.item_code = data.itemCode;
|
||||
if (data.itemName !== undefined) result.item_name = data.itemName;
|
||||
if (data.specification !== undefined) result.specification = data.specification;
|
||||
if (data.supplier !== undefined) result.supplier = data.supplier;
|
||||
if (data.orderQty !== undefined) result.order_qty = data.orderQty;
|
||||
if (data.orderUnit !== undefined) result.order_unit = data.orderUnit;
|
||||
if (data.dueDate !== undefined) result.due_date = data.dueDate;
|
||||
if (data.status !== undefined) result.status = data.status;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ===== Frontend → API 변환 (입고처리용) =====
|
||||
function transformProcessDataToApi(
|
||||
data: ReceivingProcessFormData
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
receiving_qty: data.receivingQty,
|
||||
lot_no: data.receivingLot,
|
||||
supplier_lot: data.supplierLot,
|
||||
receiving_location: data.receivingLocation,
|
||||
remark: data.remark,
|
||||
};
|
||||
}
|
||||
|
||||
// ===== 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 || '',
|
||||
};
|
||||
}
|
||||
|
||||
// ===== 페이지네이션 타입 =====
|
||||
interface PaginationMeta {
|
||||
currentPage: number;
|
||||
lastPage: number;
|
||||
perPage: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
// ===== 입고 목록 조회 =====
|
||||
export async function getReceivings(params?: {
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
status?: string;
|
||||
search?: string;
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
data: ReceivingItem[];
|
||||
pagination: PaginationMeta;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const searchParams = new URLSearchParams();
|
||||
|
||||
if (params?.page) searchParams.set('page', String(params.page));
|
||||
if (params?.perPage) searchParams.set('per_page', String(params.perPage));
|
||||
if (params?.startDate) searchParams.set('start_date', params.startDate);
|
||||
if (params?.endDate) searchParams.set('end_date', params.endDate);
|
||||
if (params?.status && params.status !== 'all') {
|
||||
searchParams.set('status', params.status);
|
||||
}
|
||||
if (params?.search) searchParams.set('search', params.search);
|
||||
|
||||
const queryString = searchParams.toString();
|
||||
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/receivings${queryString ? `?${queryString}` : ''}`;
|
||||
|
||||
console.log('[ReceivingActions] GET receivings:', url);
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn('[ReceivingActions] GET receivings 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: ReceivingApiPaginatedResponse = result.data || {
|
||||
data: [],
|
||||
current_page: 1,
|
||||
last_page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
};
|
||||
|
||||
const receivings = (paginatedData.data || []).map(transformApiToListItem);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: receivings,
|
||||
pagination: {
|
||||
currentPage: paginatedData.current_page,
|
||||
lastPage: paginatedData.last_page,
|
||||
perPage: paginatedData.per_page,
|
||||
total: paginatedData.total,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[ReceivingActions] getReceivings error:', error);
|
||||
return {
|
||||
success: false,
|
||||
data: [],
|
||||
pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 입고 통계 조회 =====
|
||||
export async function getReceivingStats(): Promise<{
|
||||
success: boolean;
|
||||
data?: ReceivingStats;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/receivings/stats`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn('[ReceivingActions] GET stats 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: transformApiToStats(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[ReceivingActions] getReceivingStats error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 입고 상세 조회 =====
|
||||
export async function getReceivingById(id: string): Promise<{
|
||||
success: boolean;
|
||||
data?: ReceivingDetail;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/receivings/${id}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('[ReceivingActions] GET receiving 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: transformApiToDetail(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[ReceivingActions] getReceivingById error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 입고 등록 =====
|
||||
export async function createReceiving(
|
||||
data: Partial<ReceivingDetail>
|
||||
): Promise<{ success: boolean; data?: ReceivingDetail; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const apiData = transformFrontendToApi(data);
|
||||
|
||||
console.log('[ReceivingActions] POST receiving request:', apiData);
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/receivings`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(apiData),
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[ReceivingActions] POST receiving response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '입고 등록에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: transformApiToDetail(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[ReceivingActions] createReceiving error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 입고 수정 =====
|
||||
export async function updateReceiving(
|
||||
id: string,
|
||||
data: Partial<ReceivingDetail>
|
||||
): Promise<{ success: boolean; data?: ReceivingDetail; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const apiData = transformFrontendToApi(data);
|
||||
|
||||
console.log('[ReceivingActions] PUT receiving request:', apiData);
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/receivings/${id}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
headers,
|
||||
body: JSON.stringify(apiData),
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[ReceivingActions] PUT receiving response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '입고 수정에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: transformApiToDetail(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[ReceivingActions] updateReceiving error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 입고 삭제 =====
|
||||
export async function deleteReceiving(
|
||||
id: string
|
||||
): Promise<{ success: boolean; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/receivings/${id}`,
|
||||
{
|
||||
method: 'DELETE',
|
||||
headers,
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[ReceivingActions] DELETE receiving response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '입고 삭제에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
console.error('[ReceivingActions] deleteReceiving error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 입고처리 =====
|
||||
export async function processReceiving(
|
||||
id: string,
|
||||
data: ReceivingProcessFormData
|
||||
): Promise<{ success: boolean; data?: ReceivingDetail; error?: string }> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const apiData = transformProcessDataToApi(data);
|
||||
|
||||
console.log('[ReceivingActions] POST process request:', apiData);
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/receivings/${id}/process`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(apiData),
|
||||
}
|
||||
);
|
||||
|
||||
const result = await response.json();
|
||||
console.log('[ReceivingActions] POST process response:', result);
|
||||
|
||||
if (!response.ok || !result.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: result.message || '입고처리에 실패했습니다.',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: transformApiToDetail(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[ReceivingActions] processReceiving error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
/**
|
||||
* 재고현황 상세 페이지
|
||||
* API 연동 버전 (2025-12-26)
|
||||
*/
|
||||
|
||||
import { useMemo } from 'react';
|
||||
import { useState, useMemo, useCallback, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { Package, AlertCircle, ArrowLeft } from 'lucide-react';
|
||||
import { Package, AlertCircle, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
@@ -19,7 +20,7 @@ import {
|
||||
TableRow,
|
||||
} from '@/components/ui/table';
|
||||
import { PageLayout } from '@/components/organisms/PageLayout';
|
||||
import { getStockDetail } from './mockData';
|
||||
import { getStockById } from './actions';
|
||||
import {
|
||||
ITEM_TYPE_LABELS,
|
||||
ITEM_TYPE_STYLES,
|
||||
@@ -35,8 +36,36 @@ interface StockStatusDetailProps {
|
||||
export function StockStatusDetail({ id }: StockStatusDetailProps) {
|
||||
const router = useRouter();
|
||||
|
||||
// Mock 데이터에서 상세 정보 가져오기 (동적 생성)
|
||||
const detail: StockDetail | undefined = getStockDetail(id);
|
||||
// API 데이터 상태
|
||||
const [detail, setDetail] = useState<StockDetail | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// API 데이터 로드
|
||||
const loadData = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await getStockById(id);
|
||||
|
||||
if (result.success && result.data) {
|
||||
setDetail(result.data);
|
||||
} else {
|
||||
setError(result.error || '재고 정보를 찾을 수 없습니다.');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[StockStatusDetail] loadData error:', err);
|
||||
setError('데이터를 불러오는 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
// 데이터 로드
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
// 가장 오래된 LOT 찾기 (FIFO 권장용)
|
||||
const oldestLot = useMemo(() => {
|
||||
@@ -53,11 +82,23 @@ export function StockStatusDetail({ id }: StockStatusDetailProps) {
|
||||
}, [detail]);
|
||||
|
||||
// 목록으로 돌아가기
|
||||
const handleGoBack = () => {
|
||||
const handleGoBack = useCallback(() => {
|
||||
router.push('/ko/material/stock-status');
|
||||
};
|
||||
}, [router]);
|
||||
|
||||
if (!detail) {
|
||||
// 로딩 상태 표시
|
||||
if (isLoading) {
|
||||
return (
|
||||
<PageLayout>
|
||||
<div className="flex items-center justify-center min-h-[400px]">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||
</div>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
|
||||
// 에러 상태 표시
|
||||
if (error || !detail) {
|
||||
return (
|
||||
<PageLayout>
|
||||
<div className="space-y-6">
|
||||
@@ -72,8 +113,12 @@ export function StockStatusDetail({ id }: StockStatusDetailProps) {
|
||||
</Button>
|
||||
</div>
|
||||
<Card>
|
||||
<CardContent className="py-12 text-center text-muted-foreground">
|
||||
재고 정보를 찾을 수 없습니다.
|
||||
<CardContent className="py-12">
|
||||
<div className="flex flex-col items-center justify-center gap-4 text-center">
|
||||
<AlertCircle className="w-12 h-12 text-red-500" />
|
||||
<p className="text-muted-foreground">{error || '재고 정보를 찾을 수 없습니다.'}</p>
|
||||
<Button onClick={loadData}>다시 시도</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
/**
|
||||
* 재고현황 목록 페이지
|
||||
* IntegratedListTemplateV2 패턴 적용
|
||||
* API 연동 완료 (2025-12-26)
|
||||
*/
|
||||
|
||||
import { useState, useMemo, useCallback } from 'react';
|
||||
import { useState, useMemo, useCallback, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import {
|
||||
Package,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
AlertCircle,
|
||||
Download,
|
||||
Eye,
|
||||
Loader2,
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
@@ -26,9 +28,9 @@ import {
|
||||
StatCard,
|
||||
} from '@/components/templates/IntegratedListTemplateV2';
|
||||
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
|
||||
import { mockStockItems, mockStats, mockFilterTabs } from './mockData';
|
||||
import { getStocks, getStockStats, getStockStatsByType } from './actions';
|
||||
import { ITEM_TYPE_LABELS, ITEM_TYPE_STYLES, STOCK_STATUS_LABELS } from './types';
|
||||
import type { StockItem, ItemType } from './types';
|
||||
import type { StockItem, StockStats, ItemType } from './types';
|
||||
|
||||
// 페이지당 항목 수
|
||||
const ITEMS_PER_PAGE = 20;
|
||||
@@ -40,29 +42,83 @@ export function StockStatusList() {
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [activeFilter, setActiveFilter] = useState<'all' | ItemType>('all');
|
||||
|
||||
// API 데이터 상태
|
||||
const [items, setItems] = useState<StockItem[]>([]);
|
||||
const [stockStats, setStockStats] = useState<StockStats | null>(null);
|
||||
const [typeStats, setTypeStats] = useState<Record<string, { label: string; count: number; total_qty: number | string }>>({});
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [totalItems, setTotalItems] = useState(0);
|
||||
const [lastPage, setLastPage] = useState(1);
|
||||
|
||||
// API 데이터 로드
|
||||
const loadData = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const [listResult, statsResult, typeStatsResult] = await Promise.all([
|
||||
getStocks({
|
||||
page: currentPage,
|
||||
perPage: ITEMS_PER_PAGE,
|
||||
itemType: activeFilter !== 'all' ? activeFilter : undefined,
|
||||
search: searchTerm || undefined,
|
||||
}),
|
||||
getStockStats(),
|
||||
getStockStatsByType(),
|
||||
]);
|
||||
|
||||
if (listResult.success) {
|
||||
setItems(listResult.data);
|
||||
setTotalItems(listResult.pagination.total);
|
||||
setLastPage(listResult.pagination.lastPage);
|
||||
} else {
|
||||
setError(listResult.error || '재고 목록 조회에 실패했습니다.');
|
||||
}
|
||||
|
||||
if (statsResult.success && statsResult.data) {
|
||||
setStockStats(statsResult.data);
|
||||
}
|
||||
|
||||
if (typeStatsResult.success && typeStatsResult.data) {
|
||||
setTypeStats(typeStatsResult.data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[StockStatusList] loadData error:', err);
|
||||
setError('데이터를 불러오는 중 오류가 발생했습니다.');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [currentPage, activeFilter, searchTerm]);
|
||||
|
||||
// 데이터 로드
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData]);
|
||||
|
||||
// 통계 카드
|
||||
const stats: StatCard[] = [
|
||||
{
|
||||
label: '전체 품목',
|
||||
value: `${mockStats.totalItems}종`,
|
||||
value: `${stockStats?.totalItems || 0}종`,
|
||||
icon: Package,
|
||||
iconColor: 'text-gray-600',
|
||||
},
|
||||
{
|
||||
label: '정상 재고',
|
||||
value: `${mockStats.normalCount}종`,
|
||||
value: `${stockStats?.normalCount || 0}종`,
|
||||
icon: CheckCircle2,
|
||||
iconColor: 'text-green-600',
|
||||
},
|
||||
{
|
||||
label: '재고 부족',
|
||||
value: `${mockStats.lowCount}종`,
|
||||
value: `${stockStats?.lowCount || 0}종`,
|
||||
icon: Clock,
|
||||
iconColor: 'text-orange-600',
|
||||
},
|
||||
{
|
||||
label: '재고 없음',
|
||||
value: `${mockStats.outCount}종`,
|
||||
value: `${stockStats?.outCount || 0}종`,
|
||||
icon: AlertCircle,
|
||||
iconColor: 'text-red-600',
|
||||
},
|
||||
@@ -83,44 +139,7 @@ export function StockStatusList() {
|
||||
{ key: 'actions', label: '작업', className: 'w-[60px] text-center' },
|
||||
];
|
||||
|
||||
// 필터링된 데이터
|
||||
const filteredResults = useMemo(() => {
|
||||
let result = [...mockStockItems];
|
||||
|
||||
// 품목유형 필터
|
||||
if (activeFilter !== 'all') {
|
||||
result = result.filter((item) => item.itemType === activeFilter);
|
||||
}
|
||||
|
||||
// 검색 필터
|
||||
if (searchTerm) {
|
||||
const term = searchTerm.toLowerCase();
|
||||
result = result.filter(
|
||||
(item) =>
|
||||
item.itemCode.toLowerCase().includes(term) ||
|
||||
item.itemName.toLowerCase().includes(term)
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [searchTerm, activeFilter]);
|
||||
|
||||
// 페이지네이션 데이터
|
||||
const paginatedData = useMemo(() => {
|
||||
const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
|
||||
return filteredResults.slice(startIndex, startIndex + ITEMS_PER_PAGE);
|
||||
}, [filteredResults, currentPage]);
|
||||
|
||||
// 페이지네이션 설정
|
||||
const pagination = {
|
||||
currentPage,
|
||||
totalPages: Math.ceil(filteredResults.length / ITEMS_PER_PAGE),
|
||||
totalItems: filteredResults.length,
|
||||
itemsPerPage: ITEMS_PER_PAGE,
|
||||
onPageChange: setCurrentPage,
|
||||
};
|
||||
|
||||
// 선택 핸들러
|
||||
// 선택 핸들러 (Hooks는 조건부 return 전에 선언되어야 함)
|
||||
const handleToggleSelection = useCallback((id: string) => {
|
||||
setSelectedItems((prev) => {
|
||||
const newSet = new Set(prev);
|
||||
@@ -134,41 +153,39 @@ export function StockStatusList() {
|
||||
}, []);
|
||||
|
||||
const handleToggleSelectAll = useCallback(() => {
|
||||
if (selectedItems.size === paginatedData.length) {
|
||||
if (selectedItems.size === items.length) {
|
||||
setSelectedItems(new Set());
|
||||
} else {
|
||||
setSelectedItems(new Set(paginatedData.map((item) => item.id)));
|
||||
setSelectedItems(new Set(items.map((item) => item.id)));
|
||||
}
|
||||
}, [paginatedData, selectedItems.size]);
|
||||
}, [items, selectedItems.size]);
|
||||
|
||||
// 검색 변경 시 페이지 리셋
|
||||
const handleSearchChange = (value: string) => {
|
||||
const handleSearchChange = useCallback((value: string) => {
|
||||
setSearchTerm(value);
|
||||
setCurrentPage(1);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 탭 변경 시 페이지 리셋
|
||||
const handleTabChange = (value: string) => {
|
||||
const handleTabChange = useCallback((value: string) => {
|
||||
setActiveFilter(value as 'all' | ItemType);
|
||||
setCurrentPage(1);
|
||||
setSelectedItems(new Set());
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 엑셀 다운로드
|
||||
const handleExcelDownload = useCallback(() => {
|
||||
console.log('엑셀 다운로드:', filteredResults);
|
||||
console.log('엑셀 다운로드:', items);
|
||||
// TODO: 엑셀 다운로드 기능 구현
|
||||
}, [filteredResults]);
|
||||
}, [items]);
|
||||
|
||||
// 상세 보기
|
||||
const handleView = useCallback((id: string) => {
|
||||
router.push(`/ko/material/stock-status/${id}`);
|
||||
}, [router]);
|
||||
|
||||
// 재고부족 수 계산
|
||||
const lowStockCount = useMemo(() => {
|
||||
return filteredResults.filter((item) => item.status === 'low').length;
|
||||
}, [filteredResults]);
|
||||
// 재고부족 수 (API 통계 사용)
|
||||
const lowStockCount = stockStats?.lowCount || 0;
|
||||
|
||||
// 테이블 행 렌더링
|
||||
const renderTableRow = (item: StockItem, index: number, globalIndex: number) => {
|
||||
@@ -287,12 +304,51 @@ export function StockStatusList() {
|
||||
);
|
||||
};
|
||||
|
||||
// 탭 옵션 (TabChip 사용)
|
||||
const tabs: TabOption[] = mockFilterTabs.map((tab) => ({
|
||||
value: tab.key,
|
||||
label: tab.label,
|
||||
count: tab.count,
|
||||
}));
|
||||
// 탭 옵션 (API typeStats 사용)
|
||||
const tabs: TabOption[] = useMemo(() => {
|
||||
const allTab: TabOption = {
|
||||
value: 'all',
|
||||
label: '전체',
|
||||
count: stockStats?.totalItems || 0,
|
||||
};
|
||||
|
||||
const typeTabs: TabOption[] = Object.entries(typeStats).map(([key, stat]) => ({
|
||||
value: key,
|
||||
label: stat.label,
|
||||
count: stat.count,
|
||||
}));
|
||||
|
||||
return [allTab, ...typeTabs];
|
||||
}, [typeStats, stockStats?.totalItems]);
|
||||
|
||||
// 페이지네이션 설정 (API 서버 사이드 페이지네이션)
|
||||
const pagination = {
|
||||
currentPage,
|
||||
totalPages: lastPage,
|
||||
totalItems,
|
||||
itemsPerPage: ITEMS_PER_PAGE,
|
||||
onPageChange: setCurrentPage,
|
||||
};
|
||||
|
||||
// 로딩 상태 표시 (모든 Hooks 선언 후)
|
||||
if (isLoading && items.length === 0) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-[400px]">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 에러 상태 표시
|
||||
if (error && items.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center min-h-[400px] gap-4">
|
||||
<AlertCircle className="w-12 h-12 text-red-500" />
|
||||
<p className="text-lg text-muted-foreground">{error}</p>
|
||||
<Button onClick={loadData}>다시 시도</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// 헤더 액션
|
||||
const headerActions = (
|
||||
@@ -307,7 +363,7 @@ export function StockStatusList() {
|
||||
<TableRow className="bg-gray-50 hover:bg-gray-50">
|
||||
<TableCell colSpan={tableColumns.length + 1} className="py-3">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
총 {filteredResults.length}종 / 재고부족 {lowStockCount}종
|
||||
총 {totalItems}종 / 재고부족 {lowStockCount}종
|
||||
</span>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
@@ -326,9 +382,9 @@ export function StockStatusList() {
|
||||
activeTab={activeFilter}
|
||||
onTabChange={handleTabChange}
|
||||
tableColumns={tableColumns}
|
||||
data={paginatedData}
|
||||
totalCount={filteredResults.length}
|
||||
allData={filteredResults}
|
||||
data={items}
|
||||
totalCount={totalItems}
|
||||
allData={items}
|
||||
selectedItems={selectedItems}
|
||||
onToggleSelection={handleToggleSelection}
|
||||
onToggleSelectAll={handleToggleSelectAll}
|
||||
|
||||
418
src/components/material/StockStatus/actions.ts
Normal file
418
src/components/material/StockStatus/actions.ts
Normal file
@@ -0,0 +1,418 @@
|
||||
/**
|
||||
* 재고 현황 서버 액션
|
||||
*
|
||||
* API Endpoints:
|
||||
* - GET /api/v1/stocks - 목록 조회
|
||||
* - GET /api/v1/stocks/stats - 통계 조회
|
||||
* - GET /api/v1/stocks/stats-by-type - 품목유형별 통계 조회
|
||||
* - GET /api/v1/stocks/{id} - 상세 조회 (LOT 포함)
|
||||
*/
|
||||
|
||||
'use server';
|
||||
|
||||
import { cookies } from 'next/headers';
|
||||
import type {
|
||||
StockItem,
|
||||
StockDetail,
|
||||
StockStats,
|
||||
LotDetail,
|
||||
ItemType,
|
||||
StockStatusType,
|
||||
LotStatusType,
|
||||
} from './types';
|
||||
|
||||
// ===== API 데이터 타입 =====
|
||||
interface StockApiData {
|
||||
id: number;
|
||||
tenant_id: number;
|
||||
item_code: string;
|
||||
item_name: string;
|
||||
item_type: ItemType;
|
||||
item_type_label?: string;
|
||||
specification?: string;
|
||||
unit: string;
|
||||
stock_qty: string | number;
|
||||
safety_stock: string | number;
|
||||
reserved_qty: string | number;
|
||||
available_qty: string | number;
|
||||
lot_count: number;
|
||||
oldest_lot_date?: string;
|
||||
days_elapsed?: number;
|
||||
location?: string;
|
||||
status: StockStatusType;
|
||||
status_label?: string;
|
||||
last_receipt_date?: string;
|
||||
last_issue_date?: string;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
lots?: StockLotApiData[];
|
||||
}
|
||||
|
||||
interface StockLotApiData {
|
||||
id: number;
|
||||
stock_id: number;
|
||||
lot_no: string;
|
||||
fifo_order: number;
|
||||
receipt_date: string;
|
||||
days_elapsed?: number;
|
||||
qty: string | number;
|
||||
reserved_qty: string | number;
|
||||
available_qty: string | number;
|
||||
unit?: string;
|
||||
supplier?: string;
|
||||
supplier_lot?: string;
|
||||
po_number?: string;
|
||||
location?: string;
|
||||
status: LotStatusType;
|
||||
status_label?: string;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
}
|
||||
|
||||
interface StockApiPaginatedResponse {
|
||||
data: StockApiData[];
|
||||
current_page: number;
|
||||
last_page: number;
|
||||
per_page: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface StockApiStatsResponse {
|
||||
total_items: number;
|
||||
normal_count: number;
|
||||
low_count: number;
|
||||
out_count: number;
|
||||
}
|
||||
|
||||
interface StockApiStatsByTypeResponse {
|
||||
[key: string]: {
|
||||
label: string;
|
||||
count: number;
|
||||
total_qty: number | string;
|
||||
};
|
||||
}
|
||||
|
||||
// ===== API → Frontend 변환 (목록용) =====
|
||||
function transformApiToListItem(data: StockApiData): StockItem {
|
||||
return {
|
||||
id: String(data.id),
|
||||
itemCode: data.item_code,
|
||||
itemName: data.item_name,
|
||||
itemType: data.item_type,
|
||||
unit: data.unit || 'EA',
|
||||
stockQty: parseFloat(String(data.stock_qty)) || 0,
|
||||
safetyStock: parseFloat(String(data.safety_stock)) || 0,
|
||||
lotCount: data.lot_count || 0,
|
||||
lotDaysElapsed: data.days_elapsed || 0,
|
||||
status: data.status,
|
||||
location: data.location || '-',
|
||||
};
|
||||
}
|
||||
|
||||
// ===== API → Frontend 변환 (LOT용) =====
|
||||
function transformApiToLot(data: StockLotApiData): LotDetail {
|
||||
return {
|
||||
id: String(data.id),
|
||||
fifoOrder: data.fifo_order,
|
||||
lotNo: data.lot_no,
|
||||
receiptDate: data.receipt_date,
|
||||
daysElapsed: data.days_elapsed || 0,
|
||||
supplier: data.supplier || '-',
|
||||
poNumber: data.po_number || '-',
|
||||
qty: parseFloat(String(data.qty)) || 0,
|
||||
unit: data.unit || 'EA',
|
||||
location: data.location || '-',
|
||||
status: data.status,
|
||||
};
|
||||
}
|
||||
|
||||
// ===== API → Frontend 변환 (상세용) =====
|
||||
function transformApiToDetail(data: StockApiData): StockDetail {
|
||||
return {
|
||||
id: String(data.id),
|
||||
itemCode: data.item_code,
|
||||
itemName: data.item_name,
|
||||
itemType: data.item_type,
|
||||
category: '-', // API에서 category 제공 안 함
|
||||
specification: data.specification || '-',
|
||||
unit: data.unit || 'EA',
|
||||
currentStock: parseFloat(String(data.stock_qty)) || 0,
|
||||
safetyStock: parseFloat(String(data.safety_stock)) || 0,
|
||||
location: data.location || '-',
|
||||
lotCount: data.lot_count || 0,
|
||||
lastReceiptDate: data.last_receipt_date || '-',
|
||||
status: data.status,
|
||||
lots: (data.lots || []).map(transformApiToLot),
|
||||
};
|
||||
}
|
||||
|
||||
// ===== API → Frontend 변환 (통계용) =====
|
||||
function transformApiToStats(data: StockApiStatsResponse): StockStats {
|
||||
return {
|
||||
totalItems: data.total_items,
|
||||
normalCount: data.normal_count,
|
||||
lowCount: data.low_count,
|
||||
outCount: data.out_count,
|
||||
};
|
||||
}
|
||||
|
||||
// ===== 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 || '',
|
||||
};
|
||||
}
|
||||
|
||||
// ===== 페이지네이션 타입 =====
|
||||
interface PaginationMeta {
|
||||
currentPage: number;
|
||||
lastPage: number;
|
||||
perPage: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
// ===== 재고 목록 조회 =====
|
||||
export async function getStocks(params?: {
|
||||
page?: number;
|
||||
perPage?: number;
|
||||
search?: string;
|
||||
itemType?: string;
|
||||
status?: string;
|
||||
location?: string;
|
||||
sortBy?: string;
|
||||
sortDir?: string;
|
||||
}): Promise<{
|
||||
success: boolean;
|
||||
data: StockItem[];
|
||||
pagination: PaginationMeta;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
const searchParams = new URLSearchParams();
|
||||
|
||||
if (params?.page) searchParams.set('page', String(params.page));
|
||||
if (params?.perPage) searchParams.set('per_page', String(params.perPage));
|
||||
if (params?.search) searchParams.set('search', params.search);
|
||||
if (params?.itemType && params.itemType !== 'all') {
|
||||
searchParams.set('item_type', params.itemType);
|
||||
}
|
||||
if (params?.status && params.status !== 'all') {
|
||||
searchParams.set('status', params.status);
|
||||
}
|
||||
if (params?.location) searchParams.set('location', params.location);
|
||||
if (params?.sortBy) searchParams.set('sort_by', params.sortBy);
|
||||
if (params?.sortDir) searchParams.set('sort_dir', params.sortDir);
|
||||
|
||||
const queryString = searchParams.toString();
|
||||
const url = `${process.env.NEXT_PUBLIC_API_URL}/api/v1/stocks${queryString ? `?${queryString}` : ''}`;
|
||||
|
||||
console.log('[StockActions] GET stocks:', url);
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn('[StockActions] GET stocks 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: StockApiPaginatedResponse = result.data || {
|
||||
data: [],
|
||||
current_page: 1,
|
||||
last_page: 1,
|
||||
per_page: 20,
|
||||
total: 0,
|
||||
};
|
||||
|
||||
const stocks = (paginatedData.data || []).map(transformApiToListItem);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: stocks,
|
||||
pagination: {
|
||||
currentPage: paginatedData.current_page,
|
||||
lastPage: paginatedData.last_page,
|
||||
perPage: paginatedData.per_page,
|
||||
total: paginatedData.total,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[StockActions] getStocks error:', error);
|
||||
return {
|
||||
success: false,
|
||||
data: [],
|
||||
pagination: { currentPage: 1, lastPage: 1, perPage: 20, total: 0 },
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 재고 통계 조회 =====
|
||||
export async function getStockStats(): Promise<{
|
||||
success: boolean;
|
||||
data?: StockStats;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/stocks/stats`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn('[StockActions] GET stats 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: transformApiToStats(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[StockActions] getStockStats error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 품목유형별 통계 조회 =====
|
||||
export async function getStockStatsByType(): Promise<{
|
||||
success: boolean;
|
||||
data?: StockApiStatsByTypeResponse;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/stocks/stats-by-type`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn('[StockActions] GET stats-by-type 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: result.data,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[StockActions] getStockStatsByType error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 재고 상세 조회 (LOT 포함) =====
|
||||
export async function getStockById(id: string): Promise<{
|
||||
success: boolean;
|
||||
data?: StockDetail;
|
||||
error?: string;
|
||||
}> {
|
||||
try {
|
||||
const headers = await getApiHeaders();
|
||||
|
||||
const response = await fetch(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/api/v1/stocks/${id}`,
|
||||
{
|
||||
method: 'GET',
|
||||
headers,
|
||||
cache: 'no-store',
|
||||
}
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('[StockActions] GET stock 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: transformApiToDetail(result.data),
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('[StockActions] getStockById error:', error);
|
||||
return {
|
||||
success: false,
|
||||
error: '서버 오류가 발생했습니다.',
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user