feat: Complete final 2 wizards - Customer Order and Recipe with full API integration
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
|
||||
import {
|
||||
Users,
|
||||
@@ -10,7 +10,26 @@ import {
|
||||
CheckCircle2,
|
||||
Calendar,
|
||||
MapPin,
|
||||
Loader2,
|
||||
} from 'lucide-react';
|
||||
import { useTenant } from '../../../../stores/tenant.store';
|
||||
import OrdersService from '../../../../api/services/orders';
|
||||
import { inventoryService } from '../../../../api/services/inventory';
|
||||
import {
|
||||
CustomerCreate,
|
||||
CustomerType,
|
||||
DeliveryMethod,
|
||||
PaymentTerms,
|
||||
CustomerSegment,
|
||||
PriorityLevel,
|
||||
OrderCreate,
|
||||
OrderItemCreate,
|
||||
OrderType,
|
||||
OrderSource,
|
||||
SalesChannel,
|
||||
PaymentMethod,
|
||||
} from '../../../../api/types/orders';
|
||||
import { ProductType } from '../../../../api/types/inventory';
|
||||
|
||||
interface WizardDataProps extends WizardStepProps {
|
||||
data: Record<string, any>;
|
||||
@@ -19,25 +38,47 @@ interface WizardDataProps extends WizardStepProps {
|
||||
|
||||
// Step 1: Customer Selection
|
||||
const CustomerSelectionStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext }) => {
|
||||
const { currentTenant } = useTenant();
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [showNewCustomerForm, setShowNewCustomerForm] = useState(false);
|
||||
const [selectedCustomer, setSelectedCustomer] = useState(data.customer || null);
|
||||
|
||||
// Mock customer data - replace with actual API call
|
||||
const mockCustomers = [
|
||||
{ id: 1, name: 'Restaurante El Molino', type: 'Mayorista', phone: '+34 123 456 789' },
|
||||
{ id: 2, name: 'Cafetería Central', type: 'Minorista', phone: '+34 987 654 321' },
|
||||
{ id: 3, name: 'Hotel Vista Mar', type: 'Eventos', phone: '+34 555 123 456' },
|
||||
];
|
||||
const [customers, setCustomers] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [creatingCustomer, setCreatingCustomer] = useState(false);
|
||||
|
||||
const [newCustomer, setNewCustomer] = useState({
|
||||
name: '',
|
||||
type: 'retail',
|
||||
type: CustomerType.BUSINESS,
|
||||
phone: '',
|
||||
email: '',
|
||||
});
|
||||
|
||||
const filteredCustomers = mockCustomers.filter((customer) =>
|
||||
useEffect(() => {
|
||||
fetchCustomers();
|
||||
}, []);
|
||||
|
||||
const fetchCustomers = async () => {
|
||||
if (!currentTenant?.id) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const result = await OrdersService.getCustomers({
|
||||
tenant_id: currentTenant.id,
|
||||
active_only: true,
|
||||
});
|
||||
setCustomers(result);
|
||||
} catch (err: any) {
|
||||
console.error('Error loading customers:', err);
|
||||
setError('Error al cargar clientes');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredCustomers = customers.filter((customer) =>
|
||||
customer.name.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
);
|
||||
|
||||
@@ -46,13 +87,47 @@ const CustomerSelectionStep: React.FC<WizardDataProps> = ({ data, onDataChange,
|
||||
setShowNewCustomerForm(false);
|
||||
};
|
||||
|
||||
const handleContinue = () => {
|
||||
const handleContinue = async () => {
|
||||
if (!currentTenant?.id) {
|
||||
setError('No se pudo obtener información del tenant');
|
||||
return;
|
||||
}
|
||||
|
||||
if (showNewCustomerForm) {
|
||||
onDataChange({ ...data, customer: newCustomer, isNewCustomer: true });
|
||||
// Create new customer via API
|
||||
setCreatingCustomer(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const customerData: CustomerCreate = {
|
||||
tenant_id: currentTenant.id,
|
||||
customer_code: `CUST-${Date.now()}`,
|
||||
name: newCustomer.name,
|
||||
customer_type: newCustomer.type,
|
||||
phone: newCustomer.phone,
|
||||
email: newCustomer.email,
|
||||
country: 'ES',
|
||||
is_active: true,
|
||||
preferred_delivery_method: DeliveryMethod.DELIVERY,
|
||||
payment_terms: PaymentTerms.IMMEDIATE,
|
||||
discount_percentage: 0,
|
||||
customer_segment: CustomerSegment.REGULAR,
|
||||
priority_level: PriorityLevel.NORMAL,
|
||||
};
|
||||
|
||||
const createdCustomer = await OrdersService.createCustomer(customerData);
|
||||
onDataChange({ ...data, customer: createdCustomer, isNewCustomer: true });
|
||||
onNext();
|
||||
} catch (err: any) {
|
||||
console.error('Error creating customer:', err);
|
||||
setError(err.response?.data?.detail || 'Error al crear el cliente');
|
||||
} finally {
|
||||
setCreatingCustomer(false);
|
||||
}
|
||||
} else {
|
||||
onDataChange({ ...data, customer: selectedCustomer, isNewCustomer: false });
|
||||
onNext();
|
||||
}
|
||||
onNext();
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -67,7 +142,18 @@ const CustomerSelectionStep: React.FC<WizardDataProps> = ({ data, onDataChange,
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{!showNewCustomerForm ? (
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-[var(--color-primary)]" />
|
||||
<span className="ml-3 text-[var(--text-secondary)]">Cargando clientes...</span>
|
||||
</div>
|
||||
) : !showNewCustomerForm ? (
|
||||
<>
|
||||
{/* Search Bar */}
|
||||
<div className="relative">
|
||||
@@ -97,7 +183,7 @@ const CustomerSelectionStep: React.FC<WizardDataProps> = ({ data, onDataChange,
|
||||
<div>
|
||||
<p className="font-semibold text-[var(--text-primary)]">{customer.name}</p>
|
||||
<p className="text-sm text-[var(--text-secondary)]">
|
||||
{customer.type} • {customer.phone}
|
||||
{customer.customer_type} • {customer.phone || 'Sin teléfono'}
|
||||
</p>
|
||||
</div>
|
||||
{selectedCustomer?.id === customer.id && (
|
||||
@@ -197,10 +283,15 @@ const CustomerSelectionStep: React.FC<WizardDataProps> = ({ data, onDataChange,
|
||||
<div className="flex justify-end pt-4 border-t border-[var(--border-primary)]">
|
||||
<button
|
||||
onClick={handleContinue}
|
||||
disabled={!selectedCustomer && (!showNewCustomerForm || !newCustomer.name || !newCustomer.phone)}
|
||||
className="px-6 py-2.5 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary)]/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
disabled={
|
||||
creatingCustomer ||
|
||||
loading ||
|
||||
(!selectedCustomer && (!showNewCustomerForm || !newCustomer.name || !newCustomer.phone))
|
||||
}
|
||||
className="px-6 py-2.5 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary)]/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors inline-flex items-center gap-2"
|
||||
>
|
||||
Continuar
|
||||
{creatingCustomer && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
{creatingCustomer ? 'Creando cliente...' : 'Continuar'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -209,15 +300,36 @@ const CustomerSelectionStep: React.FC<WizardDataProps> = ({ data, onDataChange,
|
||||
|
||||
// Step 2: Order Items
|
||||
const OrderItemsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext }) => {
|
||||
const { currentTenant } = useTenant();
|
||||
const [orderItems, setOrderItems] = useState(data.orderItems || []);
|
||||
const [products, setProducts] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Mock product data - replace with actual API call
|
||||
const mockProducts = [
|
||||
{ id: 1, name: 'Baguette Tradicional', price: 1.5, unit: 'unidad' },
|
||||
{ id: 2, name: 'Croissant de Mantequilla', price: 2.0, unit: 'unidad' },
|
||||
{ id: 3, name: 'Pan Integral', price: 2.5, unit: 'kg' },
|
||||
{ id: 4, name: 'Tarta de Manzana', price: 18.0, unit: 'unidad' },
|
||||
];
|
||||
useEffect(() => {
|
||||
fetchProducts();
|
||||
}, []);
|
||||
|
||||
const fetchProducts = async () => {
|
||||
if (!currentTenant?.id) return;
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const allIngredients = await inventoryService.getIngredients(currentTenant.id);
|
||||
// Filter for finished products only
|
||||
const finishedProducts = allIngredients.filter(
|
||||
(ingredient) => ingredient.product_type === ProductType.FINISHED_PRODUCT
|
||||
);
|
||||
setProducts(finishedProducts);
|
||||
} catch (err: any) {
|
||||
console.error('Error loading products:', err);
|
||||
setError('Error al cargar productos');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddItem = () => {
|
||||
setOrderItems([
|
||||
@@ -233,10 +345,11 @@ const OrderItemsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext
|
||||
|
||||
// If product selected, update price and name
|
||||
if (field === 'productId') {
|
||||
const product = mockProducts.find((p) => p.id === parseInt(value));
|
||||
const product = products.find((p) => p.id === value);
|
||||
if (product) {
|
||||
newItem.productName = product.name;
|
||||
newItem.unitPrice = product.price;
|
||||
newItem.unitPrice = product.average_cost || product.last_purchase_price || 0;
|
||||
newItem.unitOfMeasure = product.unit_of_measure;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,8 +389,21 @@ const OrderItemsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Order Items */}
|
||||
<div className="space-y-3">
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-[var(--color-primary)]" />
|
||||
<span className="ml-3 text-[var(--text-secondary)]">Cargando productos...</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{/* Order Items */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<label className="block text-sm font-medium text-[var(--text-secondary)]">
|
||||
Productos del Pedido
|
||||
@@ -327,9 +453,9 @@ const OrderItemsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext
|
||||
className="w-full px-3 py-2 text-sm border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
|
||||
>
|
||||
<option value="">Seleccionar producto...</option>
|
||||
{mockProducts.map((product) => (
|
||||
{products.map((product) => (
|
||||
<option key={product.id} value={product.id}>
|
||||
{product.name} - €{product.price.toFixed(2)} / {product.unit}
|
||||
{product.name} - €{(product.average_cost || product.last_purchase_price || 0).toFixed(2)} / {product.unit_of_measure}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
@@ -399,12 +525,14 @@ const OrderItemsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Continue Button */}
|
||||
<div className="flex justify-end pt-4 border-t border-[var(--border-primary)]">
|
||||
<button
|
||||
onClick={handleContinue}
|
||||
disabled={orderItems.length === 0}
|
||||
disabled={loading || orderItems.length === 0}
|
||||
className="px-6 py-2.5 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary)]/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
Continuar
|
||||
@@ -416,6 +544,9 @@ const OrderItemsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext
|
||||
|
||||
// Step 3: Delivery & Payment
|
||||
const DeliveryPaymentStep: React.FC<WizardDataProps> = ({ data, onDataChange, onComplete }) => {
|
||||
const { currentTenant } = useTenant();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deliveryData, setDeliveryData] = useState({
|
||||
deliveryDate: data.deliveryDate || '',
|
||||
deliveryTime: data.deliveryTime || '',
|
||||
@@ -426,11 +557,90 @@ const DeliveryPaymentStep: React.FC<WizardDataProps> = ({ data, onDataChange, on
|
||||
orderStatus: data.orderStatus || 'pending',
|
||||
});
|
||||
|
||||
const handleConfirm = () => {
|
||||
onDataChange({ ...data, ...deliveryData });
|
||||
// Here you would typically make an API call to save the order
|
||||
console.log('Saving order:', { ...data, ...deliveryData });
|
||||
onComplete();
|
||||
const handleConfirm = async () => {
|
||||
if (!currentTenant?.id) {
|
||||
setError('No se pudo obtener información del tenant');
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Map UI delivery method to API enum
|
||||
const deliveryMethodMap: Record<string, DeliveryMethod> = {
|
||||
pickup: DeliveryMethod.PICKUP,
|
||||
delivery: DeliveryMethod.DELIVERY,
|
||||
shipping: DeliveryMethod.DELIVERY,
|
||||
};
|
||||
|
||||
// Map UI payment method to API enum
|
||||
const paymentMethodMap: Record<string, PaymentMethod> = {
|
||||
cash: PaymentMethod.CASH,
|
||||
card: PaymentMethod.CARD,
|
||||
transfer: PaymentMethod.BANK_TRANSFER,
|
||||
invoice: PaymentMethod.ACCOUNT,
|
||||
'invoice-30': PaymentMethod.ACCOUNT,
|
||||
paid: PaymentMethod.CARD,
|
||||
};
|
||||
|
||||
// Map UI payment method to payment terms
|
||||
const paymentTermsMap: Record<string, PaymentTerms> = {
|
||||
cash: PaymentTerms.IMMEDIATE,
|
||||
card: PaymentTerms.IMMEDIATE,
|
||||
transfer: PaymentTerms.IMMEDIATE,
|
||||
invoice: PaymentTerms.NET_30,
|
||||
'invoice-30': PaymentTerms.NET_30,
|
||||
paid: PaymentTerms.IMMEDIATE,
|
||||
};
|
||||
|
||||
// Prepare order items
|
||||
const orderItems: OrderItemCreate[] = data.orderItems.map((item: any) => ({
|
||||
product_id: item.productId,
|
||||
product_name: item.productName,
|
||||
quantity: item.quantity,
|
||||
unit_of_measure: item.unitOfMeasure || 'unit',
|
||||
unit_price: item.unitPrice,
|
||||
line_discount: 0,
|
||||
customization_details: item.customRequirements || undefined,
|
||||
special_instructions: item.customRequirements || undefined,
|
||||
}));
|
||||
|
||||
// Prepare delivery address
|
||||
const deliveryAddress = (deliveryData.deliveryMethod === 'delivery' || deliveryData.deliveryMethod === 'shipping')
|
||||
? { address: deliveryData.deliveryAddress }
|
||||
: undefined;
|
||||
|
||||
// Create order data
|
||||
const orderData: OrderCreate = {
|
||||
tenant_id: currentTenant.id,
|
||||
customer_id: data.customer.id,
|
||||
order_type: OrderType.STANDARD,
|
||||
priority: PriorityLevel.NORMAL,
|
||||
requested_delivery_date: deliveryData.deliveryDate,
|
||||
delivery_method: deliveryMethodMap[deliveryData.deliveryMethod],
|
||||
delivery_address: deliveryAddress,
|
||||
delivery_instructions: deliveryData.specialInstructions || undefined,
|
||||
discount_percentage: 0,
|
||||
delivery_fee: 0,
|
||||
payment_method: paymentMethodMap[deliveryData.paymentMethod],
|
||||
payment_terms: paymentTermsMap[deliveryData.paymentMethod],
|
||||
special_instructions: deliveryData.specialInstructions || undefined,
|
||||
order_source: OrderSource.MANUAL,
|
||||
sales_channel: SalesChannel.DIRECT,
|
||||
items: orderItems,
|
||||
};
|
||||
|
||||
await OrdersService.createOrder(orderData);
|
||||
|
||||
onDataChange({ ...data, ...deliveryData });
|
||||
onComplete();
|
||||
} catch (err: any) {
|
||||
console.error('Error creating order:', err);
|
||||
setError(err.response?.data?.detail || 'Error al crear el pedido');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -445,6 +655,12 @@ const DeliveryPaymentStep: React.FC<WizardDataProps> = ({ data, onDataChange, on
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Delivery Date & Time */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
@@ -611,11 +827,24 @@ const DeliveryPaymentStep: React.FC<WizardDataProps> = ({ data, onDataChange, on
|
||||
<div className="flex justify-end gap-3 pt-4 border-t border-[var(--border-primary)]">
|
||||
<button
|
||||
onClick={handleConfirm}
|
||||
disabled={!deliveryData.deliveryDate || (deliveryData.deliveryMethod !== 'pickup' && !deliveryData.deliveryAddress)}
|
||||
disabled={
|
||||
loading ||
|
||||
!deliveryData.deliveryDate ||
|
||||
(deliveryData.deliveryMethod !== 'pickup' && !deliveryData.deliveryAddress)
|
||||
}
|
||||
className="px-8 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors font-semibold inline-flex items-center gap-2"
|
||||
>
|
||||
<CheckCircle2 className="w-5 h-5" />
|
||||
Confirmar Pedido
|
||||
{loading ? (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
Creando pedido...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle2 className="w-5 h-5" />
|
||||
Confirmar Pedido
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import React, { useState } from 'react';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
|
||||
import { ChefHat, Package, ClipboardCheck, CheckCircle2 } from 'lucide-react';
|
||||
import { ChefHat, Package, ClipboardCheck, CheckCircle2, Loader2, Plus, X, Search } from 'lucide-react';
|
||||
import { useTenant } from '../../../../stores/tenant.store';
|
||||
import { recipesService } from '../../../../api/services/recipes';
|
||||
import { inventoryService } from '../../../../api/services/inventory';
|
||||
import { IngredientResponse } from '../../../../api/types/inventory';
|
||||
import { RecipeCreate, RecipeIngredientCreate, MeasurementUnit } from '../../../../api/types/recipes';
|
||||
|
||||
interface WizardDataProps extends WizardStepProps {
|
||||
data: Record<string, any>;
|
||||
@@ -8,12 +13,37 @@ interface WizardDataProps extends WizardStepProps {
|
||||
}
|
||||
|
||||
const RecipeDetailsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext }) => {
|
||||
const { currentTenant } = useTenant();
|
||||
const [recipeData, setRecipeData] = useState({
|
||||
name: data.name || '',
|
||||
category: data.category || 'bread',
|
||||
yield: data.yield || '',
|
||||
yieldQuantity: data.yieldQuantity || '',
|
||||
yieldUnit: data.yieldUnit || 'units',
|
||||
prepTime: data.prepTime || '',
|
||||
finishedProductId: data.finishedProductId || '',
|
||||
instructions: data.instructions || '',
|
||||
});
|
||||
const [finishedProducts, setFinishedProducts] = useState<IngredientResponse[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
fetchFinishedProducts();
|
||||
}, []);
|
||||
|
||||
const fetchFinishedProducts = async () => {
|
||||
if (!currentTenant?.id) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await inventoryService.getIngredients(currentTenant.id, {
|
||||
category: 'finished_product'
|
||||
});
|
||||
setFinishedProducts(result);
|
||||
} catch (err) {
|
||||
console.error('Error loading finished products:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -24,29 +54,225 @@ const RecipeDetailsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNe
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Nombre *</label>
|
||||
<input type="text" value={recipeData.name} onChange={(e) => setRecipeData({ ...recipeData, name: e.target.value })} placeholder="Ej: Baguette Tradicional" className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]" />
|
||||
<input
|
||||
type="text"
|
||||
value={recipeData.name}
|
||||
onChange={(e) => setRecipeData({ ...recipeData, name: e.target.value })}
|
||||
placeholder="Ej: Baguette Tradicional"
|
||||
className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Categoría *</label>
|
||||
<select value={recipeData.category} onChange={(e) => setRecipeData({ ...recipeData, category: e.target.value })} className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]">
|
||||
<select
|
||||
value={recipeData.category}
|
||||
onChange={(e) => setRecipeData({ ...recipeData, category: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
|
||||
>
|
||||
<option value="bread">Pan</option>
|
||||
<option value="pastry">Pastelería</option>
|
||||
<option value="cake">Repostería</option>
|
||||
<option value="cookie">Galletas</option>
|
||||
<option value="other">Otro</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Producto Terminado *</label>
|
||||
<select
|
||||
value={recipeData.finishedProductId}
|
||||
onChange={(e) => setRecipeData({ ...recipeData, finishedProductId: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
|
||||
disabled={loading}
|
||||
>
|
||||
<option value="">Seleccionar producto...</option>
|
||||
{finishedProducts.map(product => (
|
||||
<option key={product.id} value={product.id}>{product.name}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Rendimiento *</label>
|
||||
<input type="number" value={recipeData.yield} onChange={(e) => setRecipeData({ ...recipeData, yield: e.target.value })} placeholder="12 unidades" className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]" min="1" />
|
||||
<input
|
||||
type="number"
|
||||
value={recipeData.yieldQuantity}
|
||||
onChange={(e) => setRecipeData({ ...recipeData, yieldQuantity: e.target.value })}
|
||||
placeholder="12"
|
||||
className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
|
||||
min="1"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Unidad *</label>
|
||||
<select
|
||||
value={recipeData.yieldUnit}
|
||||
onChange={(e) => setRecipeData({ ...recipeData, yieldUnit: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
|
||||
>
|
||||
<option value="units">Unidades</option>
|
||||
<option value="kg">Kilogramos</option>
|
||||
<option value="g">Gramos</option>
|
||||
<option value="l">Litros</option>
|
||||
<option value="ml">Mililitros</option>
|
||||
<option value="pieces">Piezas</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Tiempo de Preparación (min)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={recipeData.prepTime}
|
||||
onChange={(e) => setRecipeData({ ...recipeData, prepTime: e.target.value })}
|
||||
placeholder="60"
|
||||
className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
|
||||
min="0"
|
||||
/>
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Instrucciones</label>
|
||||
<textarea
|
||||
value={recipeData.instructions}
|
||||
onChange={(e) => setRecipeData({ ...recipeData, instructions: e.target.value })}
|
||||
placeholder="Pasos de preparación de la receta..."
|
||||
className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]"
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end pt-4 border-t border-[var(--border-primary)]">
|
||||
<button onClick={() => { onDataChange({ ...data, ...recipeData }); onNext(); }} disabled={!recipeData.name || !recipeData.yield} className="px-6 py-2.5 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary)]/90 disabled:opacity-50 disabled:cursor-not-allowed">Continuar</button>
|
||||
<button
|
||||
onClick={() => { onDataChange({ ...data, ...recipeData }); onNext(); }}
|
||||
disabled={!recipeData.name || !recipeData.yieldQuantity || !recipeData.finishedProductId}
|
||||
className="px-6 py-2.5 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary)]/90 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
Continuar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
interface SelectedIngredient {
|
||||
id: string;
|
||||
ingredientId: string;
|
||||
quantity: number;
|
||||
unit: MeasurementUnit;
|
||||
notes: string;
|
||||
order: number;
|
||||
}
|
||||
|
||||
const IngredientsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onComplete }) => {
|
||||
const { currentTenant } = useTenant();
|
||||
const [ingredients, setIngredients] = useState<IngredientResponse[]>([]);
|
||||
const [selectedIngredients, setSelectedIngredients] = useState<SelectedIngredient[]>(data.ingredients || []);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
fetchIngredients();
|
||||
}, []);
|
||||
|
||||
const fetchIngredients = async () => {
|
||||
if (!currentTenant?.id) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await inventoryService.getIngredients(currentTenant.id);
|
||||
// Filter out finished products - we only want raw ingredients
|
||||
const rawIngredients = result.filter(ing => ing.category !== 'finished_product');
|
||||
setIngredients(rawIngredients);
|
||||
} catch (err) {
|
||||
setError('Error al cargar ingredientes');
|
||||
console.error('Error loading ingredients:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddIngredient = () => {
|
||||
const newIngredient: SelectedIngredient = {
|
||||
id: Date.now().toString(),
|
||||
ingredientId: '',
|
||||
quantity: 0,
|
||||
unit: MeasurementUnit.GRAMS,
|
||||
notes: '',
|
||||
order: selectedIngredients.length + 1,
|
||||
};
|
||||
setSelectedIngredients([...selectedIngredients, newIngredient]);
|
||||
};
|
||||
|
||||
const handleUpdateIngredient = (id: string, field: keyof SelectedIngredient, value: any) => {
|
||||
setSelectedIngredients(
|
||||
selectedIngredients.map(ing =>
|
||||
ing.id === id ? { ...ing, [field]: value } : ing
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const handleRemoveIngredient = (id: string) => {
|
||||
setSelectedIngredients(selectedIngredients.filter(ing => ing.id !== id));
|
||||
};
|
||||
|
||||
const handleSaveRecipe = async () => {
|
||||
if (!currentTenant?.id) {
|
||||
setError('No se pudo obtener información del tenant');
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedIngredients.length === 0) {
|
||||
setError('Debes agregar al menos un ingrediente');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate all ingredients are filled
|
||||
const invalidIngredients = selectedIngredients.filter(
|
||||
ing => !ing.ingredientId || ing.quantity <= 0
|
||||
);
|
||||
if (invalidIngredients.length > 0) {
|
||||
setError('Todos los ingredientes deben tener un ingrediente seleccionado y cantidad mayor a 0');
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Prepare recipe data according to RecipeCreate interface
|
||||
const recipeIngredients: RecipeIngredientCreate[] = selectedIngredients.map((ing, index) => ({
|
||||
ingredient_id: ing.ingredientId,
|
||||
quantity: ing.quantity,
|
||||
unit: ing.unit,
|
||||
ingredient_notes: ing.notes || null,
|
||||
is_optional: false,
|
||||
ingredient_order: index + 1,
|
||||
}));
|
||||
|
||||
const recipeData: RecipeCreate = {
|
||||
name: data.name,
|
||||
category: data.category,
|
||||
finished_product_id: data.finishedProductId,
|
||||
yield_quantity: parseFloat(data.yieldQuantity),
|
||||
yield_unit: data.yieldUnit as MeasurementUnit,
|
||||
prep_time_minutes: data.prepTime ? parseInt(data.prepTime) : null,
|
||||
instructions: data.instructions ? { steps: data.instructions } : null,
|
||||
ingredients: recipeIngredients,
|
||||
};
|
||||
|
||||
await recipesService.createRecipe(currentTenant.id, recipeData);
|
||||
onDataChange({ ...data, ingredients: selectedIngredients });
|
||||
onComplete();
|
||||
} catch (err: any) {
|
||||
console.error('Error creating recipe:', err);
|
||||
setError(err.response?.data?.detail || 'Error al crear la receta');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const filteredIngredients = ingredients.filter(ing =>
|
||||
ing.name.toLowerCase().includes(searchTerm.toLowerCase())
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="text-center pb-4 border-b border-[var(--border-primary)]">
|
||||
@@ -54,12 +280,132 @@ const IngredientsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onComp
|
||||
<h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">Ingredientes</h3>
|
||||
<p className="text-sm text-[var(--text-secondary)]">{data.name}</p>
|
||||
</div>
|
||||
<div className="text-center py-12 border-2 border-dashed border-[var(--border-secondary)] rounded-lg">
|
||||
<p className="text-[var(--text-secondary)] mb-4">La selección de ingredientes será agregada en una mejora futura</p>
|
||||
<p className="text-sm text-[var(--text-tertiary)]">Por ahora, puedes crear la receta y agregar ingredientes después</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-[var(--color-primary)]" />
|
||||
<span className="ml-3 text-[var(--text-secondary)]">Cargando ingredientes...</span>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-4">
|
||||
{selectedIngredients.length === 0 ? (
|
||||
<div className="text-center py-8 border-2 border-dashed border-[var(--border-secondary)] rounded-lg">
|
||||
<Package className="w-12 h-12 mx-auto mb-3 text-[var(--text-tertiary)]" />
|
||||
<p className="text-[var(--text-secondary)] mb-2">No hay ingredientes agregados</p>
|
||||
<p className="text-sm text-[var(--text-tertiary)]">Haz clic en "Agregar Ingrediente" para comenzar</p>
|
||||
</div>
|
||||
) : (
|
||||
selectedIngredients.map((selectedIng) => (
|
||||
<div key={selectedIng.id} className="p-4 border border-[var(--border-secondary)] rounded-lg bg-[var(--bg-secondary)]">
|
||||
<div className="grid grid-cols-1 md:grid-cols-12 gap-3 items-start">
|
||||
<div className="md:col-span-5">
|
||||
<label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Ingrediente *</label>
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-[var(--text-tertiary)]" />
|
||||
<select
|
||||
value={selectedIng.ingredientId}
|
||||
onChange={(e) => handleUpdateIngredient(selectedIng.id, 'ingredientId', e.target.value)}
|
||||
className="w-full pl-9 pr-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-sm"
|
||||
>
|
||||
<option value="">Seleccionar...</option>
|
||||
{filteredIngredients.map(ing => (
|
||||
<option key={ing.id} value={ing.id}>
|
||||
{ing.name} {ing.category ? `(${ing.category})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Cantidad *</label>
|
||||
<input
|
||||
type="number"
|
||||
value={selectedIng.quantity || ''}
|
||||
onChange={(e) => handleUpdateIngredient(selectedIng.id, 'quantity', parseFloat(e.target.value) || 0)}
|
||||
placeholder="0"
|
||||
className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-sm"
|
||||
min="0"
|
||||
step="0.01"
|
||||
/>
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Unidad *</label>
|
||||
<select
|
||||
value={selectedIng.unit}
|
||||
onChange={(e) => handleUpdateIngredient(selectedIng.id, 'unit', e.target.value as MeasurementUnit)}
|
||||
className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-sm"
|
||||
>
|
||||
<option value={MeasurementUnit.GRAMS}>Gramos (g)</option>
|
||||
<option value={MeasurementUnit.KILOGRAMS}>Kilogramos (kg)</option>
|
||||
<option value={MeasurementUnit.MILLILITERS}>Mililitros (ml)</option>
|
||||
<option value={MeasurementUnit.LITERS}>Litros (l)</option>
|
||||
<option value={MeasurementUnit.UNITS}>Unidades</option>
|
||||
<option value={MeasurementUnit.PIECES}>Piezas</option>
|
||||
<option value={MeasurementUnit.CUPS}>Tazas</option>
|
||||
<option value={MeasurementUnit.TABLESPOONS}>Cucharadas</option>
|
||||
<option value={MeasurementUnit.TEASPOONS}>Cucharaditas</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="md:col-span-2">
|
||||
<label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Notas</label>
|
||||
<input
|
||||
type="text"
|
||||
value={selectedIng.notes}
|
||||
onChange={(e) => handleUpdateIngredient(selectedIng.id, 'notes', e.target.value)}
|
||||
placeholder="Opcional"
|
||||
className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div className="md:col-span-1 flex items-end">
|
||||
<button
|
||||
onClick={() => handleRemoveIngredient(selectedIng.id)}
|
||||
className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
|
||||
title="Eliminar ingrediente"
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleAddIngredient}
|
||||
className="w-full py-3 border-2 border-dashed border-[var(--border-secondary)] rounded-lg text-[var(--text-secondary)] hover:border-[var(--color-primary)] hover:text-[var(--color-primary)] transition-colors inline-flex items-center justify-center gap-2"
|
||||
>
|
||||
<Plus className="w-5 h-5" />
|
||||
Agregar Ingrediente
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-3 pt-4 border-t border-[var(--border-primary)]">
|
||||
<button onClick={() => { console.log('Saving recipe:', data); onComplete(); }} className="px-8 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 font-semibold inline-flex items-center gap-2"><CheckCircle2 className="w-5 h-5" />Crear Receta</button>
|
||||
<button
|
||||
onClick={handleSaveRecipe}
|
||||
disabled={saving || selectedIngredients.length === 0 || loading}
|
||||
className="px-8 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 font-semibold inline-flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{saving ? (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
Creando...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle2 className="w-5 h-5" />
|
||||
Crear Receta
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -67,5 +413,5 @@ const IngredientsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onComp
|
||||
|
||||
export const RecipeWizardSteps = (data: Record<string, any>, setData: (data: Record<string, any>) => void): WizardStep[] => [
|
||||
{ id: 'recipe-details', title: 'Detalles de la Receta', description: 'Nombre, categoría, rendimiento', component: (props) => <RecipeDetailsStep {...props} data={data} onDataChange={setData} /> },
|
||||
{ id: 'recipe-ingredients', title: 'Ingredientes', description: 'Configuración futura', component: (props) => <IngredientsStep {...props} data={data} onDataChange={setData} />, isOptional: true },
|
||||
{ id: 'recipe-ingredients', title: 'Ingredientes', description: 'Selección y cantidades', component: (props) => <IngredientsStep {...props} data={data} onDataChange={setData} /> },
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user