New enterprise feature

This commit is contained in:
Urtzi Alfaro
2025-11-30 09:12:40 +01:00
parent f9d0eec6ec
commit 972db02f6d
176 changed files with 19741 additions and 1361 deletions

View File

@@ -1,12 +1,92 @@
# shared/clients/forecast_client.py
"""
Forecast Service Client - Updated for refactored backend structure
Handles all API calls to the forecasting service
Forecast Service Client for Inter-Service Communication
Backend structure:
- ATOMIC: /forecasting/forecasts (CRUD)
- BUSINESS: /forecasting/operations/* (single, multi-day, batch, etc.)
- ANALYTICS: /forecasting/analytics/* (predictions-performance)
This client provides a high-level API for interacting with the Forecasting Service,
which generates demand predictions using Prophet ML algorithm, validates forecast accuracy,
and provides enterprise network demand aggregation for multi-location bakeries.
Key Capabilities:
- Forecast Generation: Single product, multi-day, batch forecasting
- Real-Time Predictions: On-demand predictions with custom features
- Forecast Validation: Compare predictions vs actual sales, track accuracy
- Analytics: Prediction performance metrics, historical accuracy trends
- Enterprise Aggregation: Network-wide demand forecasting for parent-child hierarchies
- Caching: Redis-backed caching for high-performance prediction serving
Backend Architecture:
- ATOMIC: /forecasting/forecasts (CRUD operations on forecast records)
- BUSINESS: /forecasting/operations/* (forecast generation, validation)
- ANALYTICS: /forecasting/analytics/* (performance metrics, accuracy trends)
- ENTERPRISE: /forecasting/enterprise/* (network demand aggregation)
Enterprise Features (NEW):
- Network demand aggregation across all child outlets for centralized production planning
- Child contribution tracking (each outlet's % of total network demand)
- Redis caching with 1-hour TTL for enterprise forecasts
- Subscription gating (requires Enterprise tier)
Usage Example:
```python
from shared.clients import get_forecast_client
from shared.config.base import get_settings
from datetime import date, timedelta
config = get_settings()
client = get_forecast_client(config, calling_service_name="production")
# Generate 7-day forecast for a product
forecast = await client.generate_multi_day_forecast(
tenant_id=tenant_id,
inventory_product_id=product_id,
forecast_date=date.today(),
forecast_days=7,
include_recommendations=True
)
# Batch forecast for multiple products
batch_forecast = await client.generate_batch_forecast(
tenant_id=tenant_id,
inventory_product_ids=[product_id_1, product_id_2],
forecast_date=date.today(),
forecast_days=7
)
# Validate forecasts against actual sales
validation = await client.validate_forecasts(
tenant_id=tenant_id,
date=date.today() - timedelta(days=1)
)
# Get predictions for a specific date (from cache or DB)
predictions = await client.get_predictions_for_date(
tenant_id=tenant_id,
target_date=date.today()
)
```
Service Architecture:
- Base URL: Configured via FORECASTING_SERVICE_URL environment variable
- Authentication: Uses BaseServiceClient with tenant_id header validation
- Error Handling: Returns None on errors, logs detailed error context
- Async: All methods are async and use httpx for HTTP communication
- Caching: 24-hour TTL for standard forecasts, 1-hour TTL for enterprise aggregations
ML Model Details:
- Algorithm: Facebook Prophet (time series forecasting)
- Features: 20+ temporal, weather, traffic, holiday, POI features
- Accuracy: 15-25% MAPE (Mean Absolute Percentage Error)
- Training: Weekly retraining via orchestrator automation
- Confidence Intervals: 95% confidence bounds (yhat_lower, yhat_upper)
Related Services:
- Production Service: Uses forecasts for production planning
- Procurement Service: Uses forecasts for ingredient ordering
- Orchestrator Service: Triggers daily forecast generation, displays network forecasts on enterprise dashboard
- Tenant Service: Validates hierarchy for enterprise aggregation
- Distribution Service: Network forecasts inform capacity planning
For more details, see services/forecasting/README.md
"""
from typing import Dict, Any, Optional, List
@@ -329,3 +409,9 @@ class ForecastServiceClient(BaseServiceClient):
forecast_days=1
)
return None
# Backward compatibility alias
def create_forecast_client(config: BaseServiceSettings, service_name: str = "unknown") -> ForecastServiceClient:
"""Create a forecast service client (backward compatibility)"""
return ForecastServiceClient(config, service_name)