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>
|
||||
|
||||
Reference in New Issue
Block a user