From 92a78225f0cebac1c38ab92727b114a21e96e01c Mon Sep 17 00:00:00 2001 From: Hyungi Ahn Date: Fri, 18 Jul 2025 13:12:41 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=EB=B0=B8=EB=B8=8C=20=EB=B6=84=EB=A5=98?= =?UTF-8?q?=20=EC=8B=9C=EC=8A=A4=ED=85=9C=20=EB=B0=8F=20=EA=B5=AC=EB=A7=A4?= =?UTF-8?q?=20=EA=B4=80=EB=A6=AC=20=EC=8B=9C=EC=8A=A4=ED=85=9C=20=EA=B8=B0?= =?UTF-8?q?=EC=B4=88=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ 밸브 분류 시스템: - VALVE 상세 정보 저장 로직 추가 (backend/app/routers/files.py) - 프론트엔드 밸브 사양서 표시 로직 추가 (MaterialsPage.jsx) - 밸브 분류기 테스트 스크립트 및 데이터 (test_valve_classifier.py, test_valve_bom.csv) 🛒 구매 관리 시스템: - 구매 관리 테이블 스키마 (08_create_purchase_tables.sql) - 구매확정 페이지 컴포넌트 (PurchaseConfirmationPage.jsx) - MaterialsPage에 구매확정 버튼 추가 🎯 주요 기능: - 밸브 타입, 연결방식, 압력등급, 재질 분류 - 구매 품목 마스터, 주문 관리, 리비전 추적 - 파이프 절단손실 및 6M 단위 계산 준비 --- backend/app/routers/files.py | 99 +++++ backend/scripts/08_create_purchase_tables.sql | 286 +++++++++++++ frontend/src/pages/MaterialsPage.jsx | 149 ++++++- .../src/pages/PurchaseConfirmationPage.jsx | 391 ++++++++++++++++++ test_valve_bom.csv | 11 + test_valve_classifier.py | 156 +++++++ 6 files changed, 1082 insertions(+), 10 deletions(-) create mode 100644 backend/scripts/08_create_purchase_tables.sql create mode 100644 frontend/src/pages/PurchaseConfirmationPage.jsx create mode 100644 test_valve_bom.csv create mode 100644 test_valve_classifier.py diff --git a/backend/app/routers/files.py b/backend/app/routers/files.py index 7262950..e6e9360 100644 --- a/backend/app/routers/files.py +++ b/backend/app/routers/files.py @@ -770,6 +770,105 @@ async def upload_file( }) print(f"BOLT 상세 정보 저장 완료: {bolt_type} - {material_standard} {material_grade}") + + # VALVE 분류 결과인 경우 상세 정보 저장 + if classification_result.get("category") == "VALVE": + print("VALVE 상세 정보 저장 시작") + + # 밸브 타입 정보 + valve_type_info = classification_result.get("valve_type", {}) + connection_info = classification_result.get("connection_method", {}) + pressure_info = classification_result.get("pressure_rating", {}) + material_info = classification_result.get("material", {}) + + # 밸브 타입 (GATE_VALVE, BALL_VALVE 등) + valve_type = "" + if isinstance(valve_type_info, dict): + valve_type = valve_type_info.get("type", "UNKNOWN") + else: + valve_type = str(valve_type_info) if valve_type_info else "UNKNOWN" + + # 밸브 서브타입 (특수 기능) + valve_subtype = "" + special_features = classification_result.get("special_features", []) + if special_features: + valve_subtype = ", ".join(special_features) + + # 작동 방식 + actuator_type = "MANUAL" # 기본값 + actuation_info = classification_result.get("actuation", {}) + if isinstance(actuation_info, dict): + actuator_type = actuation_info.get("method", "MANUAL") + + # 연결 방식 (FLANGED, THREADED 등) + connection_method = "" + if isinstance(connection_info, dict): + connection_method = connection_info.get("method", "UNKNOWN") + else: + connection_method = str(connection_info) if connection_info else "UNKNOWN" + + # 압력 등급 (150LB, 300LB 등) + pressure_rating = "" + if isinstance(pressure_info, dict): + pressure_rating = pressure_info.get("rating", "UNKNOWN") + else: + pressure_rating = str(pressure_info) if pressure_info else "UNKNOWN" + + # 재질 정보 + body_material = "" + trim_material = "" + if isinstance(material_info, dict): + body_material = material_info.get("grade", "") + # 트림 재질은 일반적으로 바디와 동일하거나 별도 명시 + trim_material = body_material + + # 사이즈 정보 + size_inches = material_data.get("main_nom") or material_data.get("size_spec", "") + + # 특수 기능 (Fire Safe, Anti-Static 등) + fire_safe = any("FIRE" in feature.upper() for feature in special_features) + low_temp_service = any("CRYO" in feature.upper() or "LOW" in feature.upper() for feature in special_features) + + # 추가 정보 JSON 생성 + additional_info = { + "characteristics": valve_type_info.get("characteristics", "") if isinstance(valve_type_info, dict) else "", + "typical_connections": valve_type_info.get("typical_connections", []) if isinstance(valve_type_info, dict) else [], + "special_features": special_features, + "manufacturing": classification_result.get("manufacturing", {}), + "evidence": valve_type_info.get("evidence", []) if isinstance(valve_type_info, dict) else [] + } + additional_info_json = json.dumps(additional_info, ensure_ascii=False) + + db.execute(text(""" + INSERT INTO valve_details ( + material_id, file_id, valve_type, valve_subtype, + actuator_type, connection_method, pressure_rating, + body_material, trim_material, size_inches, + fire_safe, low_temp_service, classification_confidence, additional_info + ) VALUES ( + :material_id, :file_id, :valve_type, :valve_subtype, + :actuator_type, :connection_method, :pressure_rating, + :body_material, :trim_material, :size_inches, + :fire_safe, :low_temp_service, :classification_confidence, :additional_info + ) + """), { + "material_id": material_id, + "file_id": file_id, + "valve_type": valve_type, + "valve_subtype": valve_subtype, + "actuator_type": actuator_type, + "connection_method": connection_method, + "pressure_rating": pressure_rating, + "body_material": body_material, + "trim_material": trim_material, + "size_inches": size_inches, + "fire_safe": fire_safe, + "low_temp_service": low_temp_service, + "classification_confidence": classification_result.get("overall_confidence", 0.0), + "additional_info": additional_info_json + }) + + print(f"VALVE 상세 정보 저장 완료: {valve_type} - {connection_method} - {pressure_rating}") db.commit() print(f"자재 저장 완료: {materials_inserted}개") diff --git a/backend/scripts/08_create_purchase_tables.sql b/backend/scripts/08_create_purchase_tables.sql new file mode 100644 index 0000000..db98ea7 --- /dev/null +++ b/backend/scripts/08_create_purchase_tables.sql @@ -0,0 +1,286 @@ +-- 구매 관리 시스템 테이블들 +-- 실행일: 2025.01.21 + +-- ================================ +-- 1. 구매 품목 마스터 테이블 +-- ================================ +CREATE TABLE IF NOT EXISTS purchase_items ( + id SERIAL PRIMARY KEY, + + -- 품목 식별 + item_code VARCHAR(100) UNIQUE NOT NULL, -- PI-PIPE-A106-4IN-001 + category VARCHAR(50) NOT NULL, -- PIPE, VALVE, FITTING 등 + specification TEXT NOT NULL, -- 상세 사양 + + -- 기본 정보 + material_spec VARCHAR(200), -- ASTM A106 GR B + size_spec VARCHAR(100), -- 4", 1-1/2" x 1" + unit VARCHAR(10) NOT NULL, -- EA, mm, SET + + -- BOM 수량 정보 + bom_quantity DECIMAL(10,3) NOT NULL, -- BOM상 필요 수량 + + -- 구매 계산 정보 + safety_factor DECIMAL(3,2) DEFAULT 1.10, -- 여유율 (1.1 = 10% 추가) + minimum_order_qty DECIMAL(10,3) DEFAULT 0, -- 최소 주문 수량 + order_unit_qty DECIMAL(10,3) DEFAULT 1, -- 주문 단위 (박스, 롤 등) + calculated_qty DECIMAL(10,3), -- 최종 계산된 구매 수량 + + -- PIPE 전용 정보 + cutting_loss DECIMAL(10,3) DEFAULT 0, -- 절단 손실 (mm) + standard_length DECIMAL(10,3), -- 표준 길이 (PIPE: 6000mm) + pipes_count INTEGER, -- 필요한 파이프 본수 + waste_length DECIMAL(10,3), -- 여유분 길이 + + -- 상세 스펙 (JSON) + detailed_spec JSONB, -- 압력등급, 연결방식 등 상세 정보 + + -- 구매 정보 + preferred_supplier VARCHAR(200), -- 선호 공급업체 + last_unit_price DECIMAL(10,2), -- 최근 단가 + currency VARCHAR(10) DEFAULT 'KRW', -- 통화 + lead_time_days INTEGER DEFAULT 30, -- 리드타임 + + -- 연결 정보 + job_no VARCHAR(50) NOT NULL, -- Job 번호 + revision VARCHAR(20) DEFAULT 'Rev.0', -- 리비전 + file_id INTEGER, -- 원본 파일 ID + + -- 관리 정보 + is_active BOOLEAN DEFAULT TRUE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + created_by VARCHAR(100), + + -- 외래키 + FOREIGN KEY (file_id) REFERENCES files(id) ON DELETE SET NULL +); + +-- ================================ +-- 2. 개별 자재와 구매품목 연결 테이블 +-- ================================ +CREATE TABLE IF NOT EXISTS material_purchase_mapping ( + id SERIAL PRIMARY KEY, + material_id INTEGER NOT NULL, -- materials 테이블 ID + purchase_item_id INTEGER NOT NULL, -- purchase_items 테이블 ID + quantity_ratio DECIMAL(5,2) DEFAULT 1.0, -- 변환 비율 + + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + + -- 외래키 + FOREIGN KEY (material_id) REFERENCES materials(id) ON DELETE CASCADE, + FOREIGN KEY (purchase_item_id) REFERENCES purchase_items(id) ON DELETE CASCADE, + + -- 유니크 제약 + UNIQUE(material_id, purchase_item_id) +); + +-- ================================ +-- 3. 구매 주문 테이블 +-- ================================ +CREATE TABLE IF NOT EXISTS purchase_orders ( + id SERIAL PRIMARY KEY, + + -- 주문 기본 정보 + order_no VARCHAR(50) UNIQUE NOT NULL, -- PO-2024-001 + job_no VARCHAR(50) NOT NULL, -- Job 번호 + revision VARCHAR(20) NOT NULL, -- 리비전 + + -- 주문 상태 + status VARCHAR(20) DEFAULT 'DRAFT', -- DRAFT, APPROVED, ORDERED, RECEIVED, CANCELLED + order_date DATE, -- 주문일 + required_date DATE, -- 요청일 + delivery_date DATE, -- 납기일 + + -- 공급업체 정보 + supplier_name VARCHAR(200), + supplier_contact VARCHAR(200), + + -- 금액 정보 + total_amount DECIMAL(12,2), + currency VARCHAR(10) DEFAULT 'KRW', + + -- 관리 정보 + created_by VARCHAR(100), + approved_by VARCHAR(100), + approved_at TIMESTAMP, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + + notes TEXT +); + +-- ================================ +-- 4. 구매 주문 상세 테이블 +-- ================================ +CREATE TABLE IF NOT EXISTS purchase_order_items ( + id SERIAL PRIMARY KEY, + + purchase_order_id INTEGER NOT NULL, -- purchase_orders 테이블 ID + purchase_item_id INTEGER NOT NULL, -- purchase_items 테이블 ID + + -- 수량 정보 + ordered_quantity DECIMAL(10,3) NOT NULL, -- 주문 수량 + received_quantity DECIMAL(10,3) DEFAULT 0, -- 입고 수량 + + -- 가격 정보 + unit_price DECIMAL(10,2), -- 단가 + total_price DECIMAL(12,2), -- 총액 + + -- 납기 정보 + required_date DATE, -- 요청일 + delivery_date DATE, -- 납기일 + + -- 상태 + status VARCHAR(20) DEFAULT 'ORDERED', -- ORDERED, PARTIAL, RECEIVED, CANCELLED + + -- 관리 정보 + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + + notes TEXT, + + -- 외래키 + FOREIGN KEY (purchase_order_id) REFERENCES purchase_orders(id) ON DELETE CASCADE, + FOREIGN KEY (purchase_item_id) REFERENCES purchase_items(id) ON DELETE CASCADE +); + +-- ================================ +-- 5. 구매 이력 테이블 (리비전 추적용) +-- ================================ +CREATE TABLE IF NOT EXISTS purchase_history ( + id SERIAL PRIMARY KEY, + + job_no VARCHAR(50) NOT NULL, + revision VARCHAR(20) NOT NULL, + + -- 변경 내용 + change_type VARCHAR(20) NOT NULL, -- ADDED, MODIFIED, REMOVED + purchase_item_id INTEGER, + + -- 수량 변경 + previous_quantity DECIMAL(10,3), + new_quantity DECIMAL(10,3), + quantity_diff DECIMAL(10,3), -- 차이 (음수면 감소, 양수면 증가) + + -- 변경 사유 + change_reason VARCHAR(200), + + -- 관리 정보 + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + created_by VARCHAR(100), + + -- 외래키 + FOREIGN KEY (purchase_item_id) REFERENCES purchase_items(id) ON DELETE SET NULL +); + +-- ================================ +-- 6. 인덱스 생성 +-- ================================ + +-- purchase_items 인덱스 +CREATE INDEX IF NOT EXISTS idx_purchase_items_job_revision ON purchase_items(job_no, revision); +CREATE INDEX IF NOT EXISTS idx_purchase_items_category ON purchase_items(category); +CREATE INDEX IF NOT EXISTS idx_purchase_items_item_code ON purchase_items(item_code); +CREATE INDEX IF NOT EXISTS idx_purchase_items_active ON purchase_items(is_active); + +-- material_purchase_mapping 인덱스 +CREATE INDEX IF NOT EXISTS idx_material_purchase_mapping_material ON material_purchase_mapping(material_id); +CREATE INDEX IF NOT EXISTS idx_material_purchase_mapping_purchase ON material_purchase_mapping(purchase_item_id); + +-- purchase_orders 인덱스 +CREATE INDEX IF NOT EXISTS idx_purchase_orders_job_revision ON purchase_orders(job_no, revision); +CREATE INDEX IF NOT EXISTS idx_purchase_orders_status ON purchase_orders(status); +CREATE INDEX IF NOT EXISTS idx_purchase_orders_order_date ON purchase_orders(order_date); + +-- purchase_order_items 인덱스 +CREATE INDEX IF NOT EXISTS idx_purchase_order_items_order ON purchase_order_items(purchase_order_id); +CREATE INDEX IF NOT EXISTS idx_purchase_order_items_item ON purchase_order_items(purchase_item_id); + +-- purchase_history 인덱스 +CREATE INDEX IF NOT EXISTS idx_purchase_history_job_revision ON purchase_history(job_no, revision); +CREATE INDEX IF NOT EXISTS idx_purchase_history_change_type ON purchase_history(change_type); +CREATE INDEX IF NOT EXISTS idx_purchase_history_created_at ON purchase_history(created_at); + +-- ================================ +-- 7. 트리거 생성 (updated_at 자동 업데이트) +-- ================================ + +-- purchase_items updated_at 트리거 +CREATE OR REPLACE FUNCTION update_purchase_items_timestamp() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trigger_update_purchase_items_timestamp + BEFORE UPDATE ON purchase_items + FOR EACH ROW + EXECUTE FUNCTION update_purchase_items_timestamp(); + +-- purchase_orders updated_at 트리거 +CREATE OR REPLACE FUNCTION update_purchase_orders_timestamp() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trigger_update_purchase_orders_timestamp + BEFORE UPDATE ON purchase_orders + FOR EACH ROW + EXECUTE FUNCTION update_purchase_orders_timestamp(); + +-- purchase_order_items updated_at 트리거 +CREATE OR REPLACE FUNCTION update_purchase_order_items_timestamp() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = CURRENT_TIMESTAMP; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER trigger_update_purchase_order_items_timestamp + BEFORE UPDATE ON purchase_order_items + FOR EACH ROW + EXECUTE FUNCTION update_purchase_order_items_timestamp(); + +-- ================================ +-- 8. 기본 뷰 생성 +-- ================================ + +-- 구매 요약 뷰 +CREATE OR REPLACE VIEW purchase_summary AS +SELECT + pi.job_no, + pi.revision, + pi.category, + COUNT(*) as item_count, + SUM(pi.bom_quantity) as total_bom_quantity, + SUM(pi.calculated_qty) as total_purchase_quantity, + SUM(poi.ordered_quantity) as total_ordered_quantity, + SUM(poi.received_quantity) as total_received_quantity, + AVG(pi.safety_factor) as avg_safety_factor +FROM purchase_items pi +LEFT JOIN purchase_order_items poi ON pi.id = poi.purchase_item_id +WHERE pi.is_active = TRUE +GROUP BY pi.job_no, pi.revision, pi.category; + +-- 리비전 변경 요약 뷰 +CREATE OR REPLACE VIEW revision_changes_summary AS +SELECT + ph.job_no, + ph.revision, + ph.change_type, + COUNT(*) as change_count, + SUM(CASE WHEN ph.quantity_diff > 0 THEN ph.quantity_diff ELSE 0 END) as total_increase, + SUM(CASE WHEN ph.quantity_diff < 0 THEN ABS(ph.quantity_diff) ELSE 0 END) as total_decrease, + SUM(ph.quantity_diff) as net_change +FROM purchase_history ph +GROUP BY ph.job_no, ph.revision, ph.change_type; + +-- 스크립트 완료 확인 +SELECT 'Purchase management tables created successfully!' as status; \ No newline at end of file diff --git a/frontend/src/pages/MaterialsPage.jsx b/frontend/src/pages/MaterialsPage.jsx index ef23e52..f30abbb 100644 --- a/frontend/src/pages/MaterialsPage.jsx +++ b/frontend/src/pages/MaterialsPage.jsx @@ -19,6 +19,7 @@ import { Divider } from '@mui/material'; import ArrowBackIcon from '@mui/icons-material/ArrowBack'; +import ShoppingCart from '@mui/icons-material/ShoppingCart'; import { api } from '../api'; const MaterialsPage = () => { @@ -412,6 +413,67 @@ const MaterialsPage = () => { unit: 'EA', isLength: false }; + } else if (category === 'VALVE') { + // VALVE: 타입 + 연결방식 + 압력등급 + 재질 + 사이즈 + const main_nom = material.main_nom || ''; + const valve_type = material.valve_details?.valve_type || 'VALVE'; + const valve_subtype = material.valve_details?.valve_subtype || ''; + const connection_method = material.valve_details?.connection_method || ''; + const pressure_rating = material.valve_details?.pressure_rating || ''; + const body_material = material.valve_details?.body_material || material.material_grade || ''; + const actuator_type = material.valve_details?.actuator_type || 'MANUAL'; + const fire_safe = material.valve_details?.fire_safe || false; + + // 밸브 스펙 생성 + const valve_spec_parts = []; + + // 밸브 타입 (GATE_VALVE, BALL_VALVE 등) + if (valve_type && valve_type !== 'UNKNOWN') { + valve_spec_parts.push(valve_type.replace('_', ' ')); + } + + // 연결 방식 (FLANGED, THREADED, SOCKET_WELD 등) + if (connection_method && connection_method !== 'UNKNOWN') { + valve_spec_parts.push(connection_method.replace('_', ' ')); + } + + // 압력 등급 (150LB, 300LB 등) + if (pressure_rating && pressure_rating !== 'UNKNOWN') { + valve_spec_parts.push(pressure_rating); + } + + // 작동 방식 (수동이 아닌 경우만 표시) + if (actuator_type && actuator_type !== 'MANUAL' && actuator_type !== 'UNKNOWN') { + valve_spec_parts.push(actuator_type.replace('_', ' ')); + } + + // 특수 기능 (Fire Safe 등) + if (fire_safe) { + valve_spec_parts.push('FIRE SAFE'); + } + + if (valve_subtype && valve_subtype !== 'UNKNOWN') { + valve_spec_parts.push(valve_subtype); + } + + const full_valve_spec = valve_spec_parts.join(', '); + + specKey = `${category}|${full_valve_spec}|${body_material}|${main_nom}`; + specData = { + category: 'VALVE', + valve_type, + valve_subtype, + connection_method, + pressure_rating, + body_material, + actuator_type, + fire_safe, + full_valve_spec, + size_display: main_nom, + main_nom, + unit: 'EA', + isLength: false + }; } else { // 기타 자재: 기본 분류 const material_spec = material.material_grade || ''; @@ -515,14 +577,30 @@ const MaterialsPage = () => { {/* 헤더 */} - + + + + + 📋 자재 사양서 @@ -644,7 +722,18 @@ const MaterialsPage = () => { 수량 )} - {!['PIPE', 'FITTING', 'FLANGE', 'GASKET', 'BOLT', 'INSTRUMENT'].includes(category) && ( + {category === 'VALVE' && ( + <> + 밸브 타입 + 연결방식 + 압력등급 + 재질 + 사이즈 + 작동방식 + 수량 + + )} + {!['PIPE', 'FITTING', 'FLANGE', 'GASKET', 'BOLT', 'INSTRUMENT', 'VALVE'].includes(category) && ( <> 재질 사이즈 @@ -787,7 +876,47 @@ const MaterialsPage = () => { )} - {(!['PIPE', 'FITTING', 'FLANGE', 'GASKET', 'BOLT', 'INSTRUMENT'].includes(category)) && ( + {category === 'VALVE' && ( + <> + + + {spec.valve_type?.replace('_', ' ') || 'VALVE'} + + + + + {spec.connection_method?.replace('_', ' ') || 'Unknown'} + + + + + {spec.pressure_rating || 'Unknown'} + + + + + {spec.body_material || 'Unknown'} + + + + + {spec.size_display || 'Unknown'} + + + + + {spec.actuator_type?.replace('_', ' ') || 'MANUAL'} + {spec.fire_safe && ' + FIRE SAFE'} + + + + + {spec.totalQuantity} {spec.unit} + + + + )} + {(!['PIPE', 'FITTING', 'FLANGE', 'GASKET', 'BOLT', 'INSTRUMENT', 'VALVE'].includes(category)) && ( <> {spec.material_spec || 'Unknown'} {spec.size_display || 'Unknown'} diff --git a/frontend/src/pages/PurchaseConfirmationPage.jsx b/frontend/src/pages/PurchaseConfirmationPage.jsx new file mode 100644 index 0000000..fe6c9df --- /dev/null +++ b/frontend/src/pages/PurchaseConfirmationPage.jsx @@ -0,0 +1,391 @@ +import React, { useState, useEffect } from 'react'; +import { useLocation, useNavigate } from 'react-router-dom'; +import { + Box, + Card, + CardContent, + Typography, + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Paper, + Button, + TextField, + Chip, + Alert, + IconButton, + Dialog, + DialogTitle, + DialogContent, + DialogActions, + Grid, + Divider +} from '@mui/material'; +import { + ArrowBack, + Edit, + Check, + Close, + ShoppingCart, + CompareArrows, + Warning +} from '@mui/icons-material'; +import { api } from '../api'; + +const PurchaseConfirmationPage = () => { + const location = useLocation(); + const navigate = useNavigate(); + const [purchaseItems, setPurchaseItems] = useState([]); + const [revisionComparison, setRevisionComparison] = useState(null); + const [loading, setLoading] = useState(true); + const [editingItem, setEditingItem] = useState(null); + const [confirmDialog, setConfirmDialog] = useState(false); + + // URL에서 job_no, revision 정보 가져오기 + const searchParams = new URLSearchParams(location.search); + const jobNo = searchParams.get('job_no'); + const revision = searchParams.get('revision'); + const filename = searchParams.get('filename'); + const previousRevision = searchParams.get('prev_revision'); + + useEffect(() => { + if (jobNo && revision) { + loadPurchaseItems(); + if (previousRevision) { + loadRevisionComparison(); + } + } + }, [jobNo, revision, previousRevision]); + + const loadPurchaseItems = async () => { + try { + setLoading(true); + const response = await api.get('/purchase/items/calculate', { + params: { job_no: jobNo, revision: revision } + }); + setPurchaseItems(response.data.items || []); + } catch (error) { + console.error('구매 품목 로딩 실패:', error); + } finally { + setLoading(false); + } + }; + + const loadRevisionComparison = async () => { + try { + const response = await api.get('/purchase/revision-diff', { + params: { + job_no: jobNo, + current_revision: revision, + previous_revision: previousRevision + } + }); + setRevisionComparison(response.data.comparison); + } catch (error) { + console.error('리비전 비교 실패:', error); + } + }; + + const updateItemQuantity = async (itemId, field, value) => { + try { + await api.patch(`/purchase/items/${itemId}`, { + [field]: parseFloat(value) + }); + + // 로컬 상태 업데이트 + setPurchaseItems(prev => + prev.map(item => + item.id === itemId + ? { ...item, [field]: parseFloat(value) } + : item + ) + ); + + setEditingItem(null); + } catch (error) { + console.error('수량 업데이트 실패:', error); + } + }; + + const confirmPurchase = async () => { + try { + const response = await api.post('/purchase/orders/create', { + job_no: jobNo, + revision: revision, + items: purchaseItems.map(item => ({ + purchase_item_id: item.id, + ordered_quantity: item.calculated_qty, + required_date: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30일 후 + })) + }); + + alert('구매 주문이 생성되었습니다!'); + navigate('/materials', { + state: { message: '구매 주문 생성 완료' } + }); + } catch (error) { + console.error('구매 주문 생성 실패:', error); + alert('구매 주문 생성에 실패했습니다.'); + } + }; + + const getCategoryColor = (category) => { + const colors = { + 'PIPE': 'primary', + 'FITTING': 'secondary', + 'VALVE': 'success', + 'FLANGE': 'warning', + 'BOLT': 'info', + 'GASKET': 'error', + 'INSTRUMENT': 'purple' + }; + return colors[category] || 'default'; + }; + + const formatPipeInfo = (item) => { + if (item.category !== 'PIPE') return null; + + return ( + + + 절단손실: {item.cutting_loss || 0}mm | + 구매: {item.pipes_count || 0}본 | + 여유분: {item.waste_length || 0}mm + + + ); + }; + + return ( + + {/* 헤더 */} + + navigate(-1)} sx={{ mr: 2 }}> + + + + + 🛒 구매 확정 + + + Job: {jobNo} | {filename} | {revision} + + + + + + {/* 리비전 비교 알림 */} + {revisionComparison && ( + } + > + + 리비전 변경사항: {revisionComparison.summary} + + {revisionComparison.additional_items && ( + + 추가 구매 필요: {revisionComparison.additional_items}개 품목 + + )} + + )} + + {/* 구매 품목 테이블 */} + {purchaseItems.map(item => ( + + + + + + {item.specification} + + {item.is_additional && ( + + )} + + + + {/* BOM 수량 */} + + + BOM 필요량 + + + {item.bom_quantity} {item.unit} + + {formatPipeInfo(item)} + + + {/* 구매 수량 */} + + + 구매 수량 + + {editingItem === item.id ? ( + + + setPurchaseItems(prev => + prev.map(i => + i.id === item.id + ? { ...i, calculated_qty: parseFloat(e.target.value) || 0 } + : i + ) + ) + } + size="small" + type="number" + sx={{ width: 100 }} + /> + updateItemQuantity(item.id, 'calculated_qty', item.calculated_qty)} + > + + + setEditingItem(null)} + > + + + + ) : ( + + + {item.calculated_qty} {item.unit} + + setEditingItem(item.id)} + > + + + + )} + + + {/* 이미 구매한 수량 */} + {previousRevision && ( + + + 기구매 수량 + + + {item.purchased_quantity || 0} {item.unit} + + + )} + + {/* 추가 구매 필요량 */} + {previousRevision && ( + + + 추가 구매 필요 + + 0 ? "error" : "success"} + > + {Math.max(item.additional_needed || 0, 0)} {item.unit} + + + )} + + + {/* 여유율 및 최소 주문 정보 */} + + + + + 여유율 + + + {((item.safety_factor || 1) - 1) * 100}% + + + + + 최소 주문 + + + {item.min_order_qty || 0} {item.unit} + + + + + 예상 여유분 + + + {(item.calculated_qty - item.bom_quantity).toFixed(1)} {item.unit} + + + + + 활용률 + + + {((item.bom_quantity / item.calculated_qty) * 100).toFixed(1)}% + + + + + + + ))} + + {/* 구매 주문 확인 다이얼로그 */} + setConfirmDialog(false)}> + 구매 주문 생성 확인 + + + 총 {purchaseItems.length}개 품목에 대한 구매 주문을 생성하시겠습니까? + + + {revisionComparison && revisionComparison.has_changes && ( + + 리비전 변경으로 인한 추가 구매가 포함되어 있습니다. + + )} + + + 구매 주문 생성 후에는 수량 변경이 제한됩니다. + + + + + + + + + ); +}; + +export default PurchaseConfirmationPage; \ No newline at end of file diff --git a/test_valve_bom.csv b/test_valve_bom.csv new file mode 100644 index 0000000..3edb28e --- /dev/null +++ b/test_valve_bom.csv @@ -0,0 +1,11 @@ +DESCRIPTION,QTY,MAIN_NOM +"GATE VALVE, 150LB, FL, 4"", ASTM A216 WCB, RF",2,4" +"BALL VALVE, 300LB, THREADED, 2"", SS316, FULL PORT",3,2" +"GLOBE VALVE, 600LB, SW, 1"", A105, Y-TYPE",1,1" +"CHECK VALVE, 150LB, WAFER, 6"", DCI, DUAL PLATE",4,6" +"BUTTERFLY VALVE, 150LB, WAFER, 12"", DCI, GEAR OPERATED",1,12" +"NEEDLE VALVE, 6000LB, SW, 1/2"", A182 F316, FINE ADJUST",5,1/2" +"RELIEF VALVE, PSV, 150LB, FL, 3"", A216 WCB, SET 150 PSI",2,3" +"SOLENOID VALVE, 24VDC, 150LB, THD, 1/4"", SS316, 2-WAY NC",8,1/4" +"GATE VALVE, 300LB, BW, 8"", A216 WCB, RTJ",1,8" +"BALL VALVE, 600LB, SW, 1-1/2"", A182 F316, FIRE SAFE",2,1-1/2" \ No newline at end of file diff --git a/test_valve_classifier.py b/test_valve_classifier.py new file mode 100644 index 0000000..7885531 --- /dev/null +++ b/test_valve_classifier.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +""" +밸브 분류기 테스트 +실제 밸브 데이터로 분류 성능 확인 +""" + +import sys +import os +sys.path.append('backend') + +from app.services.valve_classifier import classify_valve + +def test_valve_classifier(): + """다양한 밸브 데이터로 분류 테스트""" + + print("🔧 밸브 분류기 테스트 시작\n") + + # 테스트 데이터 (실제 BOM에서 가져온 데이터) + test_valves = [ + { + "description": "GATE VALVE, 150LB, FL, 4\", ASTM A216 WCB, RF", + "main_nom": "4\"", + "expected": "GATE_VALVE" + }, + { + "description": "BALL VALVE, 300LB, THREADED, 2\", SS316, FULL PORT", + "main_nom": "2\"", + "expected": "BALL_VALVE" + }, + { + "description": "GLOBE VALVE, 600LB, SW, 1\", A105, Y-TYPE", + "main_nom": "1\"", + "expected": "GLOBE_VALVE" + }, + { + "description": "CHECK VALVE, 150LB, WAFER, 6\", DCI, DUAL PLATE", + "main_nom": "6\"", + "expected": "CHECK_VALVE" + }, + { + "description": "BUTTERFLY VALVE, 150LB, WAFER, 12\", DCI, GEAR OPERATED", + "main_nom": "12\"", + "expected": "BUTTERFLY_VALVE" + }, + { + "description": "NEEDLE VALVE, 6000LB, SW, 1/2\", A182 F316, FINE ADJUST", + "main_nom": "1/2\"", + "expected": "NEEDLE_VALVE" + }, + { + "description": "RELIEF VALVE, PSV, 150LB, FL, 3\", A216 WCB, SET 150 PSI", + "main_nom": "3\"", + "expected": "RELIEF_VALVE" + }, + { + "description": "SOLENOID VALVE, 24VDC, 150LB, THD, 1/4\", SS316, 2-WAY NC", + "main_nom": "1/4\"", + "expected": "SOLENOID_VALVE" + } + ] + + total_tests = len(test_valves) + passed_tests = 0 + + for i, test_data in enumerate(test_valves, 1): + print(f"\n📋 테스트 {i}/{total_tests}: {test_data['description'][:50]}...") + + # 분류 실행 + result = classify_valve("", test_data["description"], test_data["main_nom"]) + + # 결과 출력 + category = result.get("category", "UNKNOWN") + confidence = result.get("overall_confidence", 0.0) + valve_type = result.get("valve_type", {}).get("type", "UNKNOWN") + connection = result.get("connection_method", {}).get("method", "UNKNOWN") + pressure = result.get("pressure_rating", {}).get("rating", "UNKNOWN") + + print(f" ✅ 분류: {category}") + print(f" 🔧 밸브타입: {valve_type}") + print(f" 🔗 연결방식: {connection}") + print(f" 📊 압력등급: {pressure}") + print(f" 🎯 신뢰도: {confidence:.2f}") + + # 성공 여부 확인 + if category == "VALVE" and valve_type == test_data["expected"]: + print(f" ✅ 성공: 예상({test_data['expected']}) = 결과({valve_type})") + passed_tests += 1 + else: + print(f" ❌ 실패: 예상({test_data['expected']}) ≠ 결과({valve_type})") + # 실패 원인 분석 + evidence = result.get("valve_type", {}).get("evidence", []) + print(f" 증거: {evidence}") + + # 최종 결과 + success_rate = (passed_tests / total_tests) * 100 + print(f"\n🎉 테스트 완료!") + print(f"📊 성공률: {passed_tests}/{total_tests} ({success_rate:.1f}%)") + + if success_rate >= 80: + print("✅ 밸브 분류기 성능 양호!") + elif success_rate >= 60: + print("⚠️ 밸브 분류기 성능 보통 - 개선 필요") + else: + print("❌ 밸브 분류기 성능 불량 - 대폭 개선 필요") + +def test_special_valve_cases(): + """특수한 밸브 케이스 테스트""" + + print("\n🔍 특수 밸브 케이스 테스트\n") + + special_cases = [ + { + "description": "밸브 없는 파이프", + "data": "PIPE, 4\", SCH40, ASTM A106 GR B, SMLS", + "main_nom": "4\"", + "should_reject": True + }, + { + "description": "밸브 키워드만 있는 애매한 케이스", + "data": "VALVE HOUSING GASKET, 4\", GRAPHITE", + "main_nom": "4\"", + "should_reject": True + }, + { + "description": "복합 밸브 (여러 타입 혼재)", + "data": "GATE BALL VALVE ASSEMBLY, 150LB, 2\"", + "main_nom": "2\"", + "should_reject": False + } + ] + + for case in special_cases: + print(f"📝 {case['description']}: {case['data']}") + + result = classify_valve("", case["data"], case["main_nom"]) + + category = result.get("category", "UNKNOWN") + confidence = result.get("overall_confidence", 0.0) + + print(f" 결과: {category} (신뢰도: {confidence:.2f})") + + if case["should_reject"]: + if category == "UNKNOWN" or confidence < 0.5: + print(" ✅ 올바르게 거부됨") + else: + print(" ❌ 잘못 수용됨") + else: + if category == "VALVE" and confidence >= 0.5: + print(" ✅ 올바르게 수용됨") + else: + print(" ❌ 잘못 거부됨") + print() + +if __name__ == "__main__": + test_valve_classifier() + test_special_valve_cases() \ No newline at end of file