Add supplier and imporve inventory frontend

This commit is contained in:
Urtzi Alfaro
2025-09-18 23:32:53 +02:00
parent ae77a0e1c5
commit d61056df33
40 changed files with 2022 additions and 629 deletions

View File

@@ -1,8 +1,11 @@
import React, { useState } from 'react';
import { Plus, Package, Euro, Calendar, FileText, Thermometer } from 'lucide-react';
import { StatusModal } from '../../ui/StatusModal/StatusModal';
import { IngredientResponse, StockCreate } from '../../../api/types/inventory';
import { IngredientResponse, StockCreate, ProductionStage } from '../../../api/types/inventory';
import { Button } from '../../ui/Button';
import { useSuppliers } from '../../../api/hooks/suppliers';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { useInventoryEnums } from '../../../utils/inventoryEnumHelpers';
import { statusColors } from '../../../styles/colors';
interface AddStockModalProps {
@@ -27,11 +30,14 @@ export const AddStockModal: React.FC<AddStockModalProps> = ({
current_quantity: 0,
unit_cost: Number(ingredient.average_cost) || 0,
expiration_date: '',
production_stage: ProductionStage.RAW_INGREDIENT,
batch_number: '',
supplier_id: '',
quality_status: 'good',
storage_location: '',
requires_refrigeration: false,
requires_freezing: false,
warehouse_zone: '',
requires_refrigeration: 'no',
requires_freezing: 'no',
storage_temperature_min: undefined,
storage_temperature_max: undefined,
storage_humidity_max: undefined,
@@ -43,12 +49,82 @@ export const AddStockModal: React.FC<AddStockModalProps> = ({
const [loading, setLoading] = useState(false);
const [mode, setMode] = useState<'overview' | 'edit'>('edit');
// Get current tenant and fetch suppliers
const currentTenant = useCurrentTenant();
const tenantId = currentTenant?.id || '';
const { data: suppliersData } = useSuppliers(tenantId, {
limit: 100
}, {
enabled: !!tenantId
});
const suppliers = (suppliersData || []).filter(supplier => supplier.status === 'active');
// Get inventory enum helpers
const inventoryEnums = useInventoryEnums();
// Create supplier options for select
const supplierOptions = [
{ value: '', label: 'Sin proveedor asignado' },
...suppliers.map(supplier => ({
value: supplier.id,
label: `${supplier.name} (${supplier.supplier_code || 'Sin código'})`
}))
];
// Create quality status options
const qualityStatusOptions = [
{ value: 'good', label: 'Bueno' },
{ value: 'damaged', label: 'Dañado' },
{ value: 'expired', label: 'Vencido' },
{ value: 'returned', label: 'Devuelto' }
];
// Create storage location options (predefined common locations)
const storageLocationOptions = [
{ value: '', label: 'Sin ubicación específica' },
{ value: 'estante-a1', label: 'Estante A-1' },
{ value: 'estante-a2', label: 'Estante A-2' },
{ value: 'estante-a3', label: 'Estante A-3' },
{ value: 'estante-b1', label: 'Estante B-1' },
{ value: 'estante-b2', label: 'Estante B-2' },
{ value: 'frigorifico', label: 'Frigorífico' },
{ value: 'congelador', label: 'Congelador' },
{ value: 'almacen-principal', label: 'Almacén Principal' },
{ value: 'zona-recepcion', label: 'Zona de Recepción' }
];
// Create warehouse zone options
const warehouseZoneOptions = [
{ value: '', label: 'Sin zona específica' },
{ value: 'zona-a', label: 'Zona A' },
{ value: 'zona-b', label: 'Zona B' },
{ value: 'zona-c', label: 'Zona C' },
{ value: 'refrigerado', label: 'Refrigerado' },
{ value: 'congelado', label: 'Congelado' },
{ value: 'ambiente', label: 'Temperatura Ambiente' }
];
// Create refrigeration requirement options
const refrigerationOptions = [
{ value: 'no', label: 'No requiere refrigeración' },
{ value: 'yes', label: 'Requiere refrigeración' },
{ value: 'recommended', label: 'Refrigeración recomendada' }
];
// Create freezing requirement options
const freezingOptions = [
{ value: 'no', label: 'No requiere congelación' },
{ value: 'yes', label: 'Requiere congelación' },
{ value: 'recommended', label: 'Congelación recomendada' }
];
const handleFieldChange = (sectionIndex: number, fieldIndex: number, value: string | number | boolean) => {
const fieldMappings = [
// Basic Stock Information section
['current_quantity', 'unit_cost', 'expiration_date'],
['current_quantity', 'unit_cost', 'expiration_date', 'production_stage'],
// Additional Information section
['batch_number', 'supplier_id', 'storage_location', 'notes'],
['batch_number', 'supplier_id', 'quality_status', 'storage_location', 'warehouse_zone', 'notes'],
// Storage Requirements section
['requires_refrigeration', 'requires_freezing', 'storage_temperature_min', 'storage_temperature_max', 'storage_humidity_max', 'shelf_life_days', 'storage_instructions']
];
@@ -80,11 +156,14 @@ export const AddStockModal: React.FC<AddStockModalProps> = ({
current_quantity: Number(formData.current_quantity),
unit_cost: Number(formData.unit_cost),
expiration_date: formData.expiration_date || undefined,
production_stage: formData.production_stage || ProductionStage.RAW_INGREDIENT,
batch_number: formData.batch_number || undefined,
supplier_id: formData.supplier_id || undefined,
quality_status: formData.quality_status || 'good',
storage_location: formData.storage_location || undefined,
requires_refrigeration: formData.requires_refrigeration || false,
requires_freezing: formData.requires_freezing || false,
warehouse_zone: formData.warehouse_zone || undefined,
requires_refrigeration: formData.requires_refrigeration === 'yes',
requires_freezing: formData.requires_freezing === 'yes',
storage_temperature_min: formData.storage_temperature_min ? Number(formData.storage_temperature_min) : undefined,
storage_temperature_max: formData.storage_temperature_max ? Number(formData.storage_temperature_max) : undefined,
storage_humidity_max: formData.storage_humidity_max ? Number(formData.storage_humidity_max) : undefined,
@@ -103,11 +182,14 @@ export const AddStockModal: React.FC<AddStockModalProps> = ({
current_quantity: 0,
unit_cost: Number(ingredient.average_cost) || 0,
expiration_date: '',
production_stage: ProductionStage.RAW_INGREDIENT,
batch_number: '',
supplier_id: '',
quality_status: 'good',
storage_location: '',
requires_refrigeration: false,
requires_freezing: false,
warehouse_zone: '',
requires_refrigeration: 'no',
requires_freezing: 'no',
storage_temperature_min: undefined,
storage_temperature_max: undefined,
storage_humidity_max: undefined,
@@ -162,8 +244,14 @@ export const AddStockModal: React.FC<AddStockModalProps> = ({
label: 'Fecha de Vencimiento',
value: formData.expiration_date || '',
type: 'date' as const,
editable: true
},
{
label: 'Etapa de Producción',
value: formData.production_stage || ProductionStage.RAW_INGREDIENT,
type: 'select' as const,
editable: true,
span: 2 as const
options: inventoryEnums.getProductionStageOptions()
}
]
},
@@ -179,19 +267,35 @@ export const AddStockModal: React.FC<AddStockModalProps> = ({
placeholder: 'Ej: LOTE2024001'
},
{
label: 'ID Proveedor',
label: 'Proveedor',
value: formData.supplier_id || '',
type: 'text' as const,
type: 'select' as const,
editable: true,
placeholder: 'Ej: PROV001'
placeholder: 'Seleccionar proveedor',
options: supplierOptions
},
{
label: 'Estado de Calidad',
value: formData.quality_status || 'good',
type: 'select' as const,
editable: true,
options: qualityStatusOptions
},
{
label: 'Ubicación de Almacenamiento',
value: formData.storage_location || '',
type: 'text' as const,
type: 'select' as const,
editable: true,
placeholder: 'Ej: Estante A-3',
span: 2 as const
placeholder: 'Seleccionar ubicación',
options: storageLocationOptions
},
{
label: 'Zona de Almacén',
value: formData.warehouse_zone || '',
type: 'select' as const,
editable: true,
placeholder: 'Seleccionar zona',
options: warehouseZoneOptions
},
{
label: 'Notas',
@@ -209,15 +313,17 @@ export const AddStockModal: React.FC<AddStockModalProps> = ({
fields: [
{
label: 'Requiere Refrigeración',
value: formData.requires_refrigeration || false,
type: 'boolean' as const,
editable: true
value: formData.requires_refrigeration || 'no',
type: 'select' as const,
editable: true,
options: refrigerationOptions
},
{
label: 'Requiere Congelación',
value: formData.requires_freezing || false,
type: 'boolean' as const,
editable: true
value: formData.requires_freezing || 'no',
type: 'select' as const,
editable: true,
options: freezingOptions
},
{
label: 'Temperatura Mínima (°C)',

View File

@@ -2,6 +2,7 @@ import React, { useState } from 'react';
import { Plus, Package, Calculator, Settings } from 'lucide-react';
import { StatusModal } from '../../ui/StatusModal/StatusModal';
import { IngredientCreate, UnitOfMeasure, IngredientCategory, ProductCategory } from '../../../api/types/inventory';
import { useInventoryEnums } from '../../../utils/inventoryEnumHelpers';
import { statusColors } from '../../../styles/colors';
interface CreateIngredientModalProps {
@@ -28,7 +29,6 @@ export const CreateIngredientModal: React.FC<CreateIngredientModalProps> = ({
reorder_point: 20,
max_stock_level: 100,
is_seasonal: false,
supplier_id: '',
average_cost: 0,
notes: ''
});
@@ -36,44 +36,16 @@ export const CreateIngredientModal: React.FC<CreateIngredientModalProps> = ({
const [loading, setLoading] = useState(false);
const [mode, setMode] = useState<'overview' | 'edit'>('edit');
// Category options combining ingredient and product categories
// Get enum options using helpers
const inventoryEnums = useInventoryEnums();
// Combine ingredient and product categories
const categoryOptions = [
// Ingredient categories
{ label: 'Harinas', value: 'flour' },
{ label: 'Levaduras', value: 'yeast' },
{ label: 'Lácteos', value: 'dairy' },
{ label: 'Huevos', value: 'eggs' },
{ label: 'Azúcar', value: 'sugar' },
{ label: 'Grasas', value: 'fats' },
{ label: 'Sal', value: 'salt' },
{ label: 'Especias', value: 'spices' },
{ label: 'Aditivos', value: 'additives' },
{ label: 'Envases', value: 'packaging' },
{ label: 'Limpieza', value: 'cleaning' },
// Product categories
{ label: 'Pan', value: 'bread' },
{ label: 'Croissants', value: 'croissants' },
{ label: 'Pastelería', value: 'pastries' },
{ label: 'Tartas', value: 'cakes' },
{ label: 'Galletas', value: 'cookies' },
{ label: 'Muffins', value: 'muffins' },
{ label: 'Sandwiches', value: 'sandwiches' },
{ label: 'Temporada', value: 'seasonal' },
{ label: 'Bebidas', value: 'beverages' },
{ label: 'Otros', value: 'other' }
...inventoryEnums.getIngredientCategoryOptions(),
...inventoryEnums.getProductCategoryOptions()
];
const unitOptions = [
{ label: 'Kilogramo (kg)', value: 'kg' },
{ label: 'Gramo (g)', value: 'g' },
{ label: 'Litro (l)', value: 'l' },
{ label: 'Mililitro (ml)', value: 'ml' },
{ label: 'Unidades', value: 'units' },
{ label: 'Piezas', value: 'pcs' },
{ label: 'Paquetes', value: 'pkg' },
{ label: 'Bolsas', value: 'bags' },
{ label: 'Cajas', value: 'boxes' }
];
const unitOptions = inventoryEnums.getUnitOfMeasureOptions();
const handleFieldChange = (sectionIndex: number, fieldIndex: number, value: string | number | boolean) => {
// Map field positions to form data fields
@@ -82,8 +54,8 @@ export const CreateIngredientModal: React.FC<CreateIngredientModalProps> = ({
['name', 'description', 'category', 'unit_of_measure'],
// Cost and Quantities section
['average_cost', 'low_stock_threshold', 'reorder_point', 'max_stock_level'],
// Additional Information section (moved up after removing storage section)
['supplier_id', 'notes']
// Additional Information section
['notes']
];
const fieldName = fieldMappings[sectionIndex]?.[fieldIndex] as keyof IngredientCreate;
@@ -146,7 +118,6 @@ export const CreateIngredientModal: React.FC<CreateIngredientModalProps> = ({
requires_refrigeration: false,
requires_freezing: false,
is_seasonal: false,
supplier_id: '',
average_cost: 0,
notes: ''
});
@@ -174,7 +145,6 @@ export const CreateIngredientModal: React.FC<CreateIngredientModalProps> = ({
requires_refrigeration: false,
requires_freezing: false,
is_seasonal: false,
supplier_id: '',
average_cost: 0,
notes: ''
});
@@ -234,7 +204,7 @@ export const CreateIngredientModal: React.FC<CreateIngredientModalProps> = ({
{
label: 'Costo Promedio',
value: formData.average_cost || 0,
type: 'number' as const,
type: 'currency' as const,
editable: true,
placeholder: '0.00'
},
@@ -267,13 +237,6 @@ export const CreateIngredientModal: React.FC<CreateIngredientModalProps> = ({
title: 'Información Adicional',
icon: Settings,
fields: [
{
label: 'Proveedor',
value: formData.supplier_id || '',
type: 'text' as const,
editable: true,
placeholder: 'ID o nombre del proveedor'
},
{
label: 'Notas',
value: formData.notes || '',

View File

@@ -0,0 +1,183 @@
// frontend/src/components/domain/suppliers/CreateSupplierForm.tsx
/**
* Example usage of enum helpers with i18n in a supplier form
*/
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Select } from '../../ui/Select';
import { Button } from '../../ui/Button/Button';
import { useSupplierEnums } from '../../../utils/enumHelpers';
import { SupplierType, SupplierStatus, PaymentTerms } from '../../../api/types/suppliers';
interface CreateSupplierFormProps {
onSubmit: (data: SupplierFormData) => void;
onCancel: () => void;
}
interface SupplierFormData {
name: string;
supplier_type: SupplierType;
status: SupplierStatus;
payment_terms: PaymentTerms;
email: string;
phone: string;
}
export const CreateSupplierForm: React.FC<CreateSupplierFormProps> = ({
onSubmit,
onCancel
}) => {
const { t } = useTranslation(['suppliers', 'common']);
const supplierEnums = useSupplierEnums();
const [formData, setFormData] = useState<SupplierFormData>({
name: '',
supplier_type: SupplierType.INGREDIENTS,
status: SupplierStatus.PENDING_APPROVAL,
payment_terms: PaymentTerms.NET_30,
email: '',
phone: ''
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
onSubmit(formData);
};
const handleFieldChange = (field: keyof SupplierFormData, value: any) => {
setFormData(prev => ({
...prev,
[field]: value
}));
};
return (
<form onSubmit={handleSubmit} className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Supplier Name */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
{t('common:forms.supplier_name')} *
</label>
<input
type="text"
required
value={formData.name}
onChange={(e) => handleFieldChange('name', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder={t('common:forms.enter_supplier_name')}
/>
</div>
{/* Supplier Type - Using enum helper */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
{supplierEnums.getFieldLabel('supplier_type')} *
</label>
<Select
options={supplierEnums.getSupplierTypeOptions()}
value={formData.supplier_type}
onChange={(value) => handleFieldChange('supplier_type', value as SupplierType)}
placeholder={t('common:forms.select_option')}
helperText={supplierEnums.getFieldDescription('supplier_type')}
/>
</div>
{/* Supplier Status - Using enum helper */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
{supplierEnums.getFieldLabel('supplier_status')}
</label>
<Select
options={supplierEnums.getSupplierStatusOptions()}
value={formData.status}
onChange={(value) => handleFieldChange('status', value as SupplierStatus)}
placeholder={t('common:forms.select_option')}
/>
</div>
{/* Payment Terms - Using enum helper */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
{supplierEnums.getFieldLabel('payment_terms')} *
</label>
<Select
options={supplierEnums.getPaymentTermsOptions()}
value={formData.payment_terms}
onChange={(value) => handleFieldChange('payment_terms', value as PaymentTerms)}
placeholder={t('common:forms.select_option')}
helperText={supplierEnums.getFieldDescription('payment_terms')}
/>
</div>
{/* Email */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
{t('common:forms.email')}
</label>
<input
type="email"
value={formData.email}
onChange={(e) => handleFieldChange('email', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder={t('common:forms.enter_email')}
/>
</div>
{/* Phone */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
{t('common:forms.phone')}
</label>
<input
type="tel"
value={formData.phone}
onChange={(e) => handleFieldChange('phone', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder={t('common:forms.enter_phone')}
/>
</div>
</div>
{/* Actions */}
<div className="flex justify-end space-x-4">
<Button
type="button"
variant="secondary"
onClick={onCancel}
>
{t('common:actions.cancel')}
</Button>
<Button
type="submit"
variant="primary"
>
{t('common:actions.create')}
</Button>
</div>
{/* Display current selections for debugging */}
<div className="mt-8 p-4 bg-gray-50 rounded-md">
<h3 className="text-sm font-medium text-gray-700 mb-2">Current Selections:</h3>
<ul className="text-sm text-gray-600 space-y-1">
<li>
<strong>Tipo:</strong> {supplierEnums.getSupplierTypeLabel(formData.supplier_type)}
</li>
<li>
<strong>Estado:</strong> {supplierEnums.getSupplierStatusLabel(formData.status)}
</li>
<li>
<strong>Términos de Pago:</strong> {supplierEnums.getPaymentTermsLabel(formData.payment_terms)}
</li>
<li>
<strong>Debug - Payment Terms Raw:</strong> {formData.payment_terms}
</li>
<li>
<strong>Debug - Translation Test:</strong> {t('suppliers:payment_terms.net_30')}
</li>
</ul>
</div>
</form>
);
};

View File

@@ -227,10 +227,6 @@ export const StatusCard: React.FC<StatusCardProps> = ({
</div>
)}
{/* Spacer for alignment when no progress bar */}
{!progress && (
<div className="h-12" />
)}
{/* Metadata */}
{metadata.length > 0 && (