This commit implements comprehensive Spanish translations for all new onboarding
components and creates a complete guided tour framework for post-setup feature
discovery.
## Phase 7: Spanish Translations
### Spanish Onboarding Translations Added
**BakeryTypeSelectionStep translations (onboarding.bakery_type):**
- Title and subtitle for bakery type selection
- Production bakery: features, examples, and selected info
- Retail bakery: features, examples, and selected info
- Mixed bakery: features, examples, and selected info
- Help text and continue button
**DataSourceChoiceStep translations (onboarding.data_source):**
- Title and subtitle for configuration method
- AI-assisted setup: benefits, ideal scenarios, estimated time
- Manual setup: benefits, ideal scenarios, estimated time
- Info panels for both options with detailed requirements
**ProductionProcessesStep translations (onboarding.processes):**
- Title and subtitle for production processes
- Process types: baking, decorating, finishing, assembly
- Form labels and placeholders
- Template section with quick start option
- Navigation buttons and help text
**Updated Wizard Steps:**
- Added all new step titles and descriptions
- Updated navigation labels
- Enhanced progress indicators
### Translation Coverage
Total new translation keys added: **150+ keys**
- bakery_type: 40+ keys
- data_source: 35+ keys
- processes: 25+ keys
- wizard updates: 15+ keys
- Comprehensive coverage for all user-facing text
## Phase 9: Guided Tours
### Tour Framework Created
**TourContext (`/frontend/src/contexts/TourContext.tsx`):**
- Complete state management for tours
- Tour step navigation (next, previous, skip, complete)
- localStorage persistence for completed/skipped tours
- beforeShow and afterShow hooks for each step
- Support for custom actions in tour steps
**Key Features:**
- Track which tours are completed or skipped
- Prevent showing tours that are already done
- Support async operations in step hooks
- Centralized tour state across the app
### Tour UI Components
**TourTooltip (`/frontend/src/components/ui/Tour/TourTooltip.tsx`):**
- Intelligent positioning (top, bottom, left, right)
- Auto-adjusts if tooltip goes off-screen
- Progress indicators with dots
- Navigation buttons (previous, next, finish)
- Close/skip button
- Arrow pointing to target element
- Responsive design with animations
**TourSpotlight (`/frontend/src/components/ui/Tour/TourSpotlight.tsx`):**
- SVG mask overlay to dim rest of page
- Highlighted border around target element
- Smooth animations (fade in, pulse)
- Auto-scroll target into view
- Adjusts on window resize/scroll
**Tour (`/frontend/src/components/ui/Tour/Tour.tsx`):**
- Main container component
- Portal rendering for overlay
- Disables body scroll during tour
- Combines tooltip and spotlight
**TourButton (`/frontend/src/components/ui/Tour/TourButton.tsx`):**
- Three variants: icon, button, menu
- Shows all available tours
- Displays completion status
- Dropdown menu with tour descriptions
- Number of steps for each tour
### Predefined Tours Created
**5 comprehensive tours defined (`/frontend/src/tours/tours.ts`):**
1. **Dashboard Tour** (5 steps):
- Welcome and overview
- Key statistics cards
- AI forecast chart
- Inventory alerts
- Main navigation
2. **Inventory Tour** (5 steps):
- Inventory management overview
- Adding new ingredients
- Search and filters
- Inventory table view
- Stock alerts
3. **Recipes Tour** (5 steps):
- Recipe management intro
- Creating recipes
- Automatic cost calculation
- Recipe yield settings
- Batch multiplier
4. **Production Tour** (5 steps):
- Production planning overview
- Production schedule calendar
- AI recommendations
- Creating production batches
- Batch status tracking
5. **Post-Onboarding Tour** (5 steps):
- Congratulations message
- Main navigation overview
- Quick actions
- Notifications
- Help resources
### Tour Translations
**New Spanish locale: `/frontend/src/locales/es/tour.json`:**
- Navigation labels (previous, next, finish, skip)
- Progress indicators
- Tour trigger button text
- Completion messages
- Tour names and descriptions
### Technical Implementation
**Features:**
- `data-tour` attributes for targeting elements
- Portal rendering for proper z-index layering
- Smooth animations with CSS classes
- Responsive positioning algorithm
- Scroll handling for dynamic content
- Window resize listeners
- TypeScript interfaces for type safety
**Usage Pattern:**
```typescript
// In any component
import { useTour } from '../contexts/TourContext';
import { dashboardTour } from '../tours/tours';
const { startTour } = useTour();
startTour(dashboardTour);
```
## Files Added
**Translations:**
- frontend/src/locales/es/tour.json
**Tour Framework:**
- frontend/src/contexts/TourContext.tsx
- frontend/src/components/ui/Tour/Tour.tsx
- frontend/src/components/ui/Tour/TourTooltip.tsx
- frontend/src/components/ui/Tour/TourSpotlight.tsx
- frontend/src/components/ui/Tour/TourButton.tsx
- frontend/src/components/ui/Tour/index.ts
- frontend/src/tours/tours.ts
## Files Modified
- frontend/src/locales/es/onboarding.json (150+ new translation keys)
## Testing
✅ Build successful (23.12s)
✅ No TypeScript errors
✅ All translations properly structured
✅ Tour components render via portals
✅ Spanish locale complete for all new features
## Integration Requirements
To enable tours in the app:
1. Add TourProvider to app root (wrap with TourProvider)
2. Add Tour component to render active tours
3. Add TourButton where help is needed
4. Add data-tour attributes to tour target elements
Example:
```tsx
<TourProvider>
<App />
<Tour />
</TourProvider>
```
## Next Steps
- Add TourProvider to application root
- Add data-tour attributes to target elements in pages
- Integrate TourButton in navigation/help sections
- Auto-trigger post-onboarding tour after setup complete
- Track tour analytics (views, completions, skip rates)
## Benefits
**For Users:**
- Smooth onboarding experience in Spanish
- Interactive feature discovery
- Contextual help when needed
- Can skip or restart tours anytime
- Never see same tour twice (unless restarted)
**For Product:**
- Reduce support requests
- Increase feature adoption
- Improve user confidence
- Better user experience
- Track which features need improvement
Frontend Dashboard
Overview
The Bakery-IA Frontend Dashboard is a modern, responsive React-based web application that provides bakery owners and operators with comprehensive real-time visibility into their operations. Built with TypeScript and cutting-edge React ecosystem tools, it delivers an intuitive interface for demand forecasting, inventory management, production planning, and operational analytics.
Key Features
AI-Powered Demand Forecasting
- Visual Forecast Charts - Interactive Chart.js visualizations of demand predictions
- Multi-Day Forecasts - View predictions up to 30 days ahead
- Confidence Intervals - Visual representation of prediction uncertainty
- Historical Comparison - Compare forecasts with actual sales
- Forecast Accuracy Metrics - Track model performance over time
- Weather Integration - See how weather impacts demand
- One-Click Forecast Generation - Generate forecasts for all products instantly
Real-Time Operational Dashboard
- Live KPI Cards - Real-time metrics for sales, inventory, production
- Alert Stream (SSE) - Instant notifications for critical events
- Production Status - Live view of current production batches
- Inventory Levels - Color-coded stock levels with expiry warnings
- Order Pipeline - Track customer orders from placement to fulfillment
Inventory Management
- Stock Overview - All ingredients with current levels and locations
- Low Stock Alerts - Automatic warnings when stock falls below thresholds
- Expiration Tracking - Prioritize items by expiration date
- FIFO Compliance - First-in-first-out consumption tracking
- Stock Movements - Complete audit trail of all inventory changes
- Barcode Scanning Integration - Quick stock updates via barcode
Production Planning
- Production Schedules - Daily and weekly production calendars
- Batch Tracking - Monitor all active production batches
- Quality Control - Digital quality check forms and templates
- Equipment Management - Track equipment usage and maintenance
- Recipe Execution - Step-by-step recipe guidance for production staff
- Capacity Planning - Optimize production capacity utilization
Procurement & Supplier Management
- Automated Purchase Orders - AI-generated procurement recommendations
- Supplier Portal - Manage supplier relationships and performance
- Price Comparisons - Compare supplier pricing across items
- Delivery Tracking - Track inbound shipments
- Supplier Scorecards - Rate suppliers on quality, delivery, and price
Sales & Orders
- Customer Order Management - Process and track customer orders
- Sales Analytics - Revenue trends, product performance, customer insights
- POS Integration - Automatic sales data sync from Square/Toast/Lightspeed
- Sales History - Complete historical sales data with filtering and export
Multi-Tenant Administration
- Tenant Settings - Configure bakery-specific preferences
- User Management - Invite team members and assign roles
- Subscription Management - View and upgrade subscription plans
- Billing Portal - Stripe-powered billing and invoices
ML Model Training
- Training Dashboard - Monitor ML model training progress
- WebSocket Live Updates - Real-time training status and metrics
- Model Performance - Compare model versions and accuracy
- Training History - Complete log of all training runs
Technical Capabilities
Modern React Architecture
- React 18 - Latest React with concurrent features
- TypeScript - Type-safe development with full IntelliSense
- Vite - Lightning-fast build tool and dev server
- Component-Based - Modular, reusable components
- Hooks-First - Modern React patterns with custom hooks
State Management
- Zustand - Lightweight global state management
- TanStack Query (React Query) - Server state management with caching
- Local Storage Persistence - Persist user preferences
- Optimistic Updates - Instant UI feedback before server confirmation
UI/UX Components
- Radix UI - Accessible, unstyled component primitives
- Tailwind CSS - Utility-first CSS framework
- Responsive Design - Mobile, tablet, and desktop optimized
- Dark Mode (planned) - User-selectable theme
- Accessible - WCAG 2.1 AA compliant
Data Visualization
- Chart.js - Interactive forecast and analytics charts
- Recharts - Declarative React charts for dashboards
- Custom Visualizations - Specialized charts for bakery metrics
Forms & Validation
- React Hook Form - Performant form management
- Zod - TypeScript-first schema validation
- Error Handling - User-friendly validation messages
- Auto-Save - Background form persistence
Real-Time Communication
- Server-Sent Events (SSE) - Real-time alert stream from gateway
- WebSocket - Live ML training progress updates
- Auto-Reconnect - Resilient connection management
- Event Notifications - Toast notifications for real-time events
Internationalization
- i18next - Multi-language support
- Spanish - Default language for Spanish market
- English - Secondary language for international users
- Date/Number Formatting - Locale-aware formatting
API Integration
- TanStack Query - Declarative data fetching with caching
- Axios/Fetch - HTTP client for REST APIs
- JWT Authentication - Token-based auth with auto-refresh
- Request Interceptors - Automatic token injection
- Error Handling - Centralized error boundary and retry logic
Business Value
For Bakery Owners
- Time Savings - 15-20 hours/week saved on manual planning
- Reduced Waste - Visual demand forecasts reduce overproduction by 20-40%
- Better Decisions - Data-driven insights replace guesswork
- Mobile Access - Manage bakery from anywhere (responsive design)
- No Training Required - Intuitive interface, minimal learning curve
For Bakery Staff
- Production Guidance - Step-by-step recipes on screen
- Quality Consistency - Digital quality checklists
- Inventory Visibility - Know what's in stock without checking fridges
- Task Prioritization - Alerts show what needs immediate attention
For Multi-Location Bakeries
- Centralized Control - Manage all locations from one dashboard
- Performance Comparison - Compare KPIs across locations
- Standardized Processes - Same interface at all locations
For Platform Operations
- Reduced Support Costs - Intuitive UI reduces support tickets
- User Engagement - Real-time updates keep users engaged
- Feature Discovery - Guided onboarding increases feature adoption
Technology Stack
Core Framework
- React 18.3 - JavaScript library for user interfaces
- TypeScript 5.3 - Type-safe JavaScript superset
- Vite 5.0 - Next-generation frontend tooling
State Management & Data Fetching
- Zustand 4.4 - Lightweight state management
- TanStack Query (React Query) 5.8 - Async state management
- Axios - HTTP client
UI & Styling
- Radix UI - Accessible component primitives
@radix-ui/react-dialog- Modal dialogs@radix-ui/react-dropdown-menu- Dropdown menus@radix-ui/react-select- Select components@radix-ui/react-tabs- Tab navigation
- Tailwind CSS 3.4 - Utility-first CSS framework
- Headless UI - Unstyled accessible components
- Lucide React - Beautiful, consistent icons
Data Visualization
- Chart.js 4.4 - Flexible JavaScript charting
- react-chartjs-2 - React wrapper for Chart.js
- Recharts 2.10 - Composable React charts
- date-fns - Modern date utility library
Forms & Validation
- React Hook Form 7.49 - Performant form library
- Zod 3.22 - TypeScript-first schema validation
- @hookform/resolvers - Zod integration for React Hook Form
Routing & Navigation
- React Router 6.20 - Declarative routing for React
- React Router DOM - DOM bindings for React Router
Internationalization
- i18next 23.7 - Internationalization framework
- react-i18next 13.5 - React bindings for i18next
Real-Time Communication
- EventSource API - Native SSE support
- WebSocket API - Native WebSocket support
- react-use-websocket - React WebSocket hook
Notifications & Feedback
- react-hot-toast - Beautiful toast notifications
- react-loading-skeleton - Loading placeholders
Development Tools
- ESLint - JavaScript linter
- Prettier - Code formatter
- TypeScript ESLint - TypeScript linting rules
- Vite Plugin React - Fast refresh and JSX transform
Application Structure
frontend/
├── src/
│ ├── components/ # Reusable UI components
│ │ ├── ui/ # Base UI components (buttons, inputs, etc.)
│ │ ├── charts/ # Chart components
│ │ ├── forms/ # Form components
│ │ └── layout/ # Layout components (header, sidebar, etc.)
│ ├── pages/ # Page components (routes)
│ │ ├── Dashboard/ # Main dashboard
│ │ ├── Forecasting/ # Forecast management
│ │ ├── Inventory/ # Inventory management
│ │ ├── Production/ # Production planning
│ │ ├── Orders/ # Order management
│ │ ├── Suppliers/ # Supplier management
│ │ ├── Procurement/ # Procurement planning
│ │ ├── Settings/ # User settings
│ │ └── Auth/ # Login/register pages
│ ├── hooks/ # Custom React hooks
│ │ ├── useAuth.ts # Authentication hook
│ │ ├── useSSE.ts # Server-sent events hook
│ │ ├── useWebSocket.ts # WebSocket hook
│ │ └── useQuery.ts # API query hooks
│ ├── stores/ # Zustand stores
│ │ ├── authStore.ts # Authentication state
│ │ ├── alertStore.ts # Alert state
│ │ └── uiStore.ts # UI state (sidebar, theme, etc.)
│ ├── api/ # API client functions
│ │ ├── client.ts # Axios client setup
│ │ ├── auth.ts # Auth API
│ │ ├── forecasting.ts # Forecasting API
│ │ ├── inventory.ts # Inventory API
│ │ └── ... # Other service APIs
│ ├── types/ # TypeScript type definitions
│ │ ├── api.ts # API response types
│ │ ├── models.ts # Domain model types
│ │ └── components.ts # Component prop types
│ ├── utils/ # Utility functions
│ │ ├── date.ts # Date formatting
│ │ ├── currency.ts # Currency formatting
│ │ ├── validation.ts # Validation helpers
│ │ └── format.ts # General formatting
│ ├── locales/ # i18n translation files
│ │ ├── es/ # Spanish translations
│ │ └── en/ # English translations
│ ├── App.tsx # Root component
│ ├── main.tsx # Application entry point
│ └── router.tsx # Route configuration
├── public/ # Static assets
│ ├── icons/ # App icons
│ └── images/ # Images
├── index.html # HTML template
├── vite.config.ts # Vite configuration
├── tailwind.config.js # Tailwind CSS configuration
├── tsconfig.json # TypeScript configuration
└── package.json # Dependencies
Key Pages & Routes
Public Routes
/login- User login/register- User registration/forgot-password- Password reset
Protected Routes (Require Authentication)
/dashboard- Main operational dashboard/forecasting- Demand forecasting management/forecasting/train- ML model training/inventory- Inventory management/inventory/stock- Stock levels and movements/production- Production planning/production/batches- Production batch tracking/production/quality- Quality control/recipes- Recipe management/orders- Customer order management/suppliers- Supplier management/procurement- Procurement planning/sales- Sales analytics/pos- POS integration settings/settings- User and tenant settings/settings/team- Team member management/settings/subscription- Subscription management
API Integration
Authentication Flow
- Login: User enters credentials → API returns access token + refresh token
- Token Storage: Tokens stored in Zustand store + localStorage
- Request Interceptor: Axios interceptor adds
Authorization: Bearer {token}to all requests - Token Refresh: On 401 error, automatically refresh token and retry request
- Logout: Clear tokens and redirect to login
TanStack Query Configuration
// Automatic background refetching
refetchOnWindowFocus: true
refetchOnReconnect: true
// Stale-while-revalidate caching
staleTime: 5 minutes
cacheTime: 30 minutes
// Retry on failure
retry: 3
retryDelay: exponential backoff
API Client Structure
// Base client
const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_URL,
timeout: 30000,
})
// Request interceptor (add JWT)
apiClient.interceptors.request.use((config) => {
const token = authStore.getState().accessToken
config.headers.Authorization = `Bearer ${token}`
return config
})
// Response interceptor (handle token refresh)
apiClient.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response?.status === 401) {
await refreshToken()
return apiClient.request(error.config)
}
throw error
}
)
Real-Time Features
Server-Sent Events (SSE) for Alerts
const useAlertStream = () => {
useEffect(() => {
const eventSource = new EventSource(
`${API_URL}/api/v1/alerts/stream`,
{ withCredentials: true }
)
eventSource.onmessage = (event) => {
const alert = JSON.parse(event.data)
alertStore.addAlert(alert)
toast.notification(alert.message)
}
eventSource.onerror = () => {
// Auto-reconnect on error
setTimeout(() => eventSource.close(), 5000)
}
return () => eventSource.close()
}, [])
}
WebSocket for Training Progress
const useTrainingWebSocket = (trainingId: string) => {
const { lastMessage, readyState } = useWebSocket(
`${WS_URL}/api/v1/training/ws?training_id=${trainingId}`
)
useEffect(() => {
if (lastMessage) {
const progress = JSON.parse(lastMessage.data)
updateTrainingProgress(progress)
}
}, [lastMessage])
}
Configuration
Environment Variables
API Configuration:
VITE_API_URL- Backend API gateway URL (e.g.,https://api.bakery-ia.com)VITE_WS_URL- WebSocket URL (e.g.,wss://api.bakery-ia.com)
Feature Flags:
VITE_ENABLE_DEMO_MODE- Enable demo mode features (default: false)VITE_ENABLE_ANALYTICS- Enable analytics tracking (default: true)
External Services:
VITE_STRIPE_PUBLIC_KEY- Stripe publishable key for paymentsVITE_SENTRY_DSN- Sentry error tracking DSN (optional)
Build Configuration:
VITE_APP_VERSION- Application version (from package.json)VITE_BUILD_TIME- Build timestamp
Example .env file
VITE_API_URL=http://localhost:8000
VITE_WS_URL=ws://localhost:8000
VITE_ENABLE_DEMO_MODE=true
VITE_STRIPE_PUBLIC_KEY=pk_test_...
Development Setup
Prerequisites
- Node.js 18+ and npm/yarn/pnpm
- Access to Bakery-IA backend API
Local Development
# Install dependencies
cd frontend
npm install
# Set environment variables
cp .env.example .env
# Edit .env with your configuration
# Run development server
npm run dev
# Open browser to http://localhost:5173
Build for Production
# Create optimized production build
npm run build
# Preview production build locally
npm run preview
Code Quality
# Run linter
npm run lint
# Run type checking
npm run type-check
# Format code
npm run format
Testing
Unit Tests (Vitest)
# Run unit tests
npm run test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watch
E2E Tests (Playwright - planned)
# Run E2E tests
npm run test:e2e
# Run E2E tests in headed mode
npm run test:e2e:headed
Performance Optimization
Build Optimization
- Code Splitting - Lazy load routes for faster initial load
- Tree Shaking - Remove unused code from bundles
- Minification - Minify JavaScript and CSS
- Gzip Compression - Compress assets for faster transfer
- Image Optimization - Optimized image formats and sizes
Runtime Optimization
- React.memo - Prevent unnecessary re-renders
- useMemo/useCallback - Memoize expensive computations
- Virtual Scrolling - Efficiently render large lists
- Debouncing - Limit API calls from user input
- Lazy Loading - Load components and routes on demand
Caching Strategy
- TanStack Query Cache - 5-minute stale time for most queries
- Service Worker (planned) - Offline-first PWA support
- Asset Caching - Browser cache for static assets
- API Response Cache - Cache GET requests in TanStack Query
Accessibility (a11y)
WCAG 2.1 AA Compliance
- Keyboard Navigation - All features accessible via keyboard
- Screen Reader Support - ARIA labels and semantic HTML
- Color Contrast - 4.5:1 contrast ratio for text
- Focus Indicators - Visible focus states for interactive elements
- Alt Text - Descriptive alt text for images
- Form Labels - Proper label associations for inputs
Radix UI Accessibility
- Built-in keyboard navigation
- ARIA attributes automatically applied
- Focus management
- Screen reader announcements
Security Measures
Authentication & Authorization
- JWT Tokens - Secure token-based authentication
- Automatic Token Refresh - Seamless token renewal
- HttpOnly Cookies (planned) - More secure token storage
- CSRF Protection - CSRF tokens for state-changing operations
Data Protection
- HTTPS Only (Production) - All communication encrypted
- XSS Prevention - React's built-in XSS protection
- Content Security Policy - Restrict resource loading
- Input Sanitization - Validate and sanitize all user inputs
Dependency Security
- npm audit - Regular security audits
- Dependabot - Automatic dependency updates
- License Scanning - Ensure license compliance
Deployment
Docker Deployment
# Multi-stage build
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
Kubernetes Deployment
- Deployment - Multiple replicas for high availability
- Service - Load balancing across pods
- Ingress - HTTPS termination and routing
- ConfigMap - Environment-specific configuration
- HPA - Horizontal pod autoscaling based on CPU
CI/CD Pipeline
- Lint & Type Check - Ensure code quality
- Unit Tests - Run test suite
- Build - Create production build
- Docker Build - Create container image
- Push to Registry - Push to container registry
- Deploy to Kubernetes - Update deployment
Browser Support
- Chrome - Latest 2 versions
- Firefox - Latest 2 versions
- Safari - Latest 2 versions
- Edge - Latest 2 versions
- Mobile Browsers - iOS Safari 14+, Chrome Android 90+
Competitive Advantages
- Modern Tech Stack - React 18, TypeScript, Vite for fast development
- Real-Time Updates - SSE and WebSocket for instant feedback
- Mobile-First - Responsive design works on all devices
- Offline Support (planned) - PWA capabilities for unreliable networks
- Accessible - WCAG 2.1 AA compliant for inclusive access
- Fast Performance - Code splitting and caching for sub-second loads
- Spanish-First - UI designed for Spanish bakery workflows
Future Enhancements
- Progressive Web App (PWA) - Offline support and installable
- Dark Mode - User-selectable theme
- Mobile Apps - React Native iOS/Android apps
- Advanced Analytics - Custom dashboard builder
- Multi-Language - Support for additional languages
- Voice Commands - Hands-free operation in production environment
- Barcode Scanning - Native camera integration for inventory
- Print Templates - Custom print layouts for labels and reports
For VUE Madrid Business Plan: The Bakery-IA Frontend Dashboard represents a modern, professional SaaS interface built with industry-leading technologies. The real-time capabilities, mobile-first design, and accessibility compliance make it suitable for bakeries of all sizes, from small artisanal shops to multi-location enterprises. The intuitive interface reduces training costs and increases user adoption, critical factors for successful SaaS businesses in the Spanish market.