feat(shopping): consolidate() fuer g/kg + ml/l Summierung
Implementiert consolidate() in unit-consolidation.ts: summiert Mengen innerhalb einer Unit-Family (Gewicht g/kg, Volumen ml/l) mit automatischer Promotion ab Schwellwert; nicht-family-units werden direkt summiert. quantity=null wird als 0 behandelt; alle-null ergibt null-Ergebnis. 9 neue Tests, alle 14 Tests gruen. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -9,3 +9,58 @@ export function unitFamily(unit: string | null | undefined): UnitFamily {
|
||||
if (VOLUME_UNITS.has(u)) return 'volume';
|
||||
return u;
|
||||
}
|
||||
|
||||
export interface QuantityInUnit {
|
||||
quantity: number | null;
|
||||
unit: string | null;
|
||||
}
|
||||
|
||||
function round2(n: number): number {
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* Konsolidiert mehrere {quantity, unit}-Eintraege derselben Unit-Family
|
||||
* zu einer gemeinsamen Menge + Display-Unit.
|
||||
*
|
||||
* - Gewicht (g, kg): summiert in g, promoted bei >=1000 g auf kg.
|
||||
* - Volumen (ml, l): summiert in ml, promoted bei >=1000 ml auf l.
|
||||
* - Andere: summiert quantity ohne Umrechnung, Display-Unit vom ersten
|
||||
* Eintrag.
|
||||
*
|
||||
* quantity=null wird als 0 behandelt. Wenn ALLE quantities null sind,
|
||||
* ist die Gesamtmenge ebenfalls null.
|
||||
*/
|
||||
export function consolidate(rows: QuantityInUnit[]): QuantityInUnit {
|
||||
if (rows.length === 0) return { quantity: null, unit: null };
|
||||
|
||||
const family = unitFamily(rows[0].unit);
|
||||
const firstUnit = rows[0].unit;
|
||||
|
||||
const allNull = rows.every((r) => r.quantity === null);
|
||||
|
||||
if (family === 'weight') {
|
||||
if (allNull) return { quantity: null, unit: firstUnit };
|
||||
const grams = rows.reduce((sum, r) => {
|
||||
const q = r.quantity ?? 0;
|
||||
return sum + (unitFamily(r.unit) === 'weight' && r.unit?.toLowerCase().trim() === 'kg' ? q * 1000 : q);
|
||||
}, 0);
|
||||
if (grams >= 1000) return { quantity: round2(grams / 1000), unit: 'kg' };
|
||||
return { quantity: round2(grams), unit: 'g' };
|
||||
}
|
||||
|
||||
if (family === 'volume') {
|
||||
if (allNull) return { quantity: null, unit: firstUnit };
|
||||
const ml = rows.reduce((sum, r) => {
|
||||
const q = r.quantity ?? 0;
|
||||
return sum + (r.unit?.toLowerCase().trim() === 'l' ? q * 1000 : q);
|
||||
}, 0);
|
||||
if (ml >= 1000) return { quantity: round2(ml / 1000), unit: 'l' };
|
||||
return { quantity: round2(ml), unit: 'ml' };
|
||||
}
|
||||
|
||||
// Non-family: summiere quantity direkt
|
||||
if (allNull) return { quantity: null, unit: firstUnit };
|
||||
const sum = rows.reduce((acc, r) => acc + (r.quantity ?? 0), 0);
|
||||
return { quantity: round2(sum), unit: firstUnit };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user