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

@ -10,6 +10,7 @@ import {RatioCalculators} from "./calculators/RatioCalculator";
import {QRCodeCalculator} from "./calculators/QRCodeCalculator";
import {DriveCalculator} from "./calculators/DriveCalculator";
import {WaterCalculator} from "./calculators/WaterCalculator";
import {FoodStorageCalculator} from "./calculators/FoodStorageCalculator";
export const useCalculators = () => {
const [calc, setCalc] = useCalcQuery();
@ -19,6 +20,7 @@ export const useCalculators = () => {
{key: 'electrical', icon: 'lightning', button: 'Electrical', contents: <ElectricalCalculators/>},
{key: 'drive', icon: 'cogs', button: 'Drive Ratio', contents: <DriveCalculator/>},
{key: 'water', icon: 'tint', button: 'Water Storage', contents: <WaterCalculator/>},
{key: 'ration', icon: 'food', button: 'Food Storage', contents: <FoodStorageCalculator/>},
{key: 'antenna', icon: 'signal', button: 'Antenna', contents: <DipoleAntennaCalculator/>},
{key: 'temperature', icon: 'thermometer', button: 'Temperature', contents: <TemperatureCalculator/>},
{key: 'qrCode', icon: 'qrcode', button: 'QR Code', contents: <QRCodeCalculator/>},

File diff suppressed because it is too large Load diff

View file

@ -23,6 +23,9 @@ import {
ListItem as SListItem,
Loader as SLoader,
Menu as SMenu,
MenuItem as SMenuItem,
MenuHeader as SMenuHeader,
MenuMenu as SMenuMenu,
Modal as SModal,
ModalActions as SModalActions,
ModalContent as SModalContent,
@ -66,6 +69,8 @@ import {
ListDescriptionProps,
LoaderProps,
MenuProps,
MenuItemProps,
MenuMenuProps,
ModalProps,
ModalActionsProps,
ModalContentProps,
@ -312,11 +317,29 @@ export function Loader(props: LoaderProps) {
return <SLoader {...i} {...props}/>
}
export function Menu(props: MenuProps) {
// Menu is a compound component (Menu.Item / Menu.Header / Menu.Menu) so callers get the same API as Semantic's
// Menu while inheriting the theme. The parent menu is `inverted` in dark mode so item text stays readable.
const MenuBase: React.FC<MenuProps> = (props) => {
const {i} = useContext(ThemeContext);
return <SMenu {...i} {...props}/>
return <SMenu {...i} {...props}/>;
};
const MenuItem: React.FC<MenuItemProps> = (props) => <SMenuItem {...props}/>;
const MenuHeader: React.FC<MenuItemProps> = (props) => <SMenuHeader {...props}/>;
const MenuMenu: React.FC<MenuMenuProps> = (props) => <SMenuMenu {...props}/>;
interface MenuComponent extends React.FC<MenuProps> {
Item: React.FC<MenuItemProps>;
Header: React.FC<MenuItemProps>;
Menu: React.FC<MenuMenuProps>;
}
export const Menu: MenuComponent = Object.assign(MenuBase, {
Item: MenuItem,
Header: MenuHeader,
Menu: MenuMenu,
});
export function Placeholder(props: PlaceholderProps) {
const {i} = useContext(ThemeContext);
return <SPlaceholder {...i} {...props}/>

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();
});
});

View file

@ -0,0 +1,108 @@
import React, {useState} from "react";
import {Input, Select, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {Button, Header, Icon, Modal, Table} from "../Theme";
import {ALL_UNITS} from "./units";
const UNIT_OPTIONS = [{key: '', value: '', text: '—'}, ...ALL_UNITS.map(u => ({key: u, value: u, text: u}))];
const COLUMNS = [
{key: 'name', label: 'Name', width: 4},
{key: 'category', label: 'Category', width: 3},
{key: 'subcategory', label: 'Subcategory', width: 3},
{key: 'item_size', label: 'Size', width: 2},
{key: 'item_size_unit', label: 'Unit', width: 2},
{key: 'calories', label: 'kcal', width: 2},
];
function blankEntry() {
return {name: '', category: '', subcategory: '', item_size: '', item_size_unit: '', calories: ''};
}
/**
* Manage the shared food catalog: a scrollable, editable table (add/edit/delete) saved as a whole list. Each
* entry's `calories` is the total for one `item_size` package — the value pre-filled onto inventory items.
*/
export function CatalogEditor({catalog, open, onClose, onSave}) {
const [draft, setDraft] = useState([]);
React.useEffect(() => {
if (open) {
setDraft((catalog || []).map(e => ({...e})));
}
}, [open, catalog]);
const update = (index, key, value) =>
setDraft(prev => prev.map((e, i) => i === index ? {...e, [key]: value} : e));
const remove = (index) => setDraft(prev => prev.filter((_, i) => i !== index));
const add = () => setDraft(prev => [blankEntry(), ...prev]);
const save = async () => {
// Drop fully-empty rows.
const cleaned = draft.filter(e => (e.name || '').trim());
await onSave(cleaned);
onClose();
};
return <Modal open={open} onClose={onClose} closeIcon size='fullscreen'>
<Modal.Header>Food Catalog</Modal.Header>
<Modal.Content scrolling>
<p style={{opacity: 0.8}}>
Known items used to autocomplete and pre-fill the entry form. <strong>kcal</strong> is the total
calories for one package of the given size.
</p>
<Button onClick={add} style={{marginBottom: '0.5em'}}><Icon name='plus'/>Add Item</Button>
<Table celled unstackable compact>
<TableHeader>
<TableRow>
{COLUMNS.map(c => <TableHeaderCell key={c.key} width={c.width}>{c.label}</TableHeaderCell>)}
<TableHeaderCell collapsing/>
</TableRow>
</TableHeader>
<TableBody>
{draft.map((entry, index) => {
const aria = (col) => `${entry.name || 'new item'} ${col}`;
return <TableRow key={entry.id ?? `new-${index}`}>
<TableCell>
<Input fluid name='catalog-name' aria-label={aria('name')} value={entry.name || ''}
placeholder='Name' onChange={e => update(index, 'name', e.target.value)}/>
</TableCell>
<TableCell>
<Input fluid name='catalog-category' aria-label={aria('category')}
value={entry.category || ''}
onChange={e => update(index, 'category', e.target.value)}/>
</TableCell>
<TableCell>
<Input fluid name='catalog-subcategory' aria-label={aria('subcategory')}
value={entry.subcategory || ''}
onChange={e => update(index, 'subcategory', e.target.value)}/>
</TableCell>
<TableCell>
<Input fluid type='number' name='catalog-size' aria-label={aria('size')}
value={entry.item_size || ''}
onChange={e => update(index, 'item_size', e.target.value)}/>
</TableCell>
<TableCell>
<Select compact search name='catalog-unit' aria-label={aria('unit')} options={UNIT_OPTIONS}
value={entry.item_size_unit || ''}
onChange={(e, data) => update(index, 'item_size_unit', data.value)}/>
</TableCell>
<TableCell>
<Input fluid type='number' name='catalog-calories' aria-label={aria('calories')}
value={entry.calories || ''}
onChange={e => update(index, 'calories', e.target.value)}/>
</TableCell>
<TableCell collapsing>
<Button color='red' icon size='mini' aria-label='Remove'
onClick={() => remove(index)}><Icon name='trash'/></Button>
</TableCell>
</TableRow>;
})}
</TableBody>
</Table>
</Modal.Content>
<Modal.Actions>
<Button onClick={onClose}>Cancel</Button>
<Button primary onClick={save}>Save Catalog</Button>
</Modal.Actions>
</Modal>;
}

View file

@ -0,0 +1,90 @@
import React from "react";
import {Input, Select} from "semantic-ui-react";
import {ALL_UNITS, UNIT_GROUPS} from "./units";
// Renders the correct editor for a single field/value, wiring up keyboard navigation. The `inputRef` is attached
// to the primary <input> so the parent table can focus the first cell of a new row.
//
// Props:
// field - {key, label, type, unit?, options?}
// value - the current item value for field.key
// unitValue- the current unit (for quantity fields; stored under `${key}_unit`)
// onChange(value) - value changed
// onUnitChange(unit) - quantity unit changed
// onEnter() - Enter pressed (submit row)
// inputRef - ref attached to the primary input
export function FieldCell({field, value, unitValue, onChange, onUnitChange, onEnter, inputRef, listId}) {
const handleKeyDown = (e) => {
if (e.key === 'Enter' && onEnter) {
e.preventDefault();
onEnter();
}
};
const common = {
value: value ?? '',
onChange: (e, data) => onChange(data ? data.value : e.target.value),
onKeyDown: handleKeyDown,
'aria-label': field.label,
name: field.key,
};
if (field.type === 'select') {
const options = (field.options || []).map(o => ({key: o, value: o, text: o}));
// Allow clearing.
return <Select
fluid search clearable selection
name={field.key}
options={options}
placeholder={field.label}
value={value ?? ''}
onChange={(e, data) => onChange(data.value)}
onKeyDown={handleKeyDown}
aria-label={field.label}
/>;
}
if (field.type === 'date') {
return <Input {...common} type='date' fluid ref={inputRef}/>;
}
if (field.type === 'number' || field.type === 'calories') {
// `calories` is a number (kcal per unit) that the Summary's ration estimate detects by type.
return <Input {...common} type='number' fluid ref={inputRef}/>;
}
if (field.type === 'quantity') {
const unitOptions = ALL_UNITS.map(u => ({key: u, value: u, text: u}));
return <Input
type='number'
fluid
ref={inputRef}
name={field.key}
value={value ?? ''}
onChange={(e) => onChange(e.target.value)}
onKeyDown={handleKeyDown}
aria-label={field.label}
label={<Select
compact
name={`${field.key}_unit`}
options={unitOptions}
value={unitValue ?? field.unit ?? ''}
onChange={(e, data) => onUnitChange(data.value)}
aria-label={`${field.label} unit`}
/>}
labelPosition='right'
/>;
}
if (field.type === 'location') {
// Native datalist autocomplete fed by all inventories' locations (basement, attic, ...). Using a datalist
// (rather than a Dropdown) keeps it a real text input, so the Tab/Enter row-entry flow still works.
return <Input {...common} fluid ref={inputRef} list={listId}/>;
}
// text / fallback (supports a datalist via listId, e.g. catalog name suggestions on the Name field).
return <Input {...common} fluid ref={inputRef} list={listId}/>;
}
// The list of selectable unit groups, re-exported for the field editor.
export {UNIT_GROUPS};

View file

@ -0,0 +1,113 @@
import React, {useState} from "react";
import {Input, Select, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {Button, Icon, Modal, Table} from "../Theme";
import {ALL_UNITS} from "./units";
const FIELD_TYPE_OPTIONS = ['text', 'number', 'quantity', 'date', 'select', 'location', 'calories']
.map(t => ({key: t, value: t, text: t}));
const UNIT_OPTIONS = ALL_UNITS.map(u => ({key: u, value: u, text: u}));
function slugifyKey(label) {
return (label || '').trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') || 'field';
}
/**
* Modal editor for an inventory's field schema: add/remove/reorder/retype fields, set a quantity field's default
* unit, and a select field's options. Saves via PUT /<slug>/fields.
*/
export function FieldSchemaEditor({fields, open, onClose, onSave}) {
const [draft, setDraft] = useState(() => fields.map(f => ({...f})));
React.useEffect(() => {
if (open) {
setDraft(fields.map(f => ({...f})));
}
}, [open, fields]);
const update = (index, patch) => setDraft(prev => prev.map((f, i) => i === index ? {...f, ...patch} : f));
const remove = (index) => setDraft(prev => prev.filter((_, i) => i !== index));
const move = (index, delta) => setDraft(prev => {
const next = [...prev];
const target = index + delta;
if (target < 0 || target >= next.length) {
return prev;
}
[next[index], next[target]] = [next[target], next[index]];
return next;
});
const add = () => setDraft(prev => [...prev, {key: '', label: '', type: 'text'}]);
const save = async () => {
// Fill any missing keys from labels and normalize order.
const cleaned = draft
.filter(f => f.label || f.key)
.map((f, index) => ({
...f,
key: f.key || slugifyKey(f.label),
label: f.label || f.key,
order: index,
}));
await onSave(cleaned);
onClose();
};
return <Modal open={open} onClose={onClose} closeIcon size='large'>
<Modal.Header>Customize Fields</Modal.Header>
<Modal.Content scrolling>
{/* NOTE: do NOT use `fixed` here — semantic gives fixed-table cells `overflow:hidden`, which clips the
Type/Unit dropdown menus to the cell height. The `width` props below size the columns without it. */}
<Table celled unstackable>
<TableHeader>
<TableRow>
<TableHeaderCell width={2}>Order</TableHeaderCell>
<TableHeaderCell width={4}>Label</TableHeaderCell>
<TableHeaderCell width={4}>Type</TableHeaderCell>
<TableHeaderCell width={5}>Unit / Options</TableHeaderCell>
<TableHeaderCell width={1}/>
</TableRow>
</TableHeader>
<TableBody>
{draft.map((f, index) => <TableRow key={index}>
<TableCell collapsing>
<Button icon size='mini' onClick={() => move(index, -1)} disabled={index === 0}
aria-label='Move up'><Icon name='arrow up'/></Button>
<Button icon size='mini' onClick={() => move(index, 1)}
disabled={index === draft.length - 1}
aria-label='Move down'><Icon name='arrow down'/></Button>
</TableCell>
<TableCell>
<Input fluid value={f.label || ''} placeholder='Label'
onChange={e => update(index, {label: e.target.value})}/>
</TableCell>
<TableCell>
<Select fluid options={FIELD_TYPE_OPTIONS} value={f.type}
onChange={(e, data) => update(index, {type: data.value})}/>
</TableCell>
<TableCell>
{f.type === 'quantity' &&
<Select fluid search options={UNIT_OPTIONS} value={f.unit || ''}
placeholder='Default unit'
onChange={(e, data) => update(index, {unit: data.value})}/>}
{f.type === 'select' &&
<Input fluid placeholder='comma,separated,options'
value={(f.options || []).join(',')}
onChange={e => update(index, {
options: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
})}/>}
</TableCell>
<TableCell collapsing>
<Button color='red' icon size='mini' onClick={() => remove(index)}
aria-label='Remove field'><Icon name='trash'/></Button>
</TableCell>
</TableRow>)}
</TableBody>
</Table>
<Button onClick={add}><Icon name='plus'/>Add Field</Button>
</Modal.Content>
<Modal.Actions>
<Button onClick={onClose}>Cancel</Button>
<Button primary onClick={save}>Save Fields</Button>
</Modal.Actions>
</Modal>;
}

View file

@ -0,0 +1,50 @@
import React from "react";
import {InventoryRoute} from "./InventoryRoute";
const FIELDS = [
{key: 'name', label: 'Name', type: 'text', order: 0},
{key: 'item_size', label: 'Size', type: 'quantity', unit: 'lb', order: 1},
{key: 'count', label: 'Count', type: 'number', order: 2},
];
const FOOD_STORAGE = {
slug: 'food-storage', name: 'Food Storage', type: 'food', version: 1, fields: FIELDS,
items: [{id: 1, name: 'Salt', item_size: '25', item_size_unit: 'lb', count: '8'}],
};
describe('Inventory Page', () => {
beforeEach(() => {
// The page loads every inventory in full from one endpoint.
cy.intercept('GET', '**/api/inventory', {statusCode: 200, body: {inventories: [FOOD_STORAGE]}})
.as('getInventories');
});
it('renders an inventory with its items', () => {
cy.mountWithTags(<InventoryRoute/>, {initialEntries: ['/inventory']});
cy.wait('@getInventories');
cy.contains('Food Storage').should('be.visible');
cy.contains('Salt').should('be.visible');
cy.get('input[name="name"]').should('exist'); // the spreadsheet add row
});
it('persists a new item with a whole-inventory PUT', () => {
cy.intercept('PUT', '**/api/inventory/food-storage', (req) => {
req.reply({statusCode: 200, body: {inventory: {...FOOD_STORAGE, version: 2, items: req.body.items}}});
}).as('saveInventory');
cy.mountWithTags(<InventoryRoute/>, {initialEntries: ['/inventory']});
cy.wait('@getInventories');
cy.get('input[name="name"]').last().type('Rice{enter}');
cy.wait('@saveInventory').its('request.body.items').should('have.length', 2);
});
it('switches to the summary tab', () => {
cy.mountWithTags(<InventoryRoute/>, {initialEntries: ['/inventory']});
cy.wait('@getInventories');
cy.contains('Summary').click();
cy.contains('Group by').should('be.visible');
});
});

View file

@ -0,0 +1,177 @@
import React, {useState} from "react";
import {Dropdown, Input, Select} from "semantic-ui-react";
import {Button, Confirm, Header, Icon, Loader, Menu, Modal, Segment} from "../Theme";
import {PageContainer, useTitle} from "../Common";
import {collectLocations, useCatalog, useInventories} from "../../hooks/customHooks";
import {InventoryTable} from "./InventoryTable";
import {InventorySummary} from "./InventorySummary";
import {FieldSchemaEditor} from "./FieldSchemaEditor";
import {CatalogEditor} from "./CatalogEditor";
const INVENTORY_TYPES = [
{key: 'food', value: 'food', text: 'Food Storage'},
{key: 'fuel', value: 'fuel', text: 'Fuel'},
{key: 'tool', value: 'tool', text: 'Tools'},
];
function NewInventoryModal({open, onClose, onCreate}) {
const [name, setName] = useState('');
const [type, setType] = useState('food');
const create = async () => {
const inventory = await onCreate(name, type);
if (inventory) {
setName('');
setType('food');
onClose();
}
};
return <Modal open={open} onClose={onClose} closeIcon>
<Modal.Header>New Inventory</Modal.Header>
<Modal.Content>
<Input fluid label='Name' value={name} onChange={e => setName(e.target.value)}
placeholder='Food Storage' style={{marginBottom: '1em'}}/>
<div>
Type:{' '}
<Select options={INVENTORY_TYPES} value={type} onChange={(e, data) => setType(data.value)}/>
<p style={{fontSize: '0.85em', opacity: 0.7, marginTop: '0.5em'}}>
The type seeds a starting set of fields — you can customize them afterward.
</p>
</div>
</Modal.Content>
<Modal.Actions>
<Button onClick={onClose}>Cancel</Button>
<Button primary onClick={create} disabled={!name.trim()}>Create</Button>
</Modal.Actions>
</Modal>;
}
export function InventoryRoute() {
useTitle('Inventory');
const {inventories, persistInventory, addInventory, removeInventory} = useInventories();
const {catalog, persistCatalog} = useCatalog();
const [slug, setSlug] = useState(null);
const [tab, setTab] = useState('items');
const [newOpen, setNewOpen] = useState(false);
const [catalogOpen, setCatalogOpen] = useState(false);
const [editFieldsOpen, setEditFieldsOpen] = useState(false);
const [renaming, setRenaming] = useState(false);
const [renameValue, setRenameValue] = useState('');
const [confirmDelete, setConfirmDelete] = useState(false);
// Default to the first inventory once loaded.
React.useEffect(() => {
if (slug == null && inventories && inventories.length > 0) {
setSlug(inventories[0].slug);
}
}, [inventories, slug]);
const current = inventories?.find(i => i.slug === slug);
const fields = current ? current.fields : [];
const items = current ? current.items : [];
// Location suggestions are pooled across every inventory.
const locations = collectLocations(inventories);
const onCreate = async (name, type) => {
const inventory = await addInventory(name, type);
if (inventory) {
setSlug(inventory.slug);
}
return inventory;
};
const doRename = async () => {
await persistInventory(slug, {name: renameValue});
setRenaming(false);
};
const doDelete = async () => {
await removeInventory(slug);
setConfirmDelete(false);
setSlug(null);
};
if (inventories === null) {
return <PageContainer><Loader active inline='centered'/></PageContainer>;
}
const inventoryOptions = inventories.map(i => ({key: i.slug, value: i.slug, text: i.name}));
return <PageContainer>
<Header as='h1'>Inventory</Header>
<Segment>
<div style={{display: 'flex', gap: '0.5em', alignItems: 'center', flexWrap: 'wrap'}}>
<Dropdown
selection
placeholder='Select an inventory'
options={inventoryOptions}
value={slug || ''}
onChange={(e, data) => setSlug(data.value)}
style={{minWidth: '14em'}}
/>
<Button primary icon onClick={() => setNewOpen(true)} aria-label='New inventory'>
<Icon name='plus'/>
</Button>
<Button icon onClick={() => setCatalogOpen(true)} aria-label='Food catalog'>
<Icon name='book'/> Catalog
</Button>
{current && <>
<Button icon onClick={() => {
setRenameValue(current.name);
setRenaming(true);
}} aria-label='Rename inventory'><Icon name='edit'/></Button>
<Button icon onClick={() => setEditFieldsOpen(true)} aria-label='Customize fields'>
<Icon name='columns'/> Fields
</Button>
<Button color='red' icon onClick={() => setConfirmDelete(true)} aria-label='Delete inventory'>
<Icon name='trash'/>
</Button>
</>}
</div>
</Segment>
{current ? <>
<Menu pointing secondary>
<Menu.Item name='Items' active={tab === 'items'} onClick={() => setTab('items')}/>
<Menu.Item name='Summary' active={tab === 'summary'} onClick={() => setTab('summary')}/>
</Menu>
{tab === 'items'
? <InventoryTable slug={slug} fields={fields} items={items} locations={locations} catalog={catalog}
onChange={newItems => persistInventory(slug, {items: newItems})}/>
: <InventorySummary fields={fields} items={items}/>}
<FieldSchemaEditor fields={fields} open={editFieldsOpen}
onClose={() => setEditFieldsOpen(false)}
onSave={newFields => persistInventory(slug, {fields: newFields})}/>
</> : <p>Create an inventory to get started.</p>}
<NewInventoryModal open={newOpen} onClose={() => setNewOpen(false)} onCreate={onCreate}/>
<CatalogEditor catalog={catalog || []} open={catalogOpen} onClose={() => setCatalogOpen(false)}
onSave={persistCatalog}/>
<Modal open={renaming} onClose={() => setRenaming(false)} closeIcon size='tiny'>
<Modal.Header>Rename Inventory</Modal.Header>
<Modal.Content>
<Input fluid value={renameValue} onChange={e => setRenameValue(e.target.value)}/>
</Modal.Content>
<Modal.Actions>
<Button onClick={() => setRenaming(false)}>Cancel</Button>
<Button primary onClick={doRename} disabled={!renameValue.trim()}>Save</Button>
</Modal.Actions>
</Modal>
<Confirm
open={confirmDelete}
header='Delete Inventory'
content={`Delete "${current?.name}" and all its items? This cannot be undone.`}
confirmButton='Delete'
onCancel={() => setConfirmDelete(false)}
onConfirm={doDelete}
/>
</PageContainer>;
}

View file

@ -0,0 +1,131 @@
import React, {useMemo, useState} from "react";
import {Select, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {Header, Segment, Table} from "../Theme";
import {formatTotals, sumQuantities} from "./units";
import {findCaloriesKey, findCountKey, RationEstimatePanel} from "../calculators/RationCalculator";
import {ThemeContext} from "../../contexts/contexts";
// Aggregate the inventory client-side: group items by a chosen text/select field and sum a chosen quantity field.
// When the inventory has a `calories` field, a ration estimate is shown below the summary table.
export function InventorySummary({fields, items}) {
const groupFields = fields.filter(f => ['text', 'select', 'location'].includes(f.type));
const quantityFields = fields.filter(f => f.type === 'quantity');
const caloriesKey = findCaloriesKey(fields);
const countKey = findCountKey(fields);
const {t} = React.useContext(ThemeContext);
// Default to grouping by Category (easier to see grains/dairy/etc.), falling back to the first group field.
const [groupKey, setGroupKey] = useState((groupFields.find(f => f.key === 'category') || groupFields[0])?.key);
const [quantityKey, setQuantityKey] = useState(quantityFields[0]?.key);
const [sort, setSort] = useState({key: 'name', dir: 'asc'});
const toggleSort = (key) => setSort(prev =>
prev.key === key
? {key, dir: prev.dir === 'asc' ? 'desc' : 'asc'}
: {key, dir: key === 'name' ? 'asc' : 'desc'});
const rows = useMemo(() => {
if (!groupKey) {
return [];
}
// A blank/zero count means a single unit (matches the ration estimate's convention).
const unitsOf = (item) => {
const c = countKey ? Number(item[countKey]) : 1;
return c > 0 ? c : 1;
};
const groups = {};
(items || []).forEach(item => {
const key = item[groupKey] || '(none)';
if (!groups[key]) {
groups[key] = {entries: [], count: 0, calories: 0};
}
const group = groups[key];
group.count += 1;
const units = unitsOf(item);
if (quantityKey) {
// Total size = per-container size × count (the count field), so the summary matches reality.
const size = Number(item[quantityKey]);
group.entries.push({
value: (size > 0 ? size : 0) * units,
unit: item[`${quantityKey}_unit`],
});
}
if (caloriesKey) {
const cal = Number(item[caloriesKey]);
if (cal > 0) {
group.calories += cal * units;
}
}
});
const mapped = Object.entries(groups).map(([name, g]) => {
const summed = sumQuantities(g.entries);
// "Total" is a multi-unit string; keep a numeric proxy (sum of magnitudes + unitless) for sorting.
const totalSort = (summed.totals || []).reduce((s, x) => s + x.magnitude, 0) + (summed.unitlessCount || 0);
return {name, count: g.count, total: formatTotals(summed), totalSort, calories: g.calories};
});
const compare = (a, b) => {
const r = sort.key === 'name' ? a.name.localeCompare(b.name)
: sort.key === 'count' ? a.count - b.count
: sort.key === 'total' ? a.totalSort - b.totalSort
: a.calories - b.calories;
return sort.dir === 'desc' ? -r : r;
};
return mapped.sort(compare);
}, [items, groupKey, quantityKey, countKey, caloriesKey, sort]);
const sortDir = (key) => sort.key === key ? (sort.dir === 'asc' ? 'ascending' : 'descending') : undefined;
if (!items || items.length === 0) {
return <p {...t}>No items to summarize yet.</p>;
}
const fieldOptions = (fs) => fs.map(f => ({key: f.key, value: f.key, text: f.label}));
return <>
<Header as='h3'>Summary</Header>
<div style={{marginBottom: '1em', display: 'flex', gap: '1em', flexWrap: 'wrap'}}>
<span {...t}>
Group by:{' '}
<Select options={fieldOptions(groupFields)} value={groupKey}
onChange={(e, data) => setGroupKey(data.value)}/>
</span>
{quantityFields.length > 0 &&
<span>
Sum:{' '}
<Select clearable options={fieldOptions(quantityFields)} value={quantityKey}
onChange={(e, data) => setQuantityKey(data.value)}/>
</span>}
</div>
<Table celled unstackable sortable>
<TableHeader>
<TableRow>
<TableHeaderCell sorted={sortDir('name')} onClick={() => toggleSort('name')}
style={{cursor: 'pointer'}}>
{groupFields.find(f => f.key === groupKey)?.label || 'Group'}
</TableHeaderCell>
<TableHeaderCell sorted={sortDir('count')} onClick={() => toggleSort('count')}
style={{cursor: 'pointer'}}>Items</TableHeaderCell>
{quantityKey && <TableHeaderCell sorted={sortDir('total')} onClick={() => toggleSort('total')}
style={{cursor: 'pointer'}}>Total</TableHeaderCell>}
{caloriesKey && <TableHeaderCell sorted={sortDir('calories')} onClick={() => toggleSort('calories')}
style={{cursor: 'pointer'}}>Calories</TableHeaderCell>}
</TableRow>
</TableHeader>
<TableBody>
{rows.map(row => <TableRow key={row.name}>
<TableCell>{row.name}</TableCell>
<TableCell>{row.count}</TableCell>
{quantityKey && <TableCell>{row.total}</TableCell>}
{caloriesKey &&
<TableCell>{row.calories > 0 ? `${row.calories.toLocaleString()} kcal` : '—'}</TableCell>}
</TableRow>)}
</TableBody>
</Table>
{caloriesKey &&
<Segment style={{marginTop: '2em'}}>
<Header as='h3'>Ration Estimate</Header>
<RationEstimatePanel items={items} caloriesKey={caloriesKey} countKey={countKey}/>
</Segment>}
</>;
}

View file

@ -0,0 +1,39 @@
import React from "react";
import {fireEvent, render, screen} from "@testing-library/react";
import {InventorySummary} from "./InventorySummary";
// Group by the first text field (category); two groups with different item counts and size totals.
const FIELDS = [
{key: 'category', label: 'Category', type: 'text', order: 0},
{key: 'item_size', label: 'Size', type: 'quantity', unit: 'lb', order: 1},
{key: 'count', label: 'Count', type: 'number', order: 2},
];
const ITEMS = [
{id: 1, category: 'grains', item_size: '10', item_size_unit: 'lb', count: '2'}, // 20 lb
{id: 2, category: 'grains', item_size: '5', item_size_unit: 'lb', count: '2'}, // 10 lb -> grains: 2 items, 30 lb
{id: 3, category: 'beans', item_size: '25', item_size_unit: 'lb', count: '4'}, // beans: 1 item, 100 lb
];
const groupOrder = () =>
[...document.querySelectorAll('tbody tr')].map(tr => tr.querySelector('td:first-child').textContent);
describe('InventorySummary sortable columns', () => {
test('defaults to group name ascending', () => {
render(<InventorySummary fields={FIELDS} items={ITEMS}/>);
expect(groupOrder()).toEqual(['beans', 'grains']);
});
test('sorting by Items uses the numeric count', () => {
render(<InventorySummary fields={FIELDS} items={ITEMS}/>);
fireEvent.click(screen.getByText('Items')); // first click -> descending
expect(groupOrder()).toEqual(['grains', 'beans']); // grains has 2 items, beans 1
fireEvent.click(screen.getByText('Items')); // toggle -> ascending
expect(groupOrder()).toEqual(['beans', 'grains']);
});
test('sorting by Total uses the summed magnitude, not the formatted string', () => {
render(<InventorySummary fields={FIELDS} items={ITEMS}/>);
fireEvent.click(screen.getByText('Total')); // descending
expect(groupOrder()).toEqual(['beans', 'grains']); // beans 100 lb > grains 30 lb
});
});

View file

@ -0,0 +1,286 @@
import React, {useMemo, useRef, useState} from "react";
import {Checkbox, TableBody, TableCell, TableFooter, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {Button, Icon, Table} from "../Theme";
import {FieldCell} from "./FieldCell";
const LOCATION_LIST_ID = 'inventory-location-suggestions';
const CATALOG_LIST_ID = 'inventory-catalog-names';
const NUMERIC_TYPES = ['number', 'quantity', 'calories'];
// Fields copied from a catalog entry onto the new-item row when its name matches a catalog entry.
const CATALOG_KEYS = ['name', 'category', 'subcategory', 'item_size', 'item_size_unit', 'calories'];
// Build an empty item keyed by the field schema (quantity fields seed their default unit).
function emptyItem(fields) {
const item = {};
fields.forEach(f => {
item[f.key] = '';
if (f.type === 'quantity') {
item[`${f.key}_unit`] = f.unit || '';
}
});
return item;
}
function nextId(items) {
return items.reduce((max, i) => (typeof i.id === 'number' && i.id > max ? i.id : max), 0) + 1;
}
// Type-aware comparison for sorting: numeric for number/quantity/calories, chronological for date, locale string
// otherwise. Blank values sort last (ascending).
function compareByField(a, b, field) {
const av = a[field.key], bv = b[field.key];
const aBlank = av === '' || av == null;
const bBlank = bv === '' || bv == null;
if (aBlank || bBlank) {
return aBlank === bBlank ? 0 : (aBlank ? 1 : -1);
}
if (NUMERIC_TYPES.includes(field.type)) {
return (Number(av) || 0) - (Number(bv) || 0);
}
if (field.type === 'date') {
return (Date.parse(av) || 0) - (Date.parse(bv) || 0);
}
return String(av).localeCompare(String(bv));
}
/**
* Spreadsheet-style item table. All edits happen on the in-memory items; `onChange(newItems)` persists the whole
* inventory (the page holds every inventory and saves the changed one). A persistent "new item" row sits at the
* bottom: Tab moves between fields and Enter submits the item then refocuses the first field.
*/
export function InventoryTable({slug, fields, items, locations, catalog, onChange}) {
const [draft, setDraft] = useState(() => emptyItem(fields));
const [edits, setEdits] = useState({}); // itemId -> edited copy
const [selected, setSelected] = useState(new Set());
const [sort, setSort] = useState(null); // {key, dir: 'asc'|'desc'} or null for entry order
const firstInputRef = useRef(null);
const hasLocationField = fields.some(f => f.type === 'location');
const hasNameField = fields.some(f => f.key === 'name');
// Catalog lookup by lower-cased name, and the set of field keys this inventory actually has (so pre-fill only
// touches existing fields). Catalog integration only applies when the inventory has a `name` field.
const catalogByName = useMemo(() => {
const map = {};
(catalog || []).forEach(e => {
if (e.name) {
map[e.name.trim().toLowerCase()] = e;
}
});
return map;
}, [catalog]);
const fieldKeySet = useMemo(() => {
const keys = new Set();
fields.forEach(f => {
keys.add(f.key);
if (f.type === 'quantity') {
keys.add(`${f.key}_unit`);
}
});
return keys;
}, [fields]);
const listIdFor = (field) => {
if (field.type === 'location') {
return LOCATION_LIST_ID;
}
if (field.key === 'name' && (catalog || []).length) {
return CATALOG_LIST_ID;
}
return undefined;
};
// Re-seed local editing state when the inventory or its schema changes.
React.useEffect(() => {
setDraft(emptyItem(fields));
setEdits({});
setSelected(new Set());
setSort(null);
}, [slug, fields]);
// Expired = any date-type field strictly before the start of today.
const dateFields = useMemo(() => fields.filter(f => f.type === 'date'), [fields]);
const todayStart = useMemo(() => {
const d = new Date();
d.setHours(0, 0, 0, 0);
return d.getTime();
}, []);
const isExpired = (item) => dateFields.some(f => {
const t = Date.parse(item[f.key]);
return !isNaN(t) && t < todayStart;
});
const toggleSort = (key) => setSort(prev =>
prev && prev.key === key
? {key, dir: prev.dir === 'asc' ? 'desc' : 'asc'}
: {key, dir: 'asc'});
// Rows are sorted for display only; the persistent entry row lives in the footer and is unaffected.
const displayItems = useMemo(() => {
const list = items || [];
if (!sort) {
return list;
}
const field = fields.find(f => f.key === sort.key);
if (!field) {
return list;
}
const sorted = [...list].sort((a, b) => compareByField(a, b, field));
return sort.dir === 'desc' ? sorted.reverse() : sorted;
}, [items, fields, sort]);
const focusFirst = () => {
const node = firstInputRef.current;
if (node && node.focus) {
node.focus();
} else if (node && node.inputRef && node.inputRef.current) {
node.inputRef.current.focus();
}
};
const setDraftValue = (key, value) => setDraft(prev => {
const next = {...prev, [key]: value};
// When the Name matches a catalog entry, pre-fill the matching fields (category, size, calories, ...).
if (key === 'name' && hasNameField) {
const entry = catalogByName[String(value).trim().toLowerCase()];
if (entry) {
CATALOG_KEYS.forEach(k => {
if (k !== 'name' && fieldKeySet.has(k) && entry[k] != null && entry[k] !== '') {
next[k] = entry[k];
}
});
}
}
return next;
});
const submitDraft = () => {
const hasValue = Object.entries(draft).some(([k, v]) => !k.endsWith('_unit') && v !== '' && v != null);
if (!hasValue) {
return;
}
onChange([...items, {...draft, id: nextId(items)}]);
setDraft(emptyItem(fields));
focusFirst();
};
const startEdit = (item) => setEdits(prev => ({...prev, [item.id]: {...item}}));
const setEditValue = (id, key, value) =>
setEdits(prev => ({...prev, [id]: {...prev[id], [key]: value}}));
const saveEdit = (id) => {
onChange(items.map(i => i.id === id ? edits[id] : i));
setEdits(prev => {
const next = {...prev};
delete next[id];
return next;
});
};
const toggleSelected = (id) => setSelected(prev => {
const next = new Set(prev);
next.has(id) ? next.delete(id) : next.add(id);
return next;
});
const removeSelected = () => {
if (selected.size === 0) {
return;
}
onChange(items.filter(i => !selected.has(i.id)));
setSelected(new Set());
};
const sortedFields = [...fields].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
return <>
{/* Shared location suggestions (pooled across all inventories), referenced by location-field inputs. */}
{hasLocationField &&
<datalist id={LOCATION_LIST_ID}>
{(locations || []).map(l => <option key={l} value={l}/>)}
</datalist>}
{/* Food-catalog name suggestions; selecting one pre-fills the matching fields. */}
{hasNameField && (catalog || []).length > 0 &&
<datalist id={CATALOG_LIST_ID}>
{catalog.map(e => <option key={e.id ?? e.name} value={e.name}/>)}
</datalist>}
{selected.size > 0 &&
<Button color='red' onClick={removeSelected} style={{marginBottom: '0.5em'}}>
Delete {selected.size} selected
</Button>}
<Table celled unstackable sortable>
<TableHeader>
<TableRow>
<TableHeaderCell collapsing/>
{sortedFields.map(f => <TableHeaderCell
key={f.key}
sorted={sort && sort.key === f.key ? (sort.dir === 'asc' ? 'ascending' : 'descending') : undefined}
onClick={() => toggleSort(f.key)}
style={{cursor: 'pointer'}}>
{f.label}
</TableHeaderCell>)}
</TableRow>
</TableHeader>
<TableBody>
{displayItems.map(item => {
const editing = edits[item.id];
const expired = isExpired(item);
return <TableRow key={item.id} negative={expired}>
<TableCell collapsing>
<Checkbox checked={selected.has(item.id)} onChange={() => toggleSelected(item.id)}/>
{expired && <Icon name='warning sign' color='red' title='Expired'
style={{marginLeft: '0.4em'}}/>}
</TableCell>
{sortedFields.map(f => <TableCell key={f.key}>
{editing
? <FieldCell
field={f}
value={editing[f.key]}
unitValue={editing[`${f.key}_unit`]}
onChange={v => setEditValue(item.id, f.key, v)}
onUnitChange={v => setEditValue(item.id, `${f.key}_unit`, v)}
onEnter={() => saveEdit(item.id)}
listId={listIdFor(f)}
/>
: <span onClick={() => startEdit(item)} style={{cursor: 'pointer'}}>
{formatValue(item, f)}
</span>}
</TableCell>)}
</TableRow>;
})}
</TableBody>
<TableFooter>
{/* The persistent new-item entry row. */}
<TableRow>
<TableCell collapsing>
<Button primary size='mini' onClick={submitDraft} aria-label='Add item'>+</Button>
</TableCell>
{sortedFields.map((f, index) => <TableCell key={f.key}>
<FieldCell
field={f}
value={draft[f.key]}
unitValue={draft[`${f.key}_unit`]}
onChange={v => setDraftValue(f.key, v)}
onUnitChange={v => setDraftValue(`${f.key}_unit`, v)}
onEnter={submitDraft}
inputRef={index === 0 ? firstInputRef : undefined}
listId={listIdFor(f)}
/>
</TableCell>)}
</TableRow>
</TableFooter>
</Table>
</>;
}
function formatValue(item, field) {
const value = item[field.key];
if (value === '' || value == null) {
return '';
}
if (field.type === 'quantity') {
const unit = item[`${field.key}_unit`] || field.unit || '';
return `${value} ${unit}`.trim();
}
return String(value);
}

View file

@ -0,0 +1,143 @@
import React from "react";
import {fireEvent, render, screen} from "@testing-library/react";
import {InventoryTable} from "./InventoryTable";
const FIELDS = [
{key: 'name', label: 'Name', type: 'text', order: 0},
{key: 'count', label: 'Count', type: 'number', order: 1},
];
describe('InventoryTable keyboard entry', () => {
test('pressing Enter in the draft row submits the new item via onChange', () => {
const onChange = jest.fn();
render(<InventoryTable slug='food-storage' fields={FIELDS} items={[]} locations={[]} onChange={onChange}/>);
const nameInput = screen.getAllByLabelText('Name')[0];
fireEvent.change(nameInput, {target: {value: 'Salt'}});
fireEvent.keyDown(nameInput, {key: 'Enter'});
expect(onChange).toHaveBeenCalledTimes(1);
const newItems = onChange.mock.calls[0][0];
expect(newItems).toHaveLength(1);
expect(newItems[0].name).toBe('Salt');
expect(typeof newItems[0].id).toBe('number');
});
test('does not submit an empty draft row', () => {
const onChange = jest.fn();
render(<InventoryTable slug='food-storage' fields={FIELDS} items={[]} locations={[]} onChange={onChange}/>);
const nameInput = screen.getAllByLabelText('Name')[0];
fireEvent.keyDown(nameInput, {key: 'Enter'});
expect(onChange).not.toHaveBeenCalled();
});
test('new item id is unique relative to existing items', () => {
const onChange = jest.fn();
const items = [{id: 7, name: 'Salt', count: '5'}];
render(<InventoryTable slug='food-storage' fields={FIELDS} items={items} locations={[]} onChange={onChange}/>);
const nameInput = screen.getAllByLabelText('Name').slice(-1)[0]; // the draft row's input
fireEvent.change(nameInput, {target: {value: 'Rice'}});
fireEvent.keyDown(nameInput, {key: 'Enter'});
const newItems = onChange.mock.calls[0][0];
expect(newItems).toHaveLength(2);
expect(newItems[1].id).toBe(8);
});
test('clicking an existing item cell starts inline edit', () => {
const items = [{id: 1, name: 'Salt', count: '5'}];
render(<InventoryTable slug='food-storage' fields={FIELDS} items={items} locations={[]} onChange={jest.fn()}/>);
fireEvent.click(screen.getByText('Salt'));
const editInputs = screen.getAllByLabelText('Name').map(i => i.value);
expect(editInputs).toContain('Salt');
});
});
describe('InventoryTable sorting', () => {
const items = [
{id: 1, name: 'Rice', count: '5'},
{id: 2, name: 'Beans', count: '20'},
{id: 3, name: 'Apples', count: '12'},
];
const bodyNames = () =>
[...document.querySelectorAll('tbody tr')].map(tr => tr.querySelector('td:nth-child(2)').textContent);
test('clicking a text header sorts ascending then descending', () => {
render(<InventoryTable slug='s' fields={FIELDS} items={items} locations={[]} onChange={jest.fn()}/>);
expect(bodyNames()).toEqual(['Rice', 'Beans', 'Apples']); // entry order
fireEvent.click(screen.getByText('Name'));
expect(bodyNames()).toEqual(['Apples', 'Beans', 'Rice']);
fireEvent.click(screen.getByText('Name'));
expect(bodyNames()).toEqual(['Rice', 'Beans', 'Apples']);
});
test('numeric column sorts numerically, not lexically', () => {
render(<InventoryTable slug='s' fields={FIELDS} items={items} locations={[]} onChange={jest.fn()}/>);
fireEvent.click(screen.getByText('Count'));
// 5 < 12 < 20 numerically (lexical would put '12','20','5').
expect(bodyNames()).toEqual(['Rice', 'Apples', 'Beans']);
});
});
describe('InventoryTable catalog pre-fill', () => {
const CAT_FIELDS = [
{key: 'name', label: 'Name', type: 'text', order: 0},
{key: 'category', label: 'Category', type: 'text', order: 1},
{key: 'item_size', label: 'Size', type: 'quantity', unit: 'lb', order: 2},
{key: 'calories', label: 'kcal', type: 'calories', order: 3},
];
const CATALOG = [
{id: 1, name: 'White Rice', category: 'grains', subcategory: 'rice',
item_size: '5', item_size_unit: 'lb', calories: '8040'},
];
test('selecting a catalog name pre-fills the matching fields', () => {
render(<InventoryTable slug='s' fields={CAT_FIELDS} items={[]} locations={[]} catalog={CATALOG}
onChange={jest.fn()}/>);
// The catalog datalist is present.
expect(document.querySelector('#inventory-catalog-names option[value="White Rice"]')).toBeTruthy();
fireEvent.change(screen.getByLabelText('Name'), {target: {value: 'White Rice'}});
expect(screen.getByLabelText('Category').value).toBe('grains');
expect(screen.getByLabelText('Size').value).toBe('5');
expect(screen.getByLabelText('kcal').value).toBe('8040');
});
test('a non-catalog name leaves other fields untouched', () => {
render(<InventoryTable slug='s' fields={CAT_FIELDS} items={[]} locations={[]} catalog={CATALOG}
onChange={jest.fn()}/>);
fireEvent.change(screen.getByLabelText('Name'), {target: {value: 'Homemade Jerky'}});
expect(screen.getByLabelText('Category').value).toBe('');
expect(screen.getByLabelText('kcal').value).toBe('');
});
});
describe('InventoryTable expired highlighting', () => {
const FIELDS_WITH_DATE = [
{key: 'name', label: 'Name', type: 'text', order: 0},
{key: 'expiration_date', label: 'Expires', type: 'date', order: 1},
];
test('rows past a date field are flagged negative with a warning icon', () => {
const items = [
{id: 1, name: 'Old', expiration_date: '2000-01-01'},
{id: 2, name: 'Fresh', expiration_date: '2999-01-01'},
];
const {container} = render(
<InventoryTable slug='s' fields={FIELDS_WITH_DATE} items={items} locations={[]} onChange={jest.fn()}/>);
const rowOf = (name) => screen.getByText(name).closest('tr');
expect(rowOf('Old').className).toContain('negative');
expect(rowOf('Fresh').className).not.toContain('negative');
// One expired row -> one warning icon.
expect(container.querySelectorAll('i.warning.sign.icon').length).toBe(1);
});
});

View file

@ -0,0 +1,141 @@
import {all, create} from "mathjs";
// A scoped mathjs instance so inventory unit handling never affects the global mathjs (used elsewhere). All
// inventory quantity math (conversion + aggregation) lives here — the backend stores quantities as opaque
// {magnitude, unit} strings and does no unit math.
const math = create(all);
// Units offered in the unit dropdown for `quantity` fields, grouped by physical dimension. Names are mathjs unit
// names (note: mathjs uses `lb`/`lbs`/`lbm`, NOT `pound`).
export const UNIT_GROUPS = [
{label: 'Mass', units: ['lb', 'oz', 'kg', 'g', 'mg', 'ton', 'tonne', 'grain']},
{label: 'Volume', units: ['gallon', 'quart', 'pint', 'cup', 'floz', 'liter', 'ml', 'tablespoon', 'teaspoon']},
{label: 'Length', units: ['inch', 'foot', 'yard', 'mile', 'meter', 'cm', 'mm', 'km']},
];
export const ALL_UNITS = UNIT_GROUPS.flatMap(g => g.units);
// Compaction ladders (ascending): a summed quantity is displayed in the largest unit on a compatible ladder where
// the magnitude is still >= 1 (mirrors the old backend `compact_unit`, e.g. 2000 lb -> 1 ton, 16 oz + 1 lb -> 2 lb).
const COMPACTION_LADDERS = [
['oz', 'lb', 'ton'],
];
// Parse a magnitude + unit into a mathjs Unit, or null if it can't be parsed (blank value, or a non-standard unit
// like "can"/"each" the user typed). Note: Number('') === 0, so blank strings are rejected explicitly.
function toUnit(value, unit) {
if (value === '' || value === null || value === undefined) {
return null;
}
if (typeof value === 'string' && value.trim() === '') {
return null;
}
const n = Number(value);
if (!Number.isFinite(n) || !unit) {
return null;
}
try {
return math.unit(n, unit);
} catch {
return null;
}
}
// Convert a {value, unit} to another unit. Returns a number, or null when incompatible/unparseable.
export function convert(value, fromUnit, toUnitName) {
const u = toUnit(value, fromUnit);
if (!u) {
return null;
}
try {
return u.toNumber(toUnitName);
} catch {
return null;
}
}
function compact(unitValue) {
// unitValue is a mathjs Unit. On a compatible ladder, pick the largest unit where the value is still >= 1.
for (const ladder of COMPACTION_LADDERS) {
let compatible = false;
try {
unitValue.toNumber(ladder[0]);
compatible = true;
} catch {
// Not this ladder's dimension.
}
if (!compatible) {
continue;
}
let chosen = ladder[0];
for (const u of ladder) {
if (unitValue.toNumber(u) >= 1) {
chosen = u;
} else {
break;
}
}
return math.unit(unitValue.toNumber(chosen), chosen);
}
return unitValue;
}
function roundNumber(n) {
return Math.round(n * 1e5) / 1e5;
}
/**
* Sum a list of {value, unit} entries, combining compatible units and compacting the result.
*
* Returns {totals: [{magnitude, unit}], unitlessCount}:
* - `totals` is one entry per distinct physical dimension (mass, volume, ...), each summed and compacted.
* - `unitlessCount` counts entries with no/blank/non-standard unit but a numeric value (e.g. "5 cans"),
* so the UI can still show a plain count.
*/
export function sumQuantities(entries) {
const buckets = []; // [{unit: mathjsUnit, sample: unitName}]
let unitlessTotal = 0;
let hasUnitless = false;
for (const {value, unit} of entries) {
const parsed = toUnit(value, unit);
if (!parsed) {
const n = Number(value);
if (Number.isFinite(n) && n !== 0) {
unitlessTotal += n;
hasUnitless = true;
}
continue;
}
// Find an existing bucket with a matching dimension.
const bucket = buckets.find(b => {
try {
return b.unit.equalBase(parsed);
} catch {
return false;
}
});
if (bucket) {
bucket.unit = math.add(bucket.unit, parsed);
} else {
buckets.push({unit: parsed});
}
}
const totals = buckets.map(b => {
const compacted = compact(b.unit);
const {value, unit} = compacted.toJSON();
return {magnitude: roundNumber(value), unit};
});
return {totals, unitlessCount: hasUnitless ? roundNumber(unitlessTotal) : null};
}
// Format the result of sumQuantities into a short human string, e.g. "1.5 lb + 2 gallon (3 unitless)".
export function formatTotals(summed) {
const parts = (summed.totals || []).map(t => `${t.magnitude} ${t.unit}`);
if (summed.unitlessCount) {
parts.push(`${summed.unitlessCount} unitless`);
}
return parts.length ? parts.join(' + ') : '—';
}

View file

@ -0,0 +1,69 @@
import {convert, formatTotals, sumQuantities} from "./units";
describe('convert', () => {
test('converts within mass', () => {
expect(convert(16, 'oz', 'lb')).toBeCloseTo(1, 5);
expect(convert(2000, 'lb', 'ton')).toBeCloseTo(1, 5);
});
test('converts within volume', () => {
expect(convert(1, 'gallon', 'quart')).toBeCloseTo(4, 5);
});
test('returns null for incompatible or unparseable units', () => {
expect(convert(1, 'lb', 'gallon')).toBeNull();
expect(convert(1, 'each', 'lb')).toBeNull();
expect(convert('', 'lb', 'oz')).toBeNull();
});
});
describe('sumQuantities', () => {
test('sums compatible units and compacts', () => {
const result = sumQuantities([
{value: '16', unit: 'oz'},
{value: '1', unit: 'lb'},
]);
expect(result.totals).toHaveLength(1);
expect(result.totals[0].unit).toBe('lb');
expect(result.totals[0].magnitude).toBeCloseTo(2, 5);
expect(result.unitlessCount).toBeNull();
});
test('compacts pounds to tons past the threshold', () => {
const result = sumQuantities([{value: '2000', unit: 'lb'}]);
expect(result.totals[0].unit).toBe('ton');
expect(result.totals[0].magnitude).toBeCloseTo(1, 5);
});
test('keeps incompatible dimensions in separate buckets', () => {
const result = sumQuantities([
{value: '1', unit: 'lb'},
{value: '1', unit: 'gallon'},
]);
expect(result.totals).toHaveLength(2);
const unitNames = result.totals.map(t => t.unit).sort();
expect(unitNames).toEqual(['gallon', 'lb']);
});
test('counts unitless / non-standard-unit entries separately', () => {
const result = sumQuantities([
{value: '5', unit: 'each'},
{value: '3', unit: ''},
{value: '1', unit: 'lb'},
]);
expect(result.unitlessCount).toBeCloseTo(8, 5);
expect(result.totals).toHaveLength(1);
expect(result.totals[0].unit).toBe('lb');
});
});
describe('formatTotals', () => {
test('joins totals and unitless count', () => {
const summed = {totals: [{magnitude: 1.5, unit: 'lb'}, {magnitude: 2, unit: 'gallon'}], unitlessCount: 3};
expect(formatTotals(summed)).toBe('1.5 lb + 2 gallon + 3 unitless');
});
test('em-dash when empty', () => {
expect(formatTotals({totals: [], unitlessCount: null})).toBe('—');
});
});