This commit removes the last hardcoded English text from reasoning fields
across all backend services, completing the i18n implementation.
Changes by service:
Safety Stock Calculator (safety_stock_calculator.py):
- CALC:STATISTICAL_Z_SCORE - Statistical calculation with Z-score
- CALC:ADVANCED_VARIABILITY - Advanced formula with demand and lead time variability
- CALC:FIXED_PERCENTAGE - Fixed percentage of lead time demand
- All calculation methods now use structured codes with pipe-separated parameters
Price Forecaster (price_forecaster.py):
- PRICE_FORECAST:DECREASE_EXPECTED - Price expected to decrease
- PRICE_FORECAST:INCREASE_EXPECTED - Price expected to increase
- PRICE_FORECAST:HIGH_VOLATILITY - High price volatility detected
- PRICE_FORECAST:BELOW_AVERAGE - Current price below average (buy opportunity)
- PRICE_FORECAST:STABLE - Price stable, normal schedule
- All forecasts include relevant parameters (change_pct, days, etc.)
Optimization Utils (shared/utils/optimization.py):
- EOQ:BASE - Economic Order Quantity base calculation
- EOQ:MOQ_APPLIED - Minimum order quantity constraint applied
- EOQ:MAX_APPLIED - Maximum order quantity constraint applied
- TIER_PRICING:CURRENT_TIER - Current tier pricing
- TIER_PRICING:UPGRADED - Upgraded to higher tier for savings
- All optimizations include calculation parameters
Format: All codes use pattern "CATEGORY:TYPE|param1=value|param2=value"
This allows frontend to parse and translate with parameters while maintaining
technical accuracy for logging and debugging.
Frontend can now translate ALL reasoning codes across the entire system.
Demo Seed Scripts:
- Updated seed_demo_purchase_orders.py to use structured reasoning_data
* Imports create_po_reasoning_low_stock and create_po_reasoning_supplier_contract
* Generates reasoning_data with product names, stock levels, and consequences
* Removed deprecated reasoning/consequence TEXT fields
- Updated seed_demo_batches.py to use structured reasoning_data
* Imports create_batch_reasoning_forecast_demand and create_batch_reasoning_regular_schedule
* Generates intelligent reasoning based on batch priority and AI assistance
* Adds reasoning_data to all production batches
Backend Services - Error Code Implementation:
- Updated safety_stock_calculator.py with error codes
* Replaced "Lead time or demand std dev is zero or negative" with ERROR:LEAD_TIME_INVALID
* Replaced "Insufficient historical demand data" with ERROR:INSUFFICIENT_DATA
- Updated replenishment_planning_service.py with error codes
* Replaced "Insufficient data for safety stock calculation" with ERROR:INSUFFICIENT_DATA
* Frontend can now translate error codes using i18n
Demo data will now display with translatable reasoning in EN/ES/EU languages.
Backend services return error codes that frontend translates for user's language.
Completed the migration to structured reasoning_data for multilingual
dashboard support. Removed hardcoded TEXT fields (reasoning, consequence)
and updated all related code to use JSONB reasoning_data.
Changes:
1. Models Updated (removed TEXT fields):
- PurchaseOrder: Removed reasoning, consequence TEXT columns
- ProductionBatch: Removed reasoning TEXT column
- Both now use only reasoning_data (JSONB/JSON)
2. Dashboard Service Updated:
- Changed to return reasoning_data instead of TEXT fields
- Creates default reasoning_data if missing
- PO actions: reasoning_data with type and parameters
- Production timeline: reasoning_data for each batch
3. Unified Schemas Updated (no separate migration):
- services/procurement/migrations/001_unified_initial_schema.py
- services/production/migrations/001_unified_initial_schema.py
- Removed reasoning/consequence columns from table definitions
- Updated comments to reflect i18n approach
Database Schema:
- purchase_orders: Only reasoning_data (JSONB)
- production_batches: Only reasoning_data (JSON)
Backend now generates:
{
"type": "low_stock_detection",
"parameters": {
"supplier_name": "Harinas del Norte",
"days_until_stockout": 3,
...
},
"consequence": {
"type": "stockout_risk",
"severity": "high"
}
}
Next Steps:
- Frontend: Create i18n translation keys
- Frontend: Update components to translate reasoning_data
- Test multilingual support (ES, EN, CA)
Implemented proper reasoning data generation for purchase orders and
production batches to enable multilingual dashboard support.
Backend Strategy:
- Generate structured JSON with type codes and parameters
- Store only reasoning_data (JSONB), not hardcoded text
- Frontend will translate using i18n libraries
Changes:
1. Created shared/schemas/reasoning_types.py
- Defined reasoning types for POs and batches
- Created helper functions for common reasoning patterns
- Supports multiple reasoning types (low_stock, forecast_demand, etc.)
2. Production Service (services/production/app/services/production_service.py)
- Generate reasoning_data when creating batches from forecast
- Include parameters: product_name, predicted_demand, current_stock, etc.
- Structure supports frontend i18n interpolation
3. Procurement Service (services/procurement/app/services/procurement_service.py)
- Implemented actual PO creation (was placeholder before!)
- Groups requirements by supplier
- Generates reasoning_data based on context (low_stock vs forecast)
- Creates PO items automatically
Example reasoning_data:
{
"type": "low_stock_detection",
"parameters": {
"supplier_name": "Harinas del Norte",
"product_names": ["Flour Type 55", "Flour Type 45"],
"days_until_stockout": 3,
"current_stock": 45.5,
"required_stock": 200
},
"consequence": {
"type": "stockout_risk",
"severity": "high",
"impact_days": 3
}
}
Frontend will translate:
- EN: "Low stock detected for Harinas del Norte. Stock runs out in 3 days."
- ES: "Stock bajo detectado para Harinas del Norte. Se agota en 3 días."
- CA: "Estoc baix detectat per Harinas del Norte. S'esgota en 3 dies."
Next steps:
- Remove TEXT fields (reasoning, consequence) from models
- Update dashboard service to use reasoning_data
- Create frontend i18n translation keys
- Update dashboard components to translate dynamically
Consolidated incremental migrations into single unified initial schema files for both procurement and production services. This simplifies database setup and eliminates migration chain complexity.
Changes:
- Procurement: Merged 3 migrations into 001_unified_initial_schema.py
- Initial schema (20251015_1229)
- Add supplier_price_list_id (20251030_0737)
- Add JTBD reasoning fields (20251107)
- Production: Merged 3 migrations into 001_unified_initial_schema.py
- Initial schema (20251015_1231)
- Add waste tracking fields (20251023_0900)
- Add JTBD reasoning fields (20251107)
All new fields (reasoning, consequence, reasoning_data, waste_defect_type, is_ai_assisted, supplier_price_list_id) are now included in the initial schemas from the start.
Updated model files to use deferred() for reasoning fields to prevent breaking queries when running against existing databases.
Implements comprehensive dashboard redesign based on Jobs To Be Done methodology
focused on answering: "What requires my attention right now?"
## Backend Implementation
### Dashboard Service (NEW)
- Health status calculation (green/yellow/red traffic light)
- Action queue prioritization (critical/important/normal)
- Orchestration summary with narrative format
- Production timeline transformation
- Insights calculation and consequence prediction
### API Endpoints (NEW)
- GET /dashboard/health-status - Overall bakery health indicator
- GET /dashboard/orchestration-summary - What system did automatically
- GET /dashboard/action-queue - Prioritized tasks requiring attention
- GET /dashboard/production-timeline - Today's production schedule
- GET /dashboard/insights - Key metrics (savings, inventory, waste, deliveries)
### Enhanced Models
- PurchaseOrder: Added reasoning, consequence, reasoning_data fields
- ProductionBatch: Added reasoning, reasoning_data fields
- Enables transparency into automation decisions
## Frontend Implementation
### API Hooks (NEW)
- useBakeryHealthStatus() - Real-time health monitoring
- useOrchestrationSummary() - System transparency
- useActionQueue() - Prioritized action management
- useProductionTimeline() - Production tracking
- useInsights() - Glanceable metrics
### Dashboard Components (NEW)
- HealthStatusCard: Traffic light indicator with checklist
- ActionQueueCard: Prioritized actions with reasoning/consequences
- OrchestrationSummaryCard: Narrative of what system did
- ProductionTimelineCard: Chronological production view
- InsightsGrid: 2x2 grid of key metrics
### Main Dashboard Page (REPLACED)
- Complete rewrite with mobile-first design
- All sections integrated with error handling
- Real-time refresh and quick action links
- Old dashboard backed up as DashboardPage.legacy.tsx
## Key Features
### Automation-First
- Shows what orchestrator did overnight
- Builds trust through transparency
- Explains reasoning for all automated decisions
### Action-Oriented
- Prioritizes tasks over information display
- Clear consequences for each action
- Large touch-friendly buttons
### Progressive Disclosure
- Shows 20% of info that matters 80% of time
- Expandable details when needed
- No overwhelming metrics
### Mobile-First
- One-handed operation
- Large touch targets (min 44px)
- Responsive grid layouts
### Trust-Building
- Narrative format ("I planned your day")
- Reasoning inputs transparency
- Clear status indicators
## User Segments Supported
1. Solo Bakery Owner (Primary)
- Simple health indicator
- Action checklist (max 3-5 items)
- Mobile-optimized
2. Multi-Location Owner
- Multi-tenant support (existing)
- Comparison capabilities
- Delegation ready
3. Enterprise/Central Bakery (Future)
- Network topology support
- Advanced analytics ready
## JTBD Analysis Delivered
Main Job: "Help me quickly understand bakery status and know what needs my intervention"
Emotional Jobs Addressed:
- Feel in control despite automation
- Reduce daily anxiety
- Feel competent with technology
- Trust system as safety net
Social Jobs Addressed:
- Demonstrate professional management
- Avoid being bottleneck
- Show sustainability
## Technical Stack
Backend: Python, FastAPI, SQLAlchemy, PostgreSQL
Frontend: React, TypeScript, TanStack Query, Tailwind CSS
Architecture: Microservices with circuit breakers
## Breaking Changes
- Complete dashboard page rewrite (old version backed up)
- New API endpoints require orchestrator service deployment
- Database migrations needed for reasoning fields
## Migration Required
Run migrations to add new model fields:
- purchase_orders: reasoning, consequence, reasoning_data
- production_batches: reasoning, reasoning_data
## Documentation
See DASHBOARD_REDESIGN_SUMMARY.md for complete implementation details,
JTBD analysis, success metrics, and deployment guide.
BREAKING CHANGE: Dashboard page completely redesigned with new data structures