Commit Graph

37 Commits

Author SHA1 Message Date
Urtzi Alfaro
21d35ea92b Add ci/cd and fix multiple pods issues 2026-01-18 09:02:27 +01:00
Urtzi Alfaro
b931a5c45e Add improvements 2 2026-01-12 22:15:11 +01:00
Urtzi Alfaro
230bbe6a19 Add improvements 2026-01-12 14:24:14 +01:00
Urtzi Alfaro
29d19087f1 Update monitoring packages to latest versions
- Updated all OpenTelemetry packages to latest versions:
  - opentelemetry-api: 1.27.0 → 1.39.1
  - opentelemetry-sdk: 1.27.0 → 1.39.1
  - opentelemetry-exporter-otlp-proto-grpc: 1.27.0 → 1.39.1
  - opentelemetry-exporter-otlp-proto-http: 1.27.0 → 1.39.1
  - opentelemetry-instrumentation-fastapi: 0.48b0 → 0.60b1
  - opentelemetry-instrumentation-httpx: 0.48b0 → 0.60b1
  - opentelemetry-instrumentation-redis: 0.48b0 → 0.60b1
  - opentelemetry-instrumentation-sqlalchemy: 0.48b0 → 0.60b1

- Removed prometheus-client==0.23.1 from all services
- Unified all services to use the same monitoring package versions

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2026-01-08 19:25:52 +01:00
Urtzi Alfaro
6b14f330e6 Fix demo supplier 2026-01-04 21:58:15 +01:00
Urtzi Alfaro
507031deaf fix issues 2026-01-01 21:09:25 +01:00
Urtzi Alfaro
8bfe4f2dd7 Fix Demo enterprise 2025-12-17 13:03:52 +01:00
Urtzi Alfaro
c68d82ca7f Fix critical bugs and standardize service integrations
Critical Fixes:
- Orchestrator: Add missing OrchestrationStatus import (fixes HTTP 500 during demo clone)
- Procurement: Migrate from custom cache utils to shared Redis utils
- Suppliers: Use proper Settings for Redis configuration with TLS/auth
- Recipes/Suppliers clients: Fix endpoint paths (remove duplicate path segments)
- Procurement client: Use suppliers service directly for supplier details

Details:
1. services/orchestrator/app/api/internal_demo.py:
   - Added OrchestrationStatus import to fix cloning error
   - This was causing HTTP 500 errors during demo session cloning

2. services/procurement/app/api/purchase_orders.py + service:
   - Replaced app.utils.cache with shared.redis_utils
   - Standardizes caching across all services
   - Removed custom cache utilities (deleted app/utils/cache.py)

3. services/suppliers/app/consumers/alert_event_consumer.py:
   - Use Settings().REDIS_URL instead of os.getenv
   - Ensures proper Redis connection with TLS and authentication

4. shared/clients/recipes_client.py:
   - Fixed endpoint paths: recipes/recipes/{id} → recipes/{id}
   - Applied to all recipe methods (by_id, by_products, instructions, yield)

5. shared/clients/suppliers_client.py:
   - Fixed endpoint path: suppliers/suppliers/{id} → suppliers/{id}

6. shared/clients/procurement_client.py:
   - get_supplier_by_id now uses SuppliersServiceClient directly
   - Removes incorrect call to procurement service for supplier details

Impact:
- Demo session cloning now works without orchestrator errors 
- Consistent Redis usage across all services
- Correct service boundaries (suppliers data from suppliers service)
- Clean client endpoint paths

🤖 Generated with Claude Code (https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-16 11:33:22 +01:00
Urtzi Alfaro
9f3b39bd28 Add comprehensive documentation and final improvements
Documentation Added:
- AI_INSIGHTS_DEMO_SETUP_GUIDE.md: Complete setup guide for demo sessions
- AI_INSIGHTS_DATA_FLOW.md: Architecture and data flow diagrams
- AI_INSIGHTS_QUICK_START.md: Quick reference guide
- DEMO_SESSION_ANALYSIS_REPORT.md: Detailed analysis of demo session d67eaae4
- ROOT_CAUSE_ANALYSIS_AND_FIXES.md: Complete analysis of 8 issues (6 fixed, 2 analyzed)
- COMPLETE_FIX_SUMMARY.md: Executive summary of all fixes
- FIX_MISSING_INSIGHTS.md: Forecasting and procurement fix guide
- FINAL_STATUS_SUMMARY.md: Status overview
- verify_fixes.sh: Automated verification script
- enhance_procurement_data.py: Procurement data enhancement script

Service Improvements:
- Demo session cleanup worker: Use proper settings for Redis configuration with TLS/auth
- Procurement service: Add Redis initialization with proper error handling and cleanup
- Production fixture: Remove duplicate worker assignments (cleaned 56 duplicates)
- Orchestrator fixture: Add purchase order metadata for better tracking

Impact:
- Complete documentation for troubleshooting and setup
- Improved Redis connection handling across services
- Clean production data without duplicates
- Better error handling and logging

🤖 Generated with Claude Code (https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-16 11:32:45 +01:00
Urtzi Alfaro
4418ff0876 Add forecasting demand insights trigger + fix RabbitMQ cleanup
Issue 1: Forecasting demand insights not triggered in demo workflow
- Created internal ML endpoint: /forecasting/internal/ml/generate-demand-insights
- Added trigger_demand_insights_internal() to ForecastServiceClient
- Integrated forecasting insights into demo session post-clone workflow
- Now triggers 4 AI insight types: price, safety stock, yield, + demand

Issue 2: RabbitMQ client cleanup error in procurement service
- Fixed: rabbitmq_client.close() → rabbitmq_client.disconnect()
- Added proper cleanup in exception handler
- Error: "'RabbitMQClient' object has no attribute 'close'"

Files modified:
- services/forecasting/app/api/ml_insights.py (new internal_router)
- services/forecasting/app/main.py (register internal router)
- shared/clients/forecast_client.py (new trigger method)
- services/demo_session/app/services/clone_orchestrator.py (+ demand insights)
- services/procurement/app/api/internal_demo.py (fix disconnect)

Expected impact:
- Demo sessions will now generate demand forecasting insights
- No more RabbitMQ cleanup errors in logs
- AI insights count should increase from 1 to 2-3 per session

🤖 Generated with Claude Code

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-16 11:28:04 +01:00
Urtzi Alfaro
c566967bea Add AI insights feature 2025-12-15 21:14:22 +01:00
Urtzi Alfaro
82f9622411 demo seed change 4 2025-12-14 19:05:37 +01:00
Urtzi Alfaro
a030bd14c8 demo seed change 2 2025-12-14 11:58:14 +01:00
Urtzi Alfaro
ff830a3415 demo seed change 2025-12-13 23:57:54 +01:00
Urtzi Alfaro
f3688dfb04 Fix PurchaseOrderItem attribute error: Use inventory_product_id instead of ingredient_id
- Fixed AttributeError in procurement service ml_insights.py
- PurchaseOrderItem model uses inventory_product_id, not ingredient_id
- This resolves the forecasting errors for ingredients

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2025-12-13 16:53:39 +01:00
Urtzi Alfaro
e116ac244c Fix and UI imporvements 3 2025-12-10 11:23:53 +01:00
Urtzi Alfaro
508f4569b9 Fix and UI imporvements 2025-12-09 10:21:41 +01:00
Urtzi Alfaro
667e6e0404 New alert service 2025-12-05 20:07:01 +01:00
Urtzi Alfaro
972db02f6d New enterprise feature 2025-11-30 09:12:40 +01:00
Urtzi Alfaro
e902419b6e New alert system and panel de control page 2025-11-27 15:52:40 +01:00
Urtzi Alfaro
3242c8d837 Improve te panel de control logic 2025-11-21 16:15:09 +01:00
Urtzi Alfaro
2ee94fb4b1 Improve frontend panel de control 2025-11-20 22:10:16 +01:00
Urtzi Alfaro
5783c7ed05 Add POI feature and imporve the overall backend implementation 2025-11-12 15:34:10 +01:00
Claude
e67a83ceb0 fix: Correct variable references in PO seed script
Fixed 'items' is not defined error in demo seed script:
- Changed 'items' references to 'items_data' (the function parameter)
- Updated product_names extraction to use dict.get() for safety
- Fixed create_po_reasoning_supplier_contract call to use correct parameters
  (contract_quantity instead of trust_score)

This resolves the warnings about failed reasoning_data generation
during purchase order seeding.
2025-11-07 19:50:31 +00:00
Claude
9d284cae46 refactor: Convert internal services to structured JSON reasoning
Convert pipe-separated reasoning codes to structured JSON format for:
- Safety stock calculator (statistical calculations, errors)
- Price forecaster (procurement recommendations, volatility)
- Order optimization (EOQ, tier pricing)

This enables i18n translation of internal calculation reasoning
and provides structured data for frontend AI insights display.

Benefits:
- Consistent with PO/Batch reasoning_data format
- Frontend can translate using same i18n infrastructure
- Structured parameters enable rich UI visualization
- No legacy string parsing needed

Changes:
- safety_stock_calculator.py: Replace reasoning str with reasoning_data dict
- price_forecaster.py: Convert recommendation reasoning to structured format
- optimization.py: Update EOQ and tier pricing to use reasoning_data

Part of complete i18n implementation for AI insights.
2025-11-07 19:22:02 +00:00
Claude
be8cb20b18 fix: Replace all remaining hardcoded English reasoning with structured codes
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.
2025-11-07 19:00:00 +00:00
Claude
ed7db4d4f2 feat: Complete backend i18n implementation with error codes and demo data
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.
2025-11-07 18:40:44 +00:00
Claude
f74b8d5402 refactor: Remove TEXT fields and use only reasoning_data for i18n
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)
2025-11-07 18:20:05 +00:00
Claude
ddc4928d78 feat: Implement structured reasoning_data generation for i18n support
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
2025-11-07 18:16:44 +00:00
Claude
392bfb186f refactor: Unify database migrations into single initial schemas
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.
2025-11-07 17:35:38 +00:00
Claude
436622dc9a fix: Resolve build errors and add database migrations
- Fix frontend import: Change from useAppContext to useTenant store
- Fix backend imports: Use app.core.database instead of shared.database
- Remove auth dependencies from dashboard endpoints
- Add database migrations for reasoning fields in procurement and production

Migrations:
- procurement: Add reasoning, consequence, reasoning_data to purchase_orders
- production: Add reasoning, reasoning_data to production_batches
2025-11-07 17:19:46 +00:00
Claude
2ced1ec670 feat: Complete JTBD-aligned bakery dashboard redesign
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
2025-11-07 17:10:17 +00:00
Urtzi Alfaro
813e8866ef Add readme files 2025-11-06 14:10:04 +01:00
Urtzi Alfaro
394ad3aea4 Improve AI logic 2025-11-05 13:34:56 +01:00
Urtzi Alfaro
0220da1725 Improve the frontend 4 2025-11-01 21:35:03 +01:00
Urtzi Alfaro
f44d235c6d Add user delete process 2 2025-10-31 18:57:58 +01:00
Urtzi Alfaro
63f5c6d512 Improve the frontend 3 2025-10-30 21:08:07 +01:00