feat: [부서관리] 기능 보완 - 필드 확장, 검색/필터, UI 개선

- Department 타입에 code, description, isActive, sortOrder 필드 추가
- DepartmentDialog: Zod + react-hook-form 폼 검증 (5개 필드)
- DepartmentToolbar: 상태 필터(전체/활성/비활성) + 검색 기능
- DepartmentTree: 트리 필터링 (검색어 + 상태)
- DepartmentTreeItem: 코드 Badge, 부서명 볼드, 설명 표시, 체크박스 크기 조정
- convertApiToLocal에서 누락 필드 매핑 복원
This commit is contained in:
2026-03-13 00:30:09 +09:00
parent ca5a9325c6
commit 13249384e2
26 changed files with 1284 additions and 915 deletions

View File

@@ -6,7 +6,7 @@ const withNextIntl = createNextIntlPlugin('./src/i18n/request.ts');
const nextConfig: NextConfig = {
reactStrictMode: false, // 🧪 TEST: Strict Mode 비활성화로 중복 요청 테스트
turbopack: {}, // ✅ CRITICAL: Next.js 15 + next-intl compatibility
allowedDevOrigins: ['192.168.0.*'], // 로컬 네트워크 기기 접속 허용
allowedDevOrigins: ['dev.sam.kr', '192.168.0.*'], // 로컬 도메인 + 네트워크 기기 접속 허용
serverExternalPackages: ['puppeteer'], // PDF 생성용 - Webpack 번들 제외
images: {
remotePatterns: [

View File

@@ -39,6 +39,9 @@ interface DocumentApi {
title: string;
date?: string;
count: number;
file_id?: number;
file_name?: string;
file_size?: number;
items?: {
id: number;
title: string;
@@ -89,6 +92,9 @@ function transformDocumentApi(api: DocumentApi) {
title: api.title,
date: api.date,
count: api.count,
fileId: api.file_id,
fileName: api.file_name,
fileSize: api.file_size,
items: api.items?.map((i) => ({
id: String(i.id),
title: i.title,
@@ -305,3 +311,30 @@ export async function deleteTemplateDocument(fileId: number, replace: boolean =
errorMessage: '파일 삭제에 실패했습니다.',
});
}
// ===== 품질관리서 파일 업로드/삭제 =====
export async function uploadQualityDocumentFile(qualityDocumentId: string, file: File) {
const formData = new FormData();
formData.append('file', file);
return executeServerAction({
url: buildApiUrl(`/api/v1/quality/documents/${qualityDocumentId}/upload-file`),
method: 'POST',
body: formData,
transform: (data: { id: number; display_name: string; file_size: number }) => ({
fileId: data.id,
fileName: data.display_name,
fileSize: data.file_size,
}),
errorMessage: '품질관리서 파일 업로드에 실패했습니다.',
});
}
export async function deleteQualityDocumentFile(qualityDocumentId: string) {
return executeServerAction({
url: buildApiUrl(`/api/v1/quality/documents/${qualityDocumentId}/file`),
method: 'DELETE',
errorMessage: '품질관리서 파일 삭제에 실패했습니다.',
});
}

View File

@@ -1,16 +1,20 @@
"use client";
import React, { useState } from 'react';
import React, { useState, useRef } from 'react';
import {
FileText, CheckCircle, ChevronDown, ChevronUp,
Eye, Truck, Calendar, ClipboardCheck, Box, FileCheck
Eye, Truck, Calendar, ClipboardCheck, Box, FileCheck,
Upload, Download, Loader2
} from 'lucide-react';
import { toast } from 'sonner';
import { Document, DocumentItem } from '../types';
import { downloadFileById } from '@/lib/utils/fileDownload';
interface DocumentListProps {
documents: Document[];
routeCode: string | null;
onViewDocument: (doc: Document, item?: DocumentItem) => void;
onQualityFileUpload?: (qualityDocumentId: string, file: File) => Promise<boolean>;
isMock?: boolean;
}
@@ -28,11 +32,76 @@ const getIcon = (type: string) => {
}
};
export const DocumentList = ({ documents, routeCode, onViewDocument, isMock }: DocumentListProps) => {
/** 파일 크기를 읽기 쉬운 형식으로 변환 */
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes}B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
}
export const DocumentList = ({ documents, routeCode, onViewDocument, onQualityFileUpload, isMock }: DocumentListProps) => {
const [expandedId, setExpandedId] = useState<string | null>(null);
const [uploadingDocId, setUploadingDocId] = useState<string | null>(null);
const [downloadingDocId, setDownloadingDocId] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const uploadTargetDocId = useRef<string | null>(null); // doc.id (상태 추적용)
const uploadApiDocId = useRef<string | null>(null); // 실제 DB ID (API 호출용)
// 품질관리서 파일 다운로드
const handleQualityDownload = async (doc: Document) => {
if (!doc.fileId) return;
setDownloadingDocId(doc.id);
try {
await downloadFileById(doc.fileId, doc.fileName);
} catch {
toast.error('파일 다운로드에 실패했습니다.');
} finally {
setDownloadingDocId(null);
}
};
// 업로드 버튼 클릭 → hidden input 트리거
const handleUploadClick = (e: React.MouseEvent, docId: string, apiDocId?: string) => {
e.stopPropagation();
uploadTargetDocId.current = docId; // 상태 추적용
uploadApiDocId.current = apiDocId || docId; // API 호출용 (품질관리서는 items[0].id)
fileInputRef.current?.click();
};
// 파일 선택 후 업로드 실행
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
const trackingId = uploadTargetDocId.current;
const apiId = uploadApiDocId.current;
if (!file || !trackingId || !apiId || !onQualityFileUpload) return;
setUploadingDocId(trackingId);
try {
const success = await onQualityFileUpload(apiId, file);
if (success) {
toast.success('파일이 업로드되었습니다.');
}
} finally {
setUploadingDocId(null);
uploadTargetDocId.current = null;
uploadApiDocId.current = null;
// input 초기화 (같은 파일 재선택 가능하도록)
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
}
};
// 문서 카테고리 클릭 핸들러
const handleDocClick = (doc: Document) => {
// 품질관리서: 파일이 있으면 다운로드, 없으면 무시
if (doc.type === 'quality') {
if (doc.fileId) {
handleQualityDownload(doc);
}
return;
}
const hasItems = doc.items && doc.items.length > 0;
if (!hasItems) return;
@@ -51,8 +120,34 @@ export const DocumentList = ({ documents, routeCode, onViewDocument, isMock }: D
onViewDocument(doc, item);
};
// 품질관리서 서브텍스트 렌더링
const renderQualitySubText = (doc: Document) => {
if (doc.fileId && doc.fileName) {
return (
<span className="flex items-center gap-1">
<Download size={10} className="text-purple-500" />
<span className="text-purple-600 truncate max-w-[150px]" title={doc.fileName}>
{doc.fileName}
</span>
{doc.fileSize && (
<span className="text-gray-400 ml-1">({formatFileSize(doc.fileSize)})</span>
)}
</span>
);
}
return <span className="text-gray-400"> </span>;
};
return (
<div className="bg-white rounded-lg p-3 sm:p-4 shadow-sm h-full flex flex-col overflow-hidden">
{/* hidden file input for quality document upload */}
<input
ref={fileInputRef}
type="file"
className="hidden"
onChange={handleFileChange}
/>
<div className="flex items-center gap-2 mb-3 sm:mb-4">
<h2 className="font-bold text-gray-800 text-xs sm:text-sm">
{' '}
@@ -75,35 +170,65 @@ export const DocumentList = ({ documents, routeCode, onViewDocument, isMock }: D
) : (
documents.map((doc) => {
const isExpanded = expandedId === doc.id;
const isQuality = doc.type === 'quality';
const hasItems = doc.items && doc.items.length > 0;
const hasMultipleItems = doc.items && doc.items.length > 1;
const isUploading = uploadingDocId === doc.id;
const isDownloading = downloadingDocId === doc.id;
// 품질관리서: 파일 유무로 클릭 가능 여부 결정
// 나머지: 아이템 유무로 결정
const isClickable = isQuality ? !!doc.fileId : hasItems;
return (
<div key={doc.id} className="border border-gray-200 rounded-lg overflow-hidden">
<div
onClick={() => handleDocClick(doc)}
className={`p-3 sm:p-4 flex justify-between items-center transition-colors ${
hasItems ? 'cursor-pointer hover:bg-gray-50' : 'cursor-default opacity-60'
isClickable ? 'cursor-pointer hover:bg-gray-50' : 'cursor-default opacity-60'
} ${isExpanded ? 'bg-green-50' : 'bg-white'}`}
>
<div className="flex items-center gap-3">
<div className={`p-2 rounded-lg ${isExpanded ? 'bg-white' : 'bg-gray-100'}`}>
{getIcon(doc.type)}
<div className="flex items-center gap-3 min-w-0 flex-1">
<div className={`p-2 rounded-lg flex-shrink-0 ${isExpanded ? 'bg-white' : 'bg-gray-100'}`}>
{(isUploading || isDownloading) ? (
<Loader2 className="text-purple-600 animate-spin" size={20} />
) : (
getIcon(doc.type)
)}
</div>
<div>
<div className="min-w-0 flex-1">
<h3 className="font-bold text-gray-800 text-sm">{doc.title}</h3>
<p className="text-xs text-gray-500">
{doc.count > 0 ? `${doc.count}건의 서류` : '서류 없음'}
{isQuality
? renderQualitySubText(doc)
: doc.count > 0 ? `${doc.count}건의 서류` : '서류 없음'
}
</p>
</div>
</div>
{hasMultipleItems && (
isExpanded ? (
<ChevronUp size={16} className="text-gray-400" />
) : (
<ChevronDown size={16} className="text-gray-400" />
)
)}
<div className="flex items-center gap-1 flex-shrink-0">
{/* 품질관리서 업로드 버튼 */}
{isQuality && onQualityFileUpload && doc.items?.[0]?.id && (
<button
type="button"
onClick={(e) => handleUploadClick(e, doc.id, doc.items![0].id)}
disabled={isUploading}
className="p-1.5 rounded-md hover:bg-purple-50 text-purple-500 hover:text-purple-700 transition-colors disabled:opacity-50"
title={doc.fileId ? '파일 교체' : '파일 업로드'}
>
<Upload size={16} />
</button>
)}
{/* 기존: 여러 아이템일 때 펼치기/접기 아이콘 */}
{!isQuality && hasMultipleItems && (
isExpanded ? (
<ChevronUp size={16} className="text-gray-400" />
) : (
<ChevronDown size={16} className="text-gray-400" />
)
)}
</div>
</div>
{isExpanded && hasMultipleItems && (
@@ -139,4 +264,4 @@ export const DocumentList = ({ documents, routeCode, onViewDocument, isMock }: D
</div>
</div>
);
};
};

View File

@@ -1,5 +1,15 @@
"use client";
/**
* InspectionModal (QMS 전용)
*
* 수입검사, 수주서, 납품확인서, 출고증, 품질관리서 등
* 아직 독립 모달이 없는 문서 타입만 처리.
*
* 작업일지(log), 중간검사(report), 제품검사(product)는
* 각각 WorkLogModal, InspectionReportModal, ProductInspectionViewModal로 분리됨.
*/
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { AlertCircle, Loader2, Save } from 'lucide-react';
import { DocumentViewer } from '@/components/document-system';
@@ -7,78 +17,114 @@ import { Button } from '@/components/ui/button';
import { toast } from 'sonner';
import { Document, DocumentItem } from '../types';
import { getDocumentDetail } from '../actions';
import { MOCK_SHIPMENT_DETAIL } from '../mockData';
// 기존 문서 컴포넌트 import
import { DeliveryConfirmation } from '@/components/outbound/ShipmentManagement/documents/DeliveryConfirmation';
import { ShippingSlip } from '@/components/outbound/ShipmentManagement/documents/ShippingSlip';
import type { ShipmentDetail } from '@/components/outbound/ShipmentManagement/types';
// 수주서 문서 컴포넌트 import
import { SalesOrderDocument } from '@/components/orders/documents/SalesOrderDocument';
import type { ProductInfo } from '@/components/orders/documents/OrderDocumentModal';
import type { OrderItem } from '@/components/orders/actions';
// 품질검사 문서 컴포넌트 import
import {
ImportInspectionDocument,
JointbarInspectionDocument,
QualityDocumentUploader,
} from './documents';
// 제품검사 성적서 (FQC 양식) import
import { FqcDocumentContent } from '@/components/quality/InspectionManagement/documents/FqcDocumentContent';
import { InspectionReportDocument } from '@/components/quality/InspectionManagement/documents/InspectionReportDocument';
import type { FqcTemplate, FqcDocumentData } from '@/components/quality/InspectionManagement/fqcActions';
import type { InspectionReportDocument as InspectionReportDocumentType, ProductInspectionData } from '@/components/quality/InspectionManagement/types';
import { mockReportInspectionItems, mapInspectionDataToItems } from '@/components/quality/InspectionManagement/mockData';
import type { ImportInspectionTemplate, ImportInspectionRef, InspectionItemValue } from './documents/ImportInspectionDocument';
// 작업일지 + 중간검사 성적서 문서 컴포넌트 import (공정별 신규 버전)
import {
ScreenWorkLogContent,
SlatWorkLogContent,
BendingWorkLogContent,
ScreenInspectionContent,
SlatInspectionContent,
BendingInspectionContent,
} from '@/components/production/WorkOrders/documents';
import type { WorkOrder } from '@/components/production/WorkOrders/types';
// 검사 템플릿 API
import { getInspectionTemplate } from '@/components/material/ReceivingManagement/actions';
// 작업지시 상세 API (QMS 작업일지/중간검사용)
import { getWorkOrderById } from '@/components/production/WorkOrders/actions';
/**
* 저장된 document.data (field_key 기반)를 ImportInspectionDocument의 initialValues로 변환
*
* field_key 패턴:
* - {itemId}_n{1,2,3} → numeric 측정값
* - {itemId}_okng_n{1,2,3} → OK/NG 값
* - {itemId}_result → 항목별 판정
* 두 가지 저장 형식을 모두 지원:
* - 정규화 형식: section_id + row_index로 항목 식별, field_key는 "n1", "n1_ok" 등
* - 레거시 형식: field_key에 item.id 포함, 예: "${itemId}_n1", "${itemId}_okng_n1"
*/
function parseSavedDataToInitialValues(
tmpl: ImportInspectionTemplate,
docData: Array<{ field_key: string; field_value: string | null }>
docData: Array<{ field_key: string; field_value: string | null; section_id?: number | null; row_index?: number }>,
sections?: Array<{ id: number; items: Array<{ id: number }> }>
): InspectionItemValue[] {
// field_key → value 맵 생성
const dataMap = new Map<string, string>();
// (sectionId, rowIndex) → inspectionItem.id 역매핑 구축
const reverseMap = new Map<string, string>();
if (sections) {
for (const section of sections) {
section.items.forEach((sItem, idx) => {
reverseMap.set(`${section.id}_${idx}`, String(sItem.id));
});
}
}
// 정규화 형식: itemId → { field_key → value }
const normalizedMap = new Map<string, Map<string, string>>();
// 레거시 형식: "${itemId}_n1" → value
const legacyMap = new Map<string, string>();
for (const d of docData) {
if (d.field_value) dataMap.set(d.field_key, d.field_value);
if (!d.field_value) continue;
const key = d.field_key;
const val = d.field_value;
// 전역 필드는 스킵
if (key === 'overall_result' || key === 'footer_judgement') continue;
if (key === 'remark' || key === 'footer_remark') continue;
// 정규화 형식: section_id가 있으면 역매핑으로 item 찾기
if (d.section_id != null && reverseMap.size > 0) {
const itemId = reverseMap.get(`${d.section_id}_${d.row_index ?? 0}`);
if (itemId) {
if (!normalizedMap.has(itemId)) normalizedMap.set(itemId, new Map());
normalizedMap.get(itemId)!.set(key, val);
}
continue;
}
// 레거시 형식 fallback
legacyMap.set(key, val);
}
return tmpl.inspectionItems.map((item) => {
const isOkng = item.measurementType === 'okng';
const measurements: (number | 'OK' | 'NG' | null)[] = Array(item.measurementCount).fill(null);
// 정규화 형식 우선 시도
const nData = normalizedMap.get(item.id);
if (nData && nData.size > 0) {
for (let n = 0; n < item.measurementCount; n++) {
if (isOkng) {
const okVal = nData.get(`n${n + 1}_ok`);
const ngVal = nData.get(`n${n + 1}_ng`);
if (okVal === 'OK') measurements[n] = 'OK';
else if (ngVal === 'NG') measurements[n] = 'NG';
} else {
const val = nData.get(`n${n + 1}`);
if (val) {
const num = parseFloat(val);
measurements[n] = isNaN(num) ? null : num;
}
}
}
const resultVal = nData.get('value');
let result: 'OK' | 'NG' | null = null;
if (resultVal === '적합' || resultVal === 'ok') result = 'OK';
else if (resultVal === '부적합' || resultVal === 'ng') result = 'NG';
return { itemId: item.id, measurements, result };
}
// 레거시 형식 fallback
for (let n = 0; n < item.measurementCount; n++) {
if (isOkng) {
const val = dataMap.get(`${item.id}_okng_n${n + 1}`);
const val = legacyMap.get(`${item.id}_okng_n${n + 1}`);
if (val === 'ok') measurements[n] = 'OK';
else if (val === 'ng') measurements[n] = 'NG';
} else {
const val = dataMap.get(`${item.id}_n${n + 1}`);
const val = legacyMap.get(`${item.id}_n${n + 1}`);
if (val) {
const num = parseFloat(val);
measurements[n] = isNaN(num) ? null : num;
@@ -86,8 +132,7 @@ function parseSavedDataToInitialValues(
}
}
// 항목별 판정
const resultVal = dataMap.get(`${item.id}_result`);
const resultVal = legacyMap.get(`${item.id}_result`);
let result: 'OK' | 'NG' | null = null;
if (resultVal === 'ok') result = 'OK';
else if (resultVal === 'ng') result = 'NG';
@@ -102,15 +147,14 @@ interface InspectionModalProps {
document: Document | null;
documentItem: DocumentItem | null;
// 수입검사 템플릿 로드용 추가 props
itemId?: number; // 품목 ID (실제 API로 템플릿 조회 시 사용)
itemId?: number;
itemName?: string;
specification?: string;
supplier?: string;
inspector?: string; // 검사자 (현재 로그인 사용자)
inspectorDept?: string; // 검사자 부서
lotSize?: number; // 로트크기 (입고수량)
materialNo?: string; // 자재번호
// 읽기 전용 모드 (QMS 심사 확인용)
inspector?: string;
inspectorDept?: string;
lotSize?: number;
materialNo?: string;
readOnly?: boolean;
}
@@ -118,11 +162,8 @@ interface InspectionModalProps {
const DOCUMENT_INFO: Record<string, { label: string; hasTemplate: boolean; color: string }> = {
import: { label: '수입검사 성적서', hasTemplate: true, color: 'text-green-600' },
order: { label: '수주서', hasTemplate: true, color: 'text-blue-600' },
log: { label: '작업일지', hasTemplate: true, color: 'text-orange-500' },
report: { label: '중간검사 성적서', hasTemplate: true, color: 'text-blue-500' },
confirmation: { label: '납품확인서', hasTemplate: true, color: 'text-red-500' },
shipping: { label: '출고증', hasTemplate: true, color: 'text-gray-600' },
product: { label: '제품검사 성적서', hasTemplate: true, color: 'text-green-500' },
quality: { label: '품질관리서', hasTemplate: false, color: 'text-purple-600' },
};
@@ -153,84 +194,54 @@ const PlaceholderDocument = ({ docType, docItem }: { docType: string; docItem: D
);
};
// QMS용 수주서 Mock 데이터
const QMS_MOCK_PRODUCTS: ProductInfo[] = [
{ productName: '방화 스크린 셔터 (표준형)', productCategory: '스크린', openWidth: '3000', openHeight: '2500', quantity: 5, floor: '1F', code: 'FSS-01' },
{ productName: '방화 스크린 셔터 (방화형)', productCategory: '스크린', openWidth: '3000', openHeight: '2500', quantity: 3, floor: '2F', code: 'FSS-02' },
];
const QMS_MOCK_ORDER_ITEMS: OrderItem[] = [
{ id: 'mt-1', itemCode: 'MT-001', itemName: '모터(380V 단상)', specification: '150K', type: '모터', quantity: 8, unit: 'EA', unitPrice: 120000, supplyAmount: 960000, taxAmount: 96000, totalAmount: 1056000, sortOrder: 1 },
{ id: 'br-1', itemCode: 'BR-001', itemName: '브라켓트', specification: '380X180 [2-4"]', type: '브라켓', quantity: 16, unit: 'EA', unitPrice: 15000, supplyAmount: 240000, taxAmount: 24000, totalAmount: 264000, sortOrder: 2 },
{ id: 'gr-1', itemCode: 'GR-001', itemName: '가이드레일 백면형 (120X70)', specification: 'EGI 1.5ST', type: '가이드레일', quantity: 16, unit: 'EA', unitPrice: 25000, supplyAmount: 400000, taxAmount: 40000, totalAmount: 440000, width: 120, height: 2500, sortOrder: 3 },
{ id: 'cs-1', itemCode: 'CS-001', itemName: '케이스(셔터박스)', specification: 'EGI 1.5ST 380X180', type: '케이스', quantity: 8, unit: 'EA', unitPrice: 35000, supplyAmount: 280000, taxAmount: 28000, totalAmount: 308000, width: 380, height: 180, sortOrder: 4 },
{ id: 'bf-1', itemCode: 'BF-001', itemName: '하단마감재', specification: 'EGI 1.5ST', type: '하단마감재', quantity: 8, unit: 'EA', unitPrice: 18000, supplyAmount: 144000, taxAmount: 14400, totalAmount: 158400, sortOrder: 5 },
];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type DocumentDetailData = Record<string, any>;
// FQC 문서 API 응답 → FqcTemplate 변환
function transformFqcApiToTemplate(apiTemplate: Record<string, unknown>): FqcTemplate {
const t = apiTemplate as {
id: number; name: string; category: string; title: string | null;
approval_lines: { id: number; name: string; department: string; sort_order: number }[];
basic_fields: { id: number; label: string; field_key: string; field_type: string; default_value: string | null; is_required: boolean; sort_order: number }[];
sections: { id: number; name: string; title: string | null; description: string | null; image_path: string | null; sort_order: number;
items: { id: number; section_id: number; item_name: string; standard: string | null; tolerance: string | null; measurement_type: string; frequency: string; sort_order: number; category: string; method: string }[];
}[];
columns: { id: number; label: string; column_type: string; width: string | null; group_name: string | null; sort_order: number }[];
};
/**
* API 출고 상세 응답 → ShipmentDetail 타입 매핑
* ShipmentOrderDocument 내부에서 아직 MOCK_ 데이터를 사용하므로
* 여기서는 헤더 정보 매핑만 수행 (Phase 2에서 완전 전환)
*/
function mapShipmentApiToDetail(api: DocumentDetailData): ShipmentDetail {
return {
id: t.id, name: t.name, category: t.category, title: t.title,
approvalLines: (t.approval_lines || []).map(a => ({ id: a.id, name: a.name, department: a.department, sortOrder: a.sort_order })),
basicFields: (t.basic_fields || []).map(f => ({ id: f.id, label: f.label, fieldKey: f.field_key, fieldType: f.field_type, defaultValue: f.default_value, isRequired: f.is_required, sortOrder: f.sort_order })),
sections: (t.sections || []).map(s => ({
id: s.id, name: s.name, title: s.title, description: s.description, imagePath: s.image_path, sortOrder: s.sort_order,
items: (s.items || []).map(i => ({ id: i.id, sectionId: i.section_id, itemName: i.item_name, standard: i.standard, tolerance: i.tolerance, measurementType: i.measurement_type, frequency: i.frequency, sortOrder: i.sort_order, category: i.category || '', method: i.method || '' })),
id: String(api.id || ''),
shipmentNo: api.shipment_no || '-',
lotNo: api.lot_no || '-',
siteName: api.site_name || '-',
customerName: api.customer_name || '-',
customerGrade: api.customer_grade || '-',
status: api.status || 'scheduled',
scheduledDate: api.scheduled_date || '-',
deliveryMethod: api.delivery_method || 'loading',
freightCost: api.shipping_cost,
receiver: api.receiver,
receiverContact: api.receiver_contact,
deliveryAddress: api.delivery_address || '-',
vehicleNo: api.vehicle_no,
driverName: api.driver_name,
driverContact: api.driver_contact,
remarks: api.remarks,
vehicleDispatches: (api.vehicle_dispatches || []).map((d: DocumentDetailData, i: number) => ({
id: String(i),
logisticsCompany: d.logistics_company || '-',
arrivalDateTime: d.arrival_datetime || '-',
tonnage: d.tonnage || '-',
vehicleNo: d.vehicle_no || '-',
driverContact: d.driver_contact || '-',
remarks: d.remarks || '',
})),
columns: (t.columns || []).map(c => ({ id: c.id, label: c.label, columnType: c.column_type, width: c.width, groupName: c.group_name ?? null, sortOrder: c.sort_order })),
};
// Phase 2: product_groups/other_parts 실 데이터 매핑 예정
productGroups: [],
otherParts: [],
// 하위 호환 필드 (최소값)
products: [],
priority: 'normal',
depositConfirmed: false,
invoiceIssued: false,
canShip: false,
} as ShipmentDetail;
}
function transformFqcApiToData(apiData: { section_id: number | null; column_id: number | null; row_index: number; field_key: string; field_value: string | null }[]): FqcDocumentData[] {
return (apiData || []).map(d => ({ sectionId: d.section_id, columnId: d.column_id, rowIndex: d.row_index, fieldKey: d.field_key, fieldValue: d.field_value }));
}
// QMS용 작업일지 Mock WorkOrder 생성
const createQmsMockWorkOrder = (subType?: string): WorkOrder => ({
id: 'qms-wo-1',
workOrderNo: 'KD-WO-240924-01',
lotNo: 'KD-SS-240924-19',
processId: 1,
processName: subType === 'slat' ? '슬랫' : subType === 'bending' ? '절곡' : '스크린',
processCode: subType || 'screen',
processType: (subType || 'screen') as 'screen' | 'slat' | 'bending',
status: 'in_progress',
client: '삼성물산(주)',
projectName: '강남 아파트 단지',
dueDate: '2024-10-05',
assignee: '김작업',
assignees: [
{ id: '1', name: '김작업', isPrimary: true },
{ id: '2', name: '이생산', isPrimary: false },
],
orderDate: '2024-09-20',
scheduledDate: '2024-09-24',
shipmentDate: '2024-10-04',
salesOrderDate: '2024-09-18',
isAssigned: true,
isStarted: true,
priority: 3,
priorityLabel: '긴급',
shutterCount: 5,
department: '생산부',
items: [
{ id: '1', no: 1, status: 'completed', productName: '와이어 스크린', floorCode: '1층/FSS-01', specification: '3000×2500', quantity: 2, unit: 'EA', orderNodeId: null, orderNodeName: '' },
{ id: '2', no: 2, status: 'in_progress', productName: '메쉬 스크린', floorCode: '2층/FSS-03', specification: '3000×2500', quantity: 3, unit: 'EA', orderNodeId: null, orderNodeName: '' },
{ id: '3', no: 3, status: 'waiting', productName: '광폭 와이어', floorCode: '3층/FSS-05', specification: '12000×4500', quantity: 1, unit: 'EA', orderNodeId: null, orderNodeName: '' },
],
currentStep: 2,
issues: [],
note: '품질 검수 철저히 진행',
});
// 로딩 컴포넌트
const LoadingDocument = () => (
<div className="bg-white shadow-sm p-16 w-full h-full rounded flex flex-col items-center justify-center text-center">
@@ -257,9 +268,9 @@ const ErrorDocument = ({ message, onRetry }: { message: string; onRetry?: () =>
);
/**
* InspectionModal V2
* - DocumentViewer 시스템 사용
* - 수입검사: 모달 열릴 때 API로 템플릿 로드 (Lazy Loading)
* InspectionModal
* - 수입검사, 수주서, 납품확인서, 출고증, 품질관리서만 처리
* - 작업일지/중간검사/제품검사는 각각 독립 모달로 분리됨
*/
export const InspectionModal = ({
isOpen,
@@ -282,84 +293,50 @@ export const InspectionModal = ({
const [isLoadingTemplate, setIsLoadingTemplate] = useState(false);
const [templateError, setTemplateError] = useState<string | null>(null);
// 작업일지/중간검사용 WorkOrder 상태
const [workOrderData, setWorkOrderData] = useState<WorkOrder | null>(null);
const [isLoadingWorkOrder, setIsLoadingWorkOrder] = useState(false);
const [workOrderError, setWorkOrderError] = useState<string | null>(null);
// 수입검사 저장용 ref/상태
const importDocRef = useRef<ImportInspectionRef>(null);
const [isSaving, setIsSaving] = useState(false);
// 제품검사 성적서 FQC 상태
const [fqcTemplate, setFqcTemplate] = useState<FqcTemplate | null>(null);
const [fqcData, setFqcData] = useState<FqcDocumentData[]>([]);
const [fqcDocumentNo, setFqcDocumentNo] = useState<string>('');
const [isLoadingFqc, setIsLoadingFqc] = useState(false);
const [fqcError, setFqcError] = useState<string | null>(null);
// 레거시 inspection_data 기반 제품검사 성적서
const [legacyReportData, setLegacyReportData] = useState<InspectionReportDocumentType | null>(null);
// 수주서/출고증/납품확인서 실 데이터 상태
const [docDetailData, setDocDetailData] = useState<DocumentDetailData | null>(null);
const [isLoadingDocDetail, setIsLoadingDocDetail] = useState(false);
// 수주서/출고증/납품확인서 데이터 로드
useEffect(() => {
if (!isOpen || !doc) return;
if (!['order', 'confirmation', 'shipping'].includes(doc.type)) return;
const docItemId = documentItem?.id || doc.id;
if (!docItemId) return;
setIsLoadingDocDetail(true);
getDocumentDetail(doc.type, docItemId)
.then((result) => {
if (result.success && result.data) {
const raw = result.data as DocumentDetailData;
setDocDetailData(raw?.data ?? raw);
}
})
.finally(() => setIsLoadingDocDetail(false));
return () => {
setDocDetailData(null);
};
}, [isOpen, doc?.type, doc?.id, documentItem?.id]);
// 수입검사 템플릿 로드 (모달 열릴 때)
useEffect(() => {
// itemId가 있으면 실제 API로 조회, 없으면 itemName/specification으로 mock 조회
if (isOpen && doc?.type === 'import' && (itemId || (itemName && specification))) {
loadInspectionTemplate();
}
// 모달 닫힐 때 상태 초기화
if (!isOpen) {
setImportTemplate(null);
setImportInitialValues(undefined);
setTemplateError(null);
setFqcTemplate(null);
setFqcData([]);
setFqcDocumentNo('');
setFqcError(null);
setLegacyReportData(null);
setWorkOrderData(null);
setWorkOrderError(null);
}
}, [isOpen, doc?.type, itemId, itemName, specification]);
// 작업일지/중간검사 WorkOrder 로드 (모달 열릴 때)
// log: documentItem.id === work_order_id, report: documentItem.workOrderId로 전달
useEffect(() => {
if (isOpen && (doc?.type === 'log' || doc?.type === 'report')) {
const woId = documentItem?.workOrderId || (doc?.type === 'log' ? Number(documentItem?.id) : null);
if (woId) {
loadWorkOrderData(woId);
}
}
}, [isOpen, doc?.type, documentItem?.workOrderId, documentItem?.id]);
// 제품검사 성적서 FQC 로드 (모달 열릴 때)
useEffect(() => {
if (isOpen && doc?.type === 'product' && documentItem?.id) {
loadFqcDocument(documentItem.id);
}
}, [isOpen, doc?.type, documentItem?.id]);
const loadWorkOrderData = async (workOrderId: number) => {
setIsLoadingWorkOrder(true);
setWorkOrderError(null);
try {
const result = await getWorkOrderById(String(workOrderId));
if (result.success && result.data) {
setWorkOrderData(result.data);
} else {
setWorkOrderError(result.error || '작업지시 데이터를 불러올 수 없습니다.');
}
} catch (error) {
console.error('[InspectionModal] loadWorkOrderData error:', error);
setWorkOrderError('작업지시 데이터 로드 중 오류가 발생했습니다.');
} finally {
setIsLoadingWorkOrder(false);
}
};
const loadInspectionTemplate = async () => {
// itemId가 있으면 실제 API 호출, 없으면 itemName/specification 필요
if (!itemId && (!itemName || !specification)) return;
setIsLoadingTemplate(true);
@@ -381,10 +358,19 @@ export const InspectionModal = ({
const tmpl = result.data as ImportInspectionTemplate;
setImportTemplate(tmpl);
// 저장된 측정값을 initialValues로 변환
const docData = result.resolveData?.document?.data;
if (docData && docData.length > 0) {
const values = parseSavedDataToInitialValues(tmpl, docData.map((d: { field_key: string; field_value?: string | null }) => ({ field_key: d.field_key, field_value: d.field_value ?? null })));
const sections = result.resolveData?.template?.sections;
const values = parseSavedDataToInitialValues(
tmpl,
docData.map((d: { field_key: string; field_value?: string | null; section_id?: number | null; row_index?: number }) => ({
field_key: d.field_key,
field_value: d.field_value ?? null,
section_id: d.section_id,
row_index: d.row_index,
})),
sections
);
setImportInitialValues(values);
} else {
setImportInitialValues(undefined);
@@ -400,74 +386,7 @@ export const InspectionModal = ({
}
};
// 제품검사 성적서 문서 로드 (FQC 우선, inspection_data fallback)
const loadFqcDocument = async (locationId: string) => {
setIsLoadingFqc(true);
setFqcError(null);
setLegacyReportData(null);
try {
const result = await getDocumentDetail('product', locationId);
if (result.success && result.data) {
const data = result.data as {
document_id: number | null;
inspection_status: string | null;
inspection_data: ProductInspectionData | null;
floor_code: string | null;
symbol_code: string | null;
fqc_document?: {
document_no: string;
template: Record<string, unknown>;
data: { section_id: number | null; column_id: number | null; row_index: number; field_key: string; field_value: string | null }[];
};
};
if (data.fqc_document) {
// FQC 문서가 있는 경우
setFqcTemplate(transformFqcApiToTemplate(data.fqc_document.template));
setFqcData(transformFqcApiToData(data.fqc_document.data));
setFqcDocumentNo(data.fqc_document.document_no || '');
} else if (data.inspection_data && data.inspection_status === 'completed') {
// FQC 없지만 inspection_data가 있는 경우 → 레거시 리포트 생성
const inspData = data.inspection_data;
const mappedItems = mapInspectionDataToItems(mockReportInspectionItems, inspData);
const locationLabel = [data.floor_code, data.symbol_code].filter(Boolean).join(' ');
setLegacyReportData({
documentNumber: '',
createdDate: '',
approvalLine: [
{ role: '작성', name: '', department: '' },
{ role: '승인', name: '', department: '' },
],
productName: inspData.productName || '',
productLotNo: '',
productCode: '',
lotSize: '1',
client: '',
inspectionDate: '',
siteName: locationLabel,
inspector: '',
productImages: inspData.productImages || [],
inspectionItems: mappedItems,
specialNotes: inspData.specialNotes || '',
finalJudgment: '합격',
});
} else {
setFqcError('제품검사 성적서 문서가 아직 생성되지 않았습니다.');
}
} else {
setFqcError(result.error || '제품검사 성적서 조회에 실패했습니다.');
}
} catch (error) {
console.error('[InspectionModal] loadFqcDocument error:', error);
setFqcError('제품검사 성적서 로드 중 오류가 발생했습니다.');
} finally {
setIsLoadingFqc(false);
}
};
// 수입검사 저장 핸들러 (hooks는 early return 전에 호출해야 함)
// 수입검사 저장 핸들러
const handleImportSave = useCallback(async () => {
if (!importDocRef.current) return;
@@ -497,66 +416,6 @@ export const InspectionModal = ({
const handleQualityFileDelete = () => {
};
// 작업일지/중간검사 공통: WorkOrder 데이터 로딩 상태 처리
const renderWorkOrderLoading = () => {
if (isLoadingWorkOrder) {
return (
<div className="bg-white shadow-sm p-16 w-full h-full rounded flex flex-col items-center justify-center text-center">
<Loader2 className="w-12 h-12 text-blue-500 animate-spin mb-4" />
<p className="text-gray-600 text-sm"> ...</p>
</div>
);
}
if (workOrderError) {
return <ErrorDocument message={workOrderError} onRetry={documentItem?.workOrderId ? () => loadWorkOrderData(documentItem.workOrderId!) : undefined} />;
}
return null;
};
// 작업일지 공정별 렌더링
const renderWorkLogDocument = () => {
const loadingEl = renderWorkOrderLoading();
if (loadingEl) return loadingEl;
const subType = documentItem?.subType;
// 실제 WorkOrder 데이터 사용, 없으면 fallback mock
const orderData = workOrderData || createQmsMockWorkOrder(subType);
switch (subType) {
case 'screen':
return <ScreenWorkLogContent data={orderData} />;
case 'slat':
return <SlatWorkLogContent data={orderData} />;
case 'bending':
return <BendingWorkLogContent data={orderData} />;
default:
return <ScreenWorkLogContent data={orderData} />;
}
};
// 중간검사 성적서 서브타입에 따른 렌더링 (신규 버전 통일)
const renderReportDocument = () => {
const loadingEl = renderWorkOrderLoading();
if (loadingEl) return loadingEl;
const subType = documentItem?.subType;
// 실제 WorkOrder 데이터 사용, 없으면 fallback mock
const orderData = workOrderData || createQmsMockWorkOrder(subType || 'screen');
switch (subType) {
case 'screen':
return <ScreenInspectionContent data={orderData} readOnly />;
case 'bending':
return <BendingInspectionContent data={orderData} readOnly />;
case 'slat':
return <SlatInspectionContent data={orderData} readOnly />;
case 'jointbar':
return <JointbarInspectionDocument />;
default:
return <ScreenInspectionContent data={orderData} readOnly />;
}
};
// 수입검사 문서 렌더링 (Lazy Loading)
const renderImportInspectionDocument = () => {
if (isLoadingTemplate) {
@@ -567,7 +426,6 @@ export const InspectionModal = ({
return <ErrorDocument message={templateError} onRetry={loadInspectionTemplate} />;
}
// 템플릿이 로드되면 전달, 아니면 기본 템플릿 사용
return (
<ImportInspectionDocument
ref={importDocRef}
@@ -579,74 +437,50 @@ export const InspectionModal = ({
);
};
// 제품검사 성적서 렌더링 (FQC 우선, inspection_data fallback)
const renderProductDocument = () => {
if (isLoadingFqc) {
return <LoadingDocument />;
}
if (fqcError) {
return <ErrorDocument message={fqcError} onRetry={documentItem?.id ? () => loadFqcDocument(documentItem.id) : undefined} />;
}
// FQC 문서 기반 렌더링
if (fqcTemplate) {
return (
<FqcDocumentContent
template={fqcTemplate}
documentData={fqcData}
documentNo={fqcDocumentNo}
readonly
/>
);
}
// 레거시 inspection_data 기반 렌더링
if (legacyReportData) {
return <InspectionReportDocument data={legacyReportData} />;
}
return <PlaceholderDocument docType="product" docItem={documentItem} />;
};
// 문서 타입에 따른 컨텐츠 렌더링
const renderDocumentContent = () => {
switch (doc.type) {
case 'order':
case 'order': {
if (isLoadingDocDetail) return <LoadingDocument />;
if (!docDetailData) return <ErrorDocument message="수주서 데이터를 불러올 수 없습니다." />;
const d = docDetailData;
return (
<SalesOrderDocument
orderNumber="KD-SS-240924-19"
documentNumber="KD-SS-240924-19"
certificationNumber="KD-SS-240924-19"
orderDate="2024-09-24"
client="삼성물산(주)"
siteName="강남 아파트 단지"
manager="김담당"
managerContact="010-1234-5678"
deliveryRequestDate="2024-10-05"
expectedShipDate="2024-10-04"
deliveryMethod="직접배차"
address="서울시 강남구 테헤란로 123"
recipientName="김인수"
recipientContact="010-9876-5432"
shutterCount={8}
products={QMS_MOCK_PRODUCTS}
items={QMS_MOCK_ORDER_ITEMS}
remarks="납기일 엄수 요청"
orderNumber={d.order_no || '-'}
documentNumber={d.order_no || '-'}
certificationNumber={d.order_no || '-'}
orderDate={d.received_at || '-'}
client={d.client_name || '-'}
siteName={d.site_name || '-'}
manager={d.manager_name || '-'}
managerContact={d.client_contact || '-'}
deliveryRequestDate={d.delivery_date || '-'}
deliveryMethod={d.delivery_method_code || '-'}
address={[d.shipping_address, d.shipping_address_detail].filter(Boolean).join(' ') || '-'}
recipientName={d.receiver || '-'}
recipientContact={d.receiver_contact || '-'}
shutterCount={d.nodes_count || 0}
remarks={d.remarks}
productRows={d.products || []}
motorsLeft={d.motors?.left || []}
motorsRight={d.motors?.right || []}
bendingParts={d.bending_parts || []}
subsidiaryParts={d.subsidiary_parts || []}
categoryCode={d.category_code}
/>
);
case 'log':
return renderWorkLogDocument();
}
case 'confirmation':
return <DeliveryConfirmation data={MOCK_SHIPMENT_DETAIL} />;
case 'shipping':
return <ShippingSlip data={MOCK_SHIPMENT_DETAIL} />;
if (isLoadingDocDetail) return <LoadingDocument />;
if (!docDetailData) return <ErrorDocument message="출고 데이터를 불러올 수 없습니다." />;
// TODO Phase 2: ShipmentOrderDocument도 실 데이터로 전환 시 여기서 매핑
// 현재는 ShipmentOrderDocument 내부 mock data를 사용하되 헤더 정보만 전달
return doc.type === 'confirmation'
? <DeliveryConfirmation data={mapShipmentApiToDetail(docDetailData)} />
: <ShippingSlip data={mapShipmentApiToDetail(docDetailData)} />;
case 'import':
return renderImportInspectionDocument();
case 'product':
return renderProductDocument();
case 'report':
return renderReportDocument();
case 'quality':
return (
<QualityDocumentUploader
@@ -689,4 +523,4 @@ export const InspectionModal = ({
{renderDocumentContent()}
</DocumentViewer>
);
};
};

View File

@@ -61,8 +61,8 @@ export const ReportList = ({ reports, selectedId, onSelect, isMock }: ReportList
isSelected ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-600'
}`}>
<Package size={16} />
<span> {report.routeCount}</span>
<span className="text-gray-400 text-xs ml-1">( {report.totalRoutes})</span>
<span> {report.totalRoutes}</span>
<span className="text-gray-400 text-xs ml-1">( {report.routeCount}/{report.totalRoutes})</span>
</div>
</div>
);

View File

@@ -81,8 +81,7 @@ export const RouteList = ({ routes, selectedId, onSelect, onToggleItem, reportCo
)}
</div>
<p className="text-xs text-gray-500 mb-0.5">: {route.date || '-'}</p>
{route.client && <p className="text-xs text-gray-500 mb-0.5">: {route.client}</p>}
<p className="text-xs text-gray-500 mb-2">: {route.site || '-'}</p>
<p className="text-xs text-gray-500 mb-2">: {route.site || '-'}{route.client ? ` (${route.client})` : ''}</p>
<div className="inline-flex items-center gap-1 bg-gray-100 px-2 py-0.5 rounded text-xs text-gray-600">
<MapPin size={10} />
<span>{route.locationCount}</span>

View File

@@ -903,13 +903,13 @@ export const ImportInspectionDocument = forwardRef<ImportInspectionRef, ImportIn
</td>
) : item.measurementType === 'single_value' ? (
// 단일 입력 (colspan으로 합침)
// 단일 입력 (colspan으로 합침) - 저장된 값이 있으면 표시
<td
className="border border-gray-400 px-2 py-1 text-center align-middle"
colSpan={3}
rowSpan={isGroupItem ? itemRowSpan : 1}
>
<span className="text-gray-400 text-xs">( )</span>
{renderMeasurementInput(item.id, 0)}
</td>
) : item.measurementType === 'okng' ? (
// OK/NG 선택형 - n 값에 따라 열 개수 결정

View File

@@ -127,6 +127,9 @@ export function useDay2LotAudit() {
}, []);
const handleViewDocument = useCallback((doc: Document, item?: DocumentItem) => {
// 품질관리서는 파일 다운로드로 처리 (DocumentList에서 직접 처리하므로 모달 열지 않음)
if (doc.type === 'quality') return;
setSelectedDoc(doc);
setSelectedDocItem(item || null);
setModalOpen(true);
@@ -168,6 +171,18 @@ export function useDay2LotAudit() {
}
}, [pendingConfirmIds]);
// 품질관리서 파일 정보 업데이트 (업로드 성공 후 documents 상태 반영)
// 품질관리서는 doc.id가 'quality' 문자열이므로 type으로 매칭
const updateQualityDocumentFile = useCallback((_docId: string, fileInfo: { fileId: number; fileName: string; fileSize: number }) => {
setDocuments((prev) =>
prev.map((doc) =>
doc.type === 'quality'
? { ...doc, fileId: fileInfo.fileId, fileName: fileInfo.fileName, fileSize: fileInfo.fileSize }
: doc
)
);
}, []);
const handleYearChange = useCallback((year: number) => {
setSelectedYear(year);
setSelectedReport(null);
@@ -218,6 +233,9 @@ export function useDay2LotAudit() {
handleToggleItem,
pendingConfirmIds,
// 품질관리서 파일
updateQualityDocumentFile,
// 로딩
loadingReports,
loadingRoutes,

View File

@@ -8,6 +8,10 @@ import { ReportList } from './components/ReportList';
import { RouteList } from './components/RouteList';
import { DocumentList } from './components/DocumentList';
import { InspectionModal } from './components/InspectionModal';
import { InspectionReportModal } from '@/components/production/WorkOrders/documents';
import { WorkLogModal } from '@/components/production/WorkOrders/documents';
import { ProductInspectionViewModal } from '@/components/quality/InspectionManagement/ProductInspectionViewModal';
import { getDocumentDetail } from './actions';
import { DayTabs } from './components/DayTabs';
import { Day1ChecklistPanel } from './components/Day1ChecklistPanel';
import { Day1DocumentSection } from './components/Day1DocumentSection';
@@ -16,7 +20,7 @@ import { AuditSettingsPanel, SettingsButton, type AuditDisplaySettings } from '.
import { useDay1Audit } from './hooks/useDay1Audit';
import { useDay2LotAudit } from './hooks/useDay2LotAudit';
import { useChecklistTemplate } from './hooks/useChecklistTemplate';
import { uploadTemplateDocument, getTemplateDocuments, deleteTemplateDocument } from './actions';
import { uploadTemplateDocument, getTemplateDocuments, deleteTemplateDocument, uploadQualityDocumentFile } from './actions';
import type { TemplateDocument } from './types';
// 기본 설정값
@@ -127,9 +131,24 @@ export default function QualityInspectionPage() {
handleViewDocument,
setModalOpen,
handleToggleItem,
updateQualityDocumentFile,
isMock: day2IsMock,
} = useDay2LotAudit();
// 품질관리서 파일 업로드 핸들러 (2일차 DocumentList용)
const handleQualityFileUpload = useCallback(async (qualityDocumentId: string, file: File): Promise<boolean> => {
const result = await uploadQualityDocumentFile(qualityDocumentId, file);
if (!result.success) {
toast.error(result.error || '품질관리서 파일 업로드에 실패했습니다.');
return false;
}
// 업로드 성공 시 documents 상태에서 해당 문서의 파일 정보 업데이트
if (result.data) {
updateQualityDocumentFile(qualityDocumentId, result.data);
}
return true;
}, [updateQualityDocumentFile]);
// 1일차 필터링된 카테고리 (완료 항목 숨기기 옵션)
const filteredDay1Categories = useMemo(() => {
if (displaySettings.showCompletedItems) return categories;
@@ -245,9 +264,9 @@ export default function QualityInspectionPage() {
)}
</div>
) : (
// ===== 로트 추적 심사 심사 =====
// ===== 로트 추적 심사 =====
<div className="flex-1 grid grid-cols-12 gap-3 sm:gap-4 lg:gap-6 lg:min-h-[500px]">
<div className="col-span-12 lg:col-span-3 min-h-[250px] sm:min-h-[300px] lg:min-h-[500px] lg:h-full overflow-auto">
<div className="col-span-12 lg:col-span-4 min-h-[250px] sm:min-h-[300px] lg:min-h-[500px] lg:h-full overflow-auto">
<ReportList
reports={filteredReports}
selectedId={selectedReport?.id || null}
@@ -267,11 +286,12 @@ export default function QualityInspectionPage() {
/>
</div>
<div className="col-span-12 lg:col-span-5 min-h-[200px] sm:min-h-[250px] lg:min-h-[500px] lg:h-full overflow-auto">
<div className="col-span-12 lg:col-span-4 min-h-[200px] sm:min-h-[250px] lg:min-h-[500px] lg:h-full overflow-auto">
<DocumentList
documents={currentDocuments}
routeCode={selectedRoute?.code || null}
onViewDocument={handleViewDocument}
onQualityFileUpload={handleQualityFileUpload}
isMock={day2IsMock}
/>
</div>
@@ -305,13 +325,51 @@ export default function QualityInspectionPage() {
}}
/>
<InspectionModal
isOpen={modalOpen}
onClose={() => setModalOpen(false)}
document={selectedDoc}
documentItem={selectedDocItem}
readOnly
/>
{/* 중간검사 성적서 → 기존 독립 모달 재사용 */}
{selectedDoc?.type === 'report' && (
<InspectionReportModal
open={modalOpen}
onOpenChange={(open) => !open && setModalOpen(false)}
workOrderId={selectedDocItem?.workOrderId ? String(selectedDocItem.workOrderId) : selectedDocItem?.id || null}
processType={
selectedDocItem?.subType === 'jointbar' ? 'slat'
: (selectedDocItem?.subType as 'screen' | 'slat' | 'bending') || 'screen'
}
readOnly
isJointBar={selectedDocItem?.subType === 'jointbar'}
/>
)}
{/* 작업일지 → 독립 WorkLogModal */}
{selectedDoc?.type === 'log' && (
<WorkLogModal
open={modalOpen}
onOpenChange={(open) => !open && setModalOpen(false)}
workOrderId={selectedDocItem?.workOrderId ? String(selectedDocItem.workOrderId) : selectedDocItem?.id || null}
processType={(selectedDocItem?.subType as 'screen' | 'slat' | 'bending') || 'screen'}
/>
)}
{/* 제품검사 성적서 → 독립 ProductInspectionViewModal */}
{selectedDoc?.type === 'product' && (
<ProductInspectionViewModal
open={modalOpen}
onOpenChange={(open) => !open && setModalOpen(false)}
locationId={selectedDocItem?.id || null}
fetchDetail={getDocumentDetail}
/>
)}
{/* 나머지 문서 타입 (수입검사, 수주서, 납품확인서, 출고증) → 기존 InspectionModal */}
{selectedDoc && !['report', 'log', 'product', 'quality'].includes(selectedDoc.type) && (
<InspectionModal
isOpen={modalOpen}
onClose={() => setModalOpen(false)}
document={selectedDoc}
documentItem={selectedDocItem}
readOnly
/>
)}
</div>
);
}

View File

@@ -34,6 +34,9 @@ export interface Document {
date?: string;
count: number; // e.g., 3건의 서류
items?: DocumentItem[];
fileId?: number; // files.id (품질관리서 파일)
fileName?: string; // 파일명
fileSize?: number; // 파일 크기 (bytes)
}
export interface DocumentItem {

View File

@@ -1030,6 +1030,7 @@ export default function OrderDetailPage() {
recipientName: order.receiver,
recipientContact: order.receiverContact,
shutterCount: order.products?.length || 0,
orderId: Number(order.id),
}}
/>
)}

View File

@@ -2,7 +2,7 @@
/**
* 단가 상세/수정 페이지 (Client Component)
* V2 패턴: ?mode=edit로 수정 모드 전환
* V2 패턴: 기본 조회(view), ?mode=edit로 수정 모드 전환
*
* 경로: /sales/pricing-management/[id]
* 수정 모드: /sales/pricing-management/[id]?mode=edit
@@ -24,9 +24,10 @@ interface PricingDetailPageProps {
export default function PricingDetailPage({ params }: PricingDetailPageProps) {
const { id } = use(params);
const _router = useRouter();
const _searchParams = useSearchParams();
const mode: 'create' | 'edit' = 'edit';
const router = useRouter();
const searchParams = useSearchParams();
const mode = searchParams.get('mode') || 'view';
const isEditMode = mode === 'edit';
const [data, setData] = useState<PricingData | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -77,7 +78,7 @@ export default function PricingDetailPage({ params }: PricingDetailPageProps) {
return (
<PricingFormClient
mode={mode}
mode={isEditMode ? 'edit' : 'view'}
initialData={data}
onSave={handleSave}
onFinalize={handleFinalize}

View File

@@ -13,15 +13,11 @@
*/
import { useEffect, useState } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { PricingListClient } from '@/components/pricing';
import { getPricingListData, type PricingListItem } from '@/components/pricing/actions';
import { GenericPageSkeleton } from '@/components/ui/skeleton';
export default function PricingManagementPage() {
const searchParams = useSearchParams();
const router = useRouter();
const mode = searchParams.get('mode');
const [data, setData] = useState<PricingListItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
@@ -33,27 +29,6 @@ export default function PricingManagementPage() {
.finally(() => setIsLoading(false));
}, []);
// mode=new: 단가 등록은 품목 선택이 필요하므로 안내 표시
if (mode === 'new') {
return (
<div className="container mx-auto py-6 px-4">
<div className="text-center py-12">
<h2 className="text-xl font-semibold mb-2"> </h2>
<p className="text-muted-foreground mb-4">
.<br />
.
</p>
<button
onClick={() => router.push('/sales/pricing-management')}
className="text-primary hover:underline"
>
</button>
</div>
</div>
);
}
if (isLoading) return <GenericPageSkeleton />;
return <PricingListClient initialData={data} />;

View File

@@ -1,6 +1,9 @@
'use client';
import { useState, useEffect } from 'react';
import { useEffect } from 'react';
import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import {
Dialog,
DialogContent,
@@ -11,7 +14,19 @@ import {
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import type { DepartmentDialogProps } from './types';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import type { DepartmentDialogProps, DepartmentFormData } from './types';
const departmentFormSchema = z.object({
code: z.string().min(1, '부서 코드를 입력하세요').max(50, '50자 이내로 입력하세요'),
name: z.string().min(1, '부서명을 입력하세요').max(100, '100자 이내로 입력하세요'),
description: z.string().max(500, '500자 이내로 입력하세요').default(''),
sortOrder: z.coerce.number().min(0, '0 이상 입력하세요').default(0),
isActive: z.boolean().default(true),
});
type FormData = z.infer<typeof departmentFormSchema>;
/**
* 부서 추가/수정 다이얼로그
@@ -22,27 +37,59 @@ export function DepartmentDialog({
mode,
parentDepartment,
department,
onSubmit
onSubmit,
}: DepartmentDialogProps) {
const [name, setName] = useState('');
const {
register,
handleSubmit,
reset,
setValue,
watch,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(departmentFormSchema),
defaultValues: {
code: '',
name: '',
description: '',
sortOrder: 0,
isActive: true,
},
});
const isActive = watch('isActive');
// 다이얼로그 열릴 때 초기값 설정
useEffect(() => {
if (isOpen) {
if (mode === 'edit' && department) {
setName(department.name);
reset({
code: department.code || '',
name: department.name,
description: department.description || '',
sortOrder: department.sortOrder,
isActive: department.isActive,
});
} else {
setName('');
reset({
code: '',
name: '',
description: '',
sortOrder: 0,
isActive: true,
});
}
}
}, [isOpen, mode, department]);
}, [isOpen, mode, department, reset]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (name.trim()) {
onSubmit(name.trim());
setName('');
}
const onFormSubmit = (data: FormData) => {
onSubmit({
code: data.code,
name: data.name,
description: data.description || '',
sortOrder: data.sortOrder,
isActive: data.isActive,
} as DepartmentFormData);
};
const title = mode === 'add' ? '부서 추가' : '부서 수정';
@@ -50,12 +97,12 @@ export function DepartmentDialog({
return (
<Dialog open={isOpen} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit}>
<form onSubmit={handleSubmit(onFormSubmit)}>
<div className="space-y-4 py-4">
{/* 부모 부서 표시 (추가 모드일 때) */}
{mode === 'add' && parentDepartment && (
@@ -64,16 +111,78 @@ export function DepartmentDialog({
</div>
)}
{/* 부서명 입력 */}
{/* 부서 코드 */}
<div className="space-y-2">
<Label htmlFor="department-name"></Label>
<Label htmlFor="department-code">
<span className="text-destructive">*</span>
</Label>
<Input
id="department-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="부서명을 입력하세요"
id="department-code"
{...register('code')}
placeholder="예: DEV, SALES, HR"
autoFocus
/>
{errors.code && (
<p className="text-sm text-destructive">{errors.code.message}</p>
)}
</div>
{/* 부서명 */}
<div className="space-y-2">
<Label htmlFor="department-name">
<span className="text-destructive">*</span>
</Label>
<Input
id="department-name"
{...register('name')}
placeholder="부서명을 입력하세요"
/>
{errors.name && (
<p className="text-sm text-destructive">{errors.name.message}</p>
)}
</div>
{/* 설명 */}
<div className="space-y-2">
<Label htmlFor="department-description"></Label>
<Textarea
id="department-description"
{...register('description')}
placeholder="부서 설명을 입력하세요"
rows={3}
/>
{errors.description && (
<p className="text-sm text-destructive">{errors.description.message}</p>
)}
</div>
{/* 정렬순서 + 활성상태 (가로 배치) */}
<div className="flex items-start gap-6">
<div className="space-y-2 flex-1">
<Label htmlFor="department-sort-order"></Label>
<Input
id="department-sort-order"
type="number"
{...register('sortOrder')}
min={0}
/>
{errors.sortOrder && (
<p className="text-sm text-destructive">{errors.sortOrder.message}</p>
)}
</div>
<div className="space-y-2">
<Label> </Label>
<div className="flex items-center gap-2 h-9">
<Switch
checked={isActive}
onCheckedChange={(checked) => setValue('isActive', checked)}
/>
<span className="text-sm text-muted-foreground">
{isActive ? '활성' : '비활성'}
</span>
</div>
</div>
</div>
</div>
@@ -81,7 +190,7 @@ export function DepartmentDialog({
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
</Button>
<Button type="submit" disabled={!name.trim()}>
<Button type="submit">
{submitText}
</Button>
</DialogFooter>
@@ -89,4 +198,4 @@ export function DepartmentDialog({
</DialogContent>
</Dialog>
);
}
}

View File

@@ -2,31 +2,58 @@
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Search, Plus, Trash2 } from 'lucide-react';
import type { DepartmentToolbarProps } from './types';
/**
* 검색 + 추가/삭제 버튼 툴바
* 검색 + 필터 + 추가/삭제 버튼 툴바
*/
export function DepartmentToolbar({
totalCount,
selectedCount,
searchQuery,
onSearchChange,
statusFilter,
onStatusFilterChange,
onAdd,
onDelete
onDelete,
}: DepartmentToolbarProps) {
return (
<div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
{/* 검색 */}
<div className="relative w-full sm:w-80">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="부서명 검색"
value={searchQuery}
onChange={(e) => onSearchChange(e.target.value)}
className="pl-9"
/>
{/* 검색 + 필터 */}
<div className="flex items-center gap-2 w-full sm:w-auto">
{/* 검색창 */}
<div className="relative flex-1 sm:w-64">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="부서명, 코드 검색"
value={searchQuery}
onChange={(e) => onSearchChange(e.target.value)}
className="pl-9"
/>
</div>
{/* 상태 필터 */}
<Select
value={statusFilter}
onValueChange={(value) => onStatusFilterChange(value as 'all' | 'active' | 'inactive')}
>
<SelectTrigger className="w-28 shrink-0">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all"></SelectItem>
<SelectItem value="active"></SelectItem>
<SelectItem value="inactive"></SelectItem>
</SelectContent>
</Select>
</div>
{/* 선택 카운트 + 버튼 */}
@@ -54,4 +81,4 @@ export function DepartmentToolbar({
</div>
</div>
);
}
}

View File

@@ -35,7 +35,7 @@ export function DepartmentTree({
onCheckedChange={onToggleSelectAll}
aria-label="전체 선택"
/>
<span className="font-medium text-sm"></span>
<span className="font-medium text-sm"> / </span>
</div>
</div>

View File

@@ -3,6 +3,7 @@
import { memo } from 'react';
import { Checkbox } from '@/components/ui/checkbox';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ChevronRight, ChevronDown, Plus, SquarePen, Trash2 } from 'lucide-react';
import type { DepartmentTreeItemProps } from './types';
@@ -56,11 +57,35 @@ export const DepartmentTreeItem = memo(function DepartmentTreeItem({
checked={isSelected}
onCheckedChange={() => onToggleSelect(department.id)}
aria-label={`${department.name} 선택`}
className="shrink-0"
className="shrink-0 size-[18px]"
/>
{/* 부서 코드 */}
<span
className="w-20 shrink-0 cursor-pointer"
onClick={() => onToggleSelect(department.id)}
>
{department.code && (
<Badge variant="outline" className="text-xs font-mono rounded-sm w-16 justify-center">
{department.code}
</Badge>
)}
</span>
{/* 부서명 */}
<span className="break-words">{department.name}</span>
<span className="w-20 shrink-0 font-bold truncate">{department.name}</span>
{/* 설명 */}
<span className="text-xs text-muted-foreground truncate">
{department.description || ''}
</span>
{/* 상태 뱃지 */}
{!department.isActive && (
<Badge variant="secondary" className="text-xs shrink-0">
</Badge>
)}
</div>
{/* 작업 버튼 (선택 시 부서명 아래에 표시, 데스크톱: 호버 시에도 표시) */}

View File

@@ -9,8 +9,8 @@ import { DepartmentToolbar } from './DepartmentToolbar';
import { DepartmentTree } from './DepartmentTree';
import { DepartmentDialog } from './DepartmentDialog';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import type { Department } from './types';
import { countAllDepartments, getAllDepartmentIds, findDepartmentById } from './types';
import type { Department, DepartmentFormData, StatusFilter } from './types';
import { countAllDepartments, getAllDepartmentIds, findDepartmentById, filterDepartmentTree } from './types';
import {
getDepartmentTree,
createDepartment,
@@ -27,8 +27,12 @@ import { isNextRedirectError } from '@/lib/utils/redirect-error';
function convertApiToLocal(record: DepartmentRecord): Department {
return {
id: record.id,
code: record.code,
name: record.name,
description: record.description,
parentId: record.parentId,
isActive: record.isActive,
sortOrder: record.sortOrder,
depth: record.depth,
children: record.children ? record.children.map(convertApiToLocal) : [],
};
@@ -51,6 +55,9 @@ export function DepartmentManagement() {
// 검색어
const [searchQuery, setSearchQuery] = useState('');
// 상태 필터
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
/**
* 부서 트리 조회 API
*/
@@ -92,11 +99,20 @@ export function DepartmentManagement() {
const [departmentToDelete, setDepartmentToDelete] = useState<Department | null>(null);
const [isBulkDelete, setIsBulkDelete] = useState(false);
// 전체 부서 수 계산
// 필터링된 부서 트리
const filteredDepartments = useMemo(
() => filterDepartmentTree(departments, searchQuery, statusFilter),
[departments, searchQuery, statusFilter],
);
// 전체 부서 수 (필터 전)
const totalCount = useMemo(() => countAllDepartments(departments), [departments]);
// 모든 부서 ID
const allIds = useMemo(() => getAllDepartmentIds(departments), [departments]);
// 필터된 부서
const filteredCount = useMemo(() => countAllDepartments(filteredDepartments), [filteredDepartments]);
// 필터된 부서 ID
const filteredAllIds = useMemo(() => getAllDepartmentIds(filteredDepartments), [filteredDepartments]);
// 펼침/접힘 토글
const handleToggleExpand = (id: number) => {
@@ -124,12 +140,12 @@ export function DepartmentManagement() {
});
};
// 전체 선택/해제
// 전체 선택/해제 (필터된 부서 기준)
const handleToggleSelectAll = () => {
if (selectedIds.size === allIds.length) {
if (selectedIds.size === filteredAllIds.length) {
setSelectedIds(new Set());
} else {
setSelectedIds(new Set(allIds));
setSelectedIds(new Set(filteredAllIds));
}
};
@@ -225,18 +241,19 @@ export function DepartmentManagement() {
/**
* 부서 추가/수정 제출 핸들러 (API 연동)
* @note parentId는 현재 API에서 미지원 - 모든 부서가 최상위로 생성됨
*/
const handleDialogSubmit = useCallback(async (name: string) => {
const handleDialogSubmit = useCallback(async (formData: DepartmentFormData) => {
if (isProcessing) return;
setIsProcessing(true);
try {
if (dialogMode === 'add') {
// 새 부서 추가 API
// NOTE: parentId는 현재 API에서 지원하지 않아 최상위에만 생성됨
const result = await createDepartment({
name,
code: formData.code,
name: formData.name,
description: formData.description || undefined,
sortOrder: formData.sortOrder,
isActive: formData.isActive,
parentId: parentDepartment?.id,
});
if (result.success) {
@@ -245,8 +262,13 @@ export function DepartmentManagement() {
console.error('[DepartmentManagement] 부서 생성 실패:', result.error);
}
} else if (dialogMode === 'edit' && selectedDepartment) {
// 부서 수정 API
const result = await updateDepartment(selectedDepartment.id, { name });
const result = await updateDepartment(selectedDepartment.id, {
code: formData.code,
name: formData.name,
description: formData.description || undefined,
sortOrder: formData.sortOrder,
isActive: formData.isActive,
});
if (result.success) {
await fetchDepartments();
} else {
@@ -262,6 +284,9 @@ export function DepartmentManagement() {
}
}, [dialogMode, parentDepartment, selectedDepartment, isProcessing, fetchDepartments]);
// 필터 활성 여부
const isFiltered = searchQuery.trim() !== '' || statusFilter !== 'all';
return (
<PageLayout>
<PageHeader
@@ -274,19 +299,21 @@ export function DepartmentManagement() {
{/* 전체 부서 카운트 */}
<DepartmentStats totalCount={totalCount} />
{/* 검색 + 추가/삭제 버튼 */}
{/* 검색 + 필터 + 추가/삭제 버튼 */}
<DepartmentToolbar
totalCount={totalCount}
totalCount={isFiltered ? filteredCount : totalCount}
selectedCount={selectedIds.size}
searchQuery={searchQuery}
onSearchChange={setSearchQuery}
statusFilter={statusFilter}
onStatusFilterChange={setStatusFilter}
onAdd={handleBulkAdd}
onDelete={handleBulkDelete}
/>
{/* 트리 테이블 */}
<DepartmentTree
departments={departments}
departments={filteredDepartments}
expandedIds={expandedIds}
selectedIds={selectedIds}
onToggleExpand={handleToggleExpand}
@@ -328,4 +355,4 @@ export function DepartmentManagement() {
/>
</PageLayout>
);
}
}

View File

@@ -8,12 +8,27 @@
*/
export interface Department {
id: number;
code: string | null;
name: string;
description: string | null;
parentId: number | null;
isActive: boolean;
sortOrder: number;
depth: number; // 깊이 (0: 최상위, 1, 2, 3, ... 무제한)
children?: Department[]; // 하위 부서 (재귀 - 무제한 깊이)
}
/**
* 부서 폼 데이터
*/
export interface DepartmentFormData {
code: string;
name: string;
description: string;
sortOrder: number;
isActive: boolean;
}
/**
* 부서 추가/수정 다이얼로그 Props
*/
@@ -23,7 +38,7 @@ export interface DepartmentDialogProps {
mode: 'add' | 'edit';
parentDepartment?: Department; // 추가 시 부모 부서
department?: Department; // 수정 시 대상 부서
onSubmit: (name: string) => void;
onSubmit: (data: DepartmentFormData) => void;
}
/**
@@ -48,6 +63,11 @@ export interface DepartmentStatsProps {
totalCount: number;
}
/**
* 상태 필터 타입
*/
export type StatusFilter = 'all' | 'active' | 'inactive';
/**
* 툴바 Props
*/
@@ -56,6 +76,8 @@ export interface DepartmentToolbarProps {
selectedCount: number;
searchQuery: string;
onSearchChange: (query: string) => void;
statusFilter: StatusFilter;
onStatusFilterChange: (filter: StatusFilter) => void;
onAdd: () => void;
onDelete: () => void;
}
@@ -107,3 +129,45 @@ export const findDepartmentById = (departments: Department[], id: number): Depar
}
return null;
};
/**
* 트리 필터링 유틸리티 (재귀 — 검색/상태 필터)
* 자식이 매칭되면 부모도 유지
*/
export const filterDepartmentTree = (
departments: Department[],
searchQuery: string,
statusFilter: StatusFilter,
): Department[] => {
const query = searchQuery.trim().toLowerCase();
const filterNode = (dept: Department): Department | null => {
// 자식 먼저 필터링
const filteredChildren = dept.children
? dept.children.map(filterNode).filter(Boolean) as Department[]
: [];
// 현재 노드가 매칭되는지 확인
const matchesSearch = !query ||
dept.name.toLowerCase().includes(query) ||
(dept.code && dept.code.toLowerCase().includes(query));
const matchesStatus = statusFilter === 'all' ||
(statusFilter === 'active' && dept.isActive) ||
(statusFilter === 'inactive' && !dept.isActive);
// 자식이 매칭되면 부모도 유지
if (filteredChildren.length > 0) {
return { ...dept, children: filteredChildren };
}
// 현재 노드가 매칭되면 유지
if (matchesSearch && matchesStatus) {
return { ...dept, children: [] };
}
return null;
};
return departments.map(filterNode).filter(Boolean) as Department[];
};

View File

@@ -237,7 +237,10 @@ export function ReceivingDetail({ id, mode = 'view' }: Props) {
// 수입검사 성적서 템플릿 존재 여부 + 첨부파일 확인
if (result.data.itemId) {
const templateCheck = await checkInspectionTemplate(result.data.itemId);
setHasInspectionTemplate(templateCheck.hasTemplate);
// API 성공 시에만 값 업데이트 (실패 시 기존 값 유지 — 버튼 사라짐 방지)
if (templateCheck.success) {
setHasInspectionTemplate(templateCheck.hasTemplate);
}
if (templateCheck.attachments && templateCheck.attachments.length > 0) {
setInspectionAttachments(templateCheck.attachments);
}

View File

@@ -1256,3 +1256,14 @@ export async function getQuotesForSelect(params?: {
},
};
}
/**
* 수주서 문서용 상세 데이터 조회
* BOM 기반 products, motors, bending_parts, subsidiary_parts 포함
*/
export async function getOrderDocumentDetail(orderId: string) {
return executeServerAction({
url: buildApiUrl(`/api/v1/qms/lot-audit/documents/order/${orderId}`),
errorMessage: '수주서 문서 데이터 조회에 실패했습니다.',
});
}

View File

@@ -12,7 +12,7 @@ import { ContractDocument } from "./ContractDocument";
import { TransactionDocument } from "./TransactionDocument";
import { PurchaseOrderDocument } from "./PurchaseOrderDocument";
import { SalesOrderDocument } from "./SalesOrderDocument";
import { OrderItem } from "../actions";
import { OrderItem, getOrderDocumentDetail } from "../actions";
import { getCompanyInfo } from "@/components/settings/CompanyInfoManagement/actions";
// 문서 타입
@@ -54,6 +54,7 @@ export interface OrderDocumentData {
recipientContact?: string;
shutterCount?: number;
fee?: number;
orderId?: number;
}
interface OrderDocumentModalProps {
@@ -79,6 +80,8 @@ export function OrderDocumentModal({
data,
}: OrderDocumentModalProps) {
const [companyInfo, setCompanyInfo] = useState<CompanyInfo | null>(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const [orderDetail, setOrderDetail] = useState<Record<string, any> | null>(null);
// 모달이 열릴 때 회사 정보 조회
useEffect(() => {
@@ -97,6 +100,21 @@ export function OrderDocumentModal({
}
}, [open, companyInfo]);
// 수주서일 때 BOM 상세 데이터 로드
useEffect(() => {
if (!open || documentType !== 'salesOrder' || !data.orderId) {
setOrderDetail(null);
return;
}
getOrderDocumentDetail(String(data.orderId)).then((result) => {
if (result.success && result.data) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const raw = result.data as Record<string, any>;
setOrderDetail(raw?.data ?? raw);
}
});
}, [open, documentType, data.orderId]);
const getDocumentTitle = () => {
switch (documentType) {
case "contract":
@@ -186,6 +204,12 @@ export function OrderDocumentModal({
items={data.items || []}
products={data.products}
remarks={data.remarks}
productRows={orderDetail?.products || []}
motorsLeft={orderDetail?.motors?.left || []}
motorsRight={orderDetail?.motors?.right || []}
bendingParts={orderDetail?.bending_parts || []}
subsidiaryParts={orderDetail?.subsidiary_parts || []}
categoryCode={orderDetail?.category_code}
/>
);
default:

View File

@@ -14,6 +14,51 @@ import { ProductInfo } from "./OrderDocumentModal";
import { ConstructionApprovalTable } from "@/components/document-system";
import { formatNumber } from '@/lib/utils/amount';
// ===== 데이터 타입 =====
interface MotorRow {
item: string;
type: string;
spec: string;
qty: number;
}
interface BendingItem {
name: string;
spec: string;
qty: number;
}
interface BendingGroup {
group: string;
items: BendingItem[];
}
interface SubsidiaryItem {
name: string;
spec: string;
qty: number;
}
interface ProductRow {
no: number;
floor?: string;
symbol?: string;
product_name?: string;
product_type?: string;
open_width?: number | string;
open_height?: number | string;
made_width?: number | string;
made_height?: number | string;
guide_rail?: string;
shaft?: string | number;
case_inch?: string | number;
bracket?: string;
capacity?: string | number;
finish?: string;
joint_bar?: number | null;
}
interface SalesOrderDocumentProps {
documentNumber?: string;
orderNumber: string;
@@ -34,61 +79,15 @@ interface SalesOrderDocumentProps {
items?: OrderItem[];
products?: ProductInfo[];
remarks?: string;
// 실 데이터 props
productRows?: ProductRow[];
motorsLeft?: MotorRow[];
motorsRight?: MotorRow[];
bendingParts?: BendingGroup[];
subsidiaryParts?: SubsidiaryItem[];
categoryCode?: string;
}
// ===== 문서 전용 목데이터 (출고증과 동일 구조) =====
const MOCK_SCREEN_ROWS = [
{ no: 1, type: '이(마)', code: 'FA123', openW: 4300, openH: 4300, madeW: 4300, madeH: 3000, guideRail: '백면형', shaft: 5, caseInch: 5, bracket: '500X300 380X180', capacity: 300, finish: 'SUS마감' },
{ no: 2, type: '이(마)', code: 'FA123', openW: 4300, openH: 4300, madeW: 4300, madeH: 3000, guideRail: '백면형', shaft: 5, caseInch: 5, bracket: '500X300 380X180', capacity: 300, finish: 'SUS마감' },
];
const MOCK_STEEL_ROWS = [
{ no: 1, code: 'FA123', openW: 4300, openH: 3000, madeW: 4300, madeH: 3000, guideRail: '백면형', shaft: 5, jointBar: 5, caseInch: 5, bracket: '500X300 380X180', capacity: 300, finish: 'SUS마감' },
{ no: 2, code: 'FA123', openW: 4300, openH: 3000, madeW: 4300, madeH: 3000, guideRail: '백면형', shaft: 5, jointBar: 5, caseInch: 5, bracket: '500X300 380X180', capacity: 300, finish: 'SUS마감' },
];
const MOCK_MOTOR_LEFT = [
{ item: '모터', type: '380V 단상', spec: 'KD-150K', qty: 6 },
{ item: '브라켓트', type: '-', spec: '380X180', qty: 6 },
{ item: '앵글', type: '밑침통 영금', spec: '40*40*380', qty: 4 },
];
const MOCK_MOTOR_RIGHT = [
{ item: '전동개폐기', type: '릴박스', spec: '-', qty: 1 },
{ item: '전동개폐기', type: '매입', spec: '-', qty: 1 },
];
const MOCK_GUIDE_RAIL_ITEMS = [
{ name: '항목명', spec: 'L: 3,000', qty: 22 },
{ name: '하부BASE', spec: '130X80', qty: 22 },
];
const MOCK_GUIDE_SMOKE = { name: '연기차단재(W50)', spec: '2,438', qty: 4 };
const MOCK_CASE_ITEMS = [
{ name: '500X330', spec: 'L: 4,000', qty: 3 },
{ name: '500X330', spec: 'L: 5,000', qty: 4 },
{ name: '상부덮개', spec: '1219X389', qty: 55 },
{ name: '측면부 (마구리)', spec: '500X355', qty: '500X355' },
];
const MOCK_CASE_SMOKE = { name: '연기차단재(W80)', spec: '3,000', qty: 4 };
const MOCK_BOTTOM_SCREEN = [
{ name: '하단마감재', spec: '60X40', l1: 'L: 3,000', q1: 6, name2: '하단마감재', spec2: '60X40', l2: 'L: 4,000', q2: 6 },
{ name: '하단보강엘비', spec: '60X17', l1: 'L: 3,000', q1: 6, name2: '하단보강엘비', spec2: '60X17', l2: 'L: 4,000', q2: 6 },
{ name: '하단보강평철', spec: '-', l1: 'L: 3,000', q1: 6, name2: '하단보강평철', spec2: '-', l2: 'L: 4,000', q2: 6 },
{ name: '하단무게평철', spec: '50X12T', l1: 'L: 3,000', q1: 6, name2: '하단무게평철', spec2: '50X12T', l2: 'L: 4,000', q2: 6 },
];
const MOCK_BOTTOM_STEEL = { spec: '60X40', length: 'L: 3,000', qty: 22 };
const MOCK_SUBSIDIARY = [
{ leftItem: '감기사프트', leftSpec: '4인치 4500', leftQty: 6, rightItem: '각파이프', rightSpec: '6000', rightQty: 4 },
{ leftItem: '조인트바', leftSpec: '300', leftQty: 6, rightItem: '환봉', rightSpec: '3000', rightQty: 5 },
];
// ===== 공통 스타일 =====
const thBase = 'border-r border-gray-400 px-1 py-1';
const tdBase = 'border-r border-gray-300 px-1 py-1';
@@ -114,10 +113,40 @@ export function SalesOrderDocument({
items: _items = [],
products = [],
remarks,
productRows = [],
motorsLeft = [],
motorsRight = [],
bendingParts = [],
subsidiaryParts = [],
}: SalesOrderDocumentProps) {
const [bottomFinishView, setBottomFinishView] = useState<'screen' | 'steel'>('screen');
const motorRows = Math.max(MOCK_MOTOR_LEFT.length, MOCK_MOTOR_RIGHT.length);
const motorRows = Math.max(motorsLeft.length, motorsRight.length);
// 절곡물 그룹 데이터 추출
const guideRailItems = bendingParts.find(g => g.group === '가이드레일')?.items ?? [];
const caseItems = bendingParts.find(g => g.group === '케이스')?.items ?? [];
const bottomItems = bendingParts.find(g => g.group === '하단마감')?.items ?? [];
const smokeItems = bendingParts.find(g => g.group === '연기차단재')?.items ?? [];
const guideSmokeItems = smokeItems.filter(i => i.name.includes('레일') || i.name.includes('가이드'));
const caseSmokeItems = smokeItems.filter(i => i.name.includes('케이스'));
// 구분 불가한 연기차단재는 그대로 표시
const otherSmokeItems = smokeItems.filter(i =>
!i.name.includes('레일') && !i.name.includes('가이드') && !i.name.includes('케이스')
);
// 부자재 좌/우 2열 변환
const subsidiaryRows = [];
for (let i = 0; i < subsidiaryParts.length; i += 2) {
subsidiaryRows.push({
left: subsidiaryParts[i],
right: subsidiaryParts[i + 1] ?? null,
});
}
// 스크린/철재 제품 분리
const screenProducts = productRows.filter(p => p.product_type !== 'steel');
const steelProducts = productRows.filter(p => p.product_type === 'steel');
return (
<div className="bg-white p-8 min-h-full text-[11px]">
@@ -142,9 +171,9 @@ export function SalesOrderDocument({
<td className="bg-gray-100 px-2 py-1 font-medium border-r border-gray-400 whitespace-nowrap"></td>
<td className="px-2 py-1 border-r border-gray-400">{orderNumber}</td>
<td className="bg-gray-100 px-2 py-1 font-medium border-r border-gray-400 whitespace-nowrap"></td>
<td className="px-2 py-1 border-r border-gray-400">{products[0]?.productName || "-"}</td>
<td className="px-2 py-1 border-r border-gray-400">{products[0]?.productName || productRows[0]?.product_name || "-"}</td>
<td className="bg-gray-100 px-2 py-1 font-medium border-r border-gray-400 whitespace-nowrap"></td>
<td className="px-2 py-1 border-r border-gray-400">KWS01</td>
<td className="px-2 py-1 border-r border-gray-400">{productRows[0]?.product_name?.split(' ')[0] || "KWS01"}</td>
<td className="bg-gray-100 px-2 py-1 font-medium border-r border-gray-400 whitespace-nowrap"></td>
<td className="px-2 py-1">{certificationNumber}</td>
</tr>
@@ -198,7 +227,7 @@ export function SalesOrderDocument({
</tr>
<tr>
<td className="bg-gray-100 px-2 py-1 font-medium"></td>
<td className="px-2 py-1">{shutterCount}</td>
<td className="px-2 py-1">{shutterCount || productRows.length}</td>
</tr>
</tbody>
</table>
@@ -239,391 +268,383 @@ export function SalesOrderDocument({
<p className="text-[10px] mb-4"> .</p>
{/* ========== 1. 스크린 ========== */}
<div className="mb-4">
<p className="font-bold mb-2">1. </p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-100 border-b border-gray-400">
<th className={`${thBase} w-8`} rowSpan={2}>No</th>
<th className={`${thBase} w-14`} rowSpan={2}></th>
<th className={`${thBase} w-14`} rowSpan={2}></th>
<th className={thBase} colSpan={2}></th>
<th className={thBase} colSpan={2}></th>
<th className={`${thBase} w-16`} rowSpan={2}><br /></th>
<th className={`${thBase} w-14`} rowSpan={2}><br />()</th>
<th className={`${thBase} w-14`} rowSpan={2}><br />()</th>
<th className={thBase} colSpan={2}></th>
<th className="px-1 py-1 w-16" rowSpan={2}></th>
</tr>
<tr className="bg-gray-50 border-b border-gray-400 text-[9px]">
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}>Kg</th>
</tr>
</thead>
<tbody>
{MOCK_SCREEN_ROWS.map((row) => (
<tr key={row.no} className="border-b border-gray-300">
<td className={tdCenter}>{row.no}</td>
<td className={tdCenter}>{row.type}</td>
<td className={tdCenter}>{row.code}</td>
<td className={tdCenter}>{formatNumber(row.openW)}</td>
<td className={tdCenter}>{formatNumber(row.openH)}</td>
<td className={tdCenter}>{formatNumber(row.madeW)}</td>
<td className={tdCenter}>{formatNumber(row.madeH)}</td>
<td className={tdCenter}>{row.guideRail}</td>
<td className={tdCenter}>{row.shaft}</td>
<td className={tdCenter}>{row.caseInch}</td>
<td className={tdCenter}>{row.bracket}</td>
<td className={tdCenter}>{row.capacity}</td>
<td className="px-1 py-1 text-center">{row.finish}</td>
{screenProducts.length > 0 && (
<div className="mb-4">
<p className="font-bold mb-2">1. </p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-100 border-b border-gray-400">
<th className={`${thBase} w-8`} rowSpan={2}>No</th>
<th className={`${thBase} w-14`} rowSpan={2}></th>
<th className={`${thBase} w-14`} rowSpan={2}></th>
<th className={thBase} colSpan={2}></th>
<th className={thBase} colSpan={2}></th>
<th className={`${thBase} w-16`} rowSpan={2}><br /></th>
<th className={`${thBase} w-14`} rowSpan={2}><br />()</th>
<th className={`${thBase} w-14`} rowSpan={2}><br />()</th>
<th className={thBase} colSpan={2}></th>
<th className="px-1 py-1 w-16" rowSpan={2}></th>
</tr>
))}
</tbody>
</table>
<tr className="bg-gray-50 border-b border-gray-400 text-[9px]">
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}>Kg</th>
</tr>
</thead>
<tbody>
{screenProducts.map((row) => (
<tr key={row.no} className="border-b border-gray-300">
<td className={tdCenter}>{row.no}</td>
<td className={tdCenter}>{row.floor ?? '-'}</td>
<td className={tdCenter}>{row.symbol ?? '-'}</td>
<td className={tdCenter}>{row.open_width ? formatNumber(Number(row.open_width)) : '-'}</td>
<td className={tdCenter}>{row.open_height ? formatNumber(Number(row.open_height)) : '-'}</td>
<td className={tdCenter}>{row.made_width ? formatNumber(Number(row.made_width)) : '-'}</td>
<td className={tdCenter}>{row.made_height ? formatNumber(Number(row.made_height)) : '-'}</td>
<td className={tdCenter}>{row.guide_rail ?? '-'}</td>
<td className={tdCenter}>{row.shaft ?? '-'}</td>
<td className={tdCenter}>{row.case_inch ?? '-'}</td>
<td className={tdCenter}>{row.bracket ?? '-'}</td>
<td className={tdCenter}>{row.capacity ?? '-'}</td>
<td className="px-1 py-1 text-center">{row.finish ?? '-'}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
)}
{/* ========== 2. 철재 ========== */}
<div className="mb-4">
<p className="font-bold mb-2">2. </p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-100 border-b border-gray-400">
<th className={`${thBase} w-8`} rowSpan={2}>No.</th>
<th className={`${thBase} w-14`} rowSpan={2}></th>
<th className={thBase} colSpan={2}></th>
<th className={thBase} colSpan={2}></th>
<th className={`${thBase} w-16`} rowSpan={2}><br /></th>
<th className={`${thBase} w-14`} rowSpan={2}><br />()</th>
<th className={`${thBase} w-14`} rowSpan={2}><br />()</th>
<th className={`${thBase} w-14`} rowSpan={2}><br />()</th>
<th className={thBase} colSpan={2}></th>
<th className="px-1 py-1 w-16" rowSpan={2}></th>
</tr>
<tr className="bg-gray-50 border-b border-gray-400 text-[9px]">
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}>Kg</th>
</tr>
</thead>
<tbody>
{MOCK_STEEL_ROWS.map((row) => (
<tr key={row.no} className="border-b border-gray-300">
<td className={tdCenter}>{row.no}</td>
<td className={tdCenter}>{row.code}</td>
<td className={tdCenter}>{formatNumber(row.openW)}</td>
<td className={tdCenter}>{formatNumber(row.openH)}</td>
<td className={tdCenter}>{formatNumber(row.madeW)}</td>
<td className={tdCenter}>{formatNumber(row.madeH)}</td>
<td className={tdCenter}>{row.guideRail}</td>
<td className={tdCenter}>{row.shaft}</td>
<td className={tdCenter}>{row.jointBar}</td>
<td className={tdCenter}>{row.caseInch}</td>
<td className={tdCenter}>{row.bracket}</td>
<td className={tdCenter}>{row.capacity}</td>
<td className="px-1 py-1 text-center">{row.finish}</td>
{steelProducts.length > 0 && (
<div className="mb-4">
<p className="font-bold mb-2">2. </p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-100 border-b border-gray-400">
<th className={`${thBase} w-8`} rowSpan={2}>No.</th>
<th className={`${thBase} w-14`} rowSpan={2}></th>
<th className={thBase} colSpan={2}></th>
<th className={thBase} colSpan={2}></th>
<th className={`${thBase} w-16`} rowSpan={2}><br /></th>
<th className={`${thBase} w-14`} rowSpan={2}><br />()</th>
<th className={`${thBase} w-14`} rowSpan={2}><br />()</th>
<th className={`${thBase} w-14`} rowSpan={2}><br />()</th>
<th className={thBase} colSpan={2}></th>
<th className="px-1 py-1 w-16" rowSpan={2}></th>
</tr>
))}
</tbody>
</table>
<tr className="bg-gray-50 border-b border-gray-400 text-[9px]">
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}></th>
<th className={thBase}>Kg</th>
</tr>
</thead>
<tbody>
{steelProducts.map((row) => (
<tr key={row.no} className="border-b border-gray-300">
<td className={tdCenter}>{row.no}</td>
<td className={tdCenter}>{row.symbol ?? '-'}</td>
<td className={tdCenter}>{row.open_width ? formatNumber(Number(row.open_width)) : '-'}</td>
<td className={tdCenter}>{row.open_height ? formatNumber(Number(row.open_height)) : '-'}</td>
<td className={tdCenter}>{row.made_width ? formatNumber(Number(row.made_width)) : '-'}</td>
<td className={tdCenter}>{row.made_height ? formatNumber(Number(row.made_height)) : '-'}</td>
<td className={tdCenter}>{row.guide_rail ?? '-'}</td>
<td className={tdCenter}>{row.shaft ?? '-'}</td>
<td className={tdCenter}>{row.joint_bar ?? '-'}</td>
<td className={tdCenter}>{row.case_inch ?? '-'}</td>
<td className={tdCenter}>{row.bracket ?? '-'}</td>
<td className={tdCenter}>{row.capacity ?? '-'}</td>
<td className="px-1 py-1 text-center">{row.finish ?? '-'}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
)}
{/* ========== 3. 모터 ========== */}
<div className="mb-4">
<p className="font-bold mb-2">3. </p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-100 border-b border-gray-400">
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-10`}></th>
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-10"></th>
</tr>
</thead>
<tbody>
{Array.from({ length: motorRows }).map((_, i) => {
const left = MOCK_MOTOR_LEFT[i];
const right = MOCK_MOTOR_RIGHT[i];
return (
<tr key={i} className="border-b border-gray-300">
<td className={tdBase}>{left?.item || ''}</td>
<td className={tdBase}>{left?.type || ''}</td>
<td className={tdBase}>{left?.spec || ''}</td>
<td className={tdCenter}>{left?.qty ?? ''}</td>
<td className={tdBase}>{right?.item || ''}</td>
<td className={tdBase}>{right?.type || ''}</td>
<td className={tdBase}>{right?.spec || ''}</td>
<td className="px-1 py-1 text-center">{right?.qty ?? ''}</td>
</tr>
);
})}
</tbody>
</table>
{motorRows > 0 && (
<div className="mb-4">
<p className="font-bold mb-2">3. </p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-100 border-b border-gray-400">
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-10`}></th>
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-10"></th>
</tr>
</thead>
<tbody>
{Array.from({ length: motorRows }).map((_, i) => {
const left = motorsLeft[i];
const right = motorsRight[i];
return (
<tr key={i} className="border-b border-gray-300">
<td className={tdBase}>{left?.item || ''}</td>
<td className={tdBase}>{left?.type || ''}</td>
<td className={tdBase}>{left?.spec || ''}</td>
<td className={tdCenter}>{left?.qty ?? ''}</td>
<td className={tdBase}>{right?.item || ''}</td>
<td className={tdBase}>{right?.type || ''}</td>
<td className={tdBase}>{right?.spec || ''}</td>
<td className="px-1 py-1 text-center">{right?.qty ?? ''}</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
</div>
)}
{/* ========== 4. 절곡물 ========== */}
<div className="mb-4">
<p className="font-bold mb-2">4. </p>
{bendingParts.length > 0 && (
<div className="mb-4">
<p className="font-bold mb-2">4. </p>
{/* 4-1. 가이드레일 */}
<div className="mb-3">
<p className="text-[10px] font-medium mb-1">4-1. - EGI 1.5ST + EGI 1.1ST + SUS 1.1ST</p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-100 border-b border-gray-400">
<th className={`${thBase} w-32`}> (120X70)</th>
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-14"></th>
</tr>
</thead>
<tbody>
{MOCK_GUIDE_RAIL_ITEMS.map((item, i) => (
<tr key={i} className="border-b border-gray-300">
{i === 0 && (
<td className={tdCenter} rowSpan={MOCK_GUIDE_RAIL_ITEMS.length}>
<div className={`${imgPlaceholder} h-20 w-full`}>IMG</div>
</td>
)}
<td className={tdCenter}>{item.name}</td>
<td className={tdCenter}>{item.spec}</td>
<td className="px-1 py-1 text-center">{item.qty}</td>
</tr>
))}
</tbody>
</table>
</div>
{/* 연기차단재 */}
<div className="mt-1 border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-50 border-b border-gray-400 text-[10px]">
<th className={`${thBase} w-32`}>&nbsp;</th>
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-14"></th>
</tr>
</thead>
<tbody>
<tr className="border-b border-gray-300">
<td className={tdCenter}>
<div className={`${imgPlaceholder} h-14 w-full`}>IMG</div>
</td>
<td className={tdCenter}>{MOCK_GUIDE_SMOKE.name}</td>
<td className={tdCenter}>{MOCK_GUIDE_SMOKE.spec}</td>
<td className="px-1 py-1 text-center">{MOCK_GUIDE_SMOKE.qty}</td>
</tr>
</tbody>
</table>
</div>
<p className="mt-1 text-[10px]">
<span className="font-medium">* <span className="text-red-600 font-bold"></span> </span> - EGI 0.8T +
</p>
</div>
{/* 4-2. 케이스(셔터박스) */}
<div className="mb-3">
<p className="text-[10px] font-medium mb-1">4-2. () - EGI 1.5ST</p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-100 border-b border-gray-400">
<th className={`${thBase} w-32`}>&nbsp;</th>
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-14"></th>
</tr>
</thead>
<tbody>
{MOCK_CASE_ITEMS.map((item, i) => (
<tr key={i} className="border-b border-gray-300">
{i === 0 && (
<td className={tdCenter} rowSpan={MOCK_CASE_ITEMS.length}>
<div className={`${imgPlaceholder} h-24 w-full`}>IMG</div>
</td>
)}
<td className={tdCenter}>{item.name}</td>
<td className={tdCenter}>{item.spec}</td>
<td className="px-1 py-1 text-center">{item.qty}</td>
</tr>
))}
</tbody>
</table>
</div>
{/* 연기차단재 */}
<div className="mt-1 border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-50 border-b border-gray-400 text-[10px]">
<th className={`${thBase} w-32`}>&nbsp;</th>
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-14"></th>
</tr>
</thead>
<tbody>
<tr className="border-b border-gray-300">
<td className={tdCenter}>
<div className={`${imgPlaceholder} h-14 w-full`}>IMG</div>
</td>
<td className={tdCenter}>{MOCK_CASE_SMOKE.name}</td>
<td className={tdCenter}>{MOCK_CASE_SMOKE.spec}</td>
<td className="px-1 py-1 text-center">{MOCK_CASE_SMOKE.qty}</td>
</tr>
</tbody>
</table>
</div>
<p className="mt-1 text-[10px]">
<span className="font-medium">* , <span className="text-red-600 font-bold"></span> </span> - EGI 0.8T +
</p>
</div>
{/* 4-3. 하단마감재 (토글: 스크린 / 절재) */}
<div className="mb-3">
<div className="flex items-center gap-2 mb-2">
<button
onClick={() => setBottomFinishView('screen')}
className={`px-3 py-1 text-[10px] font-bold border rounded ${
bottomFinishView === 'screen'
? 'bg-gray-800 text-white border-gray-800'
: 'bg-white text-gray-600 border-gray-400 hover:bg-gray-100'
}`}
>
#
</button>
<button
onClick={() => setBottomFinishView('steel')}
className={`px-3 py-1 text-[10px] font-bold border rounded ${
bottomFinishView === 'steel'
? 'bg-gray-800 text-white border-gray-800'
: 'bg-white text-gray-600 border-gray-400 hover:bg-gray-100'
}`}
>
#
</button>
</div>
{bottomFinishView === 'screen' ? (
<>
<p className="text-[10px] font-medium mb-1">
4-3. - (EGI 1.5ST) + (EGI 1.5ST) + (EGI 1.1ST) + (50X12T)
</p>
{/* 4-1. 가이드레일 */}
{guideRailItems.length > 0 && (
<div className="mb-3">
<p className="text-[10px] font-medium mb-1">4-1. </p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-100 border-b border-gray-400">
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-14`}></th>
<th className={`${thBase} w-16`}></th>
<th className={`${thBase} w-10`}></th>
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-14`}></th>
<th className={`${thBase} w-16`}></th>
<th className="px-1 py-1 w-10"></th>
<th className={`${thBase} w-32`}>&nbsp;</th>
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-14"></th>
</tr>
</thead>
<tbody>
{MOCK_BOTTOM_SCREEN.map((row, i) => (
{guideRailItems.map((item, i) => (
<tr key={i} className="border-b border-gray-300">
<td className={tdBase}>{row.name}</td>
<td className={tdCenter}>{row.spec}</td>
<td className={tdCenter}>{row.l1}</td>
<td className={tdCenter}>{row.q1}</td>
<td className={tdBase}>{row.name2}</td>
<td className={tdCenter}>{row.spec2}</td>
<td className={tdCenter}>{row.l2}</td>
<td className="px-1 py-1 text-center">{row.q2}</td>
{i === 0 && (
<td className={tdCenter} rowSpan={guideRailItems.length}>
<div className={`${imgPlaceholder} h-20 w-full`}>IMG</div>
</td>
)}
<td className={tdCenter}>{item.name}</td>
<td className={tdCenter}>{item.spec}</td>
<td className="px-1 py-1 text-center">{item.qty}</td>
</tr>
))}
</tbody>
</table>
</div>
</>
) : (
<>
<p className="text-[10px] font-medium mb-1">
4-3. -EGI 1.5ST
{/* 가이드레일 연기차단재 */}
{guideSmokeItems.length > 0 && (
<div className="mt-1 border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-50 border-b border-gray-400 text-[10px]">
<th className={`${thBase} w-32`}>&nbsp;</th>
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-14"></th>
</tr>
</thead>
<tbody>
{guideSmokeItems.map((item, i) => (
<tr key={i} className="border-b border-gray-300">
{i === 0 && (
<td className={tdCenter} rowSpan={guideSmokeItems.length}>
<div className={`${imgPlaceholder} h-14 w-full`}>IMG</div>
</td>
)}
<td className={tdCenter}>{item.name}</td>
<td className={tdCenter}>{item.spec}</td>
<td className="px-1 py-1 text-center">{item.qty}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<p className="mt-1 text-[10px]">
<span className="font-medium">* <span className="text-red-600 font-bold"></span> </span> - EGI 0.8T +
</p>
</div>
)}
{/* 4-2. 케이스(셔터박스) */}
{caseItems.length > 0 && (
<div className="mb-3">
<p className="text-[10px] font-medium mb-1">4-2. ()</p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-100 border-b border-gray-400">
<th className={`${thBase} w-32`}></th>
<th className={`${thBase} w-14`}></th>
<th className={`${thBase} w-16`}></th>
<th className="px-1 py-1 w-10"></th>
<th className={`${thBase} w-32`}>&nbsp;</th>
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-14"></th>
</tr>
</thead>
<tbody>
<tr className="border-b border-gray-300">
<td className={tdCenter}>
<div className={`${imgPlaceholder} h-16 w-full`}>IMG</div>
</td>
<td className={tdCenter}>{MOCK_BOTTOM_STEEL.spec}</td>
<td className={tdCenter}>{MOCK_BOTTOM_STEEL.length}</td>
<td className="px-1 py-1 text-center">{MOCK_BOTTOM_STEEL.qty}</td>
</tr>
{caseItems.map((item, i) => (
<tr key={i} className="border-b border-gray-300">
{i === 0 && (
<td className={tdCenter} rowSpan={caseItems.length}>
<div className={`${imgPlaceholder} h-24 w-full`}>IMG</div>
</td>
)}
<td className={tdCenter}>{item.name}</td>
<td className={tdCenter}>{item.spec}</td>
<td className="px-1 py-1 text-center">{item.qty}</td>
</tr>
))}
</tbody>
</table>
</div>
</>
{/* 케이스 연기차단재 */}
{caseSmokeItems.length > 0 && (
<div className="mt-1 border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-50 border-b border-gray-400 text-[10px]">
<th className={`${thBase} w-32`}>&nbsp;</th>
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-14"></th>
</tr>
</thead>
<tbody>
{caseSmokeItems.map((item, i) => (
<tr key={i} className="border-b border-gray-300">
{i === 0 && (
<td className={tdCenter} rowSpan={caseSmokeItems.length}>
<div className={`${imgPlaceholder} h-14 w-full`}>IMG</div>
</td>
)}
<td className={tdCenter}>{item.name}</td>
<td className={tdCenter}>{item.spec}</td>
<td className="px-1 py-1 text-center">{item.qty}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<p className="mt-1 text-[10px]">
<span className="font-medium">* , <span className="text-red-600 font-bold"></span> </span> - EGI 0.8T +
</p>
</div>
)}
{/* 4-3. 하단마감재 */}
{bottomItems.length > 0 && (
<div className="mb-3">
<p className="text-[10px] font-medium mb-1">4-3. </p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-100 border-b border-gray-400">
<th className={`${thBase} w-32`}>&nbsp;</th>
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-14"></th>
</tr>
</thead>
<tbody>
{bottomItems.map((item, i) => (
<tr key={i} className="border-b border-gray-300">
{i === 0 && (
<td className={tdCenter} rowSpan={bottomItems.length}>
<div className={`${imgPlaceholder} h-16 w-full`}>IMG</div>
</td>
)}
<td className={tdCenter}>{item.name}</td>
<td className={tdCenter}>{item.spec}</td>
<td className="px-1 py-1 text-center">{item.qty}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{/* 연기차단재 (구분 불가) */}
{otherSmokeItems.length > 0 && (
<div className="mb-3">
<p className="text-[10px] font-medium mb-1"></p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-50 border-b border-gray-400 text-[10px]">
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-14"></th>
</tr>
</thead>
<tbody>
{otherSmokeItems.map((item, i) => (
<tr key={i} className="border-b border-gray-300">
<td className={tdCenter}>{item.name}</td>
<td className={tdCenter}>{item.spec}</td>
<td className="px-1 py-1 text-center">{item.qty}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
</div>
</div>
)}
{/* ========== 5. 부자재 ========== */}
<div className="mb-4">
<p className="font-bold mb-2">5. </p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-100 border-b border-gray-400">
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-10`}></th>
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-10"></th>
</tr>
</thead>
<tbody>
{MOCK_SUBSIDIARY.map((row, i) => (
<tr key={i} className="border-b border-gray-300">
<td className={tdBase}>{row.leftItem}</td>
<td className={tdCenter}>{row.leftSpec}</td>
<td className={tdCenter}>{row.leftQty}</td>
<td className={tdBase}>{row.rightItem}</td>
<td className={tdCenter}>{row.rightSpec}</td>
<td className="px-1 py-1 text-center">{row.rightQty}</td>
{subsidiaryParts.length > 0 && (
<div className="mb-4">
<p className="font-bold mb-2">5. </p>
<div className="border border-gray-400">
<table className="w-full">
<thead>
<tr className="bg-gray-100 border-b border-gray-400">
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className={`${thBase} w-10`}></th>
<th className={`${thBase} w-24`}></th>
<th className={`${thBase} w-20`}></th>
<th className="px-1 py-1 w-10"></th>
</tr>
))}
</tbody>
</table>
</thead>
<tbody>
{subsidiaryRows.map((row, i) => (
<tr key={i} className="border-b border-gray-300">
<td className={tdBase}>{row.left?.name ?? ''}</td>
<td className={tdCenter}>{row.left?.spec ?? ''}</td>
<td className={tdCenter}>{row.left?.qty ?? ''}</td>
<td className={tdBase}>{row.right?.name ?? ''}</td>
<td className={tdCenter}>{row.right?.spec ?? ''}</td>
<td className="px-1 py-1 text-center">{row.right?.qty ?? ''}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
)}
{/* ========== 특이사항 ========== */}
{remarks && (
@@ -636,4 +657,4 @@ export function SalesOrderDocument({
)}
</div>
);
}
}

View File

@@ -162,12 +162,7 @@ export function PricingListClient({
// 네비게이션 핸들러
const handleRegister = (item: PricingListItem) => {
// item_type_code는 품목 정보에서 자동으로 가져오므로 URL에 포함하지 않음
const params = new URLSearchParams();
params.set('mode', 'new');
if (item.itemId) params.set('itemId', item.itemId);
if (item.itemCode) params.set('itemCode', item.itemCode);
router.push(`/sales/pricing-management?${params.toString()}`);
router.push(`/sales/pricing-management/create?itemId=${item.itemId}`);
};
const handleEdit = (item: PricingListItem) => {
@@ -221,12 +216,12 @@ export function PricingListClient({
) => {
const { isSelected, onToggle } = handlers;
// 행 클릭 핸들러: 등록되지 않은 항목은 등록, 등록된 항목은 수정
// 행 클릭 핸들러: 등록되지 않은 항목은 등록, 등록된 항목은 상세 조회
const handleRowClick = () => {
if (item.status === 'not_registered') {
handleRegister(item);
} else {
handleEdit(item);
router.push(`/sales/pricing-management/${item.id}`);
}
};
@@ -310,7 +305,7 @@ export function PricingListClient({
statusBadge={renderStatusBadge(item)}
isSelected={isSelected}
onToggleSelection={onToggle}
onCardClick={() => item.status !== 'not_registered' ? handleEdit(item) : handleRegister(item)}
onCardClick={() => item.status !== 'not_registered' ? router.push(`/sales/pricing-management/${item.id}`) : handleRegister(item)}
infoGrid={
<div className="grid grid-cols-2 gap-x-4 gap-y-3">
{item.specification && (

View File

@@ -171,7 +171,7 @@ export async function getPricingById(id: string): Promise<PricingData | null> {
}
export async function getItemInfo(itemId: string): Promise<ItemInfo | null> {
interface ItemApiItem { id: number; code: string; name: string; item_type: string; specification?: string; unit?: string }
interface ItemApiItem { id: number; item_code: string; code?: string; name: string; item_type: string; specification?: string; unit?: string }
const result = await executeServerAction<ItemApiItem>({
url: `${API_URL}/api/v1/items/${itemId}`,
errorMessage: '품목 조회에 실패했습니다.',
@@ -179,7 +179,7 @@ export async function getItemInfo(itemId: string): Promise<ItemInfo | null> {
if (!result.success || !result.data) return null;
const item = result.data;
return {
id: String(item.id), itemCode: item.code, itemName: item.name,
id: String(item.id), itemCode: item.item_code || item.code || '', itemName: item.name,
itemType: item.item_type || 'PT', specification: item.specification || undefined, unit: item.unit || 'EA',
};
}
@@ -243,10 +243,17 @@ export async function finalizePricing(id: string): Promise<{ success: boolean; d
interface ItemApiData {
id: number;
item_type: string; // FG, PT, SM, RM, CS (품목 유형)
code: string;
item_code?: string;
code?: string;
name: string;
specification?: string;
unit: string;
category_id: number | null;
attributes?: {
salesPrice?: number;
purchasePrice?: number;
[key: string]: unknown;
} | null;
created_at: string;
deleted_at: string | null;
}
@@ -330,11 +337,11 @@ export async function getPricingListData(): Promise<PricingListItem[]> {
const [itemsResult, pricingResult] = await Promise.all([
executeServerAction<ItemsPaginatedResponse>({
url: `${API_URL}/api/v1/items?group_id=1&size=100`,
url: `${API_URL}/api/v1/items?group_id=1&size=10000`,
errorMessage: '품목 목록 조회에 실패했습니다.',
}),
executeServerAction<PricingPaginatedResponse>({
url: `${API_URL}/api/v1/pricing?size=100`,
url: `${API_URL}/api/v1/pricing?size=10000`,
errorMessage: '단가 목록 조회에 실패했습니다.',
}),
]);
@@ -354,10 +361,13 @@ export async function getPricingListData(): Promise<PricingListItem[]> {
const key = `${item.item_type}_${item.id}`;
const pricing = pricingMap.get(key);
const itemCode = item.item_code || item.code || '';
const specification = item.specification || undefined;
if (pricing) {
return {
id: String(pricing.id), itemId: String(item.id), itemCode: item.code, itemName: item.name,
itemType: mapItemTypeForList(item.item_type), specification: undefined, unit: item.unit || 'EA',
id: String(pricing.id), itemId: String(item.id), itemCode, itemName: item.name,
itemType: mapItemTypeForList(item.item_type), specification, unit: item.unit || 'EA',
purchasePrice: pricing.purchase_price ? parseFloat(pricing.purchase_price) : undefined,
processingCost: pricing.processing_cost ? parseFloat(pricing.processing_cost) : undefined,
salesPrice: pricing.sales_price ? parseFloat(pricing.sales_price) : undefined,
@@ -367,10 +377,15 @@ export async function getPricingListData(): Promise<PricingListItem[]> {
currentRevision: 0, isFinal: pricing.is_final, itemTypeCode: item.item_type,
};
} else {
// prices 미등록 → items.attributes에서 참고 단가 표시
const attrSalesPrice = item.attributes?.salesPrice ? Number(item.attributes.salesPrice) : undefined;
const attrPurchasePrice = item.attributes?.purchasePrice ? Number(item.attributes.purchasePrice) : undefined;
return {
id: `item_${item.id}`, itemId: String(item.id), itemCode: item.code, itemName: item.name,
itemType: mapItemTypeForList(item.item_type), specification: undefined, unit: item.unit || 'EA',
purchasePrice: undefined, processingCost: undefined, salesPrice: undefined, marginRate: undefined,
id: `item_${item.id}`, itemId: String(item.id), itemCode, itemName: item.name,
itemType: mapItemTypeForList(item.item_type), specification, unit: item.unit || 'EA',
purchasePrice: attrPurchasePrice, processingCost: undefined,
salesPrice: attrSalesPrice, marginRate: undefined,
effectiveDate: undefined, status: 'not_registered' as const,
currentRevision: 0, isFinal: false, itemTypeCode: item.item_type,
};

View File

@@ -13,3 +13,4 @@ export type { InspectionContentRef } from './ScreenInspectionContent';
// 모달
export { InspectionReportModal } from './InspectionReportModal';
export { WorkLogModal } from './WorkLogModal';