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