Commit Graph

381 Commits

Author SHA1 Message Date
Urtzi Alfaro
9aee368580 fix demo issues 2026-01-01 19:56:07 +01:00
Urtzi Alfaro
93c9475239 fix UI 1 2026-01-01 19:01:33 +01:00
Urtzi Alfaro
c07df124fb Improve UI 2025-12-30 14:40:20 +01:00
Urtzi Alfaro
02f0c91a15 Fix UI issues 2025-12-29 19:33:35 +01:00
Urtzi Alfaro
adef7971a0 Fix suppliers 2025-12-29 14:48:24 +01:00
Urtzi Alfaro
2e7e1f5557 Add frontend alerts imporvements 2025-12-29 08:11:29 +01:00
Urtzi Alfaro
54662dde79 Add frontend loading imporvements 2025-12-27 21:30:42 +01:00
Urtzi Alfaro
532b057f59 fix demo load 2025-12-25 20:20:16 +01:00
Urtzi Alfaro
b95b86ee2c Add traslations 2025-12-25 18:35:37 +01:00
Urtzi Alfaro
bfa5ff0637 Imporve onboarding UI 2025-12-19 13:10:24 +01:00
Urtzi Alfaro
71ee2976a2 Update readmes and imporve UI 2025-12-19 09:28:36 +01:00
Urtzi Alfaro
acb3a40844 Add traslations 2025-12-18 20:12:32 +01:00
Urtzi Alfaro
f10a2b92ea Improve onboarding 2025-12-18 13:26:32 +01:00
Urtzi Alfaro
f8591639a7 Imporve enterprise 2025-12-17 20:50:22 +01:00
Urtzi Alfaro
b715a14848 Fix Demo enterprise list 2025-12-17 16:28:58 +01:00
Urtzi Alfaro
8e68c909de Add enhanced logging for demo session tenant queries
Added detailed logging to help diagnose empty tenant list issues:
- Log demo_session_id, demo_account_type, and tenant_count
- Log actual tenant IDs returned
- Log when demo user detected but no session ID

This will help identify:
1. If demo_session_id is being passed correctly from gateway
2. If tenants exist in DB for the session
3. Timing issues (API called before session fully initialized)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-17 16:13:45 +01:00
Urtzi Alfaro
838d25394b CRITICAL: Add demo session isolation to prevent cross-session data leakage
This commit fixes a critical security issue where multiple concurrent demo
sessions would see each other's data due to sharing the same demo user IDs.

## The Problem:

When two enterprise demo sessions run simultaneously:
- Session A: user_id=Director, tenants=[parent_A, child_A1, child_A2]
- Session B: user_id=Director, tenants=[parent_B, child_B1, child_B2]

The endpoint /api/v1/tenants/user/{user_id}/tenants was querying by user_id
only, so Session A would see BOTH its own tenants AND Session B's tenants!

## The Solution:

Added demo_session_id filtering to get_user_tenants endpoint:
- For demo sessions, use get_virtual_tenants_for_session(demo_session_id)
- This filters tenants by the demo_session_id field (set during cloning)
- Each session now sees ONLY its own virtual tenants

## Implementation:

services/tenant/app/api/tenants.py (lines 180-194):
- Check if user is_demo
- Extract demo_session_id from current_user context (set by gateway)
- Call get_virtual_tenants_for_session() instead of get_user_tenants()
- This method filters by: demo_session_id + is_active + account_type

## Database Schema:

The tenants table has a demo_session_id column (indexed) that links
each virtual tenant to its specific demo session. This is set during
tenant cloning in internal_demo.py.

## Impact:

 Complete isolation between concurrent demo sessions
 Users only see their own session's data
 No performance impact (demo_session_id is indexed)
 Backward compatible (non-demo users unchanged)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-17 16:03:23 +01:00
Urtzi Alfaro
6a0e02ff95 Fix Demo enterprise: map 'demo-user' to actual owner ID
When the frontend requests tenants with user_id='demo-user' in demo mode,
the backend now correctly maps this to the actual demo owner ID from the
current_user context (set by the gateway middleware).

This fixes the issue where the tenant list API was returning empty results
even though it returned 200 OK, because it was looking for a user with
id='demo-user' which doesn't exist in the database.

The actual user IDs are:
- Professional: c1a2b3c4-d5e6-47a8-b9c0-d1e2f3a4b5c6 (María García López)
- Enterprise: d2e3f4a5-b6c7-48d9-e0f1-a2b3c4d5e6f7 (Director)

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-17 15:58:28 +01:00
Urtzi Alfaro
d98558ed97 Refactor demo session architecture: consolidate metadata into fixture files
This commit refactors the demo session architecture to consolidate all demo
configuration data into the fixture files, removing redundant metadata files.

## Changes Made:

### 1. Data Consolidation
- **Removed**: `shared/demo/metadata/demo_users.json`
- **Removed**: `shared/demo/metadata/tenant_configs.json`
- **Updated**: Merged all user data into `02-auth.json` files
- **Updated**: Merged all tenant config data into `01-tenant.json` files

### 2. Enterprise Parent Tenant Updates
- Updated owner name to "Director" (matching auth fixtures)
- Added description field matching tenant_configs.json
- Added `base_tenant_id` to all child tenant entries
- Now includes all 5 child locations (Madrid, Barcelona, Valencia, Seville, Bilbao)

### 3. Professional Tenant Updates
- Added description field from tenant_configs.json
- Ensured consistency with auth fixtures

### 4. Code Updates
- **services/tenant/app/api/internal_demo.py**:
  - Fixed child tenant staff members to use enterprise parent users
  - Changed from professional staff IDs to enterprise staff IDs (Laura López, José Martínez, Francisco Moreno)

- **services/demo_session/app/core/config.py**:
  - Updated DEMO_ACCOUNTS configuration with all 5 child outlets
  - Updated enterprise tenant name and email to match fixtures
  - Added descriptions for all child locations

- **gateway/app/middleware/demo_middleware.py**:
  - Updated comments to reference fixture files as source of truth
  - Clarified that owner IDs come from 01-tenant.json files

- **frontend/src/stores/useTenantInitializer.ts**:
  - Updated tenant names and descriptions to match fixture files
  - Added comments linking to source fixture files

## Benefits:

1. **Single Source of Truth**: All demo data now lives in fixture files
2. **Consistency**: No more sync issues between metadata and fixtures
3. **Maintainability**: Easier to update demo data (one place per tenant type)
4. **Clarity**: Clear separation between template data (fixtures) and runtime config

## Enterprise Demo Fix:

The enterprise owner is now correctly added as a member of all child tenants, fixing
the issue where the tenant switcher didn't show parent/child tenants and the
establishments page didn't load tenants for the demo enterprise user.

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-17 15:48:14 +01:00
Urtzi Alfaro
8bfe4f2dd7 Fix Demo enterprise 2025-12-17 13:03:52 +01:00
Urtzi Alfaro
0bbfa010bf Fix AI insights feature issues 2025-12-16 13:32:33 +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
35ae23b381 Fix forecasting clone endpoint for demo sessions
Fixed two critical issues preventing forecast data from being cloned:

1. **Missing batch_name field**: The fixture uses `batch_id` but the
   PredictionBatch model requires `batch_name` (NOT NULL constraint).
   Added field mapping to handle batch_id -> batch_name conversion.

2. **UUID type mismatch**: The fixture's `product_id` is a string but
   the Forecast model expects `inventory_product_id` as UUID type.
   Added conversion from string to UUID.

3. **Field mappings added**:
   - batch_id -> batch_name
   - total_forecasts -> total_products
   - created_at -> requested_at (fallback)
   - Calculated completed_products from status

These fixes enable the forecasting service to successfully clone all
28 forecasts from the fixture file, unlocking demand forecasting
AI insights in demo sessions.

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-16 07:39:13 +01:00
Urtzi Alfaro
c566967bea Add AI insights feature 2025-12-15 21:14:22 +01:00
Urtzi Alfaro
5642b5a0c0 demo seed change 7 2025-12-15 13:39:33 +01:00
Urtzi Alfaro
46bd4f77b6 demo seed change 6 2025-12-14 21:39:53 +01:00
Urtzi Alfaro
56a1821256 demo seed change 5 2025-12-14 20:13:59 +01:00
Urtzi Alfaro
82f9622411 demo seed change 4 2025-12-14 19:05:37 +01:00
Urtzi Alfaro
4ae5356ad1 demo seed change 3 2025-12-14 16:04:16 +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
10c779858a Fix enum mismatch: Update Python enums and seed data to match database uppercase values
- Fixed ProductType enum values from lowercase to uppercase (INGREDIENT, FINISHED_PRODUCT)
- Fixed UnitOfMeasure enum values from lowercase/abbreviated to uppercase (KILOGRAMS, LITERS, etc.)
- Fixed IngredientCategory enum values from lowercase to uppercase (FLOUR, YEAST, etc.)
- Fixed ProductCategory enum values from lowercase to uppercase (BREAD, CROISSANTS, etc.)
- Updated seed data files to use correct uppercase enum values
- Fixed hardcoded enum references throughout the codebase
- This resolves the InvalidTextRepresentationError when inserting inventory data

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
2025-12-13 16:49:04 +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
0da0470786 New enterprise feature2 2025-11-30 16:29:38 +01:00
Urtzi Alfaro
972db02f6d New enterprise feature 2025-11-30 09:12:40 +01:00
Urtzi Alfaro
fd657dea02 refactor(demo): Standardize demo account type names across codebase
Standardize demo account type naming from inconsistent variants to clean names:
- individual_bakery, professional_bakery → professional
- central_baker, enterprise_chain → enterprise

This eliminates naming confusion that was causing bugs in the demo session
initialization, particularly for enterprise demo tenants where different
parts of the system used different names for the same concept.

Changes:
- Updated source of truth in demo_session config
- Updated all backend services (middleware, cloning, orchestration)
- Updated frontend types, pages, and stores
- Updated demo session models and schemas
- Removed all backward compatibility code as requested

Related to: Enterprise demo session access fix

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-30 08:48:56 +01:00
Urtzi Alfaro
e902419b6e New alert system and panel de control page 2025-11-27 15:52:40 +01:00
Urtzi Alfaro
70931cb4fd feat(dashboard): Add production batch details to execution progress
Backend changes (dashboard_service.py):
- Collect in-progress batch details with id, batchNumber, productName, etc.
- Add inProgressBatches array to production progress response

Frontend changes (ExecutionProgressTracker.tsx):
- Update ProductionProgress interface to include inProgressBatches array
- Display batch names and numbers under "En Progreso" count
- Show which specific batches are currently running

Users can now see which production batches are in progress
instead of just a count (e.g., "• Pan (BATCH-001)").

Fixes: Issue #5 - Missing production batch details

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

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-27 07:37:50 +01:00
Urtzi Alfaro
8e82f5754f docs: Add alert escalation and chaining system documentation 2025-11-26 07:07:54 +01:00
Urtzi Alfaro
945b9a3464 docs: Add delivery tracking service documentation to orchestrator README 2025-11-26 07:06:14 +01:00
Urtzi Alfaro
21651b396e docs: Add Stock Receipt System documentation to inventory service 2025-11-26 07:00:44 +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
Claude
298be127d7 Fix template variable interpolation by creating params copy
Root cause: params = reasoning_data.get('parameters', {}) created a reference
to the dictionary instead of a copy. When modifying params to add
product_names_joined, the change didn't persist because the database object
was immutable/read-only.

Changes:
- dashboard_service.py:408 - Create dict copy for PO params
- dashboard_service.py:632 - Create dict copy for batch params
- Added clean_old_dashboard_data.py utility script to remove old POs/batches
  with malformed reasoning_data

The fix ensures template variables like {{supplier_name}}, {{product_names_joined}},
{{days_until_stockout}}, etc. are properly interpolated in the dashboard.
2025-11-20 19:30:12 +00:00
Claude
3f8c269de4 Fix template variable interpolation issues in dashboard
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}}
2025-11-20 19:14:50 +00:00