diff --git a/services/orchestrator/app/api/dashboard.py b/services/orchestrator/app/api/dashboard.py index 4fef550a..1a49d895 100644 --- a/services/orchestrator/app/api/dashboard.py +++ b/services/orchestrator/app/api/dashboard.py @@ -465,11 +465,70 @@ async def get_insights( except Exception as e: logger.warning(f"Failed to fetch inventory data: {e}") - # Savings data (mock for now) - savings_data = { - "weekly_savings": 124, - "trend_percentage": 12 - } + # Deliveries data from procurement + delivery_data = {} + try: + # 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 insights = await dashboard_service.calculate_insights(