# 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
1. **Login**: User enters credentials → API returns access token + refresh token
2. **Token Storage**: Tokens stored in Zustand store + localStorage
3. **Request Interceptor**: Axios interceptor adds `Authorization: Bearer {token}` to all requests
4. **Token Refresh**: On 401 error, automatically refresh token and retry request
5. **Logout**: Clear tokens and redirect to login

### TanStack Query Configuration
```typescript
// 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
```typescript
// 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
```typescript
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
```typescript
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 payments
- `VITE_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
```env
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
```bash
# 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
```bash
# Create optimized production build
npm run build

# Preview production build locally
npm run preview
```

### Code Quality
```bash
# Run linter
npm run lint

# Run type checking
npm run type-check

# Format code
npm run format
```

## Testing

### Unit Tests (Vitest)
```bash
# 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)
```bash
# 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
```dockerfile
# 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
1. **Lint & Type Check** - Ensure code quality
2. **Unit Tests** - Run test suite
3. **Build** - Create production build
4. **Docker Build** - Create container image
5. **Push to Registry** - Push to container registry
6. **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

1. **Modern Tech Stack** - React 18, TypeScript, Vite for fast development
2. **Real-Time Updates** - SSE and WebSocket for instant feedback
3. **Mobile-First** - Responsive design works on all devices
4. **Offline Support** (planned) - PWA capabilities for unreliable networks
5. **Accessible** - WCAG 2.1 AA compliant for inclusive access
6. **Fast Performance** - Code splitting and caching for sub-second loads
7. **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.
