feat: Replace hardcoded dashboard insights with real data from services

MAJOR FIX: Dashboard now shows actual business data instead of mock values

The Bug:
--------
Dashboard insights were displaying hardcoded values:
- Savings: Always showed "€124 this week"
- Deliveries: Always showed "0 arriving today"
- Not reflecting actual business activity

Root Cause:
-----------
Line 468-472 in dashboard.py had hardcoded mock savings data:
```python
savings_data = {
    "weekly_savings": 124,
    "trend_percentage": 12
}
```

Deliveries data wasn't being fetched from any service.

The Fix:
--------
1. **Real Savings Calculation:**
   - Fetches last 7 days of purchase orders
   - Sums up actual savings from price optimization
   - Uses po.optimization_data.savings field
   - Calculates: weekly_savings from PO optimization savings
   - Result: Shows €X based on actual cost optimizations

2. **Real Deliveries Data:**
   - Fetches pending purchase orders from procurement service
   - Counts POs with expected_delivery_date == today
   - Result: Shows actual number of deliveries arriving today

3. **Data Flow:**
   ```
   procurement_client.get_pending_purchase_orders()
   → Filter by created_at (last 7 days) for savings
   → Filter by expected_delivery_date (today) for deliveries
   → Calculate totals
   → Pass to dashboard_service.calculate_insights()
   ```

Benefits:
---------
 Savings widget shows real optimization results
 Deliveries widget shows actual incoming deliveries
 Inventory widget already uses real stock data
 Waste widget already uses real sustainability data
 Dashboard reflects actual business activity

Note: Trend percentage for savings still defaults to 12% as it
requires historical comparison data (future enhancement).
This commit is contained in:
Claude
2025-11-07 23:03:05 +00:00
parent 5a877d4e76
commit fa0802c9f2

View File

@@ -465,11 +465,70 @@ async def get_insights(
except Exception as e: except Exception as e:
logger.warning(f"Failed to fetch inventory data: {e}") logger.warning(f"Failed to fetch inventory data: {e}")
# Savings data (mock for now) # Deliveries data from procurement
savings_data = { delivery_data = {}
"weekly_savings": 124, try:
"trend_percentage": 12 # Get recent POs with pending deliveries
} pos_result = await procurement_client.get_pending_purchase_orders(tenant_id, limit=100)
if pos_result and isinstance(pos_result, dict):
pos = pos_result.get("items", [])
# Count deliveries expected today
from datetime import datetime, timezone
today_start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
today_end = today_start.replace(hour=23, minute=59, second=59)
deliveries_today = 0
for po in pos:
expected_date = po.get("expected_delivery_date")
if expected_date:
if isinstance(expected_date, str):
expected_date = datetime.fromisoformat(expected_date.replace('Z', '+00:00'))
if today_start <= expected_date <= today_end:
deliveries_today += 1
delivery_data = {"deliveries_today": deliveries_today}
except Exception as e:
logger.warning(f"Failed to fetch delivery data: {e}")
# Savings data - Calculate from recent PO price optimizations
savings_data = {}
try:
# Get recent POs (last 7 days) and sum up optimization savings
from datetime import datetime, timedelta, timezone
seven_days_ago = datetime.now(timezone.utc) - timedelta(days=7)
pos_result = await procurement_client.get_pending_purchase_orders(tenant_id, limit=200)
if pos_result and isinstance(pos_result, dict):
pos = pos_result.get("items", [])
weekly_savings = 0
# Calculate savings from price optimization
for po in pos:
# Check if PO was created in last 7 days
created_at = po.get("created_at")
if created_at:
if isinstance(created_at, str):
created_at = datetime.fromisoformat(created_at.replace('Z', '+00:00'))
if created_at >= seven_days_ago:
# Sum up savings from optimization
optimization_data = po.get("optimization_data", {})
if isinstance(optimization_data, dict):
savings = optimization_data.get("savings", 0) or 0
weekly_savings += float(savings)
# Default trend percentage (would need historical data for real trend)
savings_data = {
"weekly_savings": round(weekly_savings, 2),
"trend_percentage": 12 if weekly_savings > 0 else 0
}
else:
savings_data = {"weekly_savings": 0, "trend_percentage": 0}
except Exception as e:
logger.warning(f"Failed to calculate savings data: {e}")
savings_data = {"weekly_savings": 0, "trend_percentage": 0}
# Merge delivery data into inventory data
inventory_data.update(delivery_data)
# Calculate insights # Calculate insights
insights = await dashboard_service.calculate_insights( insights = await dashboard_service.calculate_insights(