feat: 밸브 분류 시스템 및 구매 관리 시스템 기초 구현

 밸브 분류 시스템:
- 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 단위 계산 준비
This commit is contained in:
Hyungi Ahn
2025-07-18 13:12:41 +09:00
parent 3dd301cb57
commit 92a78225f0
6 changed files with 1082 additions and 10 deletions

View File

@@ -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}")

View File

@@ -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;

View File

@@ -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 = () => {
<Box sx={{ maxWidth: 1400, mx: 'auto', mt: 4, px: 2 }}>
{/* 헤더 */}
<Box sx={{ mb: 3 }}>
<Button
variant="outlined"
startIcon={<ArrowBackIcon />}
onClick={() => navigate(-1)}
sx={{ mb: 2 }}
>
뒤로가기
</Button>
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
<Button
variant="outlined"
startIcon={<ArrowBackIcon />}
onClick={() => navigate(-1)}
>
뒤로가기
</Button>
<Button
variant="contained"
color="success"
size="large"
startIcon={<ShoppingCart />}
onClick={() => {
const params = new URLSearchParams(window.location.search);
navigate(`/purchase-confirmation?${params.toString()}`);
}}
disabled={materialSpecs.length === 0}
sx={{ minWidth: 150 }}
>
구매 확정
</Button>
</Box>
<Typography variant="h4" component="h1" gutterBottom>
📋 자재 사양서
@@ -644,7 +722,18 @@ const MaterialsPage = () => {
<TableCell align="right"><strong>수량</strong></TableCell>
</>
)}
{!['PIPE', 'FITTING', 'FLANGE', 'GASKET', 'BOLT', 'INSTRUMENT'].includes(category) && (
{category === 'VALVE' && (
<>
<TableCell><strong>밸브 타입</strong></TableCell>
<TableCell><strong>연결방식</strong></TableCell>
<TableCell><strong>압력등급</strong></TableCell>
<TableCell><strong>재질</strong></TableCell>
<TableCell><strong>사이즈</strong></TableCell>
<TableCell><strong>작동방식</strong></TableCell>
<TableCell align="right"><strong>수량</strong></TableCell>
</>
)}
{!['PIPE', 'FITTING', 'FLANGE', 'GASKET', 'BOLT', 'INSTRUMENT', 'VALVE'].includes(category) && (
<>
<TableCell><strong>재질</strong></TableCell>
<TableCell><strong>사이즈</strong></TableCell>
@@ -787,7 +876,47 @@ const MaterialsPage = () => {
</TableCell>
</>
)}
{(!['PIPE', 'FITTING', 'FLANGE', 'GASKET', 'BOLT', 'INSTRUMENT'].includes(category)) && (
{category === 'VALVE' && (
<>
<TableCell>
<Typography variant="body2" sx={{ fontWeight: 'bold' }}>
{spec.valve_type?.replace('_', ' ') || 'VALVE'}
</Typography>
</TableCell>
<TableCell>
<Typography variant="body2">
{spec.connection_method?.replace('_', ' ') || 'Unknown'}
</Typography>
</TableCell>
<TableCell>
<Typography variant="body2">
{spec.pressure_rating || 'Unknown'}
</Typography>
</TableCell>
<TableCell>
<Typography variant="body2">
{spec.body_material || 'Unknown'}
</Typography>
</TableCell>
<TableCell>
<Typography variant="body2">
{spec.size_display || 'Unknown'}
</Typography>
</TableCell>
<TableCell>
<Typography variant="body2">
{spec.actuator_type?.replace('_', ' ') || 'MANUAL'}
{spec.fire_safe && ' + FIRE SAFE'}
</Typography>
</TableCell>
<TableCell align="right">
<Typography variant="body2" fontWeight="bold">
{spec.totalQuantity} {spec.unit}
</Typography>
</TableCell>
</>
)}
{(!['PIPE', 'FITTING', 'FLANGE', 'GASKET', 'BOLT', 'INSTRUMENT', 'VALVE'].includes(category)) && (
<>
<TableCell>{spec.material_spec || 'Unknown'}</TableCell>
<TableCell>{spec.size_display || 'Unknown'}</TableCell>

View File

@@ -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 (
<Box sx={{ mt: 1 }}>
<Typography variant="caption" color="textSecondary">
절단손실: {item.cutting_loss || 0}mm |
구매: {item.pipes_count || 0} |
여유분: {item.waste_length || 0}mm
</Typography>
</Box>
);
};
return (
<Box sx={{ p: 3 }}>
{/* 헤더 */}
<Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
<IconButton onClick={() => navigate(-1)} sx={{ mr: 2 }}>
<ArrowBack />
</IconButton>
<Box sx={{ flex: 1 }}>
<Typography variant="h4" gutterBottom>
🛒 구매 확정
</Typography>
<Typography variant="h6" color="primary">
Job: {jobNo} | {filename} | {revision}
</Typography>
</Box>
<Button
variant="contained"
startIcon={<ShoppingCart />}
onClick={() => setConfirmDialog(true)}
size="large"
disabled={purchaseItems.length === 0}
>
구매 주문 생성
</Button>
</Box>
{/* 리비전 비교 알림 */}
{revisionComparison && (
<Alert
severity={revisionComparison.has_changes ? "warning" : "info"}
sx={{ mb: 3 }}
icon={<CompareArrows />}
>
<Typography variant="body2">
<strong>리비전 변경사항:</strong> {revisionComparison.summary}
</Typography>
{revisionComparison.additional_items && (
<Typography variant="body2" sx={{ mt: 1 }}>
추가 구매 필요: {revisionComparison.additional_items} 품목
</Typography>
)}
</Alert>
)}
{/* 구매 품목 테이블 */}
{purchaseItems.map(item => (
<Card key={item.id} sx={{ mb: 2 }}>
<CardContent>
<Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
<Chip
label={item.category}
color={getCategoryColor(item.category)}
sx={{ mr: 2 }}
/>
<Typography variant="h6" sx={{ flex: 1 }}>
{item.specification}
</Typography>
{item.is_additional && (
<Chip
label="추가 구매"
color="warning"
variant="outlined"
/>
)}
</Box>
<Grid container spacing={3}>
{/* BOM 수량 */}
<Grid item xs={12} md={3}>
<Typography variant="body2" color="textSecondary">
BOM 필요량
</Typography>
<Typography variant="h6">
{item.bom_quantity} {item.unit}
</Typography>
{formatPipeInfo(item)}
</Grid>
{/* 구매 수량 */}
<Grid item xs={12} md={3}>
<Typography variant="body2" color="textSecondary">
구매 수량
</Typography>
{editingItem === item.id ? (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<TextField
value={item.calculated_qty}
onChange={(e) =>
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 }}
/>
<IconButton
size="small"
color="primary"
onClick={() => updateItemQuantity(item.id, 'calculated_qty', item.calculated_qty)}
>
<Check />
</IconButton>
<IconButton
size="small"
onClick={() => setEditingItem(null)}
>
<Close />
</IconButton>
</Box>
) : (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="h6" color="primary">
{item.calculated_qty} {item.unit}
</Typography>
<IconButton
size="small"
onClick={() => setEditingItem(item.id)}
>
<Edit />
</IconButton>
</Box>
)}
</Grid>
{/* 이미 구매한 수량 */}
{previousRevision && (
<Grid item xs={12} md={3}>
<Typography variant="body2" color="textSecondary">
기구매 수량
</Typography>
<Typography variant="h6">
{item.purchased_quantity || 0} {item.unit}
</Typography>
</Grid>
)}
{/* 추가 구매 필요량 */}
{previousRevision && (
<Grid item xs={12} md={3}>
<Typography variant="body2" color="textSecondary">
추가 구매 필요
</Typography>
<Typography
variant="h6"
color={item.additional_needed > 0 ? "error" : "success"}
>
{Math.max(item.additional_needed || 0, 0)} {item.unit}
</Typography>
</Grid>
)}
</Grid>
{/* 여유율 및 최소 주문 정보 */}
<Box sx={{ mt: 2, p: 2, bgcolor: 'grey.50', borderRadius: 1 }}>
<Grid container spacing={2}>
<Grid item xs={6} md={3}>
<Typography variant="caption" color="textSecondary">
여유율
</Typography>
<Typography variant="body2">
{((item.safety_factor || 1) - 1) * 100}%
</Typography>
</Grid>
<Grid item xs={6} md={3}>
<Typography variant="caption" color="textSecondary">
최소 주문
</Typography>
<Typography variant="body2">
{item.min_order_qty || 0} {item.unit}
</Typography>
</Grid>
<Grid item xs={6} md={3}>
<Typography variant="caption" color="textSecondary">
예상 여유분
</Typography>
<Typography variant="body2">
{(item.calculated_qty - item.bom_quantity).toFixed(1)} {item.unit}
</Typography>
</Grid>
<Grid item xs={6} md={3}>
<Typography variant="caption" color="textSecondary">
활용률
</Typography>
<Typography variant="body2">
{((item.bom_quantity / item.calculated_qty) * 100).toFixed(1)}%
</Typography>
</Grid>
</Grid>
</Box>
</CardContent>
</Card>
))}
{/* 구매 주문 확인 다이얼로그 */}
<Dialog open={confirmDialog} onClose={() => setConfirmDialog(false)}>
<DialogTitle>구매 주문 생성 확인</DialogTitle>
<DialogContent>
<Typography variant="body2" sx={{ mb: 2 }}>
{purchaseItems.length} 품목에 대한 구매 주문을 생성하시겠습니까?
</Typography>
{revisionComparison && revisionComparison.has_changes && (
<Alert severity="warning" sx={{ mb: 2 }}>
리비전 변경으로 인한 추가 구매가 포함되어 있습니다.
</Alert>
)}
<Typography variant="body2" color="textSecondary">
구매 주문 생성 후에는 수량 변경이 제한됩니다.
</Typography>
</DialogContent>
<DialogActions>
<Button onClick={() => setConfirmDialog(false)}>
취소
</Button>
<Button onClick={confirmPurchase} variant="contained">
주문 생성
</Button>
</DialogActions>
</Dialog>
</Box>
);
};
export default PurchaseConfirmationPage;

11
test_valve_bom.csv Normal file
View File

@@ -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"
Can't render this file because it contains an unexpected character in line 2 and column 52.

156
test_valve_classifier.py Normal file
View File

@@ -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()