Rebuild Inventory as a config-only system with food catalog and calculators
Some checks failed
CodeQL / Analyze (push) Has been cancelled
Controller Tests / controller-tests (push) Has been cancelled
Jest Tests / jest-tests (push) Has been cancelled

Replace the DB-backed inventory module with a config-only design and build out
food-storage tooling around it.

Inventory (config-only, no database)
- Each inventory is a YAML file at config/inventory/<slug>.yaml, loaded once
  into memory and the single source of truth. New reusable MultiFileConfig
  (wrolpi/common.py) manages a directory of per-entity files.
- Inventory types (food/fuel/tool) seed a customizable field schema
  (text/number/quantity/date/select/location/calories). Unit math/aggregation
  moved to the frontend (mathjs); Pint dropped from the backend.
- Minimal API: GET / (all inventories full), POST /, PUT /<slug> (whole-
  inventory save with version-based optimistic concurrency; 404 for missing),
  DELETE. Legacy inventories.yaml / old tables migrate to per-inventory files
  (pound->lb), and an alembic migration drops the tables.

Frontend
- New app/src/components/inventory/ package: spreadsheet-style table with
  Tab/Enter keyboard entry, sortable columns, expired-row highlighting,
  customizable field editor, and pooled cross-inventory location autocomplete.
- A single useInventories store loads everything once and persists whole
  inventories optimistically; list/items/summary/locations derive client-side.
- Summary groups items (default by Category), totals size x count, shows a
  calories column, and embeds a ration estimate (how long the stock lasts).

Food catalog
- Shared, editable catalog (config/inventory/catalog.yaml) seeded from
  catalog_defaults.yaml (~60 generic items, total calories per package) with
  merge-keep-edits + tombstones. GET/PUT /api/inventory/catalog, a management
  modal, and entry-row pre-fill of category/size/calories from a name match.

Calculators
- Generic Food Storage planner (like the Water calculator): household +
  editable per-person/year amounts -> total to store over a chosen duration,
  with women/children weighted by DGA calorie shares and an imperial/metric
  toggle.

Also fixes ConfigFile.save() to accept nested file_names. Backend pytest and
frontend jest suites updated/added throughout; alembic check clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Roland 2026-06-14 14:20:10 -06:00
parent ae5f64424d
commit 3d6aead072
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
46 changed files with 3612 additions and 2697 deletions

View file

@ -0,0 +1,222 @@
import React from "react";
import {GridColumn, Input, Label, TableBody, TableCell, TableFooter, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {Form, Header, Segment, Table} from "../Theme";
import {InfoPopup, roundDigits, Toggle, useLocalStorage} from "../Common";
import {ThemeContext} from "../../contexts/contexts";
// Generic food-storage planner: given a household, estimate how much of each food category to store for a chosen
// duration. Independent of any inventory (like the Water calculator). Defaults are a common one-year-per-adult
// food-storage plan (lbs per person per year); all amounts are editable.
// Each person's share of one adult man's ration, as a percent. Defaults are derived from the Dietary Guidelines
// for Americans 2020-2025 moderate-activity calorie needs (man ~2,600 / woman ~2,000 / child ~1,800 kcal/day),
// since food-storage quantities scale with energy needs. Editable.
export const DEFAULT_SHARES = {men: 100, women: 77, children: 69};
const countNum = (v) => {
const x = Number(v);
return x > 0 ? x : 0;
};
// Raw head count.
export function totalPeople(counts) {
return countNum(counts.men) + countNum(counts.women) + countNum(counts.children);
}
// Adult-man-equivalents: each person weighted by their ration share (%), so women and children need less.
export function adultEquivalents(counts, shares) {
const share = (v) => Math.max(0, Number(v) || 0) / 100;
return countNum(counts.men) * share(shares.men)
+ countNum(counts.women) * share(shares.women)
+ countNum(counts.children) * share(shares.children);
}
// Total amount of a category needed: per-person-per-year amount, scaled by people and the duration in months.
export function amountNeeded(perPersonPerYear, people, months) {
const a = Number(perPersonPerYear), m = Number(months);
if (!(a > 0) || !(people > 0) || !(m > 0)) {
return 0;
}
return a * people * (m / 12);
}
// Default per-person, per-year storage amounts (lbs), calibrated to a one-year supply for one adult man.
// Auxiliary foods and spices/condiments have no standard weight, so they default to 0 for the user to fill in.
export const FOOD_CATEGORIES = [
{key: 'grains', label: 'Grains', perYear: 300},
{key: 'legumes', label: 'Legumes', perYear: 60},
{key: 'fruits', label: 'Fruits', perYear: 185},
{key: 'vegetables', label: 'Vegetables', perYear: 185},
{key: 'powdered_milk', label: 'Powdered Milk', perYear: 16},
{key: 'cooking_oil', label: 'Cooking Oil', perYear: 25},
{key: 'meats', label: 'Meats / Meat Substitutes', perYear: 20},
{key: 'sugar', label: 'Sugar or Honey', perYear: 60},
{key: 'salt', label: 'Salt', perYear: 8},
{key: 'cooking_essentials', label: 'Cooking Essentials', perYear: 8},
{key: 'auxiliary', label: 'Auxiliary Foods', perYear: 0},
{key: 'condiments', label: 'Spices / Condiments', perYear: 0},
];
const DEFAULT_AMOUNTS = Object.fromEntries(FOOD_CATEGORIES.map(c => [c.key, String(c.perYear)]));
export const KG_PER_LB = 0.45359237;
// Convert all per-person amounts between lb and kg (used when the unit toggle flips), preserving the user's edits
// rather than resetting to defaults.
export function convertAmounts(amounts, toMetric) {
const factor = toMetric ? KG_PER_LB : 1 / KG_PER_LB;
const out = {};
for (const [key, value] of Object.entries(amounts)) {
out[key] = (value === '' || value == null) ? '' : String(roundDigits(Number(value) * factor, 2));
}
return out;
}
// Duration slider stops (months): monthly to a year, then to three years.
export const MONTH_STOPS = [1, 2, 3, 6, 9, 12, 18, 24, 36];
export function formatMonths(months) {
const m = Math.round(Number(months));
if (!(m > 0)) {
return '—';
}
if (m % 12 === 0) {
const y = m / 12;
return `${y} year${y === 1 ? '' : 's'}`;
}
return `${m} month${m === 1 ? '' : 's'}`;
}
const CATEGORY_INFO = 'Default amounts are a one-year food-storage supply for one adult man (pounds per person '
+ 'per year). Totals scale by each person\'s ration share (women and children need less — see the shares '
+ 'above), and by the duration. Edit any amount to match your own plan. Water is not included — use the Water '
+ 'Storage calculator for that.';
const SHARES_INFO = 'Each person\'s share of one adult man\'s ration. Defaults follow the Dietary Guidelines for '
+ 'Americans 2020-2025 moderate-activity calorie needs (man ~2,600, woman ~2,000, child ~1,800 kcal/day) — '
+ 'food storage scales with calories. Children vary widely by age, so adjust as needed.';
const PEOPLE_META = [
{key: 'men', label: 'Men', color: '#4477aa'},
{key: 'women', label: 'Women', color: '#aa3377'},
{key: 'children', label: 'Children', color: '#228833'},
];
function textColorFor(hex) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.6 ? '#000000' : '#ffffff';
}
function fmt(value, unit) {
return Number.isFinite(value) && value > 0 ? `${roundDigits(value, 1)} ${unit}` : '—';
}
export function FoodStorageCalculator() {
const [counts, setCounts] = useLocalStorage('food_storage_counts', {men: '1', women: '1', children: ''});
const [shares, setShares] = useLocalStorage('food_storage_shares', DEFAULT_SHARES);
const [monthsIndex, setMonthsIndex] = useLocalStorage('food_storage_months_index', MONTH_STOPS.indexOf(12));
const [amounts, setAmounts] = useLocalStorage('food_storage_amounts', DEFAULT_AMOUNTS);
const [metric, setMetric] = useLocalStorage('food_storage_metric', false);
const {t} = React.useContext(ThemeContext);
const unit = metric ? 'kg' : 'lb';
// Convert the editable amounts when switching units so the user keeps their numbers.
const toggleMetric = () => {
setAmounts(prev => convertAmounts(prev, !metric));
setMetric(!metric);
};
const equivalents = adultEquivalents(counts, shares);
const monthStop = Math.min(Math.max(0, monthsIndex), MONTH_STOPS.length - 1);
const months = MONTH_STOPS[monthStop];
const inputProps = {fluid: true, type: 'number', min: 0, onSelect: e => e.target.select(), autoComplete: 'off'};
const labelStyle = (color) =>
({backgroundColor: color, color: textColorFor(color), borderColor: color});
const countInput = ({key, label, color}) =>
<Input {...inputProps} step={1} name={`count-${key}`} labelPosition='left' value={counts[key]}
onChange={e => setCounts({...counts, [key]: e.target.value})}
label={<Label style={labelStyle(color)}>{label}</Label>}/>;
const shareInput = ({key, label, color}) =>
<Input {...inputProps} step={1} name={`share-${key}`} labelPosition='left' value={shares[key]}
onChange={e => setShares({...shares, [key]: e.target.value})}
label={<Label style={labelStyle(color)}>{label}</Label>}/>;
const rows = FOOD_CATEGORIES.map(c => {
const perYear = amounts[c.key] ?? '';
const total = amountNeeded(perYear, equivalents, months);
return {...c, perYear, total};
});
const grandTotal = rows.reduce((s, r) => s + r.total, 0);
return <Form>
<Header as='h1'>Food Storage</Header>
<p {...t}>Estimate how much food to store for your household over time.</p>
<div style={{marginBottom: '1em'}}>
<Toggle label={metric ? 'Metric (kg)' : 'Imperial (lb)'} checked={metric} onChange={toggleMetric}/>
</div>
<Header as='h3'>People</Header>
<Grid stackable columns={3}>
{PEOPLE_META.map(meta => <GridColumn key={meta.key}>{countInput(meta)}</GridColumn>)}
</Grid>
<Header as='h4' style={{marginTop: '1em', marginBottom: '0.5em'}}>
Ration share (% of an adult man) <InfoPopup content={SHARES_INFO}/>
</Header>
<Grid stackable columns={3}>
{PEOPLE_META.map(meta => <GridColumn key={meta.key}>{shareInput(meta)}</GridColumn>)}
</Grid>
<p {...t} style={{...t.style, marginTop: '0.5em', opacity: 0.8}}>
≈ {roundDigits(equivalents, 2)} adult-equivalent{equivalents === 1 ? '' : 's'}
</p>
<Header as='h3' style={{marginTop: '1em'}}>How long?</Header>
<div style={{padding: '0 0.5em'}}>
<input type='range' min={0} max={MONTH_STOPS.length - 1} step={1} value={monthStop}
aria-label='Duration' onChange={e => setMonthsIndex(Number(e.target.value))}
style={{width: '100%'}}/>
<Header as='h2' textAlign='center' style={{marginTop: '0.25em'}}>{formatMonths(months)}</Header>
</div>
<Header as='h3' style={{marginTop: '1em'}}>
Amounts ({unit} per person per year) <InfoPopup content={CATEGORY_INFO}/>
</Header>
<Segment>
<Table unstackable>
<TableHeader>
<TableRow>
<TableHeaderCell width={7}>Category</TableHeaderCell>
<TableHeaderCell width={5}>{unit === 'kg' ? 'Kg' : 'Lbs'} / person / year</TableHeaderCell>
<TableHeaderCell width={4}>Total needed</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
{rows.map(r => <TableRow key={r.key}>
<TableCell>{r.label}</TableCell>
<TableCell>
<Input fluid type='number' min={0} value={r.perYear}
aria-label={`${r.label} per person per year`}
onChange={e => setAmounts({...amounts, [r.key]: e.target.value})}/>
</TableCell>
<TableCell>{fmt(r.total, unit)}</TableCell>
</TableRow>)}
</TableBody>
<TableFooter>
<TableRow>
<TableHeaderCell>Total</TableHeaderCell>
<TableHeaderCell/>
<TableHeaderCell>{fmt(grandTotal, unit)}</TableHeaderCell>
</TableRow>
</TableFooter>
</Table>
</Segment>
</Form>;
}

View file

@ -0,0 +1,60 @@
import {adultEquivalents, amountNeeded, convertAmounts, DEFAULT_SHARES, formatMonths, totalPeople} from "./FoodStorageCalculator";
describe('convertAmounts', () => {
test('converts lb to kg and back, preserving blanks', () => {
const lb = {grains: '300', aux: ''};
const kg = convertAmounts(lb, true);
expect(Number(kg.grains)).toBeCloseTo(136.08, 1); // 300 lb -> ~136 kg
expect(kg.aux).toBe('');
const back = convertAmounts(kg, false);
expect(Number(back.grains)).toBeCloseTo(300, 0);
});
});
describe('adultEquivalents', () => {
test('weights women and children below an adult man', () => {
// 1 man (100%) + 1 woman (77%) + 1 child (69%) = 2.46 adult-equivalents.
expect(adultEquivalents({men: '1', women: '1', children: '1'}, DEFAULT_SHARES)).toBeCloseTo(2.46, 5);
});
test('a household of adult men equals the head count', () => {
expect(adultEquivalents({men: '3', women: '', children: ''}, DEFAULT_SHARES)).toBe(3);
});
test('custom shares are respected', () => {
expect(adultEquivalents({men: '0', women: '2', children: '0'}, {men: 100, women: 50, children: 69}))
.toBeCloseTo(1, 5);
});
});
describe('totalPeople', () => {
test('sums men, women, and children', () => {
expect(totalPeople({men: '2', women: '1', children: '3'})).toBe(6);
});
test('ignores blank/negative counts', () => {
expect(totalPeople({men: '1', women: '', children: '-2'})).toBe(1);
});
});
describe('amountNeeded', () => {
test('scales per-person-per-year by people and duration (one man, one year)', () => {
expect(amountNeeded(300, 1, 12)).toBe(300); // grains, 1 man, 1 year
});
test('scales by household and partial year', () => {
expect(amountNeeded(300, 4, 6)).toBe(600); // 300 * 4 people * 0.5 year
});
test('zero for impossible inputs', () => {
expect(amountNeeded(0, 4, 12)).toBe(0);
expect(amountNeeded(300, 0, 12)).toBe(0);
expect(amountNeeded(300, 4, 0)).toBe(0);
});
});
describe('formatMonths', () => {
test('whole years read as years', () => {
expect(formatMonths(12)).toBe('1 year');
expect(formatMonths(24)).toBe('2 years');
});
test('otherwise months', () => {
expect(formatMonths(3)).toBe('3 months');
expect(formatMonths(1)).toBe('1 month');
});
});

View file

@ -0,0 +1,204 @@
import React from "react";
import {GridColumn, Input, Label, TableBody, TableCell, TableRow} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {Form, Header, Table} from "../Theme";
import {InfoPopup, roundDigits, useLocalStorage} from "../Common";
import {formatDuration} from "./WaterCalculator";
// Pure calculation functions for the Ration (food storage) estimate.
//
// The model: an inventory holds food items, each with a per-unit calorie value and a count. Total stored calories
// divided by the household's daily calorie demand gives how many days the food lasts.
// Total calories stored across all items: sum of (calories * count) per item. A blank/zero count is treated as 1
// (a single unit), and a blank calorie value contributes nothing.
export function totalCalories(items, caloriesKey, countKey) {
if (!items || !caloriesKey) {
return 0;
}
return items.reduce((sum, item) => {
const calories = Number(item[caloriesKey]);
if (!(calories > 0)) {
return sum;
}
const rawCount = countKey ? Number(item[countKey]) : 1;
const count = rawCount > 0 ? rawCount : 1;
return sum + calories * count;
}, 0);
}
// Household daily calorie demand: sum of per-category counts times per-category rates.
export function dailyCalorieDemand(counts, rates) {
const term = (count, rate) => {
const c = Number(count), r = Number(rate);
return (c > 0 && r > 0) ? c * r : 0;
};
return term(counts.men, rates.men)
+ term(counts.women, rates.women)
+ term(counts.children, rates.children);
}
// Days the stored calories last at the given daily demand. Returns null for impossible inputs.
export function daysOfFood(total, dailyDemand) {
if (!(total > 0) || !(dailyDemand > 0)) {
return null;
}
return total / dailyDemand;
}
// The calories field is detected by its dedicated `calories` type (falling back to a field literally keyed
// "calories" for inventories created before the type existed).
export function findCaloriesKey(fields) {
const byType = (fields || []).find(f => f.type === 'calories');
if (byType) {
return byType.key;
}
const legacy = (fields || []).find(f => f.key === 'calories' && f.type === 'number');
return legacy ? legacy.key : null;
}
// The count multiplier: prefer a number field keyed "count", else the first number field, else none (treat as 1).
export function findCountKey(fields) {
const count = (fields || []).find(f => f.type === 'number' && f.key === 'count');
if (count) {
return count.key;
}
const firstNumber = (fields || []).find(f => f.type === 'number');
return firstNumber ? firstNumber.key : null;
}
// Per-person daily calorie needs, by activity level. Adult figures are representative working-age values
// (ages 19-60) from the Dietary Guidelines for Americans 2020-2025, Appendix 2, Table A2-2 ("Estimated Calorie
// Needs per Day, by Age, Sex, and Physical Activity Level"), corroborated by the Merck Manuals table. The single
// "children" figure is a mid-childhood approximation (the DGA child range is very wide, 1,000-3,200). "Survival"
// is a short-term emergency ration floor, below maintenance. All values are editable.
export const RATION_PRESETS = {
sedentary: {
label: 'Sedentary',
description: 'Everyday-living activity only',
rates: {men: 2400, women: 1800, children: 1600},
},
moderate: {
label: 'Moderately Active',
description: '~1.5–3 mi/day walking',
rates: {men: 2600, women: 2000, children: 1800},
},
active: {
label: 'Active',
description: '>3 mi/day walking + activity',
rates: {men: 3000, women: 2400, children: 2000},
},
survival: {
label: 'Survival',
description: 'Emergency ration floor (~1,200–1,500/adult)',
rates: {men: 1500, women: 1200, children: 1200},
},
};
const DEFAULT_PRESET = 'moderate';
const CATEGORY_META = [
{key: 'men', label: 'Men', color: '#4477aa'},
{key: 'women', label: 'Women', color: '#aa3377'},
{key: 'children', label: 'Children', color: '#228833'},
];
const DEMAND_INFO = 'Per-person daily calorie needs come from the Dietary Guidelines for Americans 2020-2025 '
+ '(Appendix 2), by sex and physical activity level. Adult values are representative for ages 19-60; the '
+ 'children figure is a mid-childhood approximation since needs vary widely with age (1,000-3,200 kcal/day). '
+ 'The Survival preset is a short-term emergency ration floor, below maintenance. All values are editable — '
+ 'adjust the household and activity level to see how long the stored food lasts.';
function textColorFor(hex) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.6 ? '#000000' : '#ffffff';
}
function fmt(value, unit) {
if (!Number.isFinite(value) || value <= 0) {
return '—';
}
return unit ? `${roundDigits(value, 0)} ${unit}` : `${roundDigits(value, 0)}`;
}
/**
* The household + preset controls and the days-of-food result. Reused by the Ration calculator page and by the
* inventory Summary (when the inventory has a `calories` field). Household/preset selections are persisted under
* shared localStorage keys, so adjusting them in one place carries to the other.
*/
export function RationEstimatePanel({items, caloriesKey, countKey}) {
const [preset, setPreset] = useLocalStorage('ration_preset', DEFAULT_PRESET);
const [counts, setCounts] = useLocalStorage('ration_counts', {men: '1', women: '1', children: ''});
const [rates, setRates] = React.useState({...RATION_PRESETS[DEFAULT_PRESET].rates});
React.useEffect(() => {
// Fall back to the default preset if a stale/unknown key is persisted in localStorage.
const p = RATION_PRESETS[preset] ?? RATION_PRESETS[DEFAULT_PRESET];
setRates({...p.rates});
}, [preset]);
const total = totalCalories(items, caloriesKey, countKey);
const daily = dailyCalorieDemand(counts, rates);
const days = daysOfFood(total, daily);
const inputProps = {fluid: true, type: 'number', onSelect: e => e.target.select(), autoComplete: 'off'};
const countInput = ({key, label, color}) =>
<Input {...inputProps} min={0} step={1} name={`count-${key}`} labelPosition='left' value={counts[key]}
onChange={e => setCounts({...counts, [key]: e.target.value})}
label={<Label style={{backgroundColor: color, color: textColorFor(color), borderColor: color}}>
{label}</Label>}/>;
const rateInput = ({key, label, color}) =>
<Input {...inputProps} min={0} step={50} name={`rate-${key}`} labelPosition='left' value={rates[key]}
onChange={e => setRates({...rates, [key]: e.target.value})}
label={<Label style={{backgroundColor: color, color: textColorFor(color), borderColor: color}}>
{label}</Label>}/>;
return <Form>
<Header as='h3'>People</Header>
<Grid stackable columns={3}>
{CATEGORY_META.map(meta => <GridColumn key={meta.key}>{countInput(meta)}</GridColumn>)}
</Grid>
<Header as='h3' style={{marginTop: '1em'}}>
Daily Calories (per person) <InfoPopup content={DEMAND_INFO}/>
</Header>
<div style={{marginBottom: '1em'}}>
{Object.entries(RATION_PRESETS).map(([key, p]) => (
<button key={key} type='button' onClick={() => setPreset(key)} style={{
marginRight: '0.5em', padding: '0.4em 0.8em',
border: preset === key ? '2px solid #2185d0' : '1px solid #ccc',
background: preset === key ? '#e8f4fc' : 'white', borderRadius: '4px', cursor: 'pointer',
}}>
<strong>{p.label}</strong> — {p.description}
</button>
))}
</div>
<Grid stackable columns={3}>
{CATEGORY_META.map(meta => <GridColumn key={meta.key}>{rateInput(meta)}</GridColumn>)}
</Grid>
<Table definition unstackable style={{marginTop: '1em'}}>
<TableBody>
<TableRow>
<TableCell width={6}>Total Stored Calories</TableCell>
<TableCell>{fmt(total, 'kcal')}</TableCell>
</TableRow>
<TableRow>
<TableCell>Daily Demand</TableCell>
<TableCell>{fmt(daily, 'kcal/day')}</TableCell>
</TableRow>
<TableRow>
<TableCell>Food Lasts</TableCell>
<TableCell>{days ? formatDuration(days) : '—'}</TableCell>
</TableRow>
</TableBody>
</Table>
</Form>;
}
// NOTE: the inventory-based "how long does my food last" estimate now lives only inside the inventory Summary
// (via RationEstimatePanel). The standalone Calculators page is the generic FoodStorageCalculator instead.

View file

@ -0,0 +1,73 @@
import {dailyCalorieDemand, daysOfFood, findCaloriesKey, findCountKey, totalCalories} from "./RationCalculator";
describe('findCaloriesKey', () => {
test('detects a calories-type field', () => {
expect(findCaloriesKey([{key: 'kcal', type: 'calories'}, {key: 'name', type: 'text'}])).toBe('kcal');
});
test('falls back to a legacy number field keyed "calories"', () => {
expect(findCaloriesKey([{key: 'calories', type: 'number'}])).toBe('calories');
});
test('returns null when no calories field exists', () => {
expect(findCaloriesKey([{key: 'name', type: 'text'}])).toBeNull();
});
});
describe('findCountKey', () => {
test('prefers a number field keyed "count"', () => {
expect(findCountKey([{key: 'qty', type: 'number'}, {key: 'count', type: 'number'}])).toBe('count');
});
test('falls back to the first number field', () => {
expect(findCountKey([{key: 'qty', type: 'number'}])).toBe('qty');
});
test('returns null when no number field exists', () => {
expect(findCountKey([{key: 'name', type: 'text'}])).toBeNull();
});
});
describe('totalCalories', () => {
const items = [
{calories: '1600', count: '4'}, // 6400
{calories: '2000', count: '2'}, // 4000
{calories: '', count: '5'}, // 0 (no calories)
{calories: '500'}, // 500 (count defaults to 1)
{calories: '300', count: '0'}, // 300 (zero count treated as 1)
];
test('sums calories times count', () => {
expect(totalCalories(items, 'calories', 'count')).toBe(6400 + 4000 + 500 + 300);
});
test('treats every item as one unit when no count field is chosen', () => {
expect(totalCalories(items, 'calories', null)).toBe(1600 + 2000 + 500 + 300);
});
test('returns 0 with no items or no calories key', () => {
expect(totalCalories(null, 'calories', 'count')).toBe(0);
expect(totalCalories(items, null, 'count')).toBe(0);
});
});
describe('dailyCalorieDemand', () => {
test('sums per-category counts times rates', () => {
const demand = dailyCalorieDemand({men: '2', women: '1', children: '3'},
{men: 2500, women: 2000, children: 1600});
expect(demand).toBe(2 * 2500 + 1 * 2000 + 3 * 1600);
});
test('ignores blank/zero counts', () => {
const demand = dailyCalorieDemand({men: '', women: '0', children: '1'},
{men: 2500, women: 2000, children: 1600});
expect(demand).toBe(1600);
});
});
describe('daysOfFood', () => {
test('divides total by daily demand', () => {
expect(daysOfFood(14000, 7000)).toBe(2);
});
test('null for impossible inputs', () => {
expect(daysOfFood(0, 2000)).toBeNull();
expect(daysOfFood(14000, 0)).toBeNull();
});
});