Add new frontend - fix 22
This commit is contained in:
@@ -17,9 +17,11 @@ import {
|
||||
import {
|
||||
TenantUser,
|
||||
TenantCreate,
|
||||
TenantInfo
|
||||
TenantInfo ,
|
||||
DataValidation
|
||||
} from '@/api/services';
|
||||
|
||||
|
||||
import api from '@/api/services';
|
||||
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
@@ -206,27 +208,86 @@ const OnboardingPage = () => {
|
||||
setCurrentTenantId(tenant.id);
|
||||
showNotification('success', 'Panadería registrada', 'Información guardada correctamente.');
|
||||
|
||||
} else if (currentStep === 3) {
|
||||
// Upload and validate sales data using real data service
|
||||
if (formData.salesFile) {
|
||||
// First validate the data
|
||||
const validation = await api.data.validateSalesData(formData.salesFile);
|
||||
setUploadValidation(validation);
|
||||
|
||||
if (validation.valid || validation.warnings.length === 0) {
|
||||
// Upload the file
|
||||
const uploadResult = await api.data.uploadSalesHistory(
|
||||
formData.salesFile,
|
||||
{ tenant_id: currentTenantId }
|
||||
);
|
||||
showNotification('success', 'Archivo subido', `${uploadResult.records_processed} registros procesados.`);
|
||||
} else {
|
||||
showNotification('warning', 'Datos con advertencias', 'Se encontraron algunas advertencias pero los datos son válidos.');
|
||||
} else if (currentStep === 3) {
|
||||
// FIXED: Sales upload step with proper validation handling
|
||||
if (formData.salesFile) {
|
||||
try {
|
||||
// Validate if not already validated
|
||||
let validation = uploadValidation;
|
||||
if (!validation) {
|
||||
validation = await api.data.validateSalesData(formData.salesFile);
|
||||
setUploadValidation(validation);
|
||||
}
|
||||
|
||||
// FIXED: Check validation using correct field names
|
||||
if (!validation.is_valid) {
|
||||
const errorMessages = validation.errors.map(error =>
|
||||
`${error.row ? `Fila ${error.row}: ` : ''}${error.message}`
|
||||
).join('; ');
|
||||
|
||||
showNotification('error', 'Datos inválidos',
|
||||
`Se encontraron errores: ${errorMessages.slice(0, 200)}${errorMessages.length > 200 ? '...' : ''}`);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Show warnings if any
|
||||
if (validation.warnings.length > 0) {
|
||||
const warningMessages = validation.warnings.map(warning =>
|
||||
`${warning.row ? `Fila ${warning.row}: ` : ''}${warning.message}`
|
||||
).join('; ');
|
||||
|
||||
showNotification('warning', 'Advertencias encontradas',
|
||||
`Advertencias: ${warningMessages.slice(0, 200)}${warningMessages.length > 200 ? '...' : ''}`);
|
||||
}
|
||||
|
||||
// Proceed with import - Use the existing uploadSalesHistory method
|
||||
// or create a new importSalesData method
|
||||
const uploadResult = await api.data.uploadSalesHistory(
|
||||
formData.salesFile,
|
||||
{ tenant_id: currentTenantId }
|
||||
);
|
||||
|
||||
showNotification('success', 'Archivo subido',
|
||||
`${uploadResult.records_processed} registros procesados exitosamente.`);
|
||||
|
||||
console.log('Upload successful:', {
|
||||
records_processed: uploadResult.records_processed,
|
||||
validation_summary: {
|
||||
total_records: validation.total_records,
|
||||
valid_records: validation.valid_records,
|
||||
invalid_records: validation.invalid_records,
|
||||
errors_count: validation.errors.length,
|
||||
warnings_count: validation.warnings.length
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Sales upload error:', error);
|
||||
|
||||
let errorMessage = 'No se pudo procesar el archivo de ventas.';
|
||||
let errorTitle = 'Error al subir';
|
||||
|
||||
if (error.response?.status === 422) {
|
||||
errorTitle = 'Error de validación';
|
||||
errorMessage = error.response.data?.detail || 'Formato de datos incorrecto';
|
||||
} else if (error.response?.status === 400) {
|
||||
errorTitle = 'Archivo inválido';
|
||||
errorMessage = error.response.data?.detail || 'El formato del archivo no es compatible';
|
||||
} else if (error.response?.status >= 500) {
|
||||
errorTitle = 'Error del servidor';
|
||||
errorMessage = 'Problema temporal del servidor. Inténtalo más tarde.';
|
||||
} else if (error.message) {
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
showNotification('error', errorTitle, errorMessage);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} else if (currentStep === 4) {
|
||||
// Start training using real training service
|
||||
// Training step
|
||||
const trainingConfig = {
|
||||
include_weather: true,
|
||||
include_traffic: true,
|
||||
@@ -245,7 +306,6 @@ const OnboardingPage = () => {
|
||||
}));
|
||||
showNotification('info', 'Entrenamiento iniciado', 'Los modelos se están entrenando...');
|
||||
|
||||
// Don't move to next step automatically, wait for training completion
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
@@ -289,7 +349,7 @@ const OnboardingPage = () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileUpload = async (event) => {
|
||||
const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (file) {
|
||||
setFormData(prev => ({ ...prev, salesFile: file }));
|
||||
@@ -298,33 +358,56 @@ const OnboardingPage = () => {
|
||||
// Auto-validate file on selection
|
||||
try {
|
||||
setLoading(true);
|
||||
console.log('Validating file:', file.name);
|
||||
|
||||
// FIXED: Use the corrected validation method
|
||||
const validation = await api.data.validateSalesData(file);
|
||||
setUploadValidation(validation);
|
||||
|
||||
if (validation.valid) {
|
||||
showNotification('success', 'Archivo válido', `${validation.recordCount} registros detectados.`);
|
||||
// FIXED: Use correct field names from backend response
|
||||
if (validation.is_valid) {
|
||||
showNotification('success', 'Archivo válido',
|
||||
`${validation.total_records} registros detectados, ${validation.valid_records} válidos.`);
|
||||
} else if (validation.warnings.length > 0 && validation.errors.length === 0) {
|
||||
showNotification('warning', 'Archivo con advertencias', 'El archivo es válido pero tiene algunas advertencias.');
|
||||
showNotification('warning', 'Archivo con advertencias',
|
||||
'El archivo es válido pero tiene algunas advertencias.');
|
||||
} else {
|
||||
showNotification('error', 'Archivo inválido', 'El archivo tiene errores que deben corregirse.');
|
||||
const errorCount = validation.errors.length;
|
||||
showNotification('error', 'Archivo con errores',
|
||||
`Se encontraron ${errorCount} errores en el archivo.`);
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Error validating file:', error);
|
||||
showNotification('error', 'Error de validación', 'No se pudo validar el archivo.');
|
||||
|
||||
// Handle network or other errors
|
||||
let errorMessage = 'Error al validar el archivo';
|
||||
if (error.response?.status === 422) {
|
||||
errorMessage = 'Formato de archivo inválido';
|
||||
} else if (error.response?.status === 400) {
|
||||
errorMessage = 'El archivo no se puede procesar';
|
||||
} else if (error.message) {
|
||||
errorMessage = error.message;
|
||||
}
|
||||
|
||||
showNotification('error', 'Error de validación', errorMessage);
|
||||
|
||||
// Set a failed validation state
|
||||
setUploadValidation({
|
||||
is_valid: false,
|
||||
total_records: 0,
|
||||
valid_records: 0,
|
||||
invalid_records: 0,
|
||||
errors: [{ message: errorMessage }],
|
||||
warnings: [],
|
||||
summary: { validation_failed: true }
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleFinalSubmit = () => {
|
||||
showNotification('success', '¡Configuración completa!', 'Tu sistema está listo para usar.');
|
||||
setTimeout(() => {
|
||||
// Navigate to dashboard
|
||||
window.location.href = '/dashboard';
|
||||
}, 2000);
|
||||
};
|
||||
|
||||
const renderStepIndicator = () => (
|
||||
<div className="mb-12">
|
||||
<div className="flex items-center justify-between">
|
||||
|
||||
Reference in New Issue
Block a user