import { syncOrdersIncremental } from "../../4-woo-orders/wooOrders.js"; import * as ordersRepo from "../../4-woo-orders/ordersRepo.js"; /** * Obtiene estadísticas de pedidos para el dashboard */ export async function handleGetOrderStats({ tenantId }) { // Sync en background — no bloqueamos el request const syncPromise = syncOrdersIncremental({ tenantId }).catch(err => console.error("[stats] sync error:", err) ); // Respondemos con lo que hay en DB mientras sincroniza const [monthlyStats, productStats, yoyStats, totals] = await Promise.all([ ordersRepo.getMonthlyStats({ tenantId }), ordersRepo.getProductStats({ tenantId }), ordersRepo.getYoyStats({ tenantId }), ordersRepo.getTotals({ tenantId }), ]); return { // Stats mensuales (para gráficas de barras/líneas) months: monthlyStats.months, totals: monthlyStats.totals, order_counts: monthlyStats.order_counts, by_source: monthlyStats.by_source, by_shipping: monthlyStats.by_shipping, // Totales agregados (para donuts) totals_aggregated: totals, // Stats por producto top_products_revenue: productStats.by_revenue, top_products_kg: productStats.by_kg, top_products_units: productStats.by_units, // YoY yoy: yoyStats, // Info de sync (sincronizando en background) synced: 0, total_in_cache: totals.total_orders ?? 0, }; }