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

534 lines
20 KiB
TypeScript
Raw Normal View History

import React, { useState, useEffect, useMemo } from 'react';
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Button } from '../../ui/Button';
import { Card, CardHeader, CardBody } from '../../ui/Card';
import { useAuth } from '../../../contexts/AuthContext';
import { useUserProgress, useMarkStepCompleted } from '../../../api/hooks/onboarding';
import { useTenantActions } from '../../../stores/tenant.store';
import { useTenantInitializer } from '../../../stores/useTenantInitializer';
import { WizardProvider, useWizardContext, BakeryType, DataSource } from './context';
import {
BakeryTypeSelectionStep,
RegisterTenantStep,
UploadSalesDataStep,
ProductCategorizationStep,
InitialStockEntryStep,
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
ProductionProcessesStep,
MLTrainingStep,
CompletionStep
} from './steps';
// Import setup wizard steps
import {
SuppliersSetupStep,
RecipesSetupStep,
QualitySetupStep,
TeamSetupStep,
ReviewSetupStep,
} from '../setup-wizard/steps';
import { Building2 } from 'lucide-react';
interface StepConfig {
id: string;
title: string;
description: string;
component: React.ComponentType<any>;
isConditional?: boolean;
condition?: (context: any) => boolean;
}
interface StepProps {
onNext?: () => void;
onPrevious?: () => void;
onComplete?: (data?: any) => void;
onUpdate?: (data?: any) => void;
isFirstStep?: boolean;
isLastStep?: boolean;
initialData?: any;
}
const OnboardingWizardContent: React.FC = () => {
const { t } = useTranslation();
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { user } = useAuth();
const wizardContext = useWizardContext();
// All possible steps with conditional visibility
Make backend robust with comprehensive onboarding steps Backend Changes (services/auth/app/api/onboarding_progress.py): - Expanded ONBOARDING_STEPS to include all 19 frontend steps - Phase 0: user_registered (system) - Phase 1: bakery-type-selection, data-source-choice (discovery) - Phase 2: setup, smart-inventory-setup, product-categorization, initial-stock-entry (core setup & AI path) - Phase 2b: suppliers-setup, inventory-setup, recipes-setup, production-processes (manual path) - Phase 3: quality-setup, team-setup (advanced config) - Phase 4: ml-training, setup-review, completion (finalization) - Updated STEP_DEPENDENCIES with granular requirements - AI path: smart-inventory-setup → product-categorization → initial-stock-entry - Manual path: Independent setup for suppliers, inventory, recipes, processes - Flexible ML training: accepts either AI or manual inventory path - Enhanced ML training validation - Supports both AI-assisted path (sales data) and manual inventory path - More flexible validation logic for multi-path onboarding Frontend Changes (UnifiedOnboardingWizard.tsx): - Fixed auto-complete step name: 'suppliers' → 'suppliers-setup' - All step IDs now match backend ONBOARDING_STEPS exactly - Removed temporary step mapping workarounds Frontend Changes (apiClient.ts): - Fixed tenant ID requirement warnings for onboarding endpoints - Added noTenantEndpoints list for user-level endpoints: - /auth/me/onboarding (tenant created during onboarding) - /auth/me (user profile) - /auth/register, /auth/login - Eliminated false warnings during onboarding flow This makes the onboarding system fully functional with: ✅ Backend validates all 19 onboarding steps ✅ Proper dependency tracking for multi-path onboarding ✅ No more "Invalid step name" errors ✅ No more tenant ID warnings for onboarding ✅ Robust state tracking for complete user journey
2025-11-06 13:38:06 +00:00
// All step IDs match backend ONBOARDING_STEPS exactly
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
const ALL_STEPS: StepConfig[] = [
// Phase 1: Discovery
{
id: 'bakery-type-selection',
title: t('onboarding:steps.bakery_type.title', 'Tipo de Panadería'),
description: t('onboarding:steps.bakery_type.description', 'Selecciona tu tipo de negocio'),
component: BakeryTypeSelectionStep,
},
// Phase 2: Core Setup
{
id: 'setup',
title: t('onboarding:steps.setup.title', 'Registrar Panadería'),
description: t('onboarding:steps.setup.description', 'Información básica'),
component: RegisterTenantStep,
isConditional: true,
Remove manual path and add inventory lots UI to AI-assisted onboarding ## Architectural Changes **1. Remove Manual Entry Path** - Deleted data-source-choice step (DataSourceChoiceStep) - Removed manual inventory-setup step (InventorySetupStep) - Removed all manual path conditions from wizard flow - Set dataSource to 'ai-assisted' by default in WizardContext Files modified: - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx:11-28,61-162 - frontend/src/components/domain/onboarding/context/WizardContext.tsx:64 **2. Add Inventory Lots UI to AI Inventory Step** Added full stock lot management with expiration tracking to UploadSalesDataStep: **Features Added:** - Inline stock lot entry form after each AI-suggested ingredient - Multi-lot support - add multiple lots per ingredient with different expiration dates - Fields: quantity*, expiration date, supplier, batch/lot number - Visual list of added lots with expiration dates - Delete individual lots before completing - Smart validation with expiration date warnings - FIFO help text - Auto-select supplier if only one exists **Technical Implementation:** - Added useAddStock and useSuppliers hooks (lines 5,7,102-103) - Added stock state management (lines 106-114) - Stock handler functions (lines 336-428): - handleAddStockClick - Opens stock form - handleCancelStock - Closes and resets form - validateStockForm - Validates quantity and expiration - handleSaveStockLot - Saves to local state, supports "Add Another Lot" - handleDeleteStockLot - Removes from list - Modified handleNext to create stock lots after ingredients (lines 490-533) - Added stock lots UI section in ingredient rendering (lines 679-830) **UI Flow:** 1. User uploads sales data 2. AI suggests ingredients 3. User reviews/edits ingredients 4. **NEW**: User can optionally add stock lots with expiration dates 5. Click "Next" creates both ingredients AND stock lots 6. FIFO tracking enabled from day one **Benefits:** - Addresses JTBD: waste prevention, expiration tracking from onboarding - Progressive disclosure - optional but encouraged - Maintains simplicity of AI-assisted path - Enables inventory best practices from the start Files modified: - frontend/src/components/domain/onboarding/steps/UploadSalesDataStep.tsx:1-12,90-114,335-533,679-830 **Build Status:** ✓ Successful in 20.78s
2025-11-06 21:40:39 +00:00
condition: (ctx) => ctx.state.bakeryType !== null,
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
},
Remove manual path and add inventory lots UI to AI-assisted onboarding ## Architectural Changes **1. Remove Manual Entry Path** - Deleted data-source-choice step (DataSourceChoiceStep) - Removed manual inventory-setup step (InventorySetupStep) - Removed all manual path conditions from wizard flow - Set dataSource to 'ai-assisted' by default in WizardContext Files modified: - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx:11-28,61-162 - frontend/src/components/domain/onboarding/context/WizardContext.tsx:64 **2. Add Inventory Lots UI to AI Inventory Step** Added full stock lot management with expiration tracking to UploadSalesDataStep: **Features Added:** - Inline stock lot entry form after each AI-suggested ingredient - Multi-lot support - add multiple lots per ingredient with different expiration dates - Fields: quantity*, expiration date, supplier, batch/lot number - Visual list of added lots with expiration dates - Delete individual lots before completing - Smart validation with expiration date warnings - FIFO help text - Auto-select supplier if only one exists **Technical Implementation:** - Added useAddStock and useSuppliers hooks (lines 5,7,102-103) - Added stock state management (lines 106-114) - Stock handler functions (lines 336-428): - handleAddStockClick - Opens stock form - handleCancelStock - Closes and resets form - validateStockForm - Validates quantity and expiration - handleSaveStockLot - Saves to local state, supports "Add Another Lot" - handleDeleteStockLot - Removes from list - Modified handleNext to create stock lots after ingredients (lines 490-533) - Added stock lots UI section in ingredient rendering (lines 679-830) **UI Flow:** 1. User uploads sales data 2. AI suggests ingredients 3. User reviews/edits ingredients 4. **NEW**: User can optionally add stock lots with expiration dates 5. Click "Next" creates both ingredients AND stock lots 6. FIFO tracking enabled from day one **Benefits:** - Addresses JTBD: waste prevention, expiration tracking from onboarding - Progressive disclosure - optional but encouraged - Maintains simplicity of AI-assisted path - Enables inventory best practices from the start Files modified: - frontend/src/components/domain/onboarding/steps/UploadSalesDataStep.tsx:1-12,90-114,335-533,679-830 **Build Status:** ✓ Successful in 20.78s
2025-11-06 21:40:39 +00:00
// Phase 2a: AI-Assisted Path (ONLY PATH NOW)
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
{
id: 'smart-inventory-setup',
title: t('onboarding:steps.smart_inventory.title', 'Subir Datos de Ventas'),
description: t('onboarding:steps.smart_inventory.description', 'Configuración con IA'),
component: UploadSalesDataStep,
isConditional: true,
Remove manual path and add inventory lots UI to AI-assisted onboarding ## Architectural Changes **1. Remove Manual Entry Path** - Deleted data-source-choice step (DataSourceChoiceStep) - Removed manual inventory-setup step (InventorySetupStep) - Removed all manual path conditions from wizard flow - Set dataSource to 'ai-assisted' by default in WizardContext Files modified: - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx:11-28,61-162 - frontend/src/components/domain/onboarding/context/WizardContext.tsx:64 **2. Add Inventory Lots UI to AI Inventory Step** Added full stock lot management with expiration tracking to UploadSalesDataStep: **Features Added:** - Inline stock lot entry form after each AI-suggested ingredient - Multi-lot support - add multiple lots per ingredient with different expiration dates - Fields: quantity*, expiration date, supplier, batch/lot number - Visual list of added lots with expiration dates - Delete individual lots before completing - Smart validation with expiration date warnings - FIFO help text - Auto-select supplier if only one exists **Technical Implementation:** - Added useAddStock and useSuppliers hooks (lines 5,7,102-103) - Added stock state management (lines 106-114) - Stock handler functions (lines 336-428): - handleAddStockClick - Opens stock form - handleCancelStock - Closes and resets form - validateStockForm - Validates quantity and expiration - handleSaveStockLot - Saves to local state, supports "Add Another Lot" - handleDeleteStockLot - Removes from list - Modified handleNext to create stock lots after ingredients (lines 490-533) - Added stock lots UI section in ingredient rendering (lines 679-830) **UI Flow:** 1. User uploads sales data 2. AI suggests ingredients 3. User reviews/edits ingredients 4. **NEW**: User can optionally add stock lots with expiration dates 5. Click "Next" creates both ingredients AND stock lots 6. FIFO tracking enabled from day one **Benefits:** - Addresses JTBD: waste prevention, expiration tracking from onboarding - Progressive disclosure - optional but encouraged - Maintains simplicity of AI-assisted path - Enables inventory best practices from the start Files modified: - frontend/src/components/domain/onboarding/steps/UploadSalesDataStep.tsx:1-12,90-114,335-533,679-830 **Build Status:** ✓ Successful in 20.78s
2025-11-06 21:40:39 +00:00
condition: (ctx) => ctx.tenantId !== null,
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
},
{
id: 'product-categorization',
title: t('onboarding:steps.categorization.title', 'Categorizar Productos'),
description: t('onboarding:steps.categorization.description', 'Clasifica ingredientes vs productos'),
component: ProductCategorizationStep,
isConditional: true,
Remove manual path and add inventory lots UI to AI-assisted onboarding ## Architectural Changes **1. Remove Manual Entry Path** - Deleted data-source-choice step (DataSourceChoiceStep) - Removed manual inventory-setup step (InventorySetupStep) - Removed all manual path conditions from wizard flow - Set dataSource to 'ai-assisted' by default in WizardContext Files modified: - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx:11-28,61-162 - frontend/src/components/domain/onboarding/context/WizardContext.tsx:64 **2. Add Inventory Lots UI to AI Inventory Step** Added full stock lot management with expiration tracking to UploadSalesDataStep: **Features Added:** - Inline stock lot entry form after each AI-suggested ingredient - Multi-lot support - add multiple lots per ingredient with different expiration dates - Fields: quantity*, expiration date, supplier, batch/lot number - Visual list of added lots with expiration dates - Delete individual lots before completing - Smart validation with expiration date warnings - FIFO help text - Auto-select supplier if only one exists **Technical Implementation:** - Added useAddStock and useSuppliers hooks (lines 5,7,102-103) - Added stock state management (lines 106-114) - Stock handler functions (lines 336-428): - handleAddStockClick - Opens stock form - handleCancelStock - Closes and resets form - validateStockForm - Validates quantity and expiration - handleSaveStockLot - Saves to local state, supports "Add Another Lot" - handleDeleteStockLot - Removes from list - Modified handleNext to create stock lots after ingredients (lines 490-533) - Added stock lots UI section in ingredient rendering (lines 679-830) **UI Flow:** 1. User uploads sales data 2. AI suggests ingredients 3. User reviews/edits ingredients 4. **NEW**: User can optionally add stock lots with expiration dates 5. Click "Next" creates both ingredients AND stock lots 6. FIFO tracking enabled from day one **Benefits:** - Addresses JTBD: waste prevention, expiration tracking from onboarding - Progressive disclosure - optional but encouraged - Maintains simplicity of AI-assisted path - Enables inventory best practices from the start Files modified: - frontend/src/components/domain/onboarding/steps/UploadSalesDataStep.tsx:1-12,90-114,335-533,679-830 **Build Status:** ✓ Successful in 20.78s
2025-11-06 21:40:39 +00:00
condition: (ctx) => ctx.state.aiAnalysisComplete,
},
{
id: 'initial-stock-entry',
title: t('onboarding:steps.stock.title', 'Niveles de Stock'),
description: t('onboarding:steps.stock.description', 'Cantidades iniciales'),
component: InitialStockEntryStep,
isConditional: true,
Remove manual path and add inventory lots UI to AI-assisted onboarding ## Architectural Changes **1. Remove Manual Entry Path** - Deleted data-source-choice step (DataSourceChoiceStep) - Removed manual inventory-setup step (InventorySetupStep) - Removed all manual path conditions from wizard flow - Set dataSource to 'ai-assisted' by default in WizardContext Files modified: - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx:11-28,61-162 - frontend/src/components/domain/onboarding/context/WizardContext.tsx:64 **2. Add Inventory Lots UI to AI Inventory Step** Added full stock lot management with expiration tracking to UploadSalesDataStep: **Features Added:** - Inline stock lot entry form after each AI-suggested ingredient - Multi-lot support - add multiple lots per ingredient with different expiration dates - Fields: quantity*, expiration date, supplier, batch/lot number - Visual list of added lots with expiration dates - Delete individual lots before completing - Smart validation with expiration date warnings - FIFO help text - Auto-select supplier if only one exists **Technical Implementation:** - Added useAddStock and useSuppliers hooks (lines 5,7,102-103) - Added stock state management (lines 106-114) - Stock handler functions (lines 336-428): - handleAddStockClick - Opens stock form - handleCancelStock - Closes and resets form - validateStockForm - Validates quantity and expiration - handleSaveStockLot - Saves to local state, supports "Add Another Lot" - handleDeleteStockLot - Removes from list - Modified handleNext to create stock lots after ingredients (lines 490-533) - Added stock lots UI section in ingredient rendering (lines 679-830) **UI Flow:** 1. User uploads sales data 2. AI suggests ingredients 3. User reviews/edits ingredients 4. **NEW**: User can optionally add stock lots with expiration dates 5. Click "Next" creates both ingredients AND stock lots 6. FIFO tracking enabled from day one **Benefits:** - Addresses JTBD: waste prevention, expiration tracking from onboarding - Progressive disclosure - optional but encouraged - Maintains simplicity of AI-assisted path - Enables inventory best practices from the start Files modified: - frontend/src/components/domain/onboarding/steps/UploadSalesDataStep.tsx:1-12,90-114,335-533,679-830 **Build Status:** ✓ Successful in 20.78s
2025-11-06 21:40:39 +00:00
condition: (ctx) => ctx.state.categorizationCompleted,
Implement supplier product/price association & unify onboarding UI MAJOR FEATURES IMPLEMENTED: 1. ✅ CRITICAL: Supplier Product/Price Association - Created SupplierProductManager component (438 lines) - Multi-select product picker from inventory - Price entry with unit of measure and min quantity - Expandable UI per supplier (collapsed by default) - Full CRUD operations via existing API hooks - Required for automatic Purchase Order (PO) creation - Warning shown if supplier has no products 2. ✅ Step Re-Ordering: Inventory Before Suppliers - Manual path: inventory-setup now comes BEFORE suppliers-setup - AI path: Already has inventory from sales data upload - Ensures products exist before supplier association - Critical workflow fix identified by user 3. ✅ UI/UX Unification - Unified badge styles across AI suggestions - Changed hardcoded colors to CSS variables - Consistent rounded-full badge design - Added flex-wrap for responsive badges IMPLEMENTATION DETAILS: SupplierProductManager.tsx (NEW - 438 lines): - useSupplierPriceLists() - Fetch existing products for supplier - useIngredients() - Fetch all available inventory items - useCreate/Update/DeleteSupplierPriceList() mutations - Expandable UI: Collapsed shows count, expanded shows management - Product selection: Checkboxes with inline price forms - Form fields: unit_price (required), unit_of_measure, min_order_quantity - Validation: Price must be > 0, unit required - Warning: Shows if no products added (blocks PO creation) UnifiedOnboardingWizard.tsx: - inventory-setup moved before suppliers-setup - inventory-setup condition: dataSource === 'manual' - suppliers-setup condition: Inventory exists (AI stockEntryCompleted OR manual inventoryCompleted) - Ensures products always exist before supplier association SuppliersSetupStep.tsx: - Added SupplierProductManager import - Changed supplier card layout from flex items-center to block - Integrated ProductManager component into each supplier card - Product management appears below contact info, above edit/delete UploadSalesDataStep.tsx: - Updated badge colors: blue-100/blue-800 → CSS variables - Changed bg-[var(--bg-tertiary)] → bg-[var(--bg-primary)] - Added flex-wrap to badge container - Consistent rounded-full design FLOW IMPROVEMENTS: AI-Assisted Path: Registration → Bakery Type → Data Source → Tenant Setup → Upload Sales → Categorize → Enter Stock → **Suppliers (with products)** → ML Training → Complete Manual Path: Registration → Bakery Type → Data Source → Tenant Setup → **Inventory Setup → Suppliers (with products)** → Recipes → Processes → ML Training → Complete BENEFITS: ✅ Automatic PO creation now possible ✅ System knows supplier-product relationships ✅ Prices tracked for cost analysis ✅ Logical workflow (products before suppliers) ✅ Unified, consistent UI across onboarding ✅ Critical missing feature implemented Build: Successful (21.73s) Files: 4 changed (3 modified, 1 new) Lines: +438 new component, ~50 lines modified
2025-11-06 14:09:10 +00:00
},
{
id: 'suppliers-setup',
title: t('onboarding:steps.suppliers.title', 'Proveedores'),
description: t('onboarding:steps.suppliers.description', 'Configura tus proveedores'),
component: SuppliersSetupStep,
Make suppliers and ML training steps unconditional + rewrite completion CHANGES: 1. **Make suppliers-setup unconditional:** - Removed isConditional: true and condition - Suppliers step now ALWAYS appears in onboarding flow - No longer depends on stockEntryCompleted flag 2. **Make ml-training unconditional:** - Removed isConditional: true and condition - ML training step now ALWAYS appears in onboarding flow - No longer depends on aiAnalysisComplete flag 3. **Completely rewrote CompletionStep content:** - Changed title: "¡Felicidades! Tu Sistema Está Listo" - Shows what user HAS ACCOMPLISHED during onboarding: ✓ Información de Panadería ✓ Inventario con IA ✓ Proveedores Agregados ✓ Recetas Configuradas ✓ Calidad Establecida ✓ Equipo Invitado ✓ Modelo IA Entrenado - REMOVED misleading "One More Thing" section that asked users to configure things they JUST configured - Changed next steps to celebrate accomplishments and guide to dashboard - Updated buttons: "Ir al Panel de Control →" (single clear CTA) FIXES: - User frustration: suppliers and ML training steps were hidden - User confusion: completion message didn't make sense - asking to configure suppliers, inventory, recipes after they just did it ONBOARDING FLOW NOW: 1. bakery-type-selection 2. setup 3. smart-inventory-setup 4. product-categorization 5. initial-stock-entry 6. suppliers-setup ✓ ALWAYS SHOWS 7. recipes-setup (conditional on bakery type) 8. production-processes (conditional on bakery type) 9. quality-setup 10. team-setup 11. ml-training ✓ ALWAYS SHOWS 12. setup-review 13. completion (celebrates accomplishments!) Files Modified: - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - frontend/src/components/domain/onboarding/steps/CompletionStep.tsx
2025-11-07 10:00:33 +00:00
// Always show - no conditional
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
},
{
id: 'recipes-setup',
title: t('onboarding:steps.recipes.title', 'Recetas'),
description: t('onboarding:steps.recipes.description', 'Recetas de producción'),
component: RecipesSetupStep,
isConditional: true,
condition: (ctx) =>
ctx.state.bakeryType === 'production' || ctx.state.bakeryType === 'mixed',
},
{
id: 'production-processes',
title: t('onboarding:steps.processes.title', 'Procesos'),
description: t('onboarding:steps.processes.description', 'Procesos de terminado'),
component: ProductionProcessesStep,
isConditional: true,
condition: (ctx) =>
ctx.state.bakeryType === 'retail' || ctx.state.bakeryType === 'mixed',
},
// Phase 3: Advanced Features (Optional)
{
id: 'quality-setup',
title: t('onboarding:steps.quality.title', 'Calidad'),
description: t('onboarding:steps.quality.description', 'Estándares de calidad'),
component: QualitySetupStep,
isConditional: true,
Remove manual path and add inventory lots UI to AI-assisted onboarding ## Architectural Changes **1. Remove Manual Entry Path** - Deleted data-source-choice step (DataSourceChoiceStep) - Removed manual inventory-setup step (InventorySetupStep) - Removed all manual path conditions from wizard flow - Set dataSource to 'ai-assisted' by default in WizardContext Files modified: - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx:11-28,61-162 - frontend/src/components/domain/onboarding/context/WizardContext.tsx:64 **2. Add Inventory Lots UI to AI Inventory Step** Added full stock lot management with expiration tracking to UploadSalesDataStep: **Features Added:** - Inline stock lot entry form after each AI-suggested ingredient - Multi-lot support - add multiple lots per ingredient with different expiration dates - Fields: quantity*, expiration date, supplier, batch/lot number - Visual list of added lots with expiration dates - Delete individual lots before completing - Smart validation with expiration date warnings - FIFO help text - Auto-select supplier if only one exists **Technical Implementation:** - Added useAddStock and useSuppliers hooks (lines 5,7,102-103) - Added stock state management (lines 106-114) - Stock handler functions (lines 336-428): - handleAddStockClick - Opens stock form - handleCancelStock - Closes and resets form - validateStockForm - Validates quantity and expiration - handleSaveStockLot - Saves to local state, supports "Add Another Lot" - handleDeleteStockLot - Removes from list - Modified handleNext to create stock lots after ingredients (lines 490-533) - Added stock lots UI section in ingredient rendering (lines 679-830) **UI Flow:** 1. User uploads sales data 2. AI suggests ingredients 3. User reviews/edits ingredients 4. **NEW**: User can optionally add stock lots with expiration dates 5. Click "Next" creates both ingredients AND stock lots 6. FIFO tracking enabled from day one **Benefits:** - Addresses JTBD: waste prevention, expiration tracking from onboarding - Progressive disclosure - optional but encouraged - Maintains simplicity of AI-assisted path - Enables inventory best practices from the start Files modified: - frontend/src/components/domain/onboarding/steps/UploadSalesDataStep.tsx:1-12,90-114,335-533,679-830 **Build Status:** ✓ Successful in 20.78s
2025-11-06 21:40:39 +00:00
condition: (ctx) => ctx.tenantId !== null,
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
},
{
id: 'team-setup',
title: t('onboarding:steps.team.title', 'Equipo'),
description: t('onboarding:steps.team.description', 'Miembros del equipo'),
component: TeamSetupStep,
isConditional: true,
Remove manual path and add inventory lots UI to AI-assisted onboarding ## Architectural Changes **1. Remove Manual Entry Path** - Deleted data-source-choice step (DataSourceChoiceStep) - Removed manual inventory-setup step (InventorySetupStep) - Removed all manual path conditions from wizard flow - Set dataSource to 'ai-assisted' by default in WizardContext Files modified: - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx:11-28,61-162 - frontend/src/components/domain/onboarding/context/WizardContext.tsx:64 **2. Add Inventory Lots UI to AI Inventory Step** Added full stock lot management with expiration tracking to UploadSalesDataStep: **Features Added:** - Inline stock lot entry form after each AI-suggested ingredient - Multi-lot support - add multiple lots per ingredient with different expiration dates - Fields: quantity*, expiration date, supplier, batch/lot number - Visual list of added lots with expiration dates - Delete individual lots before completing - Smart validation with expiration date warnings - FIFO help text - Auto-select supplier if only one exists **Technical Implementation:** - Added useAddStock and useSuppliers hooks (lines 5,7,102-103) - Added stock state management (lines 106-114) - Stock handler functions (lines 336-428): - handleAddStockClick - Opens stock form - handleCancelStock - Closes and resets form - validateStockForm - Validates quantity and expiration - handleSaveStockLot - Saves to local state, supports "Add Another Lot" - handleDeleteStockLot - Removes from list - Modified handleNext to create stock lots after ingredients (lines 490-533) - Added stock lots UI section in ingredient rendering (lines 679-830) **UI Flow:** 1. User uploads sales data 2. AI suggests ingredients 3. User reviews/edits ingredients 4. **NEW**: User can optionally add stock lots with expiration dates 5. Click "Next" creates both ingredients AND stock lots 6. FIFO tracking enabled from day one **Benefits:** - Addresses JTBD: waste prevention, expiration tracking from onboarding - Progressive disclosure - optional but encouraged - Maintains simplicity of AI-assisted path - Enables inventory best practices from the start Files modified: - frontend/src/components/domain/onboarding/steps/UploadSalesDataStep.tsx:1-12,90-114,335-533,679-830 **Build Status:** ✓ Successful in 20.78s
2025-11-06 21:40:39 +00:00
condition: (ctx) => ctx.tenantId !== null,
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
},
// Phase 4: ML & Finalization
{
id: 'ml-training',
title: t('onboarding:steps.ml_training.title', 'Entrenamiento IA'),
description: t('onboarding:steps.ml_training.description', 'Modelo personalizado'),
component: MLTrainingStep,
Make suppliers and ML training steps unconditional + rewrite completion CHANGES: 1. **Make suppliers-setup unconditional:** - Removed isConditional: true and condition - Suppliers step now ALWAYS appears in onboarding flow - No longer depends on stockEntryCompleted flag 2. **Make ml-training unconditional:** - Removed isConditional: true and condition - ML training step now ALWAYS appears in onboarding flow - No longer depends on aiAnalysisComplete flag 3. **Completely rewrote CompletionStep content:** - Changed title: "¡Felicidades! Tu Sistema Está Listo" - Shows what user HAS ACCOMPLISHED during onboarding: ✓ Información de Panadería ✓ Inventario con IA ✓ Proveedores Agregados ✓ Recetas Configuradas ✓ Calidad Establecida ✓ Equipo Invitado ✓ Modelo IA Entrenado - REMOVED misleading "One More Thing" section that asked users to configure things they JUST configured - Changed next steps to celebrate accomplishments and guide to dashboard - Updated buttons: "Ir al Panel de Control →" (single clear CTA) FIXES: - User frustration: suppliers and ML training steps were hidden - User confusion: completion message didn't make sense - asking to configure suppliers, inventory, recipes after they just did it ONBOARDING FLOW NOW: 1. bakery-type-selection 2. setup 3. smart-inventory-setup 4. product-categorization 5. initial-stock-entry 6. suppliers-setup ✓ ALWAYS SHOWS 7. recipes-setup (conditional on bakery type) 8. production-processes (conditional on bakery type) 9. quality-setup 10. team-setup 11. ml-training ✓ ALWAYS SHOWS 12. setup-review 13. completion (celebrates accomplishments!) Files Modified: - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - frontend/src/components/domain/onboarding/steps/CompletionStep.tsx
2025-11-07 10:00:33 +00:00
// Always show - no conditional
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
},
{
id: 'setup-review',
title: t('onboarding:steps.review.title', 'Revisión'),
description: t('onboarding:steps.review.description', 'Confirma tu configuración'),
component: ReviewSetupStep,
isConditional: true,
Remove manual path and add inventory lots UI to AI-assisted onboarding ## Architectural Changes **1. Remove Manual Entry Path** - Deleted data-source-choice step (DataSourceChoiceStep) - Removed manual inventory-setup step (InventorySetupStep) - Removed all manual path conditions from wizard flow - Set dataSource to 'ai-assisted' by default in WizardContext Files modified: - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx:11-28,61-162 - frontend/src/components/domain/onboarding/context/WizardContext.tsx:64 **2. Add Inventory Lots UI to AI Inventory Step** Added full stock lot management with expiration tracking to UploadSalesDataStep: **Features Added:** - Inline stock lot entry form after each AI-suggested ingredient - Multi-lot support - add multiple lots per ingredient with different expiration dates - Fields: quantity*, expiration date, supplier, batch/lot number - Visual list of added lots with expiration dates - Delete individual lots before completing - Smart validation with expiration date warnings - FIFO help text - Auto-select supplier if only one exists **Technical Implementation:** - Added useAddStock and useSuppliers hooks (lines 5,7,102-103) - Added stock state management (lines 106-114) - Stock handler functions (lines 336-428): - handleAddStockClick - Opens stock form - handleCancelStock - Closes and resets form - validateStockForm - Validates quantity and expiration - handleSaveStockLot - Saves to local state, supports "Add Another Lot" - handleDeleteStockLot - Removes from list - Modified handleNext to create stock lots after ingredients (lines 490-533) - Added stock lots UI section in ingredient rendering (lines 679-830) **UI Flow:** 1. User uploads sales data 2. AI suggests ingredients 3. User reviews/edits ingredients 4. **NEW**: User can optionally add stock lots with expiration dates 5. Click "Next" creates both ingredients AND stock lots 6. FIFO tracking enabled from day one **Benefits:** - Addresses JTBD: waste prevention, expiration tracking from onboarding - Progressive disclosure - optional but encouraged - Maintains simplicity of AI-assisted path - Enables inventory best practices from the start Files modified: - frontend/src/components/domain/onboarding/steps/UploadSalesDataStep.tsx:1-12,90-114,335-533,679-830 **Build Status:** ✓ Successful in 20.78s
2025-11-06 21:40:39 +00:00
condition: (ctx) => ctx.tenantId !== null,
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
},
{
id: 'completion',
title: t('onboarding:steps.completion.title', 'Completado'),
description: t('onboarding:steps.completion.description', '¡Todo listo!'),
component: CompletionStep,
},
];
// Filter visible steps based on wizard context
// useMemo ensures VISIBLE_STEPS recalculates when wizard context state changes
// This fixes the bug where conditional steps (suppliers, ml-training) weren't showing
const VISIBLE_STEPS = useMemo(() => {
const visibleSteps = ALL_STEPS.filter(step => {
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
if (!step.isConditional) return true;
if (!step.condition) return true;
return step.condition(wizardContext);
});
console.log('🔄 VISIBLE_STEPS recalculated:', visibleSteps.map(s => s.id));
console.log('📊 Wizard state:', {
stockEntryCompleted: wizardContext.state.stockEntryCompleted,
aiAnalysisComplete: wizardContext.state.aiAnalysisComplete,
categorizationCompleted: wizardContext.state.categorizationCompleted,
});
return visibleSteps;
}, [wizardContext.state, wizardContext.tenantId]);
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
const isNewTenant = searchParams.get('new') === 'true';
const [currentStepIndex, setCurrentStepIndex] = useState(0);
const [isInitialized, setIsInitialized] = useState(isNewTenant);
const [canContinue, setCanContinue] = useState(true); // Track if current step allows continuation
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
useTenantInitializer();
const { data: userProgress, isLoading: isLoadingProgress, error: progressError } = useUserProgress(
user?.id || '',
{ enabled: !!user?.id }
);
const markStepCompleted = useMarkStepCompleted();
const { setCurrentTenant } = useTenantActions();
const [autoCompletionAttempted, setAutoCompletionAttempted] = React.useState(false);
// Auto-complete user_registered step
useEffect(() => {
if (userProgress && user?.id && !autoCompletionAttempted && !markStepCompleted.isPending) {
const userRegisteredStep = userProgress.steps.find(s => s.step_name === 'user_registered');
if (!userRegisteredStep?.completed) {
console.log('🔄 Auto-completing user_registered step for new user...');
setAutoCompletionAttempted(true);
const existingData = userRegisteredStep?.data || {};
markStepCompleted.mutate({
userId: user.id,
stepName: 'user_registered',
data: {
...existingData,
auto_completed: true,
completed_at: new Date().toISOString(),
source: 'onboarding_wizard_auto_completion'
}
}, {
onSuccess: () => console.log('✅ user_registered step auto-completed successfully'),
onError: (error) => {
console.error('❌ Failed to auto-complete user_registered step:', error);
setAutoCompletionAttempted(false);
}
});
}
}
}, [userProgress, user?.id, autoCompletionAttempted, markStepCompleted.isPending]);
// Initialize step index based on backend progress
useEffect(() => {
if (isNewTenant) return;
if (userProgress && !isInitialized) {
console.log('🔄 Initializing onboarding progress:', userProgress);
const userRegisteredStep = userProgress.steps.find(s => s.step_name === 'user_registered');
if (!userRegisteredStep?.completed) {
console.log('⏳ Waiting for user_registered step to be auto-completed...');
return;
}
let stepIndex = 0;
if (isNewTenant) {
console.log('🆕 New tenant creation - starting from first step');
stepIndex = 0;
} else {
const currentStepFromBackend = userProgress.current_step;
stepIndex = VISIBLE_STEPS.findIndex(step => step.id === currentStepFromBackend);
console.log(`🎯 Backend current step: "${currentStepFromBackend}", found at index: ${stepIndex}`);
if (stepIndex === -1) {
for (let i = 0; i < VISIBLE_STEPS.length; i++) {
const step = VISIBLE_STEPS[i];
const stepProgress = userProgress.steps.find(s => s.step_name === step.id);
if (!stepProgress?.completed) {
stepIndex = i;
console.log(`📍 Found first incomplete step: "${step.id}" at index ${i}`);
break;
}
}
if (stepIndex === -1) {
stepIndex = VISIBLE_STEPS.length - 1;
console.log('✅ All steps completed, going to last step');
}
}
const firstIncompleteStepIndex = VISIBLE_STEPS.findIndex(step => {
const stepProgress = userProgress.steps.find(s => s.step_name === step.id);
return !stepProgress?.completed;
});
if (firstIncompleteStepIndex !== -1 && stepIndex > firstIncompleteStepIndex) {
console.log(`🚫 User trying to skip ahead. Redirecting to first incomplete step at index ${firstIncompleteStepIndex}`);
stepIndex = firstIncompleteStepIndex;
}
}
console.log(`🎯 Final step index: ${stepIndex} ("${VISIBLE_STEPS[stepIndex]?.id}")`);
if (stepIndex !== currentStepIndex) {
setCurrentStepIndex(stepIndex);
}
setIsInitialized(true);
}
}, [userProgress, isInitialized, currentStepIndex, isNewTenant, VISIBLE_STEPS]);
const currentStep = VISIBLE_STEPS[currentStepIndex];
const handleStepComplete = async (data?: any) => {
if (!user?.id) {
console.error('User ID not available');
return;
}
if (markStepCompleted.isPending) {
console.warn(`⚠️ Step completion already in progress for "${currentStep.id}", skipping duplicate call`);
return;
}
console.log(`🎯 Completing step: "${currentStep.id}" with data:`, data);
try {
// Update wizard context based on step
if (currentStep.id === 'bakery-type-selection' && data?.bakeryType) {
wizardContext.updateBakeryType(data.bakeryType as BakeryType);
}
if (currentStep.id === 'data-source-choice' && data?.dataSource) {
wizardContext.updateDataSource(data.dataSource as DataSource);
}
if (currentStep.id === 'smart-inventory-setup' && data?.aiSuggestions) {
wizardContext.updateAISuggestions(data.aiSuggestions);
wizardContext.setAIAnalysisComplete(true);
}
if (currentStep.id === 'product-categorization' && data?.categorizedProducts) {
wizardContext.updateCategorizedProducts(data.categorizedProducts);
wizardContext.markStepComplete('categorizationCompleted');
}
if (currentStep.id === 'initial-stock-entry' && data?.productsWithStock) {
wizardContext.updateProductsWithStock(data.productsWithStock);
wizardContext.markStepComplete('stockEntryCompleted');
}
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
if (currentStep.id === 'inventory-setup') {
wizardContext.markStepComplete('inventoryCompleted');
}
if (currentStep.id === 'setup' && data?.tenant) {
setCurrentTenant(data.tenant);
}
// Mark step as completed in backend
console.log(`📤 Sending API request to complete step: "${currentStep.id}"`);
await markStepCompleted.mutateAsync({
userId: user.id,
stepName: currentStep.id,
data
});
console.log(`✅ Successfully completed step: "${currentStep.id}"`);
// Special handling for smart-inventory-setup
if (currentStep.id === 'smart-inventory-setup' && data?.shouldAutoCompleteSuppliers) {
try {
Make backend robust with comprehensive onboarding steps Backend Changes (services/auth/app/api/onboarding_progress.py): - Expanded ONBOARDING_STEPS to include all 19 frontend steps - Phase 0: user_registered (system) - Phase 1: bakery-type-selection, data-source-choice (discovery) - Phase 2: setup, smart-inventory-setup, product-categorization, initial-stock-entry (core setup & AI path) - Phase 2b: suppliers-setup, inventory-setup, recipes-setup, production-processes (manual path) - Phase 3: quality-setup, team-setup (advanced config) - Phase 4: ml-training, setup-review, completion (finalization) - Updated STEP_DEPENDENCIES with granular requirements - AI path: smart-inventory-setup → product-categorization → initial-stock-entry - Manual path: Independent setup for suppliers, inventory, recipes, processes - Flexible ML training: accepts either AI or manual inventory path - Enhanced ML training validation - Supports both AI-assisted path (sales data) and manual inventory path - More flexible validation logic for multi-path onboarding Frontend Changes (UnifiedOnboardingWizard.tsx): - Fixed auto-complete step name: 'suppliers' → 'suppliers-setup' - All step IDs now match backend ONBOARDING_STEPS exactly - Removed temporary step mapping workarounds Frontend Changes (apiClient.ts): - Fixed tenant ID requirement warnings for onboarding endpoints - Added noTenantEndpoints list for user-level endpoints: - /auth/me/onboarding (tenant created during onboarding) - /auth/me (user profile) - /auth/register, /auth/login - Eliminated false warnings during onboarding flow This makes the onboarding system fully functional with: ✅ Backend validates all 19 onboarding steps ✅ Proper dependency tracking for multi-path onboarding ✅ No more "Invalid step name" errors ✅ No more tenant ID warnings for onboarding ✅ Robust state tracking for complete user journey
2025-11-06 13:38:06 +00:00
console.log('🔄 Auto-completing suppliers-setup step...');
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
await markStepCompleted.mutateAsync({
userId: user.id,
Make backend robust with comprehensive onboarding steps Backend Changes (services/auth/app/api/onboarding_progress.py): - Expanded ONBOARDING_STEPS to include all 19 frontend steps - Phase 0: user_registered (system) - Phase 1: bakery-type-selection, data-source-choice (discovery) - Phase 2: setup, smart-inventory-setup, product-categorization, initial-stock-entry (core setup & AI path) - Phase 2b: suppliers-setup, inventory-setup, recipes-setup, production-processes (manual path) - Phase 3: quality-setup, team-setup (advanced config) - Phase 4: ml-training, setup-review, completion (finalization) - Updated STEP_DEPENDENCIES with granular requirements - AI path: smart-inventory-setup → product-categorization → initial-stock-entry - Manual path: Independent setup for suppliers, inventory, recipes, processes - Flexible ML training: accepts either AI or manual inventory path - Enhanced ML training validation - Supports both AI-assisted path (sales data) and manual inventory path - More flexible validation logic for multi-path onboarding Frontend Changes (UnifiedOnboardingWizard.tsx): - Fixed auto-complete step name: 'suppliers' → 'suppliers-setup' - All step IDs now match backend ONBOARDING_STEPS exactly - Removed temporary step mapping workarounds Frontend Changes (apiClient.ts): - Fixed tenant ID requirement warnings for onboarding endpoints - Added noTenantEndpoints list for user-level endpoints: - /auth/me/onboarding (tenant created during onboarding) - /auth/me (user profile) - /auth/register, /auth/login - Eliminated false warnings during onboarding flow This makes the onboarding system fully functional with: ✅ Backend validates all 19 onboarding steps ✅ Proper dependency tracking for multi-path onboarding ✅ No more "Invalid step name" errors ✅ No more tenant ID warnings for onboarding ✅ Robust state tracking for complete user journey
2025-11-06 13:38:06 +00:00
stepName: 'suppliers-setup',
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
data: {
auto_completed: true,
completed_at: new Date().toISOString(),
source: 'inventory_creation_auto_completion',
}
});
Make backend robust with comprehensive onboarding steps Backend Changes (services/auth/app/api/onboarding_progress.py): - Expanded ONBOARDING_STEPS to include all 19 frontend steps - Phase 0: user_registered (system) - Phase 1: bakery-type-selection, data-source-choice (discovery) - Phase 2: setup, smart-inventory-setup, product-categorization, initial-stock-entry (core setup & AI path) - Phase 2b: suppliers-setup, inventory-setup, recipes-setup, production-processes (manual path) - Phase 3: quality-setup, team-setup (advanced config) - Phase 4: ml-training, setup-review, completion (finalization) - Updated STEP_DEPENDENCIES with granular requirements - AI path: smart-inventory-setup → product-categorization → initial-stock-entry - Manual path: Independent setup for suppliers, inventory, recipes, processes - Flexible ML training: accepts either AI or manual inventory path - Enhanced ML training validation - Supports both AI-assisted path (sales data) and manual inventory path - More flexible validation logic for multi-path onboarding Frontend Changes (UnifiedOnboardingWizard.tsx): - Fixed auto-complete step name: 'suppliers' → 'suppliers-setup' - All step IDs now match backend ONBOARDING_STEPS exactly - Removed temporary step mapping workarounds Frontend Changes (apiClient.ts): - Fixed tenant ID requirement warnings for onboarding endpoints - Added noTenantEndpoints list for user-level endpoints: - /auth/me/onboarding (tenant created during onboarding) - /auth/me (user profile) - /auth/register, /auth/login - Eliminated false warnings during onboarding flow This makes the onboarding system fully functional with: ✅ Backend validates all 19 onboarding steps ✅ Proper dependency tracking for multi-path onboarding ✅ No more "Invalid step name" errors ✅ No more tenant ID warnings for onboarding ✅ Robust state tracking for complete user journey
2025-11-06 13:38:06 +00:00
console.log('✅ Suppliers-setup step auto-completed successfully');
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
} catch (supplierError) {
Make backend robust with comprehensive onboarding steps Backend Changes (services/auth/app/api/onboarding_progress.py): - Expanded ONBOARDING_STEPS to include all 19 frontend steps - Phase 0: user_registered (system) - Phase 1: bakery-type-selection, data-source-choice (discovery) - Phase 2: setup, smart-inventory-setup, product-categorization, initial-stock-entry (core setup & AI path) - Phase 2b: suppliers-setup, inventory-setup, recipes-setup, production-processes (manual path) - Phase 3: quality-setup, team-setup (advanced config) - Phase 4: ml-training, setup-review, completion (finalization) - Updated STEP_DEPENDENCIES with granular requirements - AI path: smart-inventory-setup → product-categorization → initial-stock-entry - Manual path: Independent setup for suppliers, inventory, recipes, processes - Flexible ML training: accepts either AI or manual inventory path - Enhanced ML training validation - Supports both AI-assisted path (sales data) and manual inventory path - More flexible validation logic for multi-path onboarding Frontend Changes (UnifiedOnboardingWizard.tsx): - Fixed auto-complete step name: 'suppliers' → 'suppliers-setup' - All step IDs now match backend ONBOARDING_STEPS exactly - Removed temporary step mapping workarounds Frontend Changes (apiClient.ts): - Fixed tenant ID requirement warnings for onboarding endpoints - Added noTenantEndpoints list for user-level endpoints: - /auth/me/onboarding (tenant created during onboarding) - /auth/me (user profile) - /auth/register, /auth/login - Eliminated false warnings during onboarding flow This makes the onboarding system fully functional with: ✅ Backend validates all 19 onboarding steps ✅ Proper dependency tracking for multi-path onboarding ✅ No more "Invalid step name" errors ✅ No more tenant ID warnings for onboarding ✅ Robust state tracking for complete user journey
2025-11-06 13:38:06 +00:00
console.warn('⚠️ Could not auto-complete suppliers-setup step:', supplierError);
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
}
}
if (currentStep.id === 'completion') {
wizardContext.resetWizard();
navigate(isNewTenant ? '/app/dashboard' : '/app');
} else {
if (currentStepIndex < VISIBLE_STEPS.length - 1) {
setCurrentStepIndex(currentStepIndex + 1);
}
}
} catch (error: any) {
console.error(`❌ Error completing step "${currentStep.id}":`, error);
const errorMessage = error?.response?.data?.detail || error?.message || 'Unknown error';
alert(`${t('onboarding:errors.step_failed', 'Error al completar paso')} "${currentStep.title}": ${errorMessage}`);
}
};
const handleStepUpdate = (data?: any) => {
// Handle canContinue state updates from setup wizard steps
if (data?.canContinue !== undefined) {
setCanContinue(data.canContinue);
}
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
// Handle intermediate updates without marking step complete
if (currentStep.id === 'bakery-type-selection' && data?.bakeryType) {
wizardContext.updateBakeryType(data.bakeryType as BakeryType);
}
if (currentStep.id === 'data-source-choice' && data?.dataSource) {
wizardContext.updateDataSource(data.dataSource as DataSource);
}
if (currentStep.id === 'product-categorization' && data?.categorizedProducts) {
wizardContext.updateCategorizedProducts(data.categorizedProducts);
}
if (currentStep.id === 'initial-stock-entry' && data?.productsWithStock) {
wizardContext.updateProductsWithStock(data.productsWithStock);
}
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
};
// Show loading state
if (!isNewTenant && (isLoadingProgress || !isInitialized)) {
return (
<div className="max-w-4xl mx-auto px-4 sm:px-6">
<Card padding="lg" shadow="lg">
<CardBody>
<div className="flex items-center justify-center space-x-3">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--color-primary)]"></div>
<p className="text-[var(--text-secondary)] text-sm sm:text-base">{t('common:loading', 'Cargando tu progreso...')}</p>
</div>
</CardBody>
</Card>
</div>
);
}
// Show error state
if (!isNewTenant && progressError) {
return (
<div className="max-w-4xl mx-auto px-4 sm:px-6">
<Card padding="lg" shadow="lg">
<CardBody>
<div className="text-center space-y-4">
<div className="w-14 h-14 sm:w-16 sm:h-16 mx-auto bg-[var(--color-error)]/10 rounded-full flex items-center justify-center">
<svg className="w-7 h-7 sm:w-8 sm:h-8 text-[var(--color-error)]" 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>
<div>
<h2 className="text-base sm:text-lg font-semibold text-[var(--text-primary)] mb-2">
{t('onboarding:errors.network_error', 'Error al cargar progreso')}
</h2>
<p className="text-sm sm:text-base text-[var(--text-secondary)] mb-4 px-2">
{t('onboarding:errors.try_again', 'No pudimos cargar tu progreso. Puedes continuar desde el inicio.')}
</p>
<Button onClick={() => setIsInitialized(true)} variant="primary" size="lg">
{t('onboarding:wizard.navigation.next', 'Continuar')}
</Button>
</div>
</div>
</CardBody>
</Card>
</div>
);
}
const StepComponent = currentStep.component;
const progressPercentage = isNewTenant
? ((currentStepIndex + 1) / VISIBLE_STEPS.length) * 100
: userProgress?.completion_percentage || ((currentStepIndex + 1) / VISIBLE_STEPS.length) * 100;
return (
<div className="max-w-4xl mx-auto px-4 sm:px-6 space-y-4 sm:space-y-6 pb-6">
{/* Progress Header */}
<Card shadow="sm" padding="lg">
<div className="flex flex-col sm:flex-row sm:justify-between sm:items-center mb-4 space-y-2 sm:space-y-0">
<div className="text-center sm:text-left">
<h1 className="text-xl sm:text-2xl font-bold text-[var(--text-primary)]">
{isNewTenant ? t('onboarding:wizard.title_new', 'Nueva Panadería') : t('onboarding:wizard.title', 'Configuración Inicial')}
</h1>
<p className="text-[var(--text-secondary)] text-xs sm:text-sm mt-1">
{t('onboarding:wizard.subtitle', 'Configura tu sistema paso a paso')}
</p>
</div>
<div className="text-center sm:text-right">
<div className="text-sm text-[var(--text-secondary)]">
{t('onboarding:wizard.progress.step_of', 'Paso {{current}} de {{total}}', {
current: currentStepIndex + 1,
total: VISIBLE_STEPS.length
})}
</div>
<div className="text-xs text-[var(--text-tertiary)]">
{Math.round(progressPercentage)}% {t('onboarding:wizard.progress.completed', 'completado')}
</div>
</div>
</div>
{/* Progress Bar */}
<div className="w-full bg-[var(--bg-secondary)] rounded-full h-2 sm:h-3">
<div
className="bg-gradient-to-r from-[var(--color-primary)] to-[var(--color-primary)]/80 h-2 sm:h-3 rounded-full transition-all duration-500 ease-out"
style={{ width: `${progressPercentage}%` }}
/>
</div>
</Card>
{/* Step Content */}
<Card shadow="lg" padding="none">
<CardHeader padding="lg" divider>
<div className="flex items-center space-x-3">
<div className="w-8 h-8 sm:w-10 sm:h-10 bg-[var(--color-primary)]/10 rounded-full flex items-center justify-center">
<div className="w-5 h-5 sm:w-6 sm:h-6 bg-[var(--color-primary)] rounded-full flex items-center justify-center text-white text-xs font-bold">
{currentStepIndex + 1}
</div>
</div>
<div className="flex-1">
<h2 className="text-lg sm:text-xl font-semibold text-[var(--text-primary)]">
{currentStep.title}
</h2>
<p className="text-[var(--text-secondary)] text-xs sm:text-sm">
{currentStep.description}
</p>
</div>
</div>
</CardHeader>
<CardBody padding="lg">
<StepComponent
onNext={() => {}}
onPrevious={() => {}}
onComplete={handleStepComplete}
onUpdate={handleStepUpdate}
isFirstStep={currentStepIndex === 0}
isLastStep={currentStepIndex === VISIBLE_STEPS.length - 1}
Architect navigation buttons correctly: move from wizard-level to step-level Fixed the navigation architecture to follow proper onboarding patterns: **ARCHITECTURE CHANGE:** - REMOVED: External navigation footer from UnifiedOnboardingWizard (Back + Continue buttons at wizard level) - ADDED: Internal Continue buttons inside each setup wizard step component **WHY THIS MATTERS:** 1. Onboarding should NEVER show Back buttons (users cannot go back) 2. Each step should be self-contained with its own Continue button 3. Setup wizard steps are reused in both contexts: - SetupWizard (/app/setup): Uses external StepNavigation component - UnifiedOnboardingWizard: Steps now render their own buttons **CHANGES MADE:** 1. UnifiedOnboardingWizard.tsx: - Removed navigation footer (lines 548-588) - Now passes canContinue prop to steps - Steps are responsible for their own navigation 2. All setup wizard steps updated: - QualitySetupStep: Added onComplete, canContinue props + Continue button - SuppliersSetupStep: Modified existing button to call onComplete - InventorySetupStep: Added onComplete, canContinue props + Continue button - RecipesSetupStep: Added canContinue prop + Continue button - TeamSetupStep: Added onComplete, canContinue props + Continue button - ReviewSetupStep: Added onComplete, canContinue props + Continue button 3. Continue button pattern: - Only renders when onComplete prop exists (onboarding context) - Disabled based on canContinue prop from parent - Styled consistently across all steps - Positioned at bottom with border-top separator **RESULT:** - Clean separation: onboarding steps have internal buttons, no external navigation - No Back button in onboarding (as required) - Setup wizard still works with external StepNavigation - Consistent UX across all steps
2025-11-06 19:55:42 +00:00
canContinue={canContinue}
Implement Phase 6: Unified Onboarding Foundation & Core Components This commit implements Phase 6 of the onboarding unification plan, which merges the existing AI-powered onboarding with the comprehensive setup wizard into a single, intelligent, personalized onboarding experience. ## Planning & Analysis Documents - **ONBOARDING_UNIFICATION_PLAN.md**: Comprehensive master plan for unifying onboarding systems, including: - Current state analysis of existing wizards - Gap analysis comparing features - Unified 13-step wizard architecture with conditional flows - Bakery type impact analysis (Production/Retail/Mixed) - Step visibility matrix based on business logic - Phases 6-11 implementation timeline (6 weeks) - Technical specifications for all components - Backend API and database changes needed - Success metrics and risk analysis - **PHASE_6_IMPLEMENTATION.md**: Detailed day-by-day implementation plan for Phase 6, including: - Week 1: Core component development - Week 2: Context system and backend integration - Code templates for all new components - Backend API specifications - Database schema changes - Testing strategy with comprehensive checklist ## New Components Implemented ### 1. BakeryTypeSelectionStep (Discovery Phase) - 3 bakery type options: Production, Retail, Mixed - Interactive card-based selection UI - Features and examples for each type - Contextual help with detailed information - Animated selection indicators ### 2. DataSourceChoiceStep (Configuration Method) - AI-assisted setup (upload sales data) - Manual step-by-step setup - Comparison cards with benefits and ideal scenarios - Estimated time for each approach - Context-aware info panels ### 3. ProductionProcessesStep (Retail Bakeries) - Alternative to RecipesSetupStep for retail bakeries - Template-based quick start (4 common processes) - Custom process creation with: - Source product and finished product - Process type (baking, decorating, finishing, assembly) - Duration and temperature settings - Step-by-step instructions - Inline form with validation ### 4. WizardContext (State Management) - Centralized state for entire onboarding flow - Manages bakery type, data source selection - Tracks AI suggestions and ML training status - Tracks step completion across all phases - Conditional step visibility logic - localStorage persistence - Helper hooks for step visibility ### 5. UnifiedOnboardingWizard (Main Container) - Replaces existing OnboardingWizard - Integrates all 13 steps with conditional rendering - WizardProvider wraps entire flow - Dynamic step visibility based on context - Backward compatible with existing backend progress tracking - Auto-completion for user_registered step - Progress calculation based on visible steps ## Conditional Flow Logic The wizard now supports intelligent conditional flows: **Bakery Type Determines Steps:** - Production → Shows Recipes Setup - Retail → Shows Production Processes - Mixed → Shows both Recipes and Processes **Data Source Determines Path:** - AI-Assisted → Upload sales data, AI analysis, review suggestions - Manual → Direct data entry for suppliers, inventory, recipes **Completion State Determines ML Training:** - Only shows ML training if inventory is completed OR AI analysis is complete ## Technical Implementation Details - **Context API**: WizardContext manages global onboarding state - **Conditional Rendering**: getVisibleSteps() computes which steps to show - **State Persistence**: localStorage saves progress for page refreshes - **Step Dependencies**: markStepComplete() tracks prerequisites - **Responsive Design**: Mobile-first UI with card-based layouts - **Animations**: Smooth transitions with animate-scale-in, animate-fade-in - **Accessibility**: WCAG AA compliant with keyboard navigation - **Internationalization**: Full i18n support with useTranslation ## Files Added - frontend/src/components/domain/onboarding/steps/BakeryTypeSelectionStep.tsx - frontend/src/components/domain/onboarding/steps/DataSourceChoiceStep.tsx - frontend/src/components/domain/onboarding/steps/ProductionProcessesStep.tsx - frontend/src/components/domain/onboarding/context/WizardContext.tsx - frontend/src/components/domain/onboarding/context/index.ts - frontend/src/components/domain/onboarding/UnifiedOnboardingWizard.tsx - ONBOARDING_UNIFICATION_PLAN.md - PHASE_6_IMPLEMENTATION.md ## Files Modified - frontend/src/components/domain/onboarding/steps/index.ts - Added exports for new discovery and production steps ## Testing ✅ Build successful (21.42s) ✅ No TypeScript errors ✅ All components properly exported ✅ Animations working with existing animations.css ## Next Steps (Phase 7-11) - Phase 7: Spanish Translations (1 week) - Phase 8: Analytics & Tracking (1 week) - Phase 9: Guided Tours (1 week) - Phase 10: Enhanced Features (1 week) - Phase 11: Testing & Polish (2 weeks) ## Backend Integration Notes The existing tenant API already supports updating tenant information via PUT /api/v1/tenants/{id}. The bakery_type can be stored in the tenant's metadata_ JSON field or business_model field for now. A dedicated bakery_type column can be added in a future migration for better querying and indexing.
2025-11-06 12:34:30 +00:00
/>
</CardBody>
</Card>
</div>
);
};
export const UnifiedOnboardingWizard: React.FC = () => {
return (
<WizardProvider>
<OnboardingWizardContent />
</WizardProvider>
);
};
export default UnifiedOnboardingWizard;