# Production Service

## Overview

The **Production Service** orchestrates all bakery manufacturing operations, from automated production scheduling based on forecasts to quality control tracking and equipment management. It transforms demand predictions into actionable production plans, ensuring optimal efficiency, consistent quality, and minimal waste. This service is the bridge between forecasting intelligence and actual bakery operations.

## Key Features

### Automated Production Planning
- **Forecast-Driven Scheduling** - Automatic production schedules from demand forecasts
- **Batch Management** - Track all production batches from start to finish
- **Capacity Planning** - Optimize production capacity utilization
- **Multi-Day Scheduling** - Plan production up to 7 days ahead
- **Recipe Integration** - Automatic ingredient calculation from recipes
- **Equipment Scheduling** - Allocate ovens, mixers, and equipment efficiently

### Production Execution
- **Batch Tracking** - Real-time status of all active production batches
- **Production Logs** - Detailed execution records with timestamps
- **Ingredient Consumption** - Automatic FIFO stock deduction
- **Yield Tracking** - Actual vs. expected production yields
- **Waste Recording** - Track production waste and reasons
- **Real-Time Alerts** - Notifications for production issues

### Quality Control
- **Quality Check Templates** - Standardized quality control forms
- **Digital Checklists** - Paperless quality inspections
- **Quality Metrics** - Track quality scores over time
- **Non-Conformance Tracking** - Record and resolve quality issues
- **Batch Quality History** - Complete quality audit trail

### Equipment Management
- **Equipment Tracking** - All bakery equipment inventory
- **Maintenance Schedules** - Preventive maintenance tracking
- **Equipment Usage** - Monitor utilization and performance
- **Downtime Logging** - Track equipment failures
- **Maintenance Alerts** - Automatic maintenance reminders

### Analytics & Reporting
- **Production Dashboard** - Real-time production KPIs
- **Efficiency Metrics** - OEE (Overall Equipment Effectiveness)
- **Cost Analysis** - Production cost per batch
- **Trend Analysis** - Historical production patterns
- **Performance Reports** - Daily, weekly, monthly summaries

## Business Value

### For Bakery Owners
- **Automated Scheduling** - Save 10-15 hours/week on production planning
- **Waste Reduction** - 15-25% reduction through optimized batch sizes
- **Quality Consistency** - Standardized processes across all batches
- **Cost Control** - Track and reduce production costs
- **Compliance** - Complete production audit trail

### Quantifiable Impact
- **Time Savings**: 10-15 hours/week on planning
- **Waste Reduction**: 15-25% through optimization
- **Cost Savings**: €300-800/month from efficiency gains
- **Quality Improvement**: 20-30% fewer defects
- **Capacity Utilization**: 85%+ (vs 65-70% manual)

### For Production Staff
- **Clear Instructions** - Digital recipes and batch cards
- **Quality Guidance** - Step-by-step quality checks
- **Equipment Visibility** - Know what's available
- **Prioritization** - Know what to produce first

## Technology Stack

- **Framework**: FastAPI (Python 3.11+) - Async web framework
- **Database**: PostgreSQL 17 - Production data
- **Caching**: Redis 7.4 - Dashboard KPIs
- **Messaging**: RabbitMQ 4.1 - Alert publishing
- **ORM**: SQLAlchemy 2.0 (async) - Database abstraction
- **Logging**: Structlog - Structured JSON logging
- **Metrics**: Prometheus Client - Custom metrics

## API Endpoints (Key Routes)

### Production Scheduling
- `GET /api/v1/production/schedules` - List production schedules
- `POST /api/v1/production/schedules` - Create production schedule
- `GET /api/v1/production/schedules/{schedule_id}` - Get schedule details
- `PUT /api/v1/production/schedules/{schedule_id}` - Update schedule
- `POST /api/v1/production/schedules/generate` - Auto-generate from forecasts

### Batch Management
- `GET /api/v1/production/batches` - List production batches
- `POST /api/v1/production/batches` - Create production batch
- `GET /api/v1/production/batches/{batch_id}` - Get batch details
- `PUT /api/v1/production/batches/{batch_id}/status` - Update batch status
- `POST /api/v1/production/batches/{batch_id}/complete` - Complete batch

### Quality Control
- `GET /api/v1/production/quality/templates` - List QC templates
- `POST /api/v1/production/quality/checks` - Record quality check
- `GET /api/v1/production/quality/checks/{batch_id}` - Get batch quality
- `GET /api/v1/production/quality/metrics` - Quality metrics dashboard

### Equipment Management
- `GET /api/v1/production/equipment` - List all equipment
- `POST /api/v1/production/equipment` - Add equipment
- `PUT /api/v1/production/equipment/{equipment_id}` - Update equipment
- `POST /api/v1/production/equipment/{equipment_id}/maintenance` - Log maintenance

### Analytics
- `GET /api/v1/production/dashboard` - Production dashboard KPIs
- `GET /api/v1/production/analytics/efficiency` - Efficiency metrics
- `GET /api/v1/production/analytics/costs` - Cost analysis
- `GET /api/v1/production/analytics/waste` - Waste analysis

## Database Schema

### Main Tables

**production_schedules**
```sql
CREATE TABLE production_schedules (
    id UUID PRIMARY KEY,
    tenant_id UUID NOT NULL,
    schedule_name VARCHAR(255),
    schedule_date DATE NOT NULL,
    status VARCHAR(50) DEFAULT 'pending',    -- pending, in_progress, completed
    total_batches INTEGER DEFAULT 0,
    completed_batches INTEGER DEFAULT 0,
    generated_from_forecast_id UUID,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),
    INDEX idx_tenant_date (tenant_id, schedule_date)
);
```

**production_batches**
```sql
CREATE TABLE production_batches (
    id UUID PRIMARY KEY,
    tenant_id UUID NOT NULL,
    schedule_id UUID REFERENCES production_schedules(id),
    batch_number VARCHAR(100) NOT NULL,
    product_id UUID NOT NULL,
    recipe_id UUID NOT NULL,
    quantity_planned DECIMAL(10, 2) NOT NULL,
    quantity_actual DECIMAL(10, 2),
    unit VARCHAR(50) NOT NULL,
    status VARCHAR(50) DEFAULT 'planned',    -- planned, in_progress, quality_check, completed, failed
    priority INTEGER DEFAULT 5,
    start_time TIMESTAMP,
    end_time TIMESTAMP,
    assigned_to UUID,
    equipment_used JSONB,
    notes TEXT,
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW(),
    UNIQUE(tenant_id, batch_number)
);
```

**quality_check_templates**
```sql
CREATE TABLE quality_check_templates (
    id UUID PRIMARY KEY,
    tenant_id UUID NOT NULL,
    template_name VARCHAR(255) NOT NULL,
    product_category VARCHAR(100),
    check_items JSONB NOT NULL,              -- Array of check items with criteria
    passing_score INTEGER DEFAULT 80,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP DEFAULT NOW()
);
```

**quality_checks**
```sql
CREATE TABLE quality_checks (
    id UUID PRIMARY KEY,
    tenant_id UUID NOT NULL,
    batch_id UUID REFERENCES production_batches(id),
    template_id UUID REFERENCES quality_check_templates(id),
    performed_by UUID NOT NULL,
    check_results JSONB NOT NULL,            -- Results for each check item
    overall_score INTEGER,
    passed BOOLEAN,
    issues_found TEXT,
    corrective_actions TEXT,
    performed_at TIMESTAMP DEFAULT NOW()
);
```

**equipment**
```sql
CREATE TABLE equipment (
    id UUID PRIMARY KEY,
    tenant_id UUID NOT NULL,
    equipment_name VARCHAR(255) NOT NULL,
    equipment_type VARCHAR(100),             -- oven, mixer, proofer, etc.
    capacity VARCHAR(100),
    location VARCHAR(255),
    status VARCHAR(50) DEFAULT 'operational', -- operational, maintenance, broken
    last_maintenance_date DATE,
    next_maintenance_date DATE,
    maintenance_interval_days INTEGER DEFAULT 90,
    total_usage_hours INTEGER DEFAULT 0,
    created_at TIMESTAMP DEFAULT NOW(),
    UNIQUE(tenant_id, equipment_name)
);
```

**production_capacity**
```sql
CREATE TABLE production_capacity (
    id UUID PRIMARY KEY,
    tenant_id UUID NOT NULL,
    date DATE NOT NULL,
    shift VARCHAR(50),                       -- morning, afternoon, night
    available_hours DECIMAL(5, 2),
    used_hours DECIMAL(5, 2) DEFAULT 0,
    utilization_percentage DECIMAL(5, 2),
    created_at TIMESTAMP DEFAULT NOW(),
    UNIQUE(tenant_id, date, shift)
);
```

## Events & Messaging

### Published Events (RabbitMQ)

**Exchange**: `events.exchange`
**Domain**: `production`

### Business Events

**Batch Completed Event**
```json
{
    "event_type": "batch_completed",
    "tenant_id": "uuid",
    "batch_id": "uuid",
    "batch_number": "BATCH-2025-1106-001",
    "product_id": "uuid",
    "product_name": "Baguette",
    "quantity_planned": 100,
    "quantity_actual": 98,
    "yield_percentage": 98.0,
    "quality_score": 92,
    "quality_passed": true,
    "duration_minutes": 240,
    "completed_at": "2025-11-06T14:30:00Z",
    "timestamp": "2025-11-06T14:30:00Z"
}
```

### Alert Events

All alerts are published to the alert processor for enrichment and notification.

#### 1. Production Delay Alert
**Event Type**: `production.production_delay`
**Severity**: urgent (>120 min), high (>60 min), medium (otherwise)
**Trigger**: Batch delayed past scheduled start time

```json
{
    "event_type": "production.production_delay",
    "severity": "urgent",
    "metadata": {
        "batch_id": "uuid",
        "product_name": "Baguette",
        "batch_number": "BATCH-001",
        "delay_minutes": 135,
        "affected_orders": 5,
        "customer_names": ["Café A", "Café B"]
    }
}
```

#### 2. Equipment Failure Alert
**Event Type**: `production.equipment_failure`
**Severity**: urgent
**Trigger**: Equipment malfunction detected

```json
{
    "event_type": "production.equipment_failure",
    "severity": "urgent",
    "metadata": {
        "equipment_id": "uuid",
        "equipment_name": "Oven #1",
        "equipment_type": "oven",
        "affected_batches": 3
    }
}
```

#### 3. Capacity Overload Alert
**Event Type**: `production.capacity_overload`
**Severity**: urgent (>120%), high (>100%), medium (otherwise)
**Trigger**: Production capacity exceeded

```json
{
    "event_type": "production.capacity_overload",
    "severity": "urgent",
    "metadata": {
        "current_load_percent": 125,
        "planned_batches": 15,
        "available_capacity": 12,
        "affected_date": "2025-12-20"
    }
}
```

#### 4. Quality Issue Alert
**Event Type**: `production.quality_issue`
**Severity**: high
**Trigger**: Batch quality below threshold

```json
{
    "event_type": "production.quality_issue",
    "severity": "high",
    "metadata": {
        "batch_id": "uuid",
        "product_name": "Croissant",
        "issue_type": "quality_below_threshold",
        "issue_description": "Color too dark, texture inconsistent",
        "affected_quantity": 50
    }
}
```

#### 5. Production Start Alert
**Event Type**: `production.start_production`
**Severity**: medium
**Trigger**: Production batch created

```json
{
    "event_type": "production.start_production",
    "severity": "medium",
    "metadata": {
        "batch_id": "uuid",
        "product_name": "Baguette",
        "batch_number": "BATCH-001",
        "planned_start_time": "2025-12-20T06:00:00Z",
        "reasoning_data": {...}
    }
}
```

#### 6. Batch Start Delayed Alert
**Event Type**: `production.batch_start_delayed`
**Severity**: high
**Trigger**: Batch start delayed for specific reason

```json
{
    "event_type": "production.batch_start_delayed",
    "severity": "high",
    "metadata": {
        "batch_id": "uuid",
        "product_name": "Pain au Chocolat",
        "batch_number": "BATCH-002",
        "scheduled_start": "2025-12-20T07:00:00Z",
        "delay_reason": "Missing ingredients"
    }
}
```

#### 7. Missing Ingredients Alert
**Event Type**: `production.missing_ingredients`
**Severity**: urgent
**Trigger**: Required ingredients unavailable

```json
{
    "event_type": "production.missing_ingredients",
    "severity": "urgent",
    "metadata": {
        "batch_id": "uuid",
        "product_name": "Baguette",
        "batch_number": "BATCH-001",
        "missing_ingredients": [
            {"name": "Flour", "required": 50, "available": 10},
            {"name": "Yeast", "required": 2, "available": 0}
        ],
        "missing_count": 2
    }
}
```

#### 8. Equipment Maintenance Due Alert
**Event Type**: `production.equipment_maintenance_due`
**Severity**: high (>30 days overdue), medium (otherwise)
**Trigger**: Equipment maintenance overdue

```json
{
    "event_type": "production.equipment_maintenance_due",
    "severity": "high",
    "metadata": {
        "equipment_id": "uuid",
        "equipment_name": "Mixer #2",
        "last_maintenance_date": "2024-10-15",
        "days_overdue": 45
    }
}
```

### AI Recommendations

#### Efficiency Recommendation
**Event Type**: `production.efficiency_recommendation`
**Severity**: medium

#### Energy Optimization
**Event Type**: `production.energy_optimization`
**Severity**: medium

#### Batch Sequence Optimization
**Event Type**: `production.batch_sequence_optimization`
**Severity**: medium

### Consumed Events
- **From Forecasting**: Daily forecasts for production planning
- **From Orchestrator**: Scheduled production triggers
- **From Inventory**: Stock availability checks

## Custom Metrics (Prometheus)

```python
# Production metrics
batches_produced_total = Counter(
    'production_batches_total',
    'Total production batches',
    ['tenant_id', 'product_category', 'status']
)

production_yield_percentage = Histogram(
    'production_yield_percentage',
    'Production yield percentage',
    ['tenant_id', 'product_id'],
    buckets=[70, 80, 85, 90, 95, 98, 100]
)

# Quality metrics
quality_checks_total = Counter(
    'production_quality_checks_total',
    'Total quality checks performed',
    ['tenant_id', 'passed']
)

quality_score_distribution = Histogram(
    'production_quality_score',
    'Quality score distribution',
    ['tenant_id'],
    buckets=[50, 60, 70, 80, 85, 90, 95, 100]
)

# Efficiency metrics
production_duration_minutes = Histogram(
    'production_duration_minutes',
    'Production batch duration',
    ['tenant_id', 'product_category'],
    buckets=[30, 60, 120, 180, 240, 360, 480]
)

capacity_utilization = Gauge(
    'production_capacity_utilization_percentage',
    'Production capacity utilization',
    ['tenant_id', 'shift']
)
```

## Configuration

### Environment Variables

**Service Configuration:**
- `PORT` - Service port (default: 8007)
- `DATABASE_URL` - PostgreSQL connection string
- `REDIS_URL` - Redis connection string
- `RABBITMQ_URL` - RabbitMQ connection string

**Production Configuration:**
- `DEFAULT_BATCH_SIZE` - Standard batch size (default: 100)
- `MAX_BATCHES_PER_DAY` - Maximum daily batches (default: 20)
- `ENABLE_AUTO_SCHEDULING` - Auto-generate schedules (default: true)
- `SCHEDULE_GENERATION_TIME` - Daily schedule time (default: "08:00")

**Quality Control:**
- `DEFAULT_PASSING_SCORE` - Minimum quality score (default: 80)
- `ENABLE_QUALITY_ALERTS` - Alert on quality issues (default: true)
- `QUALITY_CHECK_REQUIRED` - Require QC for all batches (default: true)

**Equipment:**
- `MAINTENANCE_REMINDER_DAYS` - Days before maintenance (default: 7)
- `ENABLE_EQUIPMENT_TRACKING` - Track equipment usage (default: true)

## Development Setup

### Prerequisites
- Python 3.11+
- PostgreSQL 17
- Redis 7.4
- RabbitMQ 4.1

### Local Development
```bash
cd services/production
python -m venv venv
source venv/bin/activate

pip install -r requirements.txt

export DATABASE_URL=postgresql://user:pass@localhost:5432/production
export REDIS_URL=redis://localhost:6379/0
export RABBITMQ_URL=amqp://guest:guest@localhost:5672/

alembic upgrade head
python main.py
```

## Integration Points

### Dependencies
- **Forecasting Service** - Demand forecasts for scheduling
- **Recipes Service** - Recipe details for batches
- **Inventory Service** - Stock availability and consumption
- **Equipment data** - Equipment tracking
- **PostgreSQL** - Production data storage
- **Redis** - Dashboard caching
- **RabbitMQ** - Event publishing

### Dependents
- **Inventory Service** - Ingredient consumption updates
- **AI Insights Service** - Production efficiency insights
- **Orchestrator Service** - Triggers daily scheduling
- **Frontend Dashboard** - Display production status

## Business Value for VUE Madrid

- **Automation**: 10-15 hours/week saved on manual planning
- **Waste Reduction**: 15-25% through optimized scheduling
- **Quality Improvement**: Standardized processes, 20-30% fewer defects
- **Compliance**: Complete production audit trail
- **Efficiency**: 85%+ capacity utilization vs 65-70% manual

---

**Copyright © 2025 Bakery-IA. All rights reserved.**
