ADD new frontend
This commit is contained in:
756
frontend/src/components/domain/inventory/InventoryForm.tsx
Normal file
756
frontend/src/components/domain/inventory/InventoryForm.tsx
Normal file
@@ -0,0 +1,756 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { clsx } from 'clsx';
|
||||
import { Button } from '../../ui';
|
||||
import { Input } from '../../ui';
|
||||
import { Select } from '../../ui';
|
||||
import { Card } from '../../ui';
|
||||
import { Badge } from '../../ui';
|
||||
import { Modal } from '../../ui';
|
||||
import { IngredientFormData, UnitOfMeasure, ProductType, IngredientResponse } from '../../../types/inventory.types';
|
||||
import { inventoryService } from '../../../services/api/inventory.service';
|
||||
|
||||
export interface InventoryFormProps {
|
||||
item?: IngredientResponse;
|
||||
open?: boolean;
|
||||
onClose?: () => void;
|
||||
onSubmit?: (data: IngredientFormData) => Promise<void>;
|
||||
onClassify?: (name: string, description?: string) => Promise<any>;
|
||||
loading?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
// Spanish bakery categories with subcategories
|
||||
const BAKERY_CATEGORIES = {
|
||||
harinas: {
|
||||
label: 'Harinas',
|
||||
subcategories: ['Harina de trigo', 'Harina integral', 'Harina de fuerza', 'Harina de maíz', 'Harina de centeno', 'Harina sin gluten']
|
||||
},
|
||||
levaduras: {
|
||||
label: 'Levaduras',
|
||||
subcategories: ['Levadura fresca', 'Levadura seca', 'Levadura química', 'Masa madre', 'Levadura instantánea']
|
||||
},
|
||||
azucares: {
|
||||
label: 'Azúcares y Endulzantes',
|
||||
subcategories: ['Azúcar blanco', 'Azúcar moreno', 'Azúcar glass', 'Miel', 'Jarabe de arce', 'Stevia', 'Azúcar invertido']
|
||||
},
|
||||
chocolates: {
|
||||
label: 'Chocolates y Cacao',
|
||||
subcategories: ['Chocolate negro', 'Chocolate con leche', 'Chocolate blanco', 'Cacao en polvo', 'Pepitas de chocolate', 'Cobertura']
|
||||
},
|
||||
frutas: {
|
||||
label: 'Frutas y Frutos Secos',
|
||||
subcategories: ['Almendras', 'Nueces', 'Pasas', 'Fruta confitada', 'Mermeladas', 'Frutas frescas', 'Frutos del bosque']
|
||||
},
|
||||
lacteos: {
|
||||
label: 'Lácteos',
|
||||
subcategories: ['Leche entera', 'Leche desnatada', 'Nata', 'Queso mascarpone', 'Yogur', 'Suero de leche']
|
||||
},
|
||||
huevos: {
|
||||
label: 'Huevos',
|
||||
subcategories: ['Huevos frescos', 'Clara de huevo', 'Yema de huevo', 'Huevo pasteurizado']
|
||||
},
|
||||
mantequillas: {
|
||||
label: 'Mantequillas y Grasas',
|
||||
subcategories: ['Mantequilla', 'Margarina', 'Aceite de girasol', 'Aceite de oliva', 'Manteca']
|
||||
},
|
||||
especias: {
|
||||
label: 'Especias y Aromas',
|
||||
subcategories: ['Vainilla', 'Canela', 'Cardamomo', 'Esencias', 'Colorantes', 'Sal', 'Bicarbonato']
|
||||
},
|
||||
conservantes: {
|
||||
label: 'Conservantes y Aditivos',
|
||||
subcategories: ['Ácido ascórbico', 'Lecitina', 'Emulgentes', 'Estabilizantes', 'Antioxidantes']
|
||||
},
|
||||
decoracion: {
|
||||
label: 'Decoración',
|
||||
subcategories: ['Fondant', 'Pasta de goma', 'Perlas de azúcar', 'Sprinkles', 'Moldes', 'Papel comestible']
|
||||
},
|
||||
envases: {
|
||||
label: 'Envases y Embalajes',
|
||||
subcategories: ['Cajas de cartón', 'Bolsas', 'Papel encerado', 'Film transparente', 'Etiquetas']
|
||||
},
|
||||
utensilios: {
|
||||
label: 'Utensilios y Equipos',
|
||||
subcategories: ['Moldes', 'Boquillas', 'Espátulas', 'Batidores', 'Termómetros']
|
||||
},
|
||||
limpieza: {
|
||||
label: 'Limpieza e Higiene',
|
||||
subcategories: ['Detergentes', 'Desinfectantes', 'Guantes', 'Paños', 'Productos sanitarios']
|
||||
},
|
||||
};
|
||||
|
||||
const UNITS_OF_MEASURE = [
|
||||
{ value: UnitOfMeasure.KILOGRAM, label: 'Kilogramo (kg)' },
|
||||
{ value: UnitOfMeasure.GRAM, label: 'Gramo (g)' },
|
||||
{ value: UnitOfMeasure.LITER, label: 'Litro (l)' },
|
||||
{ value: UnitOfMeasure.MILLILITER, label: 'Mililitro (ml)' },
|
||||
{ value: UnitOfMeasure.PIECE, label: 'Pieza (pz)' },
|
||||
{ value: UnitOfMeasure.PACKAGE, label: 'Paquete' },
|
||||
{ value: UnitOfMeasure.BAG, label: 'Bolsa' },
|
||||
{ value: UnitOfMeasure.BOX, label: 'Caja' },
|
||||
{ value: UnitOfMeasure.DOZEN, label: 'Docena' },
|
||||
{ value: UnitOfMeasure.CUP, label: 'Taza' },
|
||||
{ value: UnitOfMeasure.TABLESPOON, label: 'Cucharada' },
|
||||
{ value: UnitOfMeasure.TEASPOON, label: 'Cucharadita' },
|
||||
{ value: UnitOfMeasure.POUND, label: 'Libra (lb)' },
|
||||
{ value: UnitOfMeasure.OUNCE, label: 'Onza (oz)' },
|
||||
];
|
||||
|
||||
const PRODUCT_TYPES = [
|
||||
{ value: ProductType.INGREDIENT, label: 'Ingrediente' },
|
||||
{ value: ProductType.FINISHED_PRODUCT, label: 'Producto Terminado' },
|
||||
];
|
||||
|
||||
const initialFormData: IngredientFormData = {
|
||||
name: '',
|
||||
product_type: ProductType.INGREDIENT,
|
||||
sku: '',
|
||||
barcode: '',
|
||||
category: '',
|
||||
subcategory: '',
|
||||
description: '',
|
||||
brand: '',
|
||||
unit_of_measure: UnitOfMeasure.KILOGRAM,
|
||||
package_size: undefined,
|
||||
standard_cost: undefined,
|
||||
low_stock_threshold: 10,
|
||||
reorder_point: 20,
|
||||
reorder_quantity: 50,
|
||||
max_stock_level: undefined,
|
||||
requires_refrigeration: false,
|
||||
requires_freezing: false,
|
||||
storage_temperature_min: undefined,
|
||||
storage_temperature_max: undefined,
|
||||
storage_humidity_max: undefined,
|
||||
shelf_life_days: undefined,
|
||||
storage_instructions: '',
|
||||
is_perishable: false,
|
||||
allergen_info: {},
|
||||
};
|
||||
|
||||
export const InventoryForm: React.FC<InventoryFormProps> = ({
|
||||
item,
|
||||
open = false,
|
||||
onClose,
|
||||
onSubmit,
|
||||
onClassify,
|
||||
loading = false,
|
||||
className,
|
||||
}) => {
|
||||
const [formData, setFormData] = useState<IngredientFormData>(initialFormData);
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
const [classificationSuggestions, setClassificationSuggestions] = useState<any>(null);
|
||||
const [showClassificationModal, setShowClassificationModal] = useState(false);
|
||||
const [classifying, setClassifying] = useState(false);
|
||||
const [imageFile, setImageFile] = useState<File | null>(null);
|
||||
const [imagePreview, setImagePreview] = useState<string | null>(null);
|
||||
|
||||
const isEditing = !!item;
|
||||
|
||||
// Initialize form data when item changes
|
||||
useEffect(() => {
|
||||
if (item) {
|
||||
setFormData({
|
||||
name: item.name,
|
||||
product_type: item.product_type,
|
||||
sku: item.sku || '',
|
||||
barcode: item.barcode || '',
|
||||
category: item.category || '',
|
||||
subcategory: item.subcategory || '',
|
||||
description: item.description || '',
|
||||
brand: item.brand || '',
|
||||
unit_of_measure: item.unit_of_measure,
|
||||
package_size: item.package_size,
|
||||
standard_cost: item.standard_cost,
|
||||
low_stock_threshold: item.low_stock_threshold,
|
||||
reorder_point: item.reorder_point,
|
||||
reorder_quantity: item.reorder_quantity,
|
||||
max_stock_level: item.max_stock_level,
|
||||
requires_refrigeration: item.requires_refrigeration,
|
||||
requires_freezing: item.requires_freezing,
|
||||
storage_temperature_min: item.storage_temperature_min,
|
||||
storage_temperature_max: item.storage_temperature_max,
|
||||
storage_humidity_max: item.storage_humidity_max,
|
||||
shelf_life_days: item.shelf_life_days,
|
||||
storage_instructions: item.storage_instructions || '',
|
||||
is_perishable: item.is_perishable,
|
||||
allergen_info: item.allergen_info || {},
|
||||
});
|
||||
} else {
|
||||
setFormData(initialFormData);
|
||||
}
|
||||
setErrors({});
|
||||
setClassificationSuggestions(null);
|
||||
}, [item]);
|
||||
|
||||
// Handle input changes
|
||||
const handleInputChange = useCallback((field: keyof IngredientFormData, value: any) => {
|
||||
setFormData(prev => ({ ...prev, [field]: value }));
|
||||
// Clear error for this field
|
||||
if (errors[field]) {
|
||||
setErrors(prev => ({ ...prev, [field]: '' }));
|
||||
}
|
||||
}, [errors]);
|
||||
|
||||
// Handle image upload
|
||||
const handleImageUpload = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (file) {
|
||||
setImageFile(file);
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => setImagePreview(reader.result as string);
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Auto-classify product
|
||||
const handleClassifyProduct = useCallback(async () => {
|
||||
if (!formData.name.trim()) return;
|
||||
|
||||
setClassifying(true);
|
||||
try {
|
||||
const suggestions = await onClassify?.(formData.name, formData.description);
|
||||
if (suggestions) {
|
||||
setClassificationSuggestions(suggestions);
|
||||
setShowClassificationModal(true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Classification failed:', error);
|
||||
} finally {
|
||||
setClassifying(false);
|
||||
}
|
||||
}, [formData.name, formData.description, onClassify]);
|
||||
|
||||
// Apply classification suggestions
|
||||
const handleApplyClassification = useCallback(() => {
|
||||
if (!classificationSuggestions) return;
|
||||
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
category: classificationSuggestions.category || prev.category,
|
||||
subcategory: classificationSuggestions.subcategory || prev.subcategory,
|
||||
unit_of_measure: classificationSuggestions.suggested_unit || prev.unit_of_measure,
|
||||
is_perishable: classificationSuggestions.is_perishable ?? prev.is_perishable,
|
||||
requires_refrigeration: classificationSuggestions.storage_requirements?.requires_refrigeration ?? prev.requires_refrigeration,
|
||||
requires_freezing: classificationSuggestions.storage_requirements?.requires_freezing ?? prev.requires_freezing,
|
||||
shelf_life_days: classificationSuggestions.storage_requirements?.estimated_shelf_life_days || prev.shelf_life_days,
|
||||
}));
|
||||
|
||||
setShowClassificationModal(false);
|
||||
}, [classificationSuggestions]);
|
||||
|
||||
// Validate form
|
||||
const validateForm = useCallback((): boolean => {
|
||||
const newErrors: Record<string, string> = {};
|
||||
|
||||
if (!formData.name.trim()) {
|
||||
newErrors.name = 'El nombre es obligatorio';
|
||||
}
|
||||
|
||||
if (!formData.unit_of_measure) {
|
||||
newErrors.unit_of_measure = 'La unidad de medida es obligatoria';
|
||||
}
|
||||
|
||||
if (formData.low_stock_threshold < 0) {
|
||||
newErrors.low_stock_threshold = 'El stock mínimo no puede ser negativo';
|
||||
}
|
||||
|
||||
if (formData.reorder_point < 0) {
|
||||
newErrors.reorder_point = 'El punto de reorden no puede ser negativo';
|
||||
}
|
||||
|
||||
if (formData.reorder_quantity < 0) {
|
||||
newErrors.reorder_quantity = 'La cantidad de reorden no puede ser negativa';
|
||||
}
|
||||
|
||||
if (formData.max_stock_level !== undefined && formData.max_stock_level < formData.low_stock_threshold) {
|
||||
newErrors.max_stock_level = 'El stock máximo debe ser mayor que el mínimo';
|
||||
}
|
||||
|
||||
if (formData.standard_cost !== undefined && formData.standard_cost < 0) {
|
||||
newErrors.standard_cost = 'El precio no puede ser negativo';
|
||||
}
|
||||
|
||||
if (formData.package_size !== undefined && formData.package_size <= 0) {
|
||||
newErrors.package_size = 'El tamaño del paquete debe ser mayor que 0';
|
||||
}
|
||||
|
||||
if (formData.shelf_life_days !== undefined && formData.shelf_life_days <= 0) {
|
||||
newErrors.shelf_life_days = 'La vida útil debe ser mayor que 0';
|
||||
}
|
||||
|
||||
setErrors(newErrors);
|
||||
return Object.keys(newErrors).length === 0;
|
||||
}, [formData]);
|
||||
|
||||
// Handle form submission
|
||||
const handleSubmit = useCallback(async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!validateForm()) return;
|
||||
|
||||
try {
|
||||
await onSubmit?.(formData);
|
||||
} catch (error) {
|
||||
console.error('Form submission failed:', error);
|
||||
}
|
||||
}, [formData, validateForm, onSubmit]);
|
||||
|
||||
// Get subcategories for selected category
|
||||
const subcategoryOptions = formData.category && BAKERY_CATEGORIES[formData.category as keyof typeof BAKERY_CATEGORIES]
|
||||
? BAKERY_CATEGORIES[formData.category as keyof typeof BAKERY_CATEGORIES].subcategories.map(sub => ({
|
||||
value: sub,
|
||||
label: sub,
|
||||
}))
|
||||
: [];
|
||||
|
||||
const categoryOptions = Object.entries(BAKERY_CATEGORIES).map(([key, { label }]) => ({
|
||||
value: key,
|
||||
label,
|
||||
}));
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title={isEditing ? 'Editar Ingrediente' : 'Nuevo Ingrediente'}
|
||||
size="xl"
|
||||
className={className}
|
||||
>
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Left Column - Basic Information */}
|
||||
<div className="space-y-4">
|
||||
<Card className="p-4">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-4">Información Básica</h3>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
label="Nombre del Ingrediente"
|
||||
isRequired
|
||||
value={formData.name}
|
||||
onChange={(e) => handleInputChange('name', e.target.value)}
|
||||
error={errors.name}
|
||||
placeholder="Ej. Harina de trigo"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleClassifyProduct}
|
||||
disabled={!formData.name.trim() || classifying}
|
||||
className="mt-8"
|
||||
title="Clasificar automáticamente el producto"
|
||||
>
|
||||
{classifying ? (
|
||||
<svg className="w-4 h-4 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
|
||||
</svg>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Select
|
||||
label="Tipo de Producto"
|
||||
value={formData.product_type}
|
||||
onChange={(value) => handleInputChange('product_type', value)}
|
||||
options={PRODUCT_TYPES}
|
||||
error={errors.product_type}
|
||||
/>
|
||||
<Select
|
||||
label="Unidad de Medida"
|
||||
isRequired
|
||||
value={formData.unit_of_measure}
|
||||
onChange={(value) => handleInputChange('unit_of_measure', value)}
|
||||
options={UNITS_OF_MEASURE}
|
||||
error={errors.unit_of_measure}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Input
|
||||
label="Descripción"
|
||||
value={formData.description}
|
||||
onChange={(e) => handleInputChange('description', e.target.value)}
|
||||
placeholder="Descripción detallada del ingrediente"
|
||||
helperText="Descripción opcional para ayudar con la clasificación automática"
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Input
|
||||
label="Marca"
|
||||
value={formData.brand}
|
||||
onChange={(e) => handleInputChange('brand', e.target.value)}
|
||||
placeholder="Marca del producto"
|
||||
/>
|
||||
<Input
|
||||
label="SKU"
|
||||
value={formData.sku}
|
||||
onChange={(e) => handleInputChange('sku', e.target.value)}
|
||||
placeholder="Código SKU interno"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Input
|
||||
label="Código de Barras"
|
||||
value={formData.barcode}
|
||||
onChange={(e) => handleInputChange('barcode', e.target.value)}
|
||||
placeholder="Código de barras EAN/UPC"
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Image Upload */}
|
||||
<Card className="p-4">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-4">Imagen del Producto</h3>
|
||||
|
||||
<div className="space-y-4">
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={handleImageUpload}
|
||||
className="block w-full text-sm text-text-secondary file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-medium file:bg-bg-secondary file:text-text-primary hover:file:bg-bg-tertiary"
|
||||
/>
|
||||
{imagePreview && (
|
||||
<div className="mt-2">
|
||||
<img
|
||||
src={imagePreview}
|
||||
alt="Preview"
|
||||
className="w-32 h-32 object-cover rounded-md border border-border-primary"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Right Column - Categories and Specifications */}
|
||||
<div className="space-y-4">
|
||||
<Card className="p-4">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-4">Categorización</h3>
|
||||
|
||||
<div className="space-y-4">
|
||||
<Select
|
||||
label="Categoría"
|
||||
value={formData.category}
|
||||
onChange={(value) => handleInputChange('category', value)}
|
||||
options={[{ value: '', label: 'Seleccionar categoría' }, ...categoryOptions]}
|
||||
placeholder="Seleccionar categoría"
|
||||
error={errors.category}
|
||||
/>
|
||||
|
||||
{subcategoryOptions.length > 0 && (
|
||||
<Select
|
||||
label="Subcategoría"
|
||||
value={formData.subcategory}
|
||||
onChange={(value) => handleInputChange('subcategory', value)}
|
||||
options={[{ value: '', label: 'Seleccionar subcategoría' }, ...subcategoryOptions]}
|
||||
placeholder="Seleccionar subcategoría"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card className="p-4">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-4">Precios y Cantidades</h3>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Input
|
||||
label="Precio Estándar"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={formData.standard_cost?.toString() || ''}
|
||||
onChange={(e) => handleInputChange('standard_cost', e.target.value ? parseFloat(e.target.value) : undefined)}
|
||||
error={errors.standard_cost}
|
||||
leftAddon="€"
|
||||
placeholder="0.00"
|
||||
/>
|
||||
<Input
|
||||
label="Tamaño del Paquete"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={formData.package_size?.toString() || ''}
|
||||
onChange={(e) => handleInputChange('package_size', e.target.value ? parseFloat(e.target.value) : undefined)}
|
||||
error={errors.package_size}
|
||||
rightAddon={formData.unit_of_measure}
|
||||
placeholder="0.00"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card className="p-4">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-4">Gestión de Stock</h3>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<Input
|
||||
label="Stock Mínimo"
|
||||
isRequired
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={formData.low_stock_threshold.toString()}
|
||||
onChange={(e) => handleInputChange('low_stock_threshold', parseFloat(e.target.value) || 0)}
|
||||
error={errors.low_stock_threshold}
|
||||
placeholder="10"
|
||||
/>
|
||||
<Input
|
||||
label="Punto de Reorden"
|
||||
isRequired
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={formData.reorder_point.toString()}
|
||||
onChange={(e) => handleInputChange('reorder_point', parseFloat(e.target.value) || 0)}
|
||||
error={errors.reorder_point}
|
||||
placeholder="20"
|
||||
/>
|
||||
<Input
|
||||
label="Cantidad de Reorden"
|
||||
isRequired
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={formData.reorder_quantity.toString()}
|
||||
onChange={(e) => handleInputChange('reorder_quantity', parseFloat(e.target.value) || 0)}
|
||||
error={errors.reorder_quantity}
|
||||
placeholder="50"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Input
|
||||
label="Stock Máximo (Opcional)"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
value={formData.max_stock_level?.toString() || ''}
|
||||
onChange={(e) => handleInputChange('max_stock_level', e.target.value ? parseFloat(e.target.value) : undefined)}
|
||||
error={errors.max_stock_level}
|
||||
placeholder="Ej. 100"
|
||||
helperText="Dejar vacío para stock ilimitado"
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Storage and Preservation */}
|
||||
<Card className="p-4">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-4">Almacenamiento y Conservación</h3>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-wrap gap-4">
|
||||
<label className="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={formData.is_perishable}
|
||||
onChange={(e) => handleInputChange('is_perishable', e.target.checked)}
|
||||
className="rounded border-input-border text-color-primary focus:ring-color-primary"
|
||||
/>
|
||||
<span className="ml-2 text-sm text-text-primary">Producto Perecedero</span>
|
||||
</label>
|
||||
|
||||
<label className="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={formData.requires_refrigeration}
|
||||
onChange={(e) => handleInputChange('requires_refrigeration', e.target.checked)}
|
||||
className="rounded border-input-border text-color-primary focus:ring-color-primary"
|
||||
/>
|
||||
<span className="ml-2 text-sm text-text-primary">Requiere Refrigeración</span>
|
||||
</label>
|
||||
|
||||
<label className="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={formData.requires_freezing}
|
||||
onChange={(e) => handleInputChange('requires_freezing', e.target.checked)}
|
||||
className="rounded border-input-border text-color-primary focus:ring-color-primary"
|
||||
/>
|
||||
<span className="ml-2 text-sm text-text-primary">Requiere Congelación</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{(formData.requires_refrigeration || formData.requires_freezing) && (
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Input
|
||||
label="Temperatura Mínima (°C)"
|
||||
type="number"
|
||||
value={formData.storage_temperature_min?.toString() || ''}
|
||||
onChange={(e) => handleInputChange('storage_temperature_min', e.target.value ? parseFloat(e.target.value) : undefined)}
|
||||
placeholder="Ej. -18"
|
||||
/>
|
||||
<Input
|
||||
label="Temperatura Máxima (°C)"
|
||||
type="number"
|
||||
value={formData.storage_temperature_max?.toString() || ''}
|
||||
onChange={(e) => handleInputChange('storage_temperature_max', e.target.value ? parseFloat(e.target.value) : undefined)}
|
||||
placeholder="Ej. 4"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Input
|
||||
label="Humedad Máxima (%)"
|
||||
type="number"
|
||||
min="0"
|
||||
max="100"
|
||||
value={formData.storage_humidity_max?.toString() || ''}
|
||||
onChange={(e) => handleInputChange('storage_humidity_max', e.target.value ? parseFloat(e.target.value) : undefined)}
|
||||
placeholder="Ej. 65"
|
||||
/>
|
||||
<Input
|
||||
label="Vida Útil (días)"
|
||||
type="number"
|
||||
min="1"
|
||||
value={formData.shelf_life_days?.toString() || ''}
|
||||
onChange={(e) => handleInputChange('shelf_life_days', e.target.value ? parseFloat(e.target.value) : undefined)}
|
||||
error={errors.shelf_life_days}
|
||||
placeholder="Ej. 30"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Input
|
||||
label="Instrucciones de Almacenamiento"
|
||||
value={formData.storage_instructions}
|
||||
onChange={(e) => handleInputChange('storage_instructions', e.target.value)}
|
||||
placeholder="Ej. Mantener en lugar seco y fresco, alejado de la luz solar"
|
||||
helperText="Instrucciones específicas para el almacenamiento del producto"
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Allergen Information */}
|
||||
<Card className="p-4">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-4">Información de Alérgenos</h3>
|
||||
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
{[
|
||||
{ key: 'contains_gluten', label: 'Gluten' },
|
||||
{ key: 'contains_dairy', label: 'Lácteos' },
|
||||
{ key: 'contains_eggs', label: 'Huevos' },
|
||||
{ key: 'contains_nuts', label: 'Frutos Secos' },
|
||||
{ key: 'contains_soy', label: 'Soja' },
|
||||
{ key: 'contains_shellfish', label: 'Mariscos' },
|
||||
].map(({ key, label }) => (
|
||||
<label key={key} className="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={formData.allergen_info?.[key] || false}
|
||||
onChange={(e) => handleInputChange('allergen_info', {
|
||||
...formData.allergen_info,
|
||||
[key]: e.target.checked,
|
||||
})}
|
||||
className="rounded border-input-border text-color-primary focus:ring-color-primary"
|
||||
/>
|
||||
<span className="ml-2 text-sm text-text-primary">{label}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* Form Actions */}
|
||||
<div className="flex gap-4 justify-end pt-4 border-t border-border-primary">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onClose}
|
||||
disabled={loading}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
type="submit"
|
||||
loading={loading}
|
||||
disabled={loading}
|
||||
>
|
||||
{isEditing ? 'Actualizar' : 'Crear'} Ingrediente
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{/* Classification Suggestions Modal */}
|
||||
<Modal
|
||||
open={showClassificationModal}
|
||||
onClose={() => setShowClassificationModal(false)}
|
||||
title="Sugerencias de Clasificación"
|
||||
size="md"
|
||||
>
|
||||
{classificationSuggestions && (
|
||||
<div className="space-y-4">
|
||||
<p className="text-text-secondary">
|
||||
Se han encontrado las siguientes sugerencias para "{formData.name}":
|
||||
</p>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium">Categoría:</span>
|
||||
<Badge variant="primary">
|
||||
{BAKERY_CATEGORIES[classificationSuggestions.category as keyof typeof BAKERY_CATEGORIES]?.label || classificationSuggestions.category}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{classificationSuggestions.subcategory && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium">Subcategoría:</span>
|
||||
<Badge variant="outline">{classificationSuggestions.subcategory}</Badge>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium">Unidad Sugerida:</span>
|
||||
<Badge variant="secondary">
|
||||
{UNITS_OF_MEASURE.find(u => u.value === classificationSuggestions.suggested_unit)?.label || classificationSuggestions.suggested_unit}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium">Perecedero:</span>
|
||||
<Badge variant={classificationSuggestions.is_perishable ? "warning" : "success"}>
|
||||
{classificationSuggestions.is_perishable ? 'Sí' : 'No'}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium">Confianza:</span>
|
||||
<Badge variant={
|
||||
classificationSuggestions.confidence > 0.8 ? "success" :
|
||||
classificationSuggestions.confidence > 0.6 ? "warning" : "error"
|
||||
}>
|
||||
{(classificationSuggestions.confidence * 100).toFixed(0)}%
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowClassificationModal(false)}
|
||||
>
|
||||
Ignorar
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleApplyClassification}
|
||||
>
|
||||
Aplicar Sugerencias
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default InventoryForm;
|
||||
627
frontend/src/components/domain/inventory/InventoryTable.tsx
Normal file
627
frontend/src/components/domain/inventory/InventoryTable.tsx
Normal file
@@ -0,0 +1,627 @@
|
||||
import React, { useState, useCallback, useMemo } from 'react';
|
||||
import { clsx } from 'clsx';
|
||||
import { Table, TableColumn } from '../../ui';
|
||||
import { Badge } from '../../ui';
|
||||
import { Button } from '../../ui';
|
||||
import { Input } from '../../ui';
|
||||
import { Select } from '../../ui';
|
||||
import { Modal } from '../../ui';
|
||||
import { ConfirmDialog } from '../../shared';
|
||||
import { InventoryFilters, IngredientResponse, UnitOfMeasure, SortOrder } from '../../../types/inventory.types';
|
||||
import { inventoryService } from '../../../services/api/inventory.service';
|
||||
import { StockLevelIndicator } from './StockLevelIndicator';
|
||||
|
||||
export interface InventoryTableProps {
|
||||
data: IngredientResponse[];
|
||||
loading?: boolean;
|
||||
total?: number;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
filters?: InventoryFilters;
|
||||
selectedItems?: string[];
|
||||
className?: string;
|
||||
onPageChange?: (page: number, pageSize: number) => void;
|
||||
onFiltersChange?: (filters: InventoryFilters) => void;
|
||||
onSelectionChange?: (selectedIds: string[]) => void;
|
||||
onEdit?: (item: IngredientResponse) => void;
|
||||
onDelete?: (item: IngredientResponse) => void;
|
||||
onAdjustStock?: (item: IngredientResponse) => void;
|
||||
onMarkExpired?: (item: IngredientResponse) => void;
|
||||
onRefresh?: () => void;
|
||||
onExport?: () => void;
|
||||
onBulkAction?: (action: string, items: IngredientResponse[]) => void;
|
||||
}
|
||||
|
||||
// Spanish bakery categories
|
||||
const BAKERY_CATEGORIES = [
|
||||
{ value: '', label: 'Todas las categorías' },
|
||||
{ value: 'harinas', label: 'Harinas' },
|
||||
{ value: 'levaduras', label: 'Levaduras' },
|
||||
{ value: 'azucares', label: 'Azúcares y Endulzantes' },
|
||||
{ value: 'chocolates', label: 'Chocolates y Cacao' },
|
||||
{ value: 'frutas', label: 'Frutas y Frutos Secos' },
|
||||
{ value: 'lacteos', label: 'Lácteos' },
|
||||
{ value: 'huevos', label: 'Huevos' },
|
||||
{ value: 'mantequillas', label: 'Mantequillas y Grasas' },
|
||||
{ value: 'especias', label: 'Especias y Aromas' },
|
||||
{ value: 'conservantes', label: 'Conservantes y Aditivos' },
|
||||
{ value: 'decoracion', label: 'Decoración' },
|
||||
{ value: 'envases', label: 'Envases y Embalajes' },
|
||||
{ value: 'utensilios', label: 'Utensilios y Equipos' },
|
||||
{ value: 'limpieza', label: 'Limpieza e Higiene' },
|
||||
];
|
||||
|
||||
const STOCK_LEVEL_FILTERS = [
|
||||
{ value: '', label: 'Todos los niveles' },
|
||||
{ value: 'good', label: 'Stock Normal' },
|
||||
{ value: 'low', label: 'Stock Bajo' },
|
||||
{ value: 'critical', label: 'Stock Crítico' },
|
||||
{ value: 'out', label: 'Sin Stock' },
|
||||
];
|
||||
|
||||
const SORT_OPTIONS = [
|
||||
{ value: 'name_asc', label: 'Nombre (A-Z)' },
|
||||
{ value: 'name_desc', label: 'Nombre (Z-A)' },
|
||||
{ value: 'category_asc', label: 'Categoría (A-Z)' },
|
||||
{ value: 'current_stock_asc', label: 'Stock (Menor a Mayor)' },
|
||||
{ value: 'current_stock_desc', label: 'Stock (Mayor a Menor)' },
|
||||
{ value: 'updated_at_desc', label: 'Actualizado Recientemente' },
|
||||
{ value: 'created_at_desc', label: 'Agregado Recientemente' },
|
||||
];
|
||||
|
||||
export const InventoryTable: React.FC<InventoryTableProps> = ({
|
||||
data,
|
||||
loading = false,
|
||||
total = 0,
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
filters = {},
|
||||
selectedItems = [],
|
||||
className,
|
||||
onPageChange,
|
||||
onFiltersChange,
|
||||
onSelectionChange,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onAdjustStock,
|
||||
onMarkExpired,
|
||||
onRefresh,
|
||||
onExport,
|
||||
onBulkAction,
|
||||
}) => {
|
||||
const [localFilters, setLocalFilters] = useState<InventoryFilters>(filters);
|
||||
const [searchValue, setSearchValue] = useState(filters.search || '');
|
||||
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
|
||||
const [showBulkActionModal, setShowBulkActionModal] = useState(false);
|
||||
const [itemToDelete, setItemToDelete] = useState<IngredientResponse | null>(null);
|
||||
const [selectedBulkAction, setSelectedBulkAction] = useState('');
|
||||
|
||||
// Get selected items data
|
||||
const selectedItemsData = useMemo(() => {
|
||||
return (data || []).filter(item => selectedItems.includes(item.id));
|
||||
}, [data, selectedItems]);
|
||||
|
||||
// Handle search with debouncing
|
||||
const handleSearch = useCallback((value: string) => {
|
||||
setSearchValue(value);
|
||||
const newFilters = { ...localFilters, search: value || undefined };
|
||||
setLocalFilters(newFilters);
|
||||
onFiltersChange?.(newFilters);
|
||||
}, [localFilters, onFiltersChange]);
|
||||
|
||||
// Handle filter changes
|
||||
const handleFilterChange = useCallback((key: keyof InventoryFilters, value: any) => {
|
||||
const newFilters = { ...localFilters, [key]: value || undefined };
|
||||
setLocalFilters(newFilters);
|
||||
onFiltersChange?.(newFilters);
|
||||
}, [localFilters, onFiltersChange]);
|
||||
|
||||
// Handle sort changes
|
||||
const handleSortChange = useCallback((value: string) => {
|
||||
if (!value) return;
|
||||
|
||||
const [field, order] = value.split('_');
|
||||
const newFilters = {
|
||||
...localFilters,
|
||||
sort_by: field as any,
|
||||
sort_order: order as SortOrder,
|
||||
};
|
||||
setLocalFilters(newFilters);
|
||||
onFiltersChange?.(newFilters);
|
||||
}, [localFilters, onFiltersChange]);
|
||||
|
||||
// Clear all filters
|
||||
const handleClearFilters = useCallback(() => {
|
||||
const clearedFilters = { search: undefined };
|
||||
setLocalFilters(clearedFilters);
|
||||
setSearchValue('');
|
||||
onFiltersChange?.(clearedFilters);
|
||||
}, [onFiltersChange]);
|
||||
|
||||
// Handle delete confirmation
|
||||
const handleDeleteClick = useCallback((item: IngredientResponse) => {
|
||||
setItemToDelete(item);
|
||||
setShowDeleteDialog(true);
|
||||
}, []);
|
||||
|
||||
const handleDeleteConfirm = useCallback(() => {
|
||||
if (itemToDelete) {
|
||||
onDelete?.(itemToDelete);
|
||||
setItemToDelete(null);
|
||||
}
|
||||
setShowDeleteDialog(false);
|
||||
}, [itemToDelete, onDelete]);
|
||||
|
||||
// Handle bulk actions
|
||||
const handleBulkAction = useCallback((action: string) => {
|
||||
if (selectedItemsData.length === 0) return;
|
||||
|
||||
if (action === 'delete') {
|
||||
setSelectedBulkAction(action);
|
||||
setShowBulkActionModal(true);
|
||||
} else {
|
||||
onBulkAction?.(action, selectedItemsData);
|
||||
}
|
||||
}, [selectedItemsData, onBulkAction]);
|
||||
|
||||
const handleBulkActionConfirm = useCallback(() => {
|
||||
if (selectedBulkAction && selectedItemsData.length > 0) {
|
||||
onBulkAction?.(selectedBulkAction, selectedItemsData);
|
||||
}
|
||||
setShowBulkActionModal(false);
|
||||
setSelectedBulkAction('');
|
||||
}, [selectedBulkAction, selectedItemsData, onBulkAction]);
|
||||
|
||||
// Get stock level for filtering
|
||||
const getStockLevel = useCallback((item: IngredientResponse): string => {
|
||||
if (!item.current_stock || item.current_stock <= 0) return 'out';
|
||||
if (item.needs_reorder) return 'critical';
|
||||
if (item.is_low_stock) return 'low';
|
||||
return 'good';
|
||||
}, []);
|
||||
|
||||
// Apply local filtering for stock levels
|
||||
const filteredData = useMemo(() => {
|
||||
const dataArray = data || [];
|
||||
if (!localFilters.is_low_stock && !localFilters.needs_reorder) return dataArray;
|
||||
|
||||
return dataArray.filter(item => {
|
||||
const stockLevel = getStockLevel(item);
|
||||
if (localFilters.is_low_stock && stockLevel !== 'low') return false;
|
||||
if (localFilters.needs_reorder && stockLevel !== 'critical') return false;
|
||||
return true;
|
||||
});
|
||||
}, [data, localFilters.is_low_stock, localFilters.needs_reorder, getStockLevel]);
|
||||
|
||||
// Table columns configuration
|
||||
const columns: TableColumn<IngredientResponse>[] = [
|
||||
{
|
||||
key: 'name',
|
||||
title: 'Nombre',
|
||||
dataIndex: 'name',
|
||||
sortable: true,
|
||||
width: '25%',
|
||||
render: (value: string, record: IngredientResponse) => (
|
||||
<div>
|
||||
<div className="font-medium text-text-primary">{value}</div>
|
||||
{record.brand && (
|
||||
<div className="text-sm text-text-secondary">{record.brand}</div>
|
||||
)}
|
||||
{record.sku && (
|
||||
<div className="text-xs text-text-tertiary">SKU: {record.sku}</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'category',
|
||||
title: 'Categoría',
|
||||
dataIndex: 'category',
|
||||
sortable: true,
|
||||
width: '15%',
|
||||
render: (value: string) => (
|
||||
<Badge variant="outline" size="sm">
|
||||
{BAKERY_CATEGORIES.find(cat => cat.value === value)?.label || value || 'Sin categoría'}
|
||||
</Badge>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'current_stock',
|
||||
title: 'Stock Actual',
|
||||
dataIndex: 'current_stock',
|
||||
sortable: true,
|
||||
width: '15%',
|
||||
align: 'right',
|
||||
render: (value: number | undefined, record: IngredientResponse) => (
|
||||
<div className="text-right">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<span className="font-mono">
|
||||
{value?.toFixed(2) ?? '0.00'}
|
||||
</span>
|
||||
<span className="text-text-tertiary text-sm">
|
||||
{record.unit_of_measure}
|
||||
</span>
|
||||
</div>
|
||||
<StockLevelIndicator
|
||||
current={value || 0}
|
||||
minimum={record.low_stock_threshold}
|
||||
maximum={record.max_stock_level}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'thresholds',
|
||||
title: 'Mín / Máx',
|
||||
width: '12%',
|
||||
align: 'center',
|
||||
render: (_, record: IngredientResponse) => (
|
||||
<div className="text-center text-sm">
|
||||
<div className="text-text-secondary">
|
||||
{record.low_stock_threshold} / {record.max_stock_level || '∞'}
|
||||
</div>
|
||||
<div className="text-xs text-text-tertiary">
|
||||
Reorden: {record.reorder_point}
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'price',
|
||||
title: 'Precio',
|
||||
width: '10%',
|
||||
align: 'right',
|
||||
render: (_, record: IngredientResponse) => (
|
||||
<div className="text-right">
|
||||
{record.standard_cost && (
|
||||
<div className="font-medium">
|
||||
€{record.standard_cost.toFixed(2)}
|
||||
</div>
|
||||
)}
|
||||
{record.last_purchase_price && record.last_purchase_price !== record.standard_cost && (
|
||||
<div className="text-sm text-text-secondary">
|
||||
Último: €{record.last_purchase_price.toFixed(2)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'status',
|
||||
title: 'Estado',
|
||||
width: '10%',
|
||||
align: 'center',
|
||||
render: (_, record: IngredientResponse) => {
|
||||
const badges = [];
|
||||
|
||||
if (record.needs_reorder) {
|
||||
badges.push(
|
||||
<Badge key="reorder" variant="error" size="xs">
|
||||
Crítico
|
||||
</Badge>
|
||||
);
|
||||
} else if (record.is_low_stock) {
|
||||
badges.push(
|
||||
<Badge key="low" variant="warning" size="xs">
|
||||
Bajo
|
||||
</Badge>
|
||||
);
|
||||
} else {
|
||||
badges.push(
|
||||
<Badge key="ok" variant="success" size="xs">
|
||||
OK
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
if (!record.is_active) {
|
||||
badges.push(
|
||||
<Badge key="inactive" variant="secondary" size="xs">
|
||||
Inactivo
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
if (record.is_perishable) {
|
||||
badges.push(
|
||||
<Badge key="perishable" variant="info" size="xs" title="Producto perecedero">
|
||||
P
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
{badges}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'actions',
|
||||
title: 'Acciones',
|
||||
width: '13%',
|
||||
align: 'center',
|
||||
render: (_, record: IngredientResponse) => (
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => onEdit?.(record)}
|
||||
title="Editar ingrediente"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
|
||||
</svg>
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => onAdjustStock?.(record)}
|
||||
title="Ajustar stock"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 4V2a1 1 0 011-1h8a1 1 0 011 1v2m3 0v18a1 1 0 01-1 1H5a1 1 0 01-1-1V4h16zM9 9v1a1 1 0 002 0V9a1 1 0 10-2 0zm4 0v1a1 1 0 002 0V9a1 1 0 10-2 0z" />
|
||||
</svg>
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleDeleteClick(record)}
|
||||
title="Eliminar ingrediente"
|
||||
className="text-color-error hover:text-color-error"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
|
||||
</svg>
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
const currentSortValue = localFilters.sort_by && localFilters.sort_order
|
||||
? `${localFilters.sort_by}_${localFilters.sort_order}`
|
||||
: '';
|
||||
|
||||
return (
|
||||
<div className={clsx('space-y-4', className)}>
|
||||
{/* Filters and Actions */}
|
||||
<div className="space-y-4">
|
||||
{/* Search and Quick Actions */}
|
||||
<div className="flex flex-col sm:flex-row gap-4 sm:items-center sm:justify-between">
|
||||
<div className="flex-1 max-w-md">
|
||||
<Input
|
||||
placeholder="Buscar ingredientes..."
|
||||
value={searchValue}
|
||||
onChange={(e) => handleSearch(e.target.value)}
|
||||
leftIcon={
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
|
||||
</svg>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onRefresh}
|
||||
disabled={loading}
|
||||
title="Actualizar datos"
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
|
||||
</svg>
|
||||
Actualizar
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={onExport}
|
||||
title="Exportar inventario"
|
||||
>
|
||||
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
||||
</svg>
|
||||
Exportar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Advanced Filters */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<Select
|
||||
placeholder="Categoría"
|
||||
value={localFilters.category || ''}
|
||||
onChange={(value) => handleFilterChange('category', value)}
|
||||
options={BAKERY_CATEGORIES}
|
||||
/>
|
||||
<Select
|
||||
placeholder="Nivel de stock"
|
||||
value={
|
||||
localFilters.needs_reorder ? 'critical' :
|
||||
localFilters.is_low_stock ? 'low' : ''
|
||||
}
|
||||
onChange={(value) => {
|
||||
handleFilterChange('needs_reorder', value === 'critical');
|
||||
handleFilterChange('is_low_stock', value === 'low');
|
||||
}}
|
||||
options={STOCK_LEVEL_FILTERS}
|
||||
/>
|
||||
<Select
|
||||
placeholder="Ordenar por"
|
||||
value={currentSortValue}
|
||||
onChange={handleSortChange}
|
||||
options={SORT_OPTIONS}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleClearFilters}
|
||||
className="flex-1"
|
||||
>
|
||||
Limpiar Filtros
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Active Filters Summary */}
|
||||
{(localFilters.search || localFilters.category || localFilters.is_low_stock || localFilters.needs_reorder) && (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-sm text-text-secondary">Filtros activos:</span>
|
||||
{localFilters.search && (
|
||||
<Badge variant="primary" closable onClose={() => handleFilterChange('search', '')}>
|
||||
Búsqueda: "{localFilters.search}"
|
||||
</Badge>
|
||||
)}
|
||||
{localFilters.category && (
|
||||
<Badge variant="primary" closable onClose={() => handleFilterChange('category', '')}>
|
||||
{BAKERY_CATEGORIES.find(cat => cat.value === localFilters.category)?.label}
|
||||
</Badge>
|
||||
)}
|
||||
{localFilters.is_low_stock && (
|
||||
<Badge variant="warning" closable onClose={() => handleFilterChange('is_low_stock', false)}>
|
||||
Stock Bajo
|
||||
</Badge>
|
||||
)}
|
||||
{localFilters.needs_reorder && (
|
||||
<Badge variant="error" closable onClose={() => handleFilterChange('needs_reorder', false)}>
|
||||
Stock Crítico
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Bulk Actions */}
|
||||
{selectedItems.length > 0 && (
|
||||
<div className="flex items-center justify-between bg-bg-secondary rounded-lg p-4">
|
||||
<span className="text-sm text-text-secondary">
|
||||
{selectedItems.length} elemento{selectedItems.length !== 1 ? 's' : ''} seleccionado{selectedItems.length !== 1 ? 's' : ''}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => handleBulkAction('export')}
|
||||
>
|
||||
Exportar Selección
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => handleBulkAction('adjust_stock')}
|
||||
>
|
||||
Ajustar Stock
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => handleBulkAction('delete')}
|
||||
className="text-color-error hover:text-color-error"
|
||||
>
|
||||
Eliminar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Table */}
|
||||
<Table
|
||||
columns={columns}
|
||||
data={filteredData}
|
||||
loading={loading}
|
||||
size="md"
|
||||
hover
|
||||
sticky
|
||||
rowSelection={{
|
||||
selectedRowKeys: selectedItems,
|
||||
onSelect: (record, selected, selectedRows) => {
|
||||
const newSelection = selected
|
||||
? [...selectedItems, record.id]
|
||||
: selectedItems.filter(id => id !== record.id);
|
||||
onSelectionChange?.(newSelection);
|
||||
},
|
||||
onSelectAll: (selected, selectedRows, changeRows) => {
|
||||
const newSelection = selected
|
||||
? filteredData.map(item => item.id)
|
||||
: [];
|
||||
onSelectionChange?.(newSelection);
|
||||
},
|
||||
}}
|
||||
pagination={{
|
||||
current: page,
|
||||
pageSize,
|
||||
total,
|
||||
showSizeChanger: true,
|
||||
showQuickJumper: true,
|
||||
showTotal: (total, range) =>
|
||||
`${range[0]}-${range[1]} de ${total} ingredientes`,
|
||||
onChange: onPageChange,
|
||||
}}
|
||||
locale={{
|
||||
emptyText: 'No se encontraron ingredientes',
|
||||
selectAll: 'Seleccionar todos',
|
||||
selectRow: 'Seleccionar fila',
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<ConfirmDialog
|
||||
open={showDeleteDialog}
|
||||
onOpenChange={setShowDeleteDialog}
|
||||
onConfirm={handleDeleteConfirm}
|
||||
title="Eliminar Ingrediente"
|
||||
description={
|
||||
itemToDelete
|
||||
? `¿Estás seguro de que quieres eliminar "${itemToDelete.name}"? Esta acción no se puede deshacer.`
|
||||
: ''
|
||||
}
|
||||
confirmText="Eliminar"
|
||||
cancelText="Cancelar"
|
||||
variant="destructive"
|
||||
/>
|
||||
|
||||
{/* Bulk Action Confirmation */}
|
||||
<Modal
|
||||
open={showBulkActionModal}
|
||||
onClose={() => setShowBulkActionModal(false)}
|
||||
title="Confirmar Acción Masiva"
|
||||
size="md"
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<p>
|
||||
¿Estás seguro de que quieres {selectedBulkAction === 'delete' ? 'eliminar' : 'procesar'} {' '}
|
||||
{selectedItemsData.length} elemento{selectedItemsData.length !== 1 ? 's' : ''}?
|
||||
</p>
|
||||
{selectedItemsData.length > 0 && (
|
||||
<div className="max-h-32 overflow-y-auto">
|
||||
<ul className="text-sm text-text-secondary space-y-1">
|
||||
{selectedItemsData.map(item => (
|
||||
<li key={item.id}>• {item.name}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowBulkActionModal(false)}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
variant={selectedBulkAction === 'delete' ? 'destructive' : 'primary'}
|
||||
onClick={handleBulkActionConfirm}
|
||||
>
|
||||
Confirmar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default InventoryTable;
|
||||
538
frontend/src/components/domain/inventory/LowStockAlert.tsx
Normal file
538
frontend/src/components/domain/inventory/LowStockAlert.tsx
Normal file
@@ -0,0 +1,538 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { clsx } from 'clsx';
|
||||
import { Card } from '../../ui';
|
||||
import { Badge } from '../../ui';
|
||||
import { Button } from '../../ui';
|
||||
import { Modal } from '../../ui';
|
||||
import { Input } from '../../ui';
|
||||
import { EmptyState } from '../../shared';
|
||||
import { LoadingSpinner } from '../../shared';
|
||||
import { StockAlert, IngredientResponse, AlertSeverity } from '../../../types/inventory.types';
|
||||
import { inventoryService } from '../../../services/api/inventory.service';
|
||||
import { StockLevelIndicator } from './StockLevelIndicator';
|
||||
|
||||
export interface LowStockAlertProps {
|
||||
alerts?: StockAlert[];
|
||||
autoRefresh?: boolean;
|
||||
refreshInterval?: number;
|
||||
maxItems?: number;
|
||||
showDismissed?: boolean;
|
||||
compact?: boolean;
|
||||
className?: string;
|
||||
onReorder?: (item: IngredientResponse) => void;
|
||||
onAdjustMinimums?: (item: IngredientResponse) => void;
|
||||
onDismiss?: (alertId: string) => void;
|
||||
onRefresh?: () => void;
|
||||
onViewAll?: () => void;
|
||||
}
|
||||
|
||||
interface GroupedAlerts {
|
||||
critical: StockAlert[];
|
||||
low: StockAlert[];
|
||||
out: StockAlert[];
|
||||
}
|
||||
|
||||
interface SupplierSuggestion {
|
||||
id: string;
|
||||
name: string;
|
||||
lastPrice?: number;
|
||||
lastOrderDate?: string;
|
||||
reliability: number;
|
||||
}
|
||||
|
||||
export const LowStockAlert: React.FC<LowStockAlertProps> = ({
|
||||
alerts = [],
|
||||
autoRefresh = false,
|
||||
refreshInterval = 30000,
|
||||
maxItems = 10,
|
||||
showDismissed = false,
|
||||
compact = false,
|
||||
className,
|
||||
onReorder,
|
||||
onAdjustMinimums,
|
||||
onDismiss,
|
||||
onRefresh,
|
||||
onViewAll,
|
||||
}) => {
|
||||
const [localAlerts, setLocalAlerts] = useState<StockAlert[]>(alerts);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [dismissedAlerts, setDismissedAlerts] = useState<Set<string>>(new Set());
|
||||
const [showReorderModal, setShowReorderModal] = useState(false);
|
||||
const [showAdjustModal, setShowAdjustModal] = useState(false);
|
||||
const [selectedAlert, setSelectedAlert] = useState<StockAlert | null>(null);
|
||||
const [reorderQuantity, setReorderQuantity] = useState<number>(0);
|
||||
const [newMinimumThreshold, setNewMinimumThreshold] = useState<number>(0);
|
||||
const [supplierSuggestions, setSupplierSuggestions] = useState<SupplierSuggestion[]>([]);
|
||||
|
||||
// Update local alerts when prop changes
|
||||
useEffect(() => {
|
||||
setLocalAlerts(alerts);
|
||||
}, [alerts]);
|
||||
|
||||
// Auto-refresh functionality
|
||||
useEffect(() => {
|
||||
if (!autoRefresh || refreshInterval <= 0) return;
|
||||
|
||||
const interval = setInterval(() => {
|
||||
onRefresh?.();
|
||||
}, refreshInterval);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [autoRefresh, refreshInterval, onRefresh]);
|
||||
|
||||
// Load supplier suggestions when modal opens
|
||||
useEffect(() => {
|
||||
if (showReorderModal && selectedAlert?.ingredient_id) {
|
||||
loadSupplierSuggestions(selectedAlert.ingredient_id);
|
||||
}
|
||||
}, [showReorderModal, selectedAlert]);
|
||||
|
||||
const loadSupplierSuggestions = async (ingredientId: string) => {
|
||||
try {
|
||||
// This would typically call a suppliers API
|
||||
// For now, we'll simulate some data
|
||||
setSupplierSuggestions([
|
||||
{ id: '1', name: 'Proveedor Principal', lastPrice: 2.50, reliability: 95 },
|
||||
{ id: '2', name: 'Proveedor Alternativo', lastPrice: 2.80, reliability: 87 },
|
||||
]);
|
||||
} catch (error) {
|
||||
console.error('Error loading supplier suggestions:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Group alerts by severity
|
||||
const groupedAlerts = React.useMemo((): GroupedAlerts => {
|
||||
const filtered = localAlerts.filter(alert => {
|
||||
if (!alert.is_active) return false;
|
||||
if (!showDismissed && dismissedAlerts.has(alert.id)) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
return {
|
||||
critical: filtered.filter(alert =>
|
||||
alert.severity === AlertSeverity.CRITICAL ||
|
||||
alert.alert_type === 'out_of_stock'
|
||||
),
|
||||
low: filtered.filter(alert =>
|
||||
alert.severity === AlertSeverity.HIGH &&
|
||||
alert.alert_type === 'low_stock'
|
||||
),
|
||||
out: filtered.filter(alert => alert.alert_type === 'out_of_stock'),
|
||||
};
|
||||
}, [localAlerts, showDismissed, dismissedAlerts]);
|
||||
|
||||
const totalActiveAlerts = groupedAlerts.critical.length + groupedAlerts.low.length;
|
||||
|
||||
// Handle alert dismissal
|
||||
const handleDismiss = useCallback(async (alertId: string, temporary: boolean = true) => {
|
||||
if (temporary) {
|
||||
setDismissedAlerts(prev => new Set(prev).add(alertId));
|
||||
} else {
|
||||
try {
|
||||
await inventoryService.acknowledgeAlert(alertId);
|
||||
onDismiss?.(alertId);
|
||||
} catch (error) {
|
||||
console.error('Error dismissing alert:', error);
|
||||
setError('Error al descartar la alerta');
|
||||
}
|
||||
}
|
||||
}, [onDismiss]);
|
||||
|
||||
// Handle reorder action
|
||||
const handleReorder = useCallback((alert: StockAlert) => {
|
||||
setSelectedAlert(alert);
|
||||
setReorderQuantity(alert.ingredient?.reorder_quantity || 0);
|
||||
setShowReorderModal(true);
|
||||
}, []);
|
||||
|
||||
// Handle adjust minimums action
|
||||
const handleAdjustMinimums = useCallback((alert: StockAlert) => {
|
||||
setSelectedAlert(alert);
|
||||
setNewMinimumThreshold(alert.threshold_value || alert.ingredient?.low_stock_threshold || 0);
|
||||
setShowAdjustModal(true);
|
||||
}, []);
|
||||
|
||||
// Confirm reorder
|
||||
const handleConfirmReorder = useCallback(() => {
|
||||
if (selectedAlert?.ingredient) {
|
||||
onReorder?.(selectedAlert.ingredient);
|
||||
}
|
||||
setShowReorderModal(false);
|
||||
setSelectedAlert(null);
|
||||
}, [selectedAlert, onReorder]);
|
||||
|
||||
// Confirm adjust minimums
|
||||
const handleConfirmAdjust = useCallback(() => {
|
||||
if (selectedAlert?.ingredient) {
|
||||
onAdjustMinimums?.(selectedAlert.ingredient);
|
||||
}
|
||||
setShowAdjustModal(false);
|
||||
setSelectedAlert(null);
|
||||
}, [selectedAlert, onAdjustMinimums]);
|
||||
|
||||
// Get severity badge variant
|
||||
const getSeverityVariant = (severity: AlertSeverity): any => {
|
||||
switch (severity) {
|
||||
case AlertSeverity.CRITICAL:
|
||||
return 'error';
|
||||
case AlertSeverity.HIGH:
|
||||
return 'warning';
|
||||
case AlertSeverity.MEDIUM:
|
||||
return 'info';
|
||||
default:
|
||||
return 'secondary';
|
||||
}
|
||||
};
|
||||
|
||||
// Render alert item
|
||||
const renderAlertItem = (alert: StockAlert, index: number) => {
|
||||
const ingredient = alert.ingredient;
|
||||
if (!ingredient) return null;
|
||||
|
||||
const isCompact = compact || index >= maxItems;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={alert.id}
|
||||
className={clsx(
|
||||
'flex items-center justify-between p-3 border border-border-primary rounded-lg',
|
||||
'hover:bg-bg-secondary transition-colors duration-150',
|
||||
{
|
||||
'bg-color-error/5 border-color-error/20': alert.severity === AlertSeverity.CRITICAL,
|
||||
'bg-color-warning/5 border-color-warning/20': alert.severity === AlertSeverity.HIGH,
|
||||
'py-2': isCompact,
|
||||
}
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-3 flex-1 min-w-0">
|
||||
{/* Stock indicator */}
|
||||
<StockLevelIndicator
|
||||
current={alert.current_quantity || 0}
|
||||
minimum={ingredient.low_stock_threshold}
|
||||
maximum={ingredient.max_stock_level}
|
||||
reorderPoint={ingredient.reorder_point}
|
||||
unit={ingredient.unit_of_measure}
|
||||
size={isCompact ? 'xs' : 'sm'}
|
||||
variant="minimal"
|
||||
/>
|
||||
|
||||
{/* Alert info */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h4 className="font-medium text-text-primary truncate">
|
||||
{ingredient.name}
|
||||
</h4>
|
||||
<Badge
|
||||
variant={getSeverityVariant(alert.severity)}
|
||||
size="xs"
|
||||
>
|
||||
{alert.severity === AlertSeverity.CRITICAL ? 'Crítico' :
|
||||
alert.severity === AlertSeverity.HIGH ? 'Bajo' :
|
||||
'Normal'}
|
||||
</Badge>
|
||||
{ingredient.category && (
|
||||
<Badge variant="outline" size="xs">
|
||||
{ingredient.category}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!isCompact && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
{alert.message}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-4 mt-1">
|
||||
<span className="text-sm text-text-tertiary">
|
||||
Stock: {alert.current_quantity || 0} {ingredient.unit_of_measure}
|
||||
</span>
|
||||
{alert.threshold_value && (
|
||||
<span className="text-sm text-text-tertiary">
|
||||
Mín: {alert.threshold_value} {ingredient.unit_of_measure}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
{!isCompact && (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => handleReorder(alert)}
|
||||
title="Crear orden de compra"
|
||||
>
|
||||
<svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
|
||||
</svg>
|
||||
Reordenar
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleAdjustMinimums(alert)}
|
||||
title="Ajustar umbrales mínimos"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4" />
|
||||
</svg>
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleDismiss(alert.id, true)}
|
||||
title="Descartar alerta temporalmente"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Loading state
|
||||
if (loading) {
|
||||
return (
|
||||
<Card className={clsx('p-6', className)}>
|
||||
<div className="flex items-center justify-center">
|
||||
<LoadingSpinner size="md" />
|
||||
<span className="ml-2 text-text-secondary">Cargando alertas...</span>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Error state
|
||||
if (error) {
|
||||
return (
|
||||
<Card className={clsx('p-6 border-color-error/20 bg-color-error/5', className)}>
|
||||
<div className="flex items-center gap-3">
|
||||
<svg className="w-5 h-5 text-color-error flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<div className="flex-1">
|
||||
<h3 className="font-medium text-color-error">Error al cargar alertas</h3>
|
||||
<p className="text-sm text-text-secondary">{error}</p>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={onRefresh}
|
||||
>
|
||||
Reintentar
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Empty state
|
||||
if (totalActiveAlerts === 0) {
|
||||
return (
|
||||
<Card className={clsx('p-6', className)}>
|
||||
<EmptyState
|
||||
title="Sin alertas de stock"
|
||||
description="Todos los productos tienen niveles de stock adecuados"
|
||||
icon={
|
||||
<svg className="w-12 h-12 text-color-success" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
}
|
||||
/>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const visibleAlerts = [...groupedAlerts.critical, ...groupedAlerts.low].slice(0, maxItems);
|
||||
const hasMoreAlerts = totalActiveAlerts > maxItems;
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
<Card className="overflow-hidden">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-4 border-b border-border-primary bg-bg-secondary">
|
||||
<div className="flex items-center gap-3">
|
||||
<h2 className="text-lg font-semibold text-text-primary">
|
||||
Alertas de Stock
|
||||
</h2>
|
||||
<Badge variant="error" count={groupedAlerts.critical.length} />
|
||||
<Badge variant="warning" count={groupedAlerts.low.length} />
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={onRefresh}
|
||||
title="Actualizar alertas"
|
||||
disabled={loading}
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
|
||||
</svg>
|
||||
</Button>
|
||||
|
||||
{hasMoreAlerts && onViewAll && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={onViewAll}
|
||||
>
|
||||
Ver Todas ({totalActiveAlerts})
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Alerts list */}
|
||||
<div className="p-4 space-y-3">
|
||||
{visibleAlerts.map((alert, index) => renderAlertItem(alert, index))}
|
||||
</div>
|
||||
|
||||
{/* Footer actions */}
|
||||
{hasMoreAlerts && (
|
||||
<div className="px-4 py-3 border-t border-border-primary bg-bg-tertiary">
|
||||
<p className="text-sm text-text-secondary text-center">
|
||||
Mostrando {visibleAlerts.length} de {totalActiveAlerts} alertas
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Reorder Modal */}
|
||||
<Modal
|
||||
open={showReorderModal}
|
||||
onClose={() => setShowReorderModal(false)}
|
||||
title="Crear Orden de Compra"
|
||||
size="md"
|
||||
>
|
||||
{selectedAlert && (
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 bg-bg-secondary rounded-lg">
|
||||
<h3 className="font-medium text-text-primary">
|
||||
{selectedAlert.ingredient?.name}
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Stock actual: {selectedAlert.current_quantity || 0} {selectedAlert.ingredient?.unit_of_measure}
|
||||
</p>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Stock mínimo: {selectedAlert.ingredient?.low_stock_threshold} {selectedAlert.ingredient?.unit_of_measure}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Input
|
||||
label="Cantidad a Ordenar"
|
||||
type="number"
|
||||
min="1"
|
||||
step="0.01"
|
||||
value={reorderQuantity.toString()}
|
||||
onChange={(e) => setReorderQuantity(parseFloat(e.target.value) || 0)}
|
||||
rightAddon={selectedAlert.ingredient?.unit_of_measure}
|
||||
helperText="Cantidad sugerida basada en el punto de reorden configurado"
|
||||
/>
|
||||
|
||||
{supplierSuggestions.length > 0 && (
|
||||
<div>
|
||||
<h4 className="text-sm font-medium text-text-primary mb-2">
|
||||
Proveedores Sugeridos
|
||||
</h4>
|
||||
<div className="space-y-2">
|
||||
{supplierSuggestions.map(supplier => (
|
||||
<div key={supplier.id} className="p-2 border border-border-primary rounded-lg">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-medium">{supplier.name}</span>
|
||||
<Badge variant="success" size="xs">
|
||||
{supplier.reliability}% confiable
|
||||
</Badge>
|
||||
</div>
|
||||
{supplier.lastPrice && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
Último precio: €{supplier.lastPrice.toFixed(2)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowReorderModal(false)}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleConfirmReorder}
|
||||
disabled={reorderQuantity <= 0}
|
||||
>
|
||||
Crear Orden de Compra
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
{/* Adjust Minimums Modal */}
|
||||
<Modal
|
||||
open={showAdjustModal}
|
||||
onClose={() => setShowAdjustModal(false)}
|
||||
title="Ajustar Umbrales Mínimos"
|
||||
size="md"
|
||||
>
|
||||
{selectedAlert && (
|
||||
<div className="space-y-4">
|
||||
<div className="p-4 bg-bg-secondary rounded-lg">
|
||||
<h3 className="font-medium text-text-primary">
|
||||
{selectedAlert.ingredient?.name}
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Stock actual: {selectedAlert.current_quantity || 0} {selectedAlert.ingredient?.unit_of_measure}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Input
|
||||
label="Nuevo Umbral Mínimo"
|
||||
type="number"
|
||||
min="0"
|
||||
step="0.01"
|
||||
value={newMinimumThreshold.toString()}
|
||||
onChange={(e) => setNewMinimumThreshold(parseFloat(e.target.value) || 0)}
|
||||
rightAddon={selectedAlert.ingredient?.unit_of_measure}
|
||||
helperText="Ajusta el nivel mínimo de stock para este producto"
|
||||
/>
|
||||
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowAdjustModal(false)}
|
||||
>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleConfirmAdjust}
|
||||
disabled={newMinimumThreshold < 0}
|
||||
>
|
||||
Actualizar Umbral
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LowStockAlert;
|
||||
411
frontend/src/components/domain/inventory/StockLevelIndicator.tsx
Normal file
411
frontend/src/components/domain/inventory/StockLevelIndicator.tsx
Normal file
@@ -0,0 +1,411 @@
|
||||
import React, { useMemo } from 'react';
|
||||
import { clsx } from 'clsx';
|
||||
import { Tooltip } from '../../ui/Tooltip';
|
||||
|
||||
export interface StockLevelIndicatorProps {
|
||||
current: number;
|
||||
minimum?: number;
|
||||
maximum?: number;
|
||||
reorderPoint?: number;
|
||||
unit?: string;
|
||||
size?: 'xs' | 'sm' | 'md' | 'lg';
|
||||
variant?: 'bar' | 'gauge' | 'badge' | 'minimal';
|
||||
showLabels?: boolean;
|
||||
showPercentage?: boolean;
|
||||
showTrend?: boolean;
|
||||
trend?: 'up' | 'down' | 'stable';
|
||||
className?: string;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
type StockStatus = 'good' | 'low' | 'critical' | 'out' | 'overstocked';
|
||||
|
||||
interface StockLevel {
|
||||
status: StockStatus;
|
||||
label: string;
|
||||
color: string;
|
||||
bgColor: string;
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export const StockLevelIndicator: React.FC<StockLevelIndicatorProps> = ({
|
||||
current,
|
||||
minimum = 0,
|
||||
maximum,
|
||||
reorderPoint,
|
||||
unit = '',
|
||||
size = 'md',
|
||||
variant = 'bar',
|
||||
showLabels = false,
|
||||
showPercentage = false,
|
||||
showTrend = false,
|
||||
trend = 'stable',
|
||||
className,
|
||||
onClick,
|
||||
}) => {
|
||||
// Calculate stock level and status
|
||||
const stockLevel = useMemo<StockLevel>(() => {
|
||||
// Handle out of stock
|
||||
if (current <= 0) {
|
||||
return {
|
||||
status: 'out',
|
||||
label: 'Sin Stock',
|
||||
color: 'text-color-error',
|
||||
bgColor: 'bg-color-error',
|
||||
percentage: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// Calculate percentage based on maximum or use current value relative to minimum
|
||||
const percentage = maximum
|
||||
? Math.min((current / maximum) * 100, 100)
|
||||
: Math.min(((current - minimum) / (minimum || 1)) * 100 + 100, 200);
|
||||
|
||||
// Handle overstocked (if maximum is defined)
|
||||
if (maximum && current > maximum * 1.2) {
|
||||
return {
|
||||
status: 'overstocked',
|
||||
label: 'Sobrestock',
|
||||
color: 'text-color-info',
|
||||
bgColor: 'bg-color-info',
|
||||
percentage: Math.min(percentage, 150),
|
||||
};
|
||||
}
|
||||
|
||||
// Handle critical level (reorder point or below minimum)
|
||||
const criticalThreshold = reorderPoint || minimum;
|
||||
if (current <= criticalThreshold) {
|
||||
return {
|
||||
status: 'critical',
|
||||
label: 'Crítico',
|
||||
color: 'text-color-error',
|
||||
bgColor: 'bg-color-error',
|
||||
percentage: Math.max(percentage, 5), // Minimum visible bar
|
||||
};
|
||||
}
|
||||
|
||||
// Handle low stock (within 20% above critical threshold)
|
||||
const lowThreshold = criticalThreshold * 1.2;
|
||||
if (current <= lowThreshold) {
|
||||
return {
|
||||
status: 'low',
|
||||
label: 'Bajo',
|
||||
color: 'text-color-warning',
|
||||
bgColor: 'bg-color-warning',
|
||||
percentage,
|
||||
};
|
||||
}
|
||||
|
||||
// Good stock level
|
||||
return {
|
||||
status: 'good',
|
||||
label: 'Normal',
|
||||
color: 'text-color-success',
|
||||
bgColor: 'bg-color-success',
|
||||
percentage,
|
||||
};
|
||||
}, [current, minimum, maximum, reorderPoint]);
|
||||
|
||||
const sizeClasses = {
|
||||
xs: {
|
||||
container: 'h-1',
|
||||
text: 'text-xs',
|
||||
badge: 'px-1.5 py-0.5 text-xs',
|
||||
gauge: 'w-6 h-6',
|
||||
},
|
||||
sm: {
|
||||
container: 'h-2',
|
||||
text: 'text-sm',
|
||||
badge: 'px-2 py-0.5 text-xs',
|
||||
gauge: 'w-8 h-8',
|
||||
},
|
||||
md: {
|
||||
container: 'h-3',
|
||||
text: 'text-sm',
|
||||
badge: 'px-2.5 py-1 text-sm',
|
||||
gauge: 'w-10 h-10',
|
||||
},
|
||||
lg: {
|
||||
container: 'h-4',
|
||||
text: 'text-base',
|
||||
badge: 'px-3 py-1.5 text-sm',
|
||||
gauge: 'w-12 h-12',
|
||||
},
|
||||
};
|
||||
|
||||
// Trend arrow component
|
||||
const TrendArrow = () => {
|
||||
if (!showTrend || trend === 'stable') return null;
|
||||
|
||||
const trendClasses = {
|
||||
up: 'text-color-success transform rotate-0',
|
||||
down: 'text-color-error transform rotate-180',
|
||||
stable: 'text-text-tertiary',
|
||||
};
|
||||
|
||||
return (
|
||||
<svg
|
||||
className={clsx('w-3 h-3 ml-1', trendClasses[trend])}
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path fillRule="evenodd" d="M5.293 7.707a1 1 0 010-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 01-1.414 1.414L11 5.414V17a1 1 0 11-2 0V5.414L6.707 7.707a1 1 0 01-1.414 0z" clipRule="evenodd" />
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
// Tooltip content
|
||||
const tooltipContent = (
|
||||
<div className="text-sm space-y-1">
|
||||
<div className="font-medium">Estado: {stockLevel.label}</div>
|
||||
<div>Stock actual: {current.toFixed(2)} {unit}</div>
|
||||
{minimum > 0 && <div>Mínimo: {minimum.toFixed(2)} {unit}</div>}
|
||||
{maximum && <div>Máximo: {maximum.toFixed(2)} {unit}</div>}
|
||||
{reorderPoint && <div>Punto de reorden: {reorderPoint.toFixed(2)} {unit}</div>}
|
||||
{showPercentage && maximum && (
|
||||
<div>Nivel: {((current / maximum) * 100).toFixed(1)}%</div>
|
||||
)}
|
||||
{showTrend && trend !== 'stable' && (
|
||||
<div>Tendencia: {trend === 'up' ? 'Subiendo' : 'Bajando'}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
// Badge variant
|
||||
if (variant === 'badge') {
|
||||
const badgeContent = (
|
||||
<span
|
||||
className={clsx(
|
||||
'inline-flex items-center font-medium rounded-full',
|
||||
stockLevel.color,
|
||||
stockLevel.bgColor.replace('bg-', 'bg-opacity-10 bg-'),
|
||||
'border border-current border-opacity-20',
|
||||
sizeClasses[size].badge,
|
||||
onClick && 'cursor-pointer hover:bg-opacity-20',
|
||||
className
|
||||
)}
|
||||
onClick={onClick}
|
||||
>
|
||||
{stockLevel.label}
|
||||
{showPercentage && maximum && ` (${((current / maximum) * 100).toFixed(0)}%)`}
|
||||
<TrendArrow />
|
||||
</span>
|
||||
);
|
||||
|
||||
return (
|
||||
<Tooltip content={tooltipContent}>
|
||||
{badgeContent}
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
// Minimal variant (just colored dot)
|
||||
if (variant === 'minimal') {
|
||||
const minimalContent = (
|
||||
<div
|
||||
className={clsx(
|
||||
'inline-flex items-center gap-2',
|
||||
onClick && 'cursor-pointer',
|
||||
className
|
||||
)}
|
||||
onClick={onClick}
|
||||
>
|
||||
<div
|
||||
className={clsx(
|
||||
'rounded-full flex-shrink-0',
|
||||
stockLevel.bgColor,
|
||||
size === 'xs' ? 'w-2 h-2' :
|
||||
size === 'sm' ? 'w-3 h-3' :
|
||||
size === 'md' ? 'w-3 h-3' : 'w-4 h-4'
|
||||
)}
|
||||
/>
|
||||
{showLabels && (
|
||||
<span className={clsx(sizeClasses[size].text, stockLevel.color)}>
|
||||
{stockLevel.label}
|
||||
</span>
|
||||
)}
|
||||
<TrendArrow />
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Tooltip content={tooltipContent}>
|
||||
{minimalContent}
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
// Gauge variant (circular progress)
|
||||
if (variant === 'gauge') {
|
||||
const radius = size === 'xs' ? 8 : size === 'sm' ? 12 : size === 'md' ? 16 : 20;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
const strokeDasharray = `${(stockLevel.percentage / 100) * circumference} ${circumference}`;
|
||||
|
||||
const gaugeContent = (
|
||||
<div
|
||||
className={clsx(
|
||||
'relative inline-flex items-center justify-center',
|
||||
sizeClasses[size].gauge,
|
||||
onClick && 'cursor-pointer',
|
||||
className
|
||||
)}
|
||||
onClick={onClick}
|
||||
>
|
||||
<svg
|
||||
className="transform -rotate-90"
|
||||
width="100%"
|
||||
height="100%"
|
||||
viewBox={`0 0 ${radius * 2 + 8} ${radius * 2 + 8}`}
|
||||
>
|
||||
{/* Background circle */}
|
||||
<circle
|
||||
cx={radius + 4}
|
||||
cy={radius + 4}
|
||||
r={radius}
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
fill="none"
|
||||
className="text-bg-tertiary"
|
||||
/>
|
||||
{/* Progress circle */}
|
||||
<circle
|
||||
cx={radius + 4}
|
||||
cy={radius + 4}
|
||||
r={radius}
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
fill="none"
|
||||
strokeDasharray={strokeDasharray}
|
||||
strokeLinecap="round"
|
||||
className={stockLevel.color}
|
||||
/>
|
||||
</svg>
|
||||
{(showLabels || showPercentage) && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<span className={clsx('font-medium', sizeClasses[size].text, stockLevel.color)}>
|
||||
{showPercentage && maximum
|
||||
? `${Math.round((current / maximum) * 100)}%`
|
||||
: showLabels
|
||||
? stockLevel.label.charAt(0)
|
||||
: ''
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<TrendArrow />
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Tooltip content={tooltipContent}>
|
||||
{gaugeContent}
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
// Default bar variant
|
||||
const barContent = (
|
||||
<div
|
||||
className={clsx(
|
||||
'w-full space-y-1',
|
||||
onClick && 'cursor-pointer',
|
||||
className
|
||||
)}
|
||||
onClick={onClick}
|
||||
>
|
||||
{(showLabels || showPercentage) && (
|
||||
<div className="flex items-center justify-between">
|
||||
{showLabels && (
|
||||
<span className={clsx(sizeClasses[size].text, stockLevel.color, 'font-medium')}>
|
||||
{stockLevel.label}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex items-center">
|
||||
{showPercentage && maximum && (
|
||||
<span className={clsx(sizeClasses[size].text, 'text-text-secondary')}>
|
||||
{((current / maximum) * 100).toFixed(1)}%
|
||||
</span>
|
||||
)}
|
||||
<TrendArrow />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={clsx(
|
||||
'w-full bg-bg-tertiary rounded-full overflow-hidden',
|
||||
sizeClasses[size].container
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={clsx(
|
||||
'h-full rounded-full transition-all duration-300 ease-out',
|
||||
stockLevel.bgColor
|
||||
)}
|
||||
style={{ width: `${Math.min(Math.max(stockLevel.percentage, 2), 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Threshold indicators for bar variant */}
|
||||
{size !== 'xs' && (minimum > 0 || reorderPoint || maximum) && (
|
||||
<div className="relative">
|
||||
{/* Minimum threshold */}
|
||||
{minimum > 0 && maximum && (
|
||||
<div
|
||||
className="absolute top-0 w-0.5 h-2 bg-color-warning opacity-60"
|
||||
style={{ left: `${(minimum / maximum) * 100}%` }}
|
||||
title={`Mínimo: ${minimum} ${unit}`}
|
||||
/>
|
||||
)}
|
||||
{/* Reorder point */}
|
||||
{reorderPoint && maximum && reorderPoint !== minimum && (
|
||||
<div
|
||||
className="absolute top-0 w-0.5 h-2 bg-color-error opacity-60"
|
||||
style={{ left: `${(reorderPoint / maximum) * 100}%` }}
|
||||
title={`Reorden: ${reorderPoint} ${unit}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<Tooltip content={tooltipContent}>
|
||||
{barContent}
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
|
||||
// Helper hook for multiple stock indicators
|
||||
export const useStockLevels = (items: Array<{ current: number; minimum?: number; maximum?: number; reorderPoint?: number }>) => {
|
||||
return useMemo(() => {
|
||||
const levels = {
|
||||
good: 0,
|
||||
low: 0,
|
||||
critical: 0,
|
||||
out: 0,
|
||||
overstocked: 0,
|
||||
};
|
||||
|
||||
items.forEach(item => {
|
||||
const { current, minimum = 0, maximum, reorderPoint } = item;
|
||||
|
||||
if (current <= 0) {
|
||||
levels.out++;
|
||||
} else if (maximum && current > maximum * 1.2) {
|
||||
levels.overstocked++;
|
||||
} else if (current <= (reorderPoint || minimum)) {
|
||||
levels.critical++;
|
||||
} else if (current <= (reorderPoint || minimum) * 1.2) {
|
||||
levels.low++;
|
||||
} else {
|
||||
levels.good++;
|
||||
}
|
||||
});
|
||||
|
||||
return levels;
|
||||
}, [items]);
|
||||
};
|
||||
|
||||
export default StockLevelIndicator;
|
||||
91
frontend/src/components/domain/inventory/index.ts
Normal file
91
frontend/src/components/domain/inventory/index.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
// Inventory Domain Components
|
||||
export { default as InventoryTable, type InventoryTableProps } from './InventoryTable';
|
||||
export { default as StockLevelIndicator, type StockLevelIndicatorProps, useStockLevels } from './StockLevelIndicator';
|
||||
export { default as InventoryForm, type InventoryFormProps } from './InventoryForm';
|
||||
export { default as LowStockAlert, type LowStockAlertProps } from './LowStockAlert';
|
||||
|
||||
// Re-export related types from inventory types
|
||||
export type {
|
||||
InventoryFilters,
|
||||
IngredientResponse,
|
||||
StockAlert,
|
||||
IngredientFormData,
|
||||
UnitOfMeasure,
|
||||
ProductType,
|
||||
AlertSeverity,
|
||||
AlertType,
|
||||
SortOrder,
|
||||
} from '../../../types/inventory.types';
|
||||
|
||||
// Utility exports for common inventory operations
|
||||
export const INVENTORY_CONSTANTS = {
|
||||
// Spanish bakery categories
|
||||
BAKERY_CATEGORIES: [
|
||||
{ value: 'harinas', label: 'Harinas' },
|
||||
{ value: 'levaduras', label: 'Levaduras' },
|
||||
{ value: 'azucares', label: 'Az<41>cares y Endulzantes' },
|
||||
{ value: 'chocolates', label: 'Chocolates y Cacao' },
|
||||
{ value: 'frutas', label: 'Frutas y Frutos Secos' },
|
||||
{ value: 'lacteos', label: 'L<>cteos' },
|
||||
{ value: 'huevos', label: 'Huevos' },
|
||||
{ value: 'mantequillas', label: 'Mantequillas y Grasas' },
|
||||
{ value: 'especias', label: 'Especias y Aromas' },
|
||||
{ value: 'conservantes', label: 'Conservantes y Aditivos' },
|
||||
{ value: 'decoracion', label: 'Decoraci<63>n' },
|
||||
{ value: 'envases', label: 'Envases y Embalajes' },
|
||||
{ value: 'utensilios', label: 'Utensilios y Equipos' },
|
||||
{ value: 'limpieza', label: 'Limpieza e Higiene' },
|
||||
],
|
||||
|
||||
// Stock level filters
|
||||
STOCK_LEVEL_FILTERS: [
|
||||
{ value: '', label: 'Todos los niveles' },
|
||||
{ value: 'good', label: 'Stock Normal' },
|
||||
{ value: 'low', label: 'Stock Bajo' },
|
||||
{ value: 'critical', label: 'Stock Cr<43>tico' },
|
||||
{ value: 'out', label: 'Sin Stock' },
|
||||
],
|
||||
|
||||
// Units of measure commonly used in Spanish bakeries
|
||||
BAKERY_UNITS: [
|
||||
{ value: 'kg', label: 'Kilogramo (kg)' },
|
||||
{ value: 'g', label: 'Gramo (g)' },
|
||||
{ value: 'l', label: 'Litro (l)' },
|
||||
{ value: 'ml', label: 'Mililitro (ml)' },
|
||||
{ value: 'piece', label: 'Pieza (pz)' },
|
||||
{ value: 'package', label: 'Paquete' },
|
||||
{ value: 'bag', label: 'Bolsa' },
|
||||
{ value: 'box', label: 'Caja' },
|
||||
{ value: 'dozen', label: 'Docena' },
|
||||
{ value: 'cup', label: 'Taza' },
|
||||
{ value: 'tbsp', label: 'Cucharada' },
|
||||
{ value: 'tsp', label: 'Cucharadita' },
|
||||
],
|
||||
|
||||
// Default form values for new ingredients
|
||||
DEFAULT_INGREDIENT_VALUES: {
|
||||
low_stock_threshold: 10,
|
||||
reorder_point: 20,
|
||||
reorder_quantity: 50,
|
||||
is_perishable: false,
|
||||
requires_refrigeration: false,
|
||||
requires_freezing: false,
|
||||
},
|
||||
|
||||
// Alert severity colors and labels
|
||||
ALERT_SEVERITY: {
|
||||
CRITICAL: { label: 'Cr<43>tico', color: 'error', priority: 1 },
|
||||
HIGH: { label: 'Alto', color: 'warning', priority: 2 },
|
||||
MEDIUM: { label: 'Medio', color: 'info', priority: 3 },
|
||||
LOW: { label: 'Bajo', color: 'secondary', priority: 4 },
|
||||
},
|
||||
|
||||
// Stock status indicators
|
||||
STOCK_STATUS: {
|
||||
GOOD: { label: 'Normal', color: 'success' },
|
||||
LOW: { label: 'Bajo', color: 'warning' },
|
||||
CRITICAL: { label: 'Cr<43>tico', color: 'error' },
|
||||
OUT: { label: 'Sin Stock', color: 'error' },
|
||||
OVERSTOCKED: { label: 'Sobrestock', color: 'info' },
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user