Fix seasonality bias: Default to flat weighting if history is sparse (<4 months)

This commit is contained in:
Christian Vidal Wolf
2026-01-28 13:11:08 +01:00
parent d1a522a446
commit cfce00cd63
+11 -1
View File
@@ -1628,15 +1628,25 @@ export const calculateForecastViewData = (
const getWeights = (records: SalesRecord[]) => { const getWeights = (records: SalesRecord[]) => {
const weights = new Array(12).fill(0); const weights = new Array(12).fill(0);
let total = 0; let total = 0;
const seenMonths = new Set<string>();
records.forEach(r => { records.forEach(r => {
const m = r.month.split('-')[0]; const m = r.month.split('-')[0];
const idx = MONTH_ORDER.indexOf(m); const idx = MONTH_ORDER.indexOf(m);
if (idx !== -1) { if (idx !== -1) {
weights[idx] += r.units; weights[idx] += r.units;
total += r.units; total += r.units;
if (r.units > 0) seenMonths.add(m);
} }
}); });
if (total === 0) return new Array(12).fill(1 / 12);
// Safety Fallback: If we have sparse data (e.g., only Jan loaded),
// using it as 100% seasonality skews the forecast entirely to that month.
// We require at least 4 months of history to trust the curve; otherwise, we assume flat seasonality (1/12).
if (total === 0 || seenMonths.size < 4) {
return new Array(12).fill(1 / 12);
}
return weights.map(w => w / total); return weights.map(w => w / total);
}; };