Fix AI insights feature issues

This commit is contained in:
Urtzi Alfaro
2025-12-16 13:32:33 +01:00
parent b43648e0f8
commit 0bbfa010bf
5 changed files with 576 additions and 55 deletions

View File

@@ -858,11 +858,11 @@ async def trigger_demand_insights_internal(
)
# Fetch historical sales data
sales_data_raw = await sales_client.get_product_sales(
sales_data_raw = await sales_client.get_sales_data(
tenant_id=tenant_id,
product_id=product_id,
start_date=start_date,
end_date=end_date
start_date=start_date.strftime('%Y-%m-%d'),
end_date=end_date.strftime('%Y-%m-%d')
)
if not sales_data_raw or len(sales_data_raw) < 10:
@@ -876,26 +876,47 @@ async def trigger_demand_insights_internal(
# Convert to DataFrame
sales_df = pd.DataFrame(sales_data_raw)
# Map field names to expected format
if 'quantity' not in sales_df.columns:
if 'total_quantity' in sales_df.columns:
sales_df['quantity'] = sales_df['total_quantity']
elif 'quantity_sold' in sales_df.columns:
sales_df['quantity'] = sales_df['quantity_sold']
else:
logger.warning(
"No quantity field found for product",
product_id=product_id
)
continue
if 'date' not in sales_df.columns:
if 'sale_date' in sales_df.columns:
sales_df['date'] = sales_df['sale_date']
else:
logger.warning(
"No date field found for product",
product_id=product_id
)
continue
# Run demand insights orchestrator
insights = await orchestrator.analyze_and_generate_insights(
results = await orchestrator.analyze_and_post_demand_insights(
tenant_id=tenant_id,
product_id=product_id,
product_name=product_name,
inventory_product_id=product_id,
sales_data=sales_df,
lookback_days=90,
db=db
forecast_horizon_days=30,
min_history_days=90
)
if insights:
total_insights_generated += len(insights)
total_insights_posted += len(insights)
total_insights_generated += results['insights_generated']
total_insights_posted += results['insights_posted']
logger.info(
"Demand insights generated for product",
tenant_id=tenant_id,
product_id=product_id,
insights_count=len(insights)
)
logger.info(
"Demand insights generated for product",
tenant_id=tenant_id,
product_id=product_id,
insights_posted=results['insights_posted']
)
except Exception as e:
logger.warning(