feat: Add full API integration to Sales Entry and Supplier wizards
Sales Entry Wizard: - Implemented complete file upload functionality with validation - Added CSV template download via salesService.downloadImportTemplate() - File validation before import via salesService.validateImportFile() - Bulk import via salesService.importSalesData() - Manual entry saves via salesService.createSalesRecord() - Removed all mock data and console.log - Added comprehensive error handling and loading states Supplier Wizard: - Replaced mock ingredients with inventoryService.getIngredients() - Added real-time ingredient fetching with loading states - Supplier creation via suppliersService.createSupplier() - Price list creation via suppliersService.createSupplierPriceList() - Removed all mock data and console.log - Added comprehensive error handling Both wizards now fully integrated with backend APIs.
This commit is contained in:
@@ -11,7 +11,11 @@ import {
|
||||
DollarSign,
|
||||
Package,
|
||||
CreditCard,
|
||||
Loader2,
|
||||
X,
|
||||
} from 'lucide-react';
|
||||
import { useTenant } from '../../../../stores/tenant.store';
|
||||
import { salesService } from '../../../../api/services/sales';
|
||||
|
||||
// ========================================
|
||||
// STEP 1: Entry Method Selection
|
||||
@@ -394,10 +398,90 @@ const ManualEntryStep: React.FC<EntryMethodStepProps> = ({ data, onDataChange, o
|
||||
};
|
||||
|
||||
// ========================================
|
||||
// STEP 2b: File Upload (Placeholder for now)
|
||||
// STEP 2b: File Upload
|
||||
// ========================================
|
||||
|
||||
const FileUploadStep: React.FC<EntryMethodStepProps> = ({ data, onDataChange, onNext }) => {
|
||||
const { currentTenant } = useTenant();
|
||||
const [file, setFile] = useState<File | null>(data.uploadedFile || null);
|
||||
const [validating, setValidating] = useState(false);
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [validationResult, setValidationResult] = useState<any>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [downloadingTemplate, setDownloadingTemplate] = useState(false);
|
||||
|
||||
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const selectedFile = e.target.files?.[0];
|
||||
if (selectedFile) {
|
||||
setFile(selectedFile);
|
||||
setValidationResult(null);
|
||||
setError(null);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRemoveFile = () => {
|
||||
setFile(null);
|
||||
setValidationResult(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const handleValidate = async () => {
|
||||
if (!file || !currentTenant?.id) return;
|
||||
|
||||
setValidating(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await salesService.validateImportFile(currentTenant.id, file);
|
||||
setValidationResult(result);
|
||||
} catch (err: any) {
|
||||
console.error('Error validating file:', err);
|
||||
setError(err.response?.data?.detail || 'Error al validar el archivo');
|
||||
} finally {
|
||||
setValidating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImport = async () => {
|
||||
if (!file || !currentTenant?.id) return;
|
||||
|
||||
setImporting(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await salesService.importSalesData(currentTenant.id, file, false);
|
||||
onDataChange({ ...data, uploadedFile: file, importResult: result });
|
||||
onNext();
|
||||
} catch (err: any) {
|
||||
console.error('Error importing file:', err);
|
||||
setError(err.response?.data?.detail || 'Error al importar el archivo');
|
||||
} finally {
|
||||
setImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDownloadTemplate = async () => {
|
||||
if (!currentTenant?.id) return;
|
||||
|
||||
setDownloadingTemplate(true);
|
||||
try {
|
||||
const blob = await salesService.downloadImportTemplate(currentTenant.id);
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'plantilla_ventas.csv';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
document.body.removeChild(a);
|
||||
} catch (err: any) {
|
||||
console.error('Error downloading template:', err);
|
||||
setError('Error al descargar la plantilla');
|
||||
} finally {
|
||||
setDownloadingTemplate(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="text-center pb-4 border-b border-[var(--border-primary)]">
|
||||
@@ -409,34 +493,144 @@ const FileUploadStep: React.FC<EntryMethodStepProps> = ({ data, onDataChange, on
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="text-center py-12 border-2 border-dashed border-[var(--border-secondary)] rounded-xl bg-[var(--bg-secondary)]/30">
|
||||
<FileSpreadsheet className="w-16 h-16 mx-auto mb-4 text-[var(--color-primary)]/50" />
|
||||
<h4 className="text-lg font-semibold text-[var(--text-primary)] mb-2">
|
||||
Función de Carga de Archivos
|
||||
</h4>
|
||||
<p className="text-sm text-[var(--text-secondary)] mb-6 max-w-md mx-auto">
|
||||
Esta funcionalidad avanzada incluirá:
|
||||
<br />
|
||||
• Carga de CSV/Excel
|
||||
<br />
|
||||
• Mapeo de columnas
|
||||
<br />
|
||||
• Validación de datos
|
||||
<br />
|
||||
• Importación masiva
|
||||
</p>
|
||||
<div className="flex gap-3 justify-center">
|
||||
<button className="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-lg hover:bg-[var(--bg-secondary)] transition-colors inline-flex items-center gap-2">
|
||||
<Download className="w-4 h-4" />
|
||||
Descargar Plantilla CSV
|
||||
</button>
|
||||
<button
|
||||
onClick={onNext}
|
||||
className="px-6 py-2 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary)]/90 transition-colors"
|
||||
>
|
||||
Continuar (Demo)
|
||||
</button>
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm flex items-start gap-2">
|
||||
<AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Download Template Button */}
|
||||
<div className="flex justify-center">
|
||||
<button
|
||||
onClick={handleDownloadTemplate}
|
||||
disabled={downloadingTemplate}
|
||||
className="px-4 py-2 border border-[var(--border-secondary)] text-[var(--text-secondary)] rounded-lg hover:bg-[var(--bg-secondary)] transition-colors inline-flex items-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
{downloadingTemplate ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Descargando...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download className="w-4 h-4" />
|
||||
Descargar Plantilla CSV
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* File Upload Area */}
|
||||
{!file ? (
|
||||
<div className="border-2 border-dashed border-[var(--border-secondary)] rounded-xl p-8 text-center bg-[var(--bg-secondary)]/30">
|
||||
<FileSpreadsheet className="w-16 h-16 mx-auto mb-4 text-[var(--color-primary)]/50" />
|
||||
<h4 className="text-lg font-semibold text-[var(--text-primary)] mb-2">
|
||||
Arrastra un archivo aquí
|
||||
</h4>
|
||||
<p className="text-sm text-[var(--text-secondary)] mb-4">
|
||||
o haz clic para seleccionar
|
||||
</p>
|
||||
<label className="inline-block">
|
||||
<input
|
||||
type="file"
|
||||
accept=".csv,.xlsx,.xls"
|
||||
onChange={handleFileSelect}
|
||||
className="hidden"
|
||||
/>
|
||||
<span className="px-6 py-2 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary)]/90 transition-colors cursor-pointer inline-block">
|
||||
Seleccionar Archivo
|
||||
</span>
|
||||
</label>
|
||||
<p className="text-xs text-[var(--text-tertiary)] mt-3">
|
||||
Formatos soportados: CSV, Excel (.xlsx, .xls)
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="border border-[var(--border-secondary)] rounded-lg p-4 bg-[var(--bg-primary)]">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<FileSpreadsheet className="w-8 h-8 text-[var(--color-primary)]" />
|
||||
<div>
|
||||
<p className="font-medium text-[var(--text-primary)]">{file.name}</p>
|
||||
<p className="text-sm text-[var(--text-secondary)]">
|
||||
{(file.size / 1024).toFixed(2)} KB
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleRemoveFile}
|
||||
className="p-1 text-red-500 hover:text-red-700 transition-colors"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Validation Result */}
|
||||
{validationResult && (
|
||||
<div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
|
||||
<p className="text-sm text-blue-800 font-medium mb-2">
|
||||
✓ Archivo validado correctamente
|
||||
</p>
|
||||
<div className="text-xs text-blue-700 space-y-1">
|
||||
<p>Registros encontrados: {validationResult.total_rows || 0}</p>
|
||||
<p>Registros válidos: {validationResult.valid_rows || 0}</p>
|
||||
{validationResult.errors?.length > 0 && (
|
||||
<p className="text-red-600">
|
||||
Errores: {validationResult.errors.length}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="mt-4 flex gap-3">
|
||||
{!validationResult && (
|
||||
<button
|
||||
onClick={handleValidate}
|
||||
disabled={validating}
|
||||
className="flex-1 px-4 py-2 border border-[var(--color-primary)] text-[var(--color-primary)] rounded-lg hover:bg-[var(--color-primary)]/5 transition-colors inline-flex items-center justify-center gap-2 disabled:opacity-50"
|
||||
>
|
||||
{validating ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Validando...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle2 className="w-4 h-4" />
|
||||
Validar Archivo
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={handleImport}
|
||||
disabled={importing || !validationResult}
|
||||
className="flex-1 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors inline-flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{importing ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
Importando...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="w-4 h-4" />
|
||||
Importar Datos
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-center text-sm text-[var(--text-tertiary)]">
|
||||
<p>El archivo debe contener las columnas:</p>
|
||||
<p className="font-mono text-xs mt-1">
|
||||
fecha, producto, cantidad, precio_unitario, método_pago
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -447,13 +641,51 @@ const FileUploadStep: React.FC<EntryMethodStepProps> = ({ data, onDataChange, on
|
||||
// ========================================
|
||||
|
||||
const ReviewStep: React.FC<EntryMethodStepProps> = ({ data, onComplete }) => {
|
||||
const handleConfirm = () => {
|
||||
// Here you would typically make an API call to save the data
|
||||
console.log('Saving sales data:', data);
|
||||
onComplete();
|
||||
const { currentTenant } = useTenant();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleConfirm = async () => {
|
||||
if (!currentTenant?.id) {
|
||||
setError('No se pudo obtener información del tenant');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (data.entryMethod === 'manual' && data.salesItems) {
|
||||
// Create individual sales records for each item
|
||||
for (const item of data.salesItems) {
|
||||
const salesData = {
|
||||
product_name: item.product,
|
||||
product_category: 'general', // Could be enhanced with category selection
|
||||
quantity_sold: item.quantity,
|
||||
unit_price: item.unitPrice,
|
||||
total_amount: item.subtotal,
|
||||
sale_date: data.saleDate,
|
||||
sales_channel: 'retail',
|
||||
source: 'manual',
|
||||
payment_method: data.paymentMethod,
|
||||
notes: data.notes,
|
||||
};
|
||||
|
||||
await salesService.createSalesRecord(currentTenant.id, salesData);
|
||||
}
|
||||
}
|
||||
|
||||
onComplete();
|
||||
} catch (err: any) {
|
||||
console.error('Error saving sales data:', err);
|
||||
setError(err.response?.data?.detail || 'Error al guardar los datos de ventas');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const isManual = data.entryMethod === 'manual';
|
||||
const isUpload = data.entryMethod === 'upload';
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -471,6 +703,13 @@ const ReviewStep: React.FC<EntryMethodStepProps> = ({ data, onComplete }) => {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm flex items-start gap-2">
|
||||
<AlertCircle className="w-4 h-4 mt-0.5 flex-shrink-0" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isManual && data.salesItems && (
|
||||
<div className="space-y-4">
|
||||
{/* Summary */}
|
||||
@@ -536,14 +775,38 @@ const ReviewStep: React.FC<EntryMethodStepProps> = ({ data, onComplete }) => {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isUpload && data.importResult && (
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 bg-green-50 border border-green-200 rounded-lg">
|
||||
<p className="text-green-800 font-semibold mb-2">
|
||||
✓ Archivo importado correctamente
|
||||
</p>
|
||||
<div className="text-sm text-green-700 space-y-1">
|
||||
<p>Registros importados: {data.importResult.successful_imports || 0}</p>
|
||||
<p>Registros fallidos: {data.importResult.failed_imports || 0}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Confirm Button */}
|
||||
<div className="flex justify-end gap-3 pt-4 border-t border-[var(--border-primary)]">
|
||||
<button
|
||||
onClick={handleConfirm}
|
||||
className="px-8 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-semibold inline-flex items-center gap-2"
|
||||
disabled={loading || (isUpload && !data.importResult)}
|
||||
className="px-8 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors font-semibold inline-flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<CheckCircle2 className="w-5 h-5" />
|
||||
Confirmar y Guardar
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
Guardando...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle2 className="w-5 h-5" />
|
||||
Confirmar y Guardar
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user