This commit fixes the template interpolation issues where variables like
{{supplier_name}}, {{product_names_joined}}, {{current_stock}}, etc. were
showing as literal strings instead of being replaced with actual values.
Changes made:
1. **Dashboard Service (Orchestrator):**
- Added missing `current_stock` parameter to default reasoning_data for
production batches
- This ensures all required template variables are present when batches
don't have proper reasoning_data from the database
2. **Production Service:**
- Updated batch creation to properly populate `product_name` field
- Improved product name resolution to check forecast data and stock_info
before falling back to placeholder
- Added missing `product_id` field to batch_data
- Added required `planned_duration_minutes` field to batch_data
- Ensures reasoning_data has all required parameters (product_name,
predicted_demand, current_stock, confidence_score)
The root cause was that the default reasoning_data used by the dashboard
service when database records lacked proper reasoning_data was missing
required parameters. This resulted in i18n template variables being
displayed as literal {{variable}} strings instead of interpolated values.
Fixes dashboard display issues for:
- Purchase order cards showing {{supplier_name}}, {{product_names_joined}},
{{days_until_stockout}}
- Production plan items showing {{product_name}}, {{predicted_demand}},
{{current_stock}}, {{confidence_score}}
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 schedulesPOST /api/v1/production/schedules- Create production scheduleGET /api/v1/production/schedules/{schedule_id}- Get schedule detailsPUT /api/v1/production/schedules/{schedule_id}- Update schedulePOST /api/v1/production/schedules/generate- Auto-generate from forecasts
Batch Management
GET /api/v1/production/batches- List production batchesPOST /api/v1/production/batches- Create production batchGET /api/v1/production/batches/{batch_id}- Get batch detailsPUT /api/v1/production/batches/{batch_id}/status- Update batch statusPOST /api/v1/production/batches/{batch_id}/complete- Complete batch
Quality Control
GET /api/v1/production/quality/templates- List QC templatesPOST /api/v1/production/quality/checks- Record quality checkGET /api/v1/production/quality/checks/{batch_id}- Get batch qualityGET /api/v1/production/quality/metrics- Quality metrics dashboard
Equipment Management
GET /api/v1/production/equipment- List all equipmentPOST /api/v1/production/equipment- Add equipmentPUT /api/v1/production/equipment/{equipment_id}- Update equipmentPOST /api/v1/production/equipment/{equipment_id}/maintenance- Log maintenance
Analytics
GET /api/v1/production/dashboard- Production dashboard KPIsGET /api/v1/production/analytics/efficiency- Efficiency metricsGET /api/v1/production/analytics/costs- Cost analysisGET /api/v1/production/analytics/waste- Waste analysis
Database Schema
Main Tables
production_schedules
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
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
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
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
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
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: production
Routing Keys: production.batch.completed, production.quality.issue, production.equipment.maintenance
Batch Completed Event
{
"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"
}
Quality Issue Alert
{
"event_type": "quality_issue",
"tenant_id": "uuid",
"batch_id": "uuid",
"product_name": "Croissant",
"quality_score": 65,
"passing_score": 80,
"issues_found": "Color too dark, texture inconsistent",
"severity": "high",
"corrective_actions": "Adjust oven temperature, check proofing time",
"timestamp": "2025-11-06T10:30:00Z"
}
Consumed Events
- From Forecasting: Daily forecasts for production planning
- From Orchestrator: Scheduled production triggers
- From Inventory: Stock availability checks
Custom Metrics (Prometheus)
# 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 stringREDIS_URL- Redis connection stringRABBITMQ_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
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.