Files
bakery-ia/frontend
2025-09-17 16:06:30 +02:00
..
2025-08-28 10:41:04 +02:00
2025-09-17 16:06:30 +02:00
2025-08-28 10:41:04 +02:00
2025-08-28 10:41:04 +02:00
2025-08-28 10:41:04 +02:00
2025-08-03 19:36:17 +02:00
2025-08-03 19:36:17 +02:00
2025-08-28 10:41:04 +02:00
2025-08-03 19:36:17 +02:00
2025-08-03 20:16:19 +02:00
2025-08-28 10:41:04 +02:00
2025-08-28 10:41:04 +02:00
2025-08-28 10:41:04 +02:00

frontend/ ├── public/ │ ├── icons/ # PWA icons (multiple sizes) │ ├── manifest.json # PWA manifest │ └── sw.js # Service worker ├── src/ │ ├── components/ │ │ ├── ui/ # Design system components │ │ │ ├── Button/ │ │ │ │ ├── Button.tsx │ │ │ │ ├── Button.stories.tsx │ │ │ │ ├── Button.test.tsx │ │ │ │ └── index.ts │ │ │ ├── Input/ │ │ │ ├── Card/ │ │ │ ├── Modal/ │ │ │ ├── Table/ │ │ │ ├── Badge/ │ │ │ ├── Avatar/ │ │ │ ├── Tooltip/ │ │ │ ├── Select/ │ │ │ ├── DatePicker/ │ │ │ └── index.ts │ │ ├── layout/ │ │ │ ├── AppShell/ │ │ │ ├── Header/ │ │ │ ├── Sidebar/ │ │ │ ├── Breadcrumbs/ │ │ │ ├── PageHeader/ │ │ │ └── Footer/ │ │ ├── domain/ │ │ │ ├── auth/ │ │ │ ├── dashboard/ │ │ │ ├── inventory/ │ │ │ ├── production/ │ │ │ ├── sales/ │ │ │ ├── forecasting/ │ │ │ ├── analytics/ │ │ │ └── onboarding/ │ │ └── shared/ │ │ ├── LoadingSpinner/ │ │ ├── EmptyState/ │ │ ├── ErrorBoundary/ │ │ ├── ConfirmDialog/ │ │ └── DataTable/ │ ├── pages/ │ │ ├── public/ │ │ │ ├── LandingPage/ │ │ │ ├── LoginPage/ │ │ │ └── RegisterPage/ │ │ ├── app/ │ │ │ ├── DashboardPage/ │ │ │ ├── operations/ │ │ │ │ ├── InventoryPage/ │ │ │ │ ├── ProductionPage/ │ │ │ │ ├── OrdersPage/ │ │ │ │ ├── ProcurementPage/ │ │ │ │ └── POSPage/ │ │ │ ├── analytics/ │ │ │ │ ├── ForecastingPage/ │ │ │ │ ├── SalesAnalyticsPage/ │ │ │ │ ├── PerformancePage/ │ │ │ │ └── AIInsightsPage/ │ │ │ ├── data/ │ │ │ │ ├── WeatherPage/ │ │ │ │ ├── TrafficPage/ │ │ │ │ └── EventsPage/ │ │ │ ├── communications/ │ │ │ │ ├── NotificationsPage/ │ │ │ │ ├── AlertsPage/ │ │ │ │ └── PreferencesPage/ │ │ │ ├── settings/ │ │ │ │ ├── TeamPage/ │ │ │ │ ├── BakeryConfigPage/ │ │ │ │ ├── TrainingPage/ │ │ │ │ └── SystemPage/ │ │ │ └── onboarding/ │ │ │ ├── UploadPage/ │ │ │ ├── AnalysisPage/ │ │ │ ├── ReviewPage/ │ │ │ └── SetupPage/ │ │ └── index.ts │ ├── hooks/ │ │ ├── api/ │ │ │ ├── useAuth.ts │ │ │ ├── useInventory.ts │ │ │ ├── useProduction.ts │ │ │ ├── useForecasting.ts │ │ │ ├── useSales.ts │ │ │ ├── useSSE.ts │ │ │ └── useWebSocket.ts │ │ ├── ui/ │ │ │ ├── useModal.ts │ │ │ ├── useTheme.ts │ │ │ ├── useToast.ts │ │ │ └── useDebounce.ts │ │ └── business/ │ │ ├── useBakeryWorkflow.ts │ │ ├── useProductionSchedule.ts │ │ └── useAlerts.ts │ ├── stores/ │ │ ├── auth.store.ts │ │ ├── ui.store.ts │ │ ├── bakery.store.ts │ │ ├── alerts.store.ts │ │ └── index.ts │ ├── services/ │ │ ├── api/ │ │ │ ├── client.ts │ │ │ ├── auth.service.ts │ │ │ ├── tenant.service.ts │ │ │ ├── sales.service.ts │ │ │ ├── inventory.service.ts │ │ │ ├── forecasting.service.ts │ │ │ ├── training.service.ts │ │ │ ├── data.service.ts │ │ │ ├── notification.service.ts │ │ │ ├── orders.service.ts │ │ │ ├── production.service.ts │ │ │ ├── procurement.service.ts │ │ │ └── pos.service.ts │ │ ├── realtime/ │ │ │ ├── sse.service.ts │ │ │ └── websocket.service.ts │ │ └── utils/ │ │ ├── storage.service.ts │ │ └── cache.service.ts │ ├── router/ │ │ ├── AppRouter.tsx │ │ ├── ProtectedRoute.tsx │ │ ├── routes.config.ts │ │ └── index.ts │ ├── styles/ │ │ ├── globals.css │ │ ├── components.css │ │ ├── animations.css │ │ └── themes/ │ │ ├── light.css │ │ └── dark.css │ ├── utils/ │ │ ├── format.ts │ │ ├── validation.ts │ │ ├── constants.ts │ │ ├── date.ts │ │ └── currency.ts │ ├── types/ │ │ ├── auth.types.ts │ │ ├── inventory.types.ts │ │ ├── production.types.ts │ │ ├── sales.types.ts │ │ ├── forecasting.types.ts │ │ ├── api.types.ts │ │ └── index.ts │ ├── locales/ │ │ ├── es/ │ │ │ ├── common.json │ │ │ ├── auth.json │ │ │ ├── inventory.json │ │ │ └── errors.json │ │ └── index.ts │ ├── App.tsx │ ├── main.tsx │ └── vite-env.d.ts ├── .env.example ├── .gitignore ├── index.html ├── package.json ├── tsconfig.json ├── vite.config.ts ├── tailwind.config.js └── README.md

🚀 Bakery AI Platform - Complete Frontend Rebuild from Scratch

📋 Project Context

You are working on Bakery AI (PanIA), an intelligent platform for Madrid's bakery ecosystem that provides AI-powered demand forecasting, inventory management, and automated onboarding. The current frontend codebase has become disorganized and unmaintainable. Your task is to build a completely new frontend from scratch using modern best practices while preserving the existing backend API infrastructure.

🎯 Mission: Complete Frontend Rebuild

Current Situation

  • Frontend architecture is a mess - components, pages, and logic scattered without organization
  • No consistent design system - UI components lack standardization
  • Poor code structure - files and folders organized without logic
  • Outdated patterns - not following modern React/TypeScript best practices
  • Poor user experience - interface doesn't meet 2024-2025 standards

Your Objective

Build a brand new frontend from the ground up that is:

  • Modern, maintainable, and scalable
  • Following 2024-2025 UX/UI best practices
  • Properly organized with clear architecture
  • Type-safe and performant
  • Mobile-first and accessible

🏗️ What to Preserve vs Rebuild

PRESERVE: Existing Backend Microservices Architecture

The backend has a comprehensive microservices architecture that should be fully integrated:

🏗️ Backend Microservices:
├── 🔐 auth/              # Authentication & user management
├── 🏢 tenant/            # Multi-tenant organization management  
├── 📊 sales/             # Sales data processing & onboarding
├── 📦 inventory/         # Product catalog & stock management
├── 📈 forecasting/       # AI demand predictions & analytics
├── 🎯 training/          # ML model training & management
├── 🌍 data/              # External data (weather, traffic)
├── 📧 notification/      # Email & WhatsApp alerts
├── 📋 orders/            # Order management & tracking
├── 🏭 production/        # Production planning & batches
├── 🛍️ procurement/       # Purchase orders & supplier management
├── 📍 pos/               # Point of sale integrations
└── 🌐 gateway/           # API gateway & routing

Complete API Endpoint Mapping:

🔐 Authentication Service

POST   /api/v1/auth/register
POST   /api/v1/auth/login  
POST   /api/v1/auth/refresh
DELETE /api/v1/auth/logout
GET    /api/v1/auth/me
PUT    /api/v1/auth/profile
POST   /api/v1/auth/password/reset
PUT    /api/v1/auth/password/change

🏢 Tenant Service

POST   /api/v1/tenants/register
GET    /api/v1/tenants/{tenant_id}
PUT    /api/v1/tenants/{tenant_id}
DELETE /api/v1/tenants/{tenant_id}
GET    /api/v1/tenants/{tenant_id}/members
POST   /api/v1/tenants/{tenant_id}/invite
DELETE /api/v1/tenants/{tenant_id}/members/{user_id}
PATCH  /api/v1/tenants/{tenant_id}/members/{user_id}
GET    /api/v1/tenants/{tenant_id}/stats
GET    /api/v1/tenants/user/{user_id}

📊 Sales Service (includes Onboarding & Analytics)

# Sales Data Management
GET    /api/v1/tenants/{tenant_id}/sales
POST   /api/v1/tenants/{tenant_id}/sales/upload
GET    /api/v1/tenants/{tenant_id}/sales/summary
GET    /api/v1/tenants/{tenant_id}/sales/trends

# AI Onboarding Automation
POST   /api/v1/tenants/{tenant_id}/onboarding/analyze
POST   /api/v1/tenants/{tenant_id}/onboarding/create-inventory
POST   /api/v1/tenants/{tenant_id}/onboarding/import-sales
GET    /api/v1/tenants/{tenant_id}/onboarding/business-model-guide

# Analytics
GET    /api/v1/tenants/{tenant_id}/analytics/revenue
GET    /api/v1/tenants/{tenant_id}/analytics/products
GET    /api/v1/tenants/{tenant_id}/analytics/trends
GET    /api/v1/tenants/{tenant_id}/analytics/reports

📦 Inventory Service (Product Catalog & Stock Management)

# Product Management
GET    /api/v1/tenants/{tenant_id}/inventory/products
POST   /api/v1/tenants/{tenant_id}/inventory/products
GET    /api/v1/tenants/{tenant_id}/inventory/products/{product_id}
PUT    /api/v1/tenants/{tenant_id}/inventory/products/{product_id}
DELETE /api/v1/tenants/{tenant_id}/inventory/products/{product_id}

# Stock Management
GET    /api/v1/tenants/{tenant_id}/inventory/stock
POST   /api/v1/tenants/{tenant_id}/inventory/stock/adjustment
GET    /api/v1/tenants/{tenant_id}/inventory/stock/movements
GET    /api/v1/tenants/{tenant_id}/inventory/stock/alerts

# AI Classification (300+ Bakery Products)
POST   /api/v1/tenants/{tenant_id}/inventory/classify-product
POST   /api/v1/tenants/{tenant_id}/inventory/classify-products-batch

# Import/Export
POST   /api/v1/tenants/{tenant_id}/inventory/import
GET    /api/v1/tenants/{tenant_id}/inventory/export
GET    /api/v1/tenants/{tenant_id}/inventory/search

📈 Forecasting Service (AI Demand Predictions)

GET    /api/v1/tenants/{tenant_id}/forecasts
POST   /api/v1/tenants/{tenant_id}/forecasts/generate
GET    /api/v1/tenants/{tenant_id}/forecasts/{forecast_id}
GET    /api/v1/tenants/{tenant_id}/predictions
GET    /api/v1/tenants/{tenant_id}/predictions/daily
GET    /api/v1/tenants/{tenant_id}/predictions/weekly
GET    /api/v1/tenants/{tenant_id}/predictions/alerts
POST   /api/v1/tenants/{tenant_id}/predictions/validate

🎯 Training Service (ML Model Management)

POST   /api/v1/tenants/{tenant_id}/training/start
GET    /api/v1/tenants/{tenant_id}/training/status
GET    /api/v1/tenants/{tenant_id}/training/history
POST   /api/v1/tenants/{tenant_id}/training/stop
GET    /api/v1/tenants/{tenant_id}/models
GET    /api/v1/tenants/{tenant_id}/models/{model_id}
GET    /api/v1/tenants/{tenant_id}/models/{model_id}/metrics

🌍 Data Service (External Data Integration)

GET    /api/v1/tenants/{tenant_id}/weather
GET    /api/v1/tenants/{tenant_id}/weather/forecast
GET    /api/v1/tenants/{tenant_id}/traffic
GET    /api/v1/tenants/{tenant_id}/traffic/patterns
GET    /api/v1/tenants/{tenant_id}/holidays
GET    /api/v1/tenants/{tenant_id}/events

📧 Notification Service

POST   /api/v1/tenants/{tenant_id}/notifications/send
GET    /api/v1/tenants/{tenant_id}/notifications/history
GET    /api/v1/tenants/{tenant_id}/notifications/preferences
PUT    /api/v1/tenants/{tenant_id}/notifications/preferences
POST   /api/v1/tenants/{tenant_id}/notifications/test

📋 Orders Service

GET    /api/v1/tenants/{tenant_id}/orders
POST   /api/v1/tenants/{tenant_id}/orders
GET    /api/v1/tenants/{tenant_id}/orders/{order_id}
PUT    /api/v1/tenants/{tenant_id}/orders/{order_id}
DELETE /api/v1/tenants/{tenant_id}/orders/{order_id}
GET    /api/v1/tenants/{tenant_id}/orders/dashboard-summary
POST   /api/v1/tenants/{tenant_id}/orders/{order_id}/status

🏭 Production Service

GET    /api/v1/tenants/{tenant_id}/production/batches
POST   /api/v1/tenants/{tenant_id}/production/batches
GET    /api/v1/tenants/{tenant_id}/production/batches/{batch_id}
PUT    /api/v1/tenants/{tenant_id}/production/batches/{batch_id}
GET    /api/v1/tenants/{tenant_id}/production/schedule
POST   /api/v1/tenants/{tenant_id}/production/schedule
GET    /api/v1/tenants/{tenant_id}/production/equipment

🛍️ Procurement Service

GET    /api/v1/tenants/{tenant_id}/procurement/plans
POST   /api/v1/tenants/{tenant_id}/procurement/plans/generate
GET    /api/v1/tenants/{tenant_id}/procurement/plans/{plan_id}
PUT    /api/v1/tenants/{tenant_id}/procurement/plans/{plan_id}/status
GET    /api/v1/tenants/{tenant_id}/procurement/suppliers
GET    /api/v1/tenants/{tenant_id}/procurement/requirements

📍 POS Service (Point of Sale Integration)

GET    /api/v1/tenants/{tenant_id}/pos/configurations
POST   /api/v1/tenants/{tenant_id}/pos/configurations
GET    /api/v1/tenants/{tenant_id}/pos/transactions
POST   /api/v1/tenants/{tenant_id}/pos/sync
GET    /api/v1/tenants/{tenant_id}/pos/sync-status

📡 Real-Time SSE Infrastructure

The backend includes a sophisticated Server-Sent Events (SSE) system for real-time alerts and recommendations:

SSE Service Architecture:

🔄 Real-Time Stream Flow:
Alert/Recommendation Generated → Alert Processor → Redis Channel → SSE Service → Frontend Dashboard

📡 SSE Endpoints:
GET /api/v1/sse/alerts/stream/{tenant_id}  # Real-time alert & recommendation stream

🚨 Alert Types & Severity Levels:
- URGENT: All channels (WhatsApp, Email, Push, Dashboard)
- HIGH: WhatsApp + Email (6AM-10PM), Email only (night)  
- MEDIUM: Email (business hours 7AM-8PM), Dashboard always
- LOW: Dashboard only

💡 Recommendation Types:
- Production optimization suggestions
- Inventory reorder recommendations  
- Demand forecast insights
- Cost optimization tips
- Equipment maintenance alerts

Channel Routing Logic:

// Backend determines channels by severity & time:
const channels = {
  urgent: ['whatsapp', 'email', 'push', 'dashboard'],    // Immediate
  high: ['whatsapp', 'email', 'dashboard'],              // Extended hours  
  medium: ['email', 'dashboard'],                        // Business hours
  low: ['dashboard']                                      // Always visible
};

// Frontend receives via SSE:
eventSource.addEventListener('alert', (event) => {
  const alert = JSON.parse(event.data);
  // Auto-display urgent/high alerts
  // Browser notifications for urgent alerts
  // Sound alerts for critical items
});

eventSource.addEventListener('recommendation', (event) => {
  const recommendation = JSON.parse(event.data);
  // Display in recommendations panel
  // Non-intrusive UI integration
});

SSE Message Format:

interface SSEMessage {
  id: string;
  item_type: 'alert' | 'recommendation';
  type: string;                    // Specific alert type
  severity: 'urgent' | 'high' | 'medium' | 'low';
  title: string;
  message: string;
  actions: string[];               // Suggested actions
  metadata: Record<string, any>;   // Context data
  timestamp: string;
  status: 'active' | 'acknowledged' | 'resolved';
}

🔄 Real-Time WebSocket Training Monitoring

In addition to SSE alerts, the system includes dedicated WebSocket connections for ML model training progress:

WebSocket Training Architecture:

🎯 Training WebSocket Flow:
Training Job Started → WebSocket Connection → Real-time Progress → Completion Status

📡 WebSocket Endpoints:
WS /api/v1/ws/tenants/{tenant_id}/training/jobs/{job_id}/live  # Real-time training progress

🤖 ML Training Process Types:
- Data validation and preprocessing
- Prophet model training (demand forecasting)  
- Model performance evaluation (MAPE, MAE, RMSE, R2 score)
- Model storage and versioning
- Training completion with metrics

WebSocket Message Types:

interface TrainingWebSocketMessage {
  // Progress Updates
  type: 'training_progress';
  job_id: string;
  progress: {
    percentage: number;           // 0-100
    current_step: string;         // "Data validation", "Model training", etc.
    products_completed: number;   // Products processed so far
    products_total: number;       // Total products to process
    estimated_time_remaining: number; // Seconds
    started_at: string;
  };
  
  // Completion Events
  type: 'training_completed';
  job_id: string;
  results: {
    successful_trainings: number;
    failed_trainings: number;
    models_created: string[];
    performance_metrics: {
      accuracy: number;           // R2 score
      mape: number;              // Mean Absolute Percentage Error
      mae: number;               // Mean Absolute Error
      rmse: number;              // Root Mean Square Error
    };
    training_duration: number;   // Total training time in seconds
  };
  
  // Error Events  
  type: 'training_error';
  job_id: string;
  error: string;
  timestamp: string;
}

Training Configuration:

// Backend training settings optimized for bakery data:
const trainingConfig = {
  maxTrainingTimeMinutes: 30,        // 30 minute timeout
  maxConcurrentJobs: 3,              // Max 3 parallel training jobs
  minTrainingDataDays: 30,           // Require 30+ days of sales data
  
  // Prophet algorithm parameters for bakery forecasting:
  seasonalityMode: 'additive',       // Better for bakery patterns
  changePointPriorScale: 0.05,       // Sensitivity to trend changes
  seasonalityPriorScale: 10.0,       // Strength of seasonal patterns
  holidaysPriorScale: 10.0,          // Spanish/Madrid holiday impact
  
  // Spanish context:
  enableSpanishHolidays: true,       // National holidays
  enableMadridHolidays: true,        // Local Madrid holidays
  enableCustomHolidays: true         // Bakery-specific holidays
};

WebSocket Integration Features:

  • Real-Time Progress: Live percentage updates during training
  • Step-by-Step Monitoring: Current training phase visibility
  • Performance Metrics: Live model accuracy metrics (MAPE, MAE, RMSE)
  • Connection Management: Auto-reconnection with JWT authentication
  • Tenant Isolation: Secure per-tenant training job monitoring
  • Completion Detection: Automatic WebSocket closure on job completion
  • Error Handling: Comprehensive error reporting and recovery

REBUILD COMPLETELY: Frontend

Replace the entire frontend directory structure and codebase:

# Remove the old frontend completely:
rm -rf frontend/src/components/
rm -rf frontend/src/pages/
rm -rf frontend/src/hooks/
rm -rf frontend/src/styles/
rm -rf frontend/src/router/
# Keep only: package.json, vite.config.ts, index.html

📱 New Frontend Requirements

Target Users & Use Cases

  1. Small Bakery Owners (Madrid): Mobile-first, simple workflows, 4AM production schedules
  2. Operations Managers: Desktop analytics, detailed reports, multi-location oversight
  3. Production Staff: Tablet-friendly, quick actions, hands-free when possible

Core User Workflows to Support

1. Morning Production Planning (4:00 AM):
   Login → Check Forecasts → Plan Production → Update Inventory

2. Daily Operations Management:
   Monitor Sales → Adjust Production → Track Inventory → Handle Alerts

3. Weekly Business Analysis:
   Review Performance → Analyze Trends → Plan Improvements → Generate Reports

4. New User Onboarding:
   Register → Upload Sales Data → AI Setup → Start Forecasting (5-10 minutes)

🎨 Modern Frontend Architecture to Build

Tech Stack (Keep Existing Dependencies)

{
  "react": "^18.2.0",
  "typescript": "^5.0.2", 
  "vite": "^4.4.5",
  "react-router-dom": "^6.15.0",
  "@reduxjs/toolkit": "^1.9.5", 
  "tailwindcss": "^3.3.0",
  "react-hook-form": "^7.45.4",
  "lucide-react": "^0.263.1",
  "recharts": "^2.8.0",
  "zod": "^3.22.2"
}

🏗️ New Architecture Pattern: Service-Aligned Hub-and-Spoke

Based on the comprehensive backend microservices, organize the frontend around service domains:

🏠 Central Dashboard
├── 🔐 Authentication Hub
│   ├── Login/Register
│   ├── Profile Management  
│   └── Password Reset
├── 🥖 Operations Hub
│   ├── 📦 Inventory (Products, Stock, Alerts)
│   ├── 🏭 Production (Batches, Schedule, Equipment)
│   ├── 📋 Orders (Management, Status, Tracking)
│   ├── 🛍️ Procurement (Plans, Suppliers, Requirements)
│   └── 📍 POS (Integration, Sync, Transactions)
├── 📊 Analytics Hub
│   ├── 🔮 Forecasting (Predictions, Models, Validation)
│   ├── 📈 Sales Analytics (Trends, Reports, Revenue)
│   ├── 📉 Performance KPIs (Metrics, Dashboards)
│   └── 🤖 AI Insights (Classifications, Recommendations)
├── 🌍 Data Hub
│   ├── Weather Integration (AEMET API)
│   ├── Traffic Patterns
│   ├── External Events
│   └── Market Data  
├── 📧 Communications Hub
│   ├── Notifications (Email, WhatsApp)
│   ├── Alert Management
│   └── Preference Settings
└── ⚙️ Settings Hub
    ├── 👥 Team Management (Members, Roles, Invites)
    ├── 🏢 Bakery Configuration (Business Model, Settings)
    ├── 🎯 Training (ML Models, Status, History)
    └── 🔧 System Settings (API Keys, Integrations)

🧱 Component Architecture to Build

// Design System Foundation
components/ui/
├── Button/          # Primary, secondary, ghost variants
├── Input/           # Text, email, number with validation
├── Card/            # Elevation levels, padding variants
├── Modal/           # Sizes, overlay, animations
├── Table/           # Sorting, filtering, pagination
├── Form/            # React Hook Form + Zod integration
├── Badge/           # Status indicators, color variants  
├── Avatar/          # User profile images, initials
└── index.ts         # Export all UI components

// Layout Components
components/layout/
├── AppShell/        # Main application container
├── Header/          # Top navigation, user menu
├── Sidebar/         # Main navigation, collapsible  
├── Breadcrumbs/     # Navigation trail
├── PageHeader/      # Page title, actions
└── Footer/          # Copyright, links

// Business Components
components/domain/
├── auth/            # Login, register, password reset
├── dashboard/       # KPI cards, charts, activity feed
├── inventory/       # Product cards, stock alerts
├── production/      # Batch cards, equipment status
├── sales/           # Transaction lists, POS integration
├── forecasting/     # Prediction charts, confidence indicators
└── onboarding/      # Step-by-step setup wizard

// Shared Components  
components/shared/
├── LoadingSpinner/  # Various loading states
├── EmptyState/      # No data illustrations
├── ErrorBoundary/   # Error handling with retry
├── ConfirmDialog/   # Confirmation modals
└── DataTable/       # Reusable table with features

🎨 2024-2025 Design System to Implement

Visual Identity (Bakery Theme)

/* Color Palette */
:root {
  /* Primary: Warm Orange (artisan bread) */
  --orange-50: #fff7ed;
  --orange-500: #f97316; 
  --orange-900: #9a3412;
  
  /* Secondary: Golden Wheat */  
  --amber-50: #fffbeb;
  --amber-500: #f59e0b;
  --amber-900: #92400e;
  
  /* Success: Fresh Green */
  --green-500: #22c55e;
  
  /* Warning: Alert Orange */
  --red-500: #ef4444;
  
  /* Neutral: Modern Grays */
  --slate-50: #f8fafc;
  --slate-500: #64748b;
  --slate-900: #0f172a;
}

/* Typography System */
.text-display { font-size: 2.25rem; font-weight: 700; }    /* Page headlines */
.text-heading { font-size: 1.875rem; font-weight: 600; }   /* Section titles */
.text-title { font-size: 1.5rem; font-weight: 600; }       /* Card titles */
.text-body { font-size: 1rem; font-weight: 400; }          /* Body text */
.text-caption { font-size: 0.875rem; font-weight: 400; }   /* Captions */

/* Spacing System (8px grid) */
.space-xs { margin: 0.5rem; }      /* 8px */
.space-sm { margin: 1rem; }        /* 16px */  
.space-md { margin: 1.5rem; }      /* 24px */
.space-lg { margin: 2rem; }        /* 32px */
.space-xl { margin: 3rem; }        /* 48px */

Modern UI Patterns to Implement

  1. Glassmorphism Cards:
.glass-card {
  background: rgba(255, 255, 255, 0.25);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.18);
  border-radius: 12px;
}
  1. Neumorphism Buttons:
.neu-button {
  background: linear-gradient(145deg, #f0f0f0, #cacaca);
  box-shadow: 20px 20px 60px #bebebe, -20px -20px 60px #ffffff;
}
  1. Micro-Interactions:
  • Hover state transitions (200ms ease)
  • Loading button animations
  • Form field focus effects
  • Success/error state changes

📱 Mobile-First Design Requirements

Responsive Breakpoints

/* Mobile First Approach */
.container {
  padding: 1rem;                    /* Mobile: 16px */
}

@media (min-width: 640px) {         /* Tablet */
  .container { padding: 1.5rem; }
}

@media (min-width: 1024px) {        /* Desktop */
  .container { padding: 2rem; }
}

@media (min-width: 1280px) {        /* Large Desktop */
  .container { max-width: 1200px; margin: 0 auto; }
}

Touch-Optimized Interactions

  • 44px minimum touch targets for all buttons/links
  • Swipe gestures for mobile navigation
  • Pull-to-refresh on data lists
  • Long press for context menus
  • Double-tap for quick actions

Progressive Web App Features

// Implement PWA capabilities:
- Service Worker for offline functionality
- Web App Manifest for home screen install
- Push notifications for alerts
- Background sync for data updates
- Cache strategies for fast loading

🤖 AI-Enhanced UX Features

Intelligent Interface Elements

  1. Smart Search: Predictive suggestions based on context
  2. AI Recommendations: Contextual tips and insights
  3. Auto-Complete: Forms pre-filled with AI predictions
  4. Anomaly Highlights: Visual indicators for unusual data
  5. Voice Commands: "Show today's production plan"

Conversational Interface Components

// AI Assistant Components to Build:
<AIAssistant />           // Floating chat widget
<SmartSearch />          // Predictive search bar
<ContextualHelp />       // Smart help tooltips
<VoiceInput />           // Speech-to-text input
<AIInsightCard />        // AI-generated insights

🔄 State Management Architecture

Modern State Pattern with Zustand

// Replace Redux with focused Zustand stores:

// Authentication State
interface AuthState {
  user: User | null;
  isAuthenticated: boolean;
  login: (credentials: LoginRequest) => Promise<void>;
  logout: () => void;
}

// UI State  
interface UIState {
  sidebarOpen: boolean;
  theme: 'light' | 'dark';
  currentModal: string | null;
  toggleSidebar: () => void;
  setTheme: (theme: 'light' | 'dark') => void;
}

// Business State
interface BakeryState {
  currentTenant: Tenant | null;
  businessModel: 'individual' | 'central';
  notifications: Notification[];
  setTenant: (tenant: Tenant) => void;
}

API Integration with React Query

// Replace custom hooks with React Query:
import { useQuery, useMutation } from '@tanstack/react-query';

export const useInventory = (tenantId: string) => {
  return useQuery({
    queryKey: ['inventory', tenantId],
    queryFn: () => apiClient.get(`/tenants/${tenantId}/inventory/products`),
    staleTime: 5 * 60 * 1000, // 5 minutes
    cacheTime: 10 * 60 * 1000, // 10 minutes
  });
};

export const useCreateProduct = () => {
  return useMutation({
    mutationFn: (product: CreateProductRequest) => 
      apiClient.post('/inventory/products', product),
    onSuccess: () => {
      queryClient.invalidateQueries(['inventory']);
    },
  });
};

🛣️ Routing & Navigation Architecture

URL-Based Navigation with Service-Aligned Structure

// Clean, RESTful URL structure aligned with backend services:
const routes = [
  // Public Routes
  '/',                                    # Landing page
  '/auth/login',                          # Authentication
  '/auth/register',
  
  // Protected Application Routes
  '/app',                                 # Redirect to dashboard
  '/app/dashboard',                       # Cross-service dashboard
  
  // Operations Hub (aligned with backend services)
  '/app/operations',                      # Operations hub overview
  '/app/operations/inventory',            # Inventory service frontend
  '/app/operations/inventory/products',   # Product catalog
  '/app/operations/inventory/stock',      # Stock management
  '/app/operations/inventory/alerts',     # Low stock alerts
  '/app/operations/production',           # Production service frontend  
  '/app/operations/production/batches',   # Production batches
  '/app/operations/production/schedule',  # Production scheduling
  '/app/operations/orders',               # Orders service frontend
  '/app/operations/orders/management',    # Order management
  '/app/operations/orders/tracking',      # Order status tracking
  '/app/operations/procurement',          # Procurement service frontend
  '/app/operations/procurement/plans',    # Procurement planning
  '/app/operations/procurement/suppliers', # Supplier management
  '/app/operations/pos',                  # POS service frontend
  '/app/operations/pos/integration',      # POS configuration
  '/app/operations/pos/transactions',     # Transaction sync
  
  // Analytics Hub (forecasting + sales analytics)
  '/app/analytics',                       # Analytics hub overview
  '/app/analytics/forecasting',           # Forecasting service frontend
  '/app/analytics/forecasting/predictions', # AI demand predictions
  '/app/analytics/forecasting/models',    # ML model management
  '/app/analytics/sales',                 # Sales analytics
  '/app/analytics/sales/trends',          # Sales trend analysis
  '/app/analytics/sales/reports',         # Sales reporting
  '/app/analytics/performance',           # Performance KPIs
  
  // Data Hub (external data integration)
  '/app/data',                           # Data hub overview
  '/app/data/weather',                   # Weather integration (AEMET)
  '/app/data/traffic',                   # Traffic patterns
  '/app/data/events',                    # External events
  
  // Communications Hub
  '/app/communications',                  # Communications overview
  '/app/communications/notifications',    # Notification management
  '/app/communications/alerts',          # Alert configuration
  '/app/communications/preferences',     # Communication preferences
  
  // Settings Hub
  '/app/settings',                       # Settings hub overview  
  '/app/settings/team',                  # Tenant service frontend
  '/app/settings/team/members',          # Team member management
  '/app/settings/team/roles',            # Role management
  '/app/settings/bakery',                # Bakery configuration
  '/app/settings/training',              # Training service frontend
  '/app/settings/training/models',       # ML model settings
  '/app/settings/training/history',      # Training history
  '/app/settings/system',                # System configuration
  
  // Onboarding (special workflow)
  '/app/onboarding',                     # AI-powered onboarding
  '/app/onboarding/upload',              # Sales data upload
  '/app/onboarding/analysis',            # AI analysis phase
  '/app/onboarding/review',              # Review AI suggestions
  '/app/onboarding/setup',               # Complete setup
];

// Context-aware navigation based on backend service responses
<Route path="/app/operations/inventory/products/:productId" />
<Route path="/app/operations/production/batches/:batchId" />
<Route path="/app/analytics/forecasting/models/:modelId" />

Context-Aware Navigation

// Smart navigation based on user context:
- Bakery type (individual vs central) determines available features
- User role (owner, manager, staff) controls access levels  
- Business model affects workflow organization
- Mobile vs desktop changes navigation patterns

📊 Data Visualization & Analytics

Chart Components with Recharts

// Standardized chart components:
<ForecastChart 
  data={forecastData}
  confidence={confidenceInterval}
  period="week"
  interactive={true}
/>

<SalesChart
  data={salesData}  
  comparison="previous_period"
  breakdown="product_category"
/>

<InventoryChart
  data={inventoryLevels}
  alerts={lowStockAlerts}
  predictions={restockPredictions}
/>

Dashboard Widget System

// Modular dashboard widgets:
<DashboardGrid>
  <Widget title="Today's Sales" size="md">
    <SalesKPICard />
  </Widget>
  
  <Widget title="Production Status" size="lg">
    <ProductionStatusTable />
  </Widget>
  
  <Widget title="AI Insights" size="sm">
    <AIInsightsList />
  </Widget>
</DashboardGrid>

🔐 Authentication & Authorization

Modern Auth Flow

// JWT-based authentication with refresh tokens:
interface AuthContext {
  user: User | null;
  isLoading: boolean;
  login: (email: string, password: string) => Promise<void>;
  register: (data: RegisterRequest) => Promise<void>;
  logout: () => void;
  refreshToken: () => Promise<void>;
}

// Route protection:
<ProtectedRoute requiredRoles={['admin', 'manager']}>
  <AdvancedAnalytics />
</ProtectedRoute>

Permission-Based UI

// Components adapt based on user permissions:
<ActionButton
  visible={hasPermission('inventory:create')}
  onClick={handleCreateProduct}
>
  Add Product
</ActionButton>

🧪 Form Management & Validation

React Hook Form + Zod Integration

// Type-safe forms with validation:
const productSchema = z.object({
  name: z.string().min(1, 'Product name required'),
  category: z.enum(['bread', 'pastry', 'ingredient']),
  price: z.number().positive('Price must be positive'),
});

const CreateProductForm = () => {
  const form = useForm({
    resolver: zodResolver(productSchema),
    defaultValues: { name: '', category: 'bread', price: 0 }
  });

  return (
    <Form onSubmit={form.handleSubmit(onSubmit)}>
      <FormField name="name" label="Product Name" />
      <FormField name="category" label="Category" type="select" />
      <FormField name="price" label="Price" type="number" />
    </Form>
  );
};

📁 New Project Structure to Build

frontend/
├── public/
│   ├── icons/                      # PWA icons
│   ├── manifest.json              # PWA manifest  
│   └── sw.js                      # Service worker
├── src/
│   ├── components/                # Component library
│   │   ├── ui/                    # Design system components
│   │   │   ├── Button/
│   │   │   │   ├── Button.tsx
│   │   │   │   ├── Button.stories.tsx
│   │   │   │   ├── Button.test.tsx
│   │   │   │   └── index.ts
│   │   │   ├── Input/
│   │   │   ├── Card/
│   │   │   └── index.ts           # Export all UI components
│   │   ├── layout/                # Layout components
│   │   │   ├── AppShell/
│   │   │   ├── Header/
│   │   │   ├── Sidebar/
│   │   │   └── index.ts
│   │   ├── domain/                # Business components
│   │   │   ├── auth/
│   │   │   ├── dashboard/
│   │   │   ├── inventory/
│   │   │   ├── production/
│   │   │   └── index.ts
│   │   └── shared/                # Shared utilities
│   │       ├── LoadingSpinner/
│   │       ├── ErrorBoundary/
│   │       └── index.ts
│   ├── pages/                     # Page components
│   │   ├── LandingPage/
│   │   ├── LoginPage/
│   │   ├── DashboardPage/
│   │   ├── InventoryPage/
│   │   └── index.ts
│   ├── hooks/                     # Custom hooks
│   │   ├── api/                   # API hooks (React Query)
│   │   │   ├── useAuth.ts
│   │   │   ├── useInventory.ts
│   │   │   └── index.ts
│   │   ├── ui/                    # UI state hooks
│   │   │   ├── useModal.ts
│   │   │   ├── useTheme.ts
│   │   │   └── index.ts
│   │   └── business/              # Business logic hooks
│   │       ├── useBakeryWorkflow.ts
│   │       └── index.ts
│   ├── stores/                    # State management
│   │   ├── auth.store.ts          # Zustand stores
│   │   ├── ui.store.ts
│   │   ├── bakery.store.ts
│   │   └── index.ts
│   ├── services/                  # API services
│   │   ├── api.client.ts          # HTTP client setup
│   │   ├── auth.service.ts        # Authentication API
│   │   ├── inventory.service.ts   # Inventory API
│   │   └── index.ts
│   ├── router/                    # Routing configuration
│   │   ├── AppRouter.tsx          # Main router setup
│   │   ├── ProtectedRoute.tsx     # Route guards
│   │   └── index.ts
│   ├── styles/                    # Global styles
│   │   ├── globals.css            # Global CSS
│   │   ├── components.css         # Component styles
│   │   └── animations.css         # Animation utilities
│   ├── utils/                     # Helper functions
│   │   ├── format.ts              # Data formatting
│   │   ├── validation.ts          # Validation helpers
│   │   ├── constants.ts           # App constants
│   │   └── index.ts
│   ├── types/                     # TypeScript definitions
│   │   ├── auth.types.ts
│   │   ├── inventory.types.ts
│   │   ├── api.types.ts
│   │   └── index.ts
│   ├── App.tsx                    # Root component
│   ├── main.tsx                   # Application entry
│   └── vite-env.d.ts             # Vite types
├── package.json
├── vite.config.ts
├── tailwind.config.js
├── tsconfig.json
└── README.md

🎯 Implementation Phases

Phase 1: Foundation (Week 1-2)

  1. Setup new project structure with proper folder organization
  2. Build design system - UI components with Storybook
  3. Implement authentication flow - login, register, JWT handling
  4. Create routing structure - React Router with protected routes
  5. Setup state management - Zustand stores for auth, UI, business logic

Phase 2: Core Features (Week 3-4)

  1. Dashboard implementation - KPI cards, charts, activity feed
  2. Inventory management - product lists, stock levels, alerts
  3. Production planning - batch scheduling, recipe management
  4. Sales tracking - transaction history, POS integration
  5. Mobile optimization - responsive design, touch interactions

Phase 3: Advanced Features (Week 5-6)

  1. Analytics hub - forecasting charts, trend analysis, reports
  2. AI integration - smart suggestions, predictive features
  3. PWA capabilities - offline mode, push notifications
  4. Performance optimization - lazy loading, caching strategies
  5. Accessibility audit - WCAG 2.2 compliance, keyboard navigation

Phase 4: Polish & Launch (Week 7-8)

  1. UI/UX refinement - micro-interactions, animations
  2. Testing implementation - unit tests, integration tests
  3. Documentation - component docs, user guides
  4. Performance monitoring - analytics, error tracking
  5. Production deployment - CI/CD pipeline, monitoring

🔧 Development Guidelines

Code Quality Standards

// TypeScript strict mode with no 'any'
interface StrictTyping {
  user: User;                      // ✅ Proper typing
  data: unknown;                   // ✅ Use unknown for uncertain types
  error: ApiError;                 // ✅ Define error types
  // avoid: data: any;             // ❌ Never use 'any'
}

// Component composition patterns:
const ProductCard = ({ product, onEdit, onDelete }: ProductCardProps) => {
  return (
    <Card>
      <CardHeader>
        <CardTitle>{product.name}</CardTitle>
      </CardHeader>
      <CardContent>
        <ProductDetails product={product} />
      </CardContent>
      <CardFooter>
        <Button onClick={onEdit}>Edit</Button>
        <Button variant="destructive" onClick={onDelete}>Delete</Button>
      </CardFooter>
    </Card>
  );
};

Performance Best Practices

// Lazy loading for code splitting:
const AnalyticsPage = lazy(() => import('./pages/AnalyticsPage'));

// Memoization for expensive calculations:
const expensiveCalculation = useMemo(() => {
  return processLargeDataset(data);
}, [data]);

// Debounced search:
const debouncedSearch = useDebounce(searchTerm, 300);

Accessibility Requirements

// WCAG 2.2 AA compliance:
<Button 
  aria-label="Add new product to inventory"
  tabIndex={0}
  onKeyDown={handleKeyDown}
>
  <PlusIcon aria-hidden="true" />
  Add Product
</Button>

// Focus management:
const DialogComponent = () => {
  const focusRef = useRef<HTMLButtonElement>(null);
  
  useEffect(() => {
    focusRef.current?.focus();
  }, []);
  
  return (
    <Dialog>
      <Button ref={focusRef}>Close</Button>
    </Dialog>
  );
};

📋 Specific Business Requirements

Bakery-Specific Features

  1. Dual Business Model Support:

    • Individual bakeries: On-site production, direct sales
    • Central production: Mass production, multi-outlet distribution
  2. Production Scheduling:

    • Early morning workflows (4:00-6:00 AM)
    • Recipe scaling and ingredient calculations
    • Equipment scheduling and capacity planning
  3. Inventory Management:

    • Ingredient tracking with expiration dates
    • Finished product inventory with shelf-life
    • Automated reorder points and supplier integration
  4. AI-Powered Forecasting:

    • Weather impact on demand (rainy days = less foot traffic)
    • Seasonal patterns (holidays, local events)
    • Product-specific demand predictions

Madrid Market Context

  • Language: Spanish UI with proper localization
  • Currency: Euro (€) formatting throughout
  • Business Hours: Early morning operations (4AM start)
  • Mobile Usage: 60%+ of interactions on mobile devices
  • Internet: Sometimes unreliable, need offline capabilities

🚀 Success Metrics & Goals

Performance Targets

  • Page Load Time: < 2 seconds on 3G connections
  • Bundle Size: < 500KB initial bundle (gzipped)
  • Lighthouse Score: 90+ for Performance, Accessibility, Best Practices
  • Mobile Score: 95+ for mobile usability

User Experience Goals

  • Onboarding Time: 5-10 minutes (down from 2-3 hours)
  • Task Completion: 90%+ success rate for core workflows
  • User Satisfaction: NPS score > 8.5
  • Mobile Adoption: 60%+ of daily active users on mobile

Business Impact

  • User Retention: 80%+ monthly active users
  • Feature Adoption: 90%+ using core features within 30 days
  • Support Tickets: 50% reduction in UI/UX related issues
  • Conversion Rate: 85%+ trial-to-paid conversion

🎨 Design Inspiration & Research

Modern SaaS Platforms to Study

  1. Linear - Clean design, excellent navigation, keyboard shortcuts
  2. Notion - Flexible layouts, contextual menus, progressive disclosure
  3. Figma - Collaborative features, real-time updates, intuitive interactions
  4. Stripe Dashboard - Data visualization, clear hierarchy, mobile-first
  5. Vercel - Performance focus, minimalist design, status indicators

AI-Enhanced Interfaces

  1. Claude.ai - Conversational interface, contextual help, smart suggestions
  2. Cursor - Predictive features, auto-completion, AI assistance
  3. GitHub Copilot - Code suggestions, contextual recommendations
  4. Replit - Real-time collaboration, AI-powered development environment

Mobile-First Enterprise Apps

  1. Slack Mobile - Touch-optimized, gesture navigation, offline support
  2. Asana Mobile - Task management, quick actions, responsive design
  3. Trello Mobile - Card-based interface, drag-and-drop interactions

🔍 Research Requirements

Before starting implementation, research:

  • Micro-interactions: Subtle animations that provide feedback
  • Glassmorphism: Translucent elements with backdrop blur
  • Neumorphism: Soft, inset shadow effects for buttons/cards
  • Dark Mode: System-preference aware theming
  • Accessibility First: WCAG 2.2 compliance from the start

AI-UX Patterns

  • Predictive Interface: UI that anticipates user needs
  • Contextual Help: Smart assistance based on current task
  • Progressive Enhancement: AI features that enhance without blocking
  • Explainable AI: Transparent AI decision-making

Performance Optimization

  • Core Web Vitals: LCP, FID, CLS optimization
  • Progressive Loading: Critical path prioritization
  • Edge Computing: CDN optimization for global performance
  • Bundle Analysis: Tree-shaking and code-splitting strategies

Quick Start Checklist

Week 1: Foundation

  • Create new project structure with proper organization
  • Setup Tailwind CSS with custom design system
  • Implement authentication flow (login/register/logout)
  • Create basic layout components (Header, Sidebar, AppShell)
  • Setup React Router with protected routes

Week 2: Core Components

  • Build complete UI component library with Storybook
  • Implement Zustand stores for state management
  • Create API service layer with React Query
  • Build dashboard with KPI cards and charts
  • Add mobile-responsive navigation

Week 3: Business Features

  • Inventory management (products, stock levels, alerts)
  • Production planning (batches, recipes, scheduling)
  • Sales tracking (transactions, POS integration)
  • Forecasting (charts, predictions, confidence intervals)
  • Basic analytics and reporting

Week 4: UX Enhancement

  • AI-powered features (smart search, recommendations)
  • Progressive Web App (offline, notifications, install)
  • Accessibility audit and improvements (WCAG 2.2 AA)
  • Performance optimization (lazy loading, caching)
  • Cross-device testing and optimization

🎯 Final Outcome

Transform the Bakery AI Platform into:

Modern, Professional Interface - Following 2024-2025 design standards with glassmorphism, micro-interactions, and AI-enhanced UX

Clean, Maintainable Codebase - TypeScript-first, component-driven architecture with clear separation of concerns

Mobile-First Experience - Touch-optimized, responsive design with PWA capabilities and offline functionality

AI-Enhanced Workflows - Predictive features, smart suggestions, and contextual help that guide users intelligently

High-Performance Application - Fast loading, efficient rendering, and optimized for Madrid bakery operations

Accessible Platform - WCAG 2.2 AA compliant with support for all users and assistive technologies

Remember: You're building for Madrid bakery owners who start work at 4:00 AM and need reliable, fast, intuitive tools to manage their businesses profitably. Every design and technical decision should prioritize their real operational needs over technical elegance.