Files
bakery-ia/frontend/src/components/domain/onboarding/steps/RegisterTenantStep.tsx

227 lines
7.4 KiB
TypeScript
Raw Normal View History

import React, { useState } from 'react';
import { Button, Input } from '../../../ui';
import { AddressAutocomplete } from '../../../ui/AddressAutocomplete';
import { useRegisterBakery } from '../../../../api/hooks/tenant';
import { BakeryRegistration } from '../../../../api/types/tenant';
import { AddressResult } from '../../../../services/api/geocodingApi';
import { useWizardContext } from '../context';
feat: Improve onboarding wizard UI, UX and dark mode support This commit implements multiple improvements to the onboarding wizard: **1. Unified UI Components:** - Created InfoCard component for consistent "why is important" blocks across all steps - Created TemplateCard component for consistent template displays - Both components use global CSS variables for proper dark mode support **2. Initial Stock Entry Step Improvements:** - Fixed title/subtitle positioning using unified InfoCard component - Fixed missing count bug in warning message (now uses {{count}} interpolation) - Fixed dark mode colors using CSS variables (--color-success, --color-info, etc.) - Changed next button title from "completar configuración" to "Continuar →" - Implemented stock creation API call using useAddStock hook - Products with stock now properly save to backend on step completion **3. Dark Mode Fixes:** - Fixed QualitySetupStep: Enhanced button selection visibility with rings and shadows - Fixed TeamSetupStep: Enhanced role selection visibility with rings and shadows - Fixed AddressAutocomplete: Replaced all hardcoded colors with CSS variables - All dropdown results, icons, and hover states now properly adapt to dark mode **4. Streamlined Wizard Flow:** - Removed POI Detection step from wizard (step previously added complexity) - POI detection now runs automatically in background after tenant registration - Non-blocking approach ensures users aren't delayed by POI detection - Removed Revision step (setup-review) as it adds no user value - Completion step is now the final step before dashboard **5. Backend Updates:** - Updated onboarding_progress.py to remove poi-detection from ONBOARDING_STEPS - Updated onboarding_progress.py to remove setup-review from ONBOARDING_STEPS - Updated step dependencies to reflect streamlined flow - POI detection documented as automatic background process All changes maintain backward compatibility and use proper TypeScript types.
2025-11-12 14:48:46 +00:00
import { poiContextApi } from '../../../../services/api/poiContextApi';
interface RegisterTenantStepProps {
onNext: () => void;
onPrevious: () => void;
onComplete: (data?: any) => void;
isFirstStep: boolean;
isLastStep: boolean;
}
export const RegisterTenantStep: React.FC<RegisterTenantStepProps> = ({
onComplete,
isFirstStep
}) => {
const wizardContext = useWizardContext();
const [formData, setFormData] = useState<BakeryRegistration>({
name: '',
address: '',
postal_code: '',
phone: '',
city: 'Madrid',
business_type: 'bakery',
business_model: 'individual_bakery'
});
const [errors, setErrors] = useState<Record<string, string>>({});
const registerBakery = useRegisterBakery();
const handleInputChange = (field: keyof BakeryRegistration, value: string) => {
setFormData(prev => ({
...prev,
[field]: value
}));
if (errors[field]) {
setErrors(prev => ({
...prev,
[field]: ''
}));
}
};
const handleAddressSelect = (address: AddressResult) => {
setFormData(prev => ({
...prev,
address: address.display_name,
city: address.address.city || address.address.municipality || address.address.suburb || prev.city,
postal_code: address.address.postcode || prev.postal_code,
}));
};
const handleCoordinatesChange = (lat: number, lon: number) => {
// Store coordinates in the wizard context immediately
// This allows the POI detection step to access location information when it's available
wizardContext.updateLocation({ latitude: lat, longitude: lon });
console.log('Coordinates captured and stored:', { latitude: lat, longitude: lon });
};
const validateForm = () => {
const newErrors: Record<string, string> = {};
// Required fields according to backend BakeryRegistration schema
if (!formData.name.trim()) {
newErrors.name = 'El nombre de la panadería es obligatorio';
} else if (formData.name.length < 2 || formData.name.length > 200) {
newErrors.name = 'El nombre debe tener entre 2 y 200 caracteres';
}
if (!formData.address.trim()) {
newErrors.address = 'La dirección es obligatoria';
} else if (formData.address.length < 10 || formData.address.length > 500) {
newErrors.address = 'La dirección debe tener entre 10 y 500 caracteres';
}
if (!formData.postal_code.trim()) {
newErrors.postal_code = 'El código postal es obligatorio';
} else if (!/^\d{5}$/.test(formData.postal_code)) {
newErrors.postal_code = 'El código postal debe tener exactamente 5 dígitos';
}
if (!formData.phone.trim()) {
newErrors.phone = 'El número de teléfono es obligatorio';
} else if (formData.phone.length < 9 || formData.phone.length > 20) {
newErrors.phone = 'El teléfono debe tener entre 9 y 20 caracteres';
} else {
// Basic Spanish phone validation
const phone = formData.phone.replace(/[\s\-\(\)]/g, '');
const patterns = [
/^(\+34|0034|34)?[6789]\d{8}$/, // Mobile
/^(\+34|0034|34)?9\d{8}$/ // Landline
];
if (!patterns.some(pattern => pattern.test(phone))) {
newErrors.phone = 'Introduce un número de teléfono español válido';
}
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = async () => {
if (!validateForm()) {
return;
}
try {
const tenant = await registerBakery.mutateAsync(formData);
feat: Improve onboarding wizard UI, UX and dark mode support This commit implements multiple improvements to the onboarding wizard: **1. Unified UI Components:** - Created InfoCard component for consistent "why is important" blocks across all steps - Created TemplateCard component for consistent template displays - Both components use global CSS variables for proper dark mode support **2. Initial Stock Entry Step Improvements:** - Fixed title/subtitle positioning using unified InfoCard component - Fixed missing count bug in warning message (now uses {{count}} interpolation) - Fixed dark mode colors using CSS variables (--color-success, --color-info, etc.) - Changed next button title from "completar configuración" to "Continuar →" - Implemented stock creation API call using useAddStock hook - Products with stock now properly save to backend on step completion **3. Dark Mode Fixes:** - Fixed QualitySetupStep: Enhanced button selection visibility with rings and shadows - Fixed TeamSetupStep: Enhanced role selection visibility with rings and shadows - Fixed AddressAutocomplete: Replaced all hardcoded colors with CSS variables - All dropdown results, icons, and hover states now properly adapt to dark mode **4. Streamlined Wizard Flow:** - Removed POI Detection step from wizard (step previously added complexity) - POI detection now runs automatically in background after tenant registration - Non-blocking approach ensures users aren't delayed by POI detection - Removed Revision step (setup-review) as it adds no user value - Completion step is now the final step before dashboard **5. Backend Updates:** - Updated onboarding_progress.py to remove poi-detection from ONBOARDING_STEPS - Updated onboarding_progress.py to remove setup-review from ONBOARDING_STEPS - Updated step dependencies to reflect streamlined flow - POI detection documented as automatic background process All changes maintain backward compatibility and use proper TypeScript types.
2025-11-12 14:48:46 +00:00
// Trigger POI detection in the background (non-blocking)
// This replaces the removed POI Detection step
const bakeryLocation = wizardContext.state.bakeryLocation;
if (bakeryLocation?.latitude && bakeryLocation?.longitude && tenant.id) {
// Run POI detection asynchronously without blocking the wizard flow
poiContextApi.detectPOIs(
tenant.id,
bakeryLocation.latitude,
bakeryLocation.longitude,
false // use_cache = false for initial detection
).then((result) => {
console.log(`✅ POI detection completed automatically for tenant ${tenant.id}:`, result.summary);
}).catch((error) => {
console.warn('⚠️ Background POI detection failed (non-blocking):', error);
// This is non-critical, so we don't block the user
});
}
// Update the wizard context with tenant info
onComplete({
tenant,
tenantId: tenant.id,
bakeryLocation: wizardContext.state.bakeryLocation
});
} catch (error) {
console.error('Error registering bakery:', error);
setErrors({ submit: 'Error al registrar la panadería. Por favor, inténtalo de nuevo.' });
}
};
return (
2025-11-09 09:22:08 +01:00
<div className="space-y-4 md:space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-6">
<Input
label="Nombre de la Panadería"
placeholder="Ingresa el nombre de tu panadería"
value={formData.name}
onChange={(e) => handleInputChange('name', e.target.value)}
error={errors.name}
isRequired
/>
<Input
label="Teléfono"
type="tel"
placeholder="+34 123 456 789"
value={formData.phone}
onChange={(e) => handleInputChange('phone', e.target.value)}
error={errors.phone}
isRequired
/>
<div className="md:col-span-2">
<label className="block text-sm font-medium text-gray-700 mb-1">
Dirección <span className="text-red-500">*</span>
</label>
<AddressAutocomplete
value={formData.address}
placeholder="Enter bakery address..."
onAddressSelect={(address) => {
console.log('Selected:', address.display_name);
handleAddressSelect(address);
}}
onCoordinatesChange={handleCoordinatesChange}
countryCode="es"
required
/>
{errors.address && (
<div className="mt-1 text-sm text-red-600">
{errors.address}
</div>
)}
</div>
<Input
label="Código Postal"
placeholder="28001"
value={formData.postal_code}
onChange={(e) => handleInputChange('postal_code', e.target.value)}
error={errors.postal_code}
isRequired
maxLength={5}
/>
<Input
label="Ciudad (Opcional)"
placeholder="Madrid"
value={formData.city}
onChange={(e) => handleInputChange('city', e.target.value)}
error={errors.city}
/>
</div>
{errors.submit && (
<div className="text-[var(--color-error)] text-sm bg-[var(--color-error)]/10 p-3 rounded-lg">
{errors.submit}
</div>
)}
<div className="flex justify-end">
<Button
onClick={handleSubmit}
isLoading={registerBakery.isPending}
loadingText="Registrando..."
size="lg"
>
Crear Panadería y Continuar
</Button>
</div>
</div>
);
};