Add a recommended Food Storage example, a Ration tab, and a supply planner

Build on the rebuilt config-only Inventory with three related additions.

Recommended example inventory:
- A fresh install now seeds the "Food Storage" example with the recommended
  one-adult / one-year (~3,000 kcal/day) emergency food supply (60 items,
  ~1.12M kcal), instead of an empty inventory.
- The counts are layered on top of the shipped food catalog (single source of
  per-package nutrition) via RECOMMENDED_ONE_YEAR_FOOD_COUNTS, joined at seed
  time by recommended_food_storage_items().
- Genericized the two remaining brand names in the catalog defaults
  (Velveeta -> Processed Cheese, Spam -> Canned Lunch Meat) so both the catalog
  and the seeded inventory stay brand-free.

Ration tab (split out of Summary):
- Moved the Ration Estimate (People / Daily Calories / estimate table) out of
  the increasingly long Summary tab into its own "Ration" tab, shown only for
  inventories that have a calories field.

Supply planner ("Plan More Supply"):
- A slider picks a target duration longer than the current estimate; the whole
  inventory is scaled up proportionally (every item by the same factor, mix
  kept balanced) into a sortable shopping list of what to buy.
- Any split package rounds UP to a whole one (ceil), matching the "1.6 buckets
  -> buy 1 more" rule.
- The shopping list is exportable as CSV (reusing toCSV) and PDF (reusing the
  print-to-PDF path, scoped via body.printing-shopping so only the list prints
  -- no inventory or summary).

Search filter:
- Moved the items search out of the top toolbar (which implied it filtered
  every tab) into the Items tab, so it clearly narrows Items only;
  Summary/Ration/Export/print always use the full inventory.

Aggregation/role helpers (findNameKey, planSupplyPurchase) live in summarize.js,
the single source of truth shared by Summary, export, and the ration views.
All new pure functions and UI flows are covered by tests.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Roland 2026-06-19 12:39:58 -06:00
parent 5427beb5fb
commit ee0b827c71
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
14 changed files with 545 additions and 38 deletions

View file

@ -8,7 +8,8 @@ import {InventoryItemsMobile} from "./InventoryItemsMobile";
import {InventorySummary} from "./InventorySummary";
import {InventoryExportPanel} from "./InventoryExportPanel";
import {InventoryPrint} from "./InventoryPrint";
import {defaultGroupKey, defaultSumKey} from "./summarize";
import {RationEstimatePanel} from "../calculators/RationCalculator";
import {defaultGroupKey, defaultSumKey, findCaloriesKey, findCountKey} from "./summarize";
import {FieldSchemaEditor} from "./FieldSchemaEditor";
import {CatalogEditor} from "./CatalogEditor";
import {Media} from "../../contexts/contexts";
@ -82,6 +83,9 @@ export function InventoryRoute() {
const current = inventories?.find(i => i.slug === slug);
const fields = useMemo(() => (current ? current.fields : []), [current]);
const items = useMemo(() => (current ? current.items : []), [current]);
// The Ration tab (estimate + supply plan) only applies to inventories with a calories field.
const caloriesKey = useMemo(() => findCaloriesKey(fields), [fields]);
const countKey = useMemo(() => findCountKey(fields), [fields]);
// Re-seed the export grouping when the selected inventory (or its schema) changes.
React.useEffect(() => {
@ -90,9 +94,16 @@ export function InventoryRoute() {
}, [fields]);
// Clear the search when switching inventories.
React.useEffect(() => setSearch(''), [slug]);
// The Ration tab disappears for inventories without a calories field; fall back to Items if it was active.
React.useEffect(() => {
if (tab === 'ration' && !caloriesKey) {
setTab('items');
}
}, [tab, caloriesKey]);
// The search narrows the whole inventory view (Items display, Summary, Export); edits/adds in InventoryTable
// still operate on the full `items`, so filtering never drops data.
// The search lives in (and only narrows) the Items tab. It feeds the read-only mobile list here; the desktop
// table filters its own display from the full `items` it receives. Summary/Ration/Export always use the full
// inventory, so the filter never silently hides data on those tabs.
const filteredItems = useMemo(() => filterItems(items, fields, search), [items, fields, search]);
// Location suggestions are pooled across every inventory.
@ -155,20 +166,22 @@ export function InventoryRoute() {
</Button>
</>}
</div>
{current &&
<Input fluid icon='search' iconPosition='left' placeholder='Search items…' value={search}
aria-label='Search items' clearable style={{marginTop: '0.75em'}}
onChange={(e, data) => setSearch(data.value)}/>}
</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')}/>
{caloriesKey &&
<Menu.Item name='Ration' active={tab === 'ration'} onClick={() => setTab('ration')}/>}
<Menu.Item name='Export' active={tab === 'export'} onClick={() => setTab('export')}/>
</Menu>
{tab === 'items' && <>
{/* The search filter lives here so it clearly applies to the Items tab only, not Summary/Ration/Export. */}
<Input fluid icon='search' iconPosition='left' placeholder='Search items…' value={search}
aria-label='Search items' clearable style={{marginBottom: '0.75em'}}
onChange={(e, data) => setSearch(data.value)}/>
{/* Portrait mobile: condensed, read-only. Rotate to landscape (tablet+) for the full editor. */}
<Media at='mobile'>
<InventoryItemsMobile fields={fields} items={filteredItems}/>
@ -181,14 +194,17 @@ export function InventoryRoute() {
onChange={newItems => persistInventory(slug, {items: newItems})}/>
</Media>
</>}
{tab === 'summary' && <InventorySummary fields={fields} items={filteredItems}/>}
{tab === 'summary' && <InventorySummary fields={fields} items={items}/>}
{tab === 'ration' && caloriesKey &&
<RationEstimatePanel name={current.name} fields={fields} items={items}
caloriesKey={caloriesKey} countKey={countKey}/>}
{tab === 'export' &&
<InventoryExportPanel name={current.name} fields={fields} items={filteredItems}
<InventoryExportPanel name={current.name} fields={fields} items={items}
groupKey={exportGroupKey} sumKey={exportSumKey}
onGroupKey={setExportGroupKey} onSumKey={setExportSumKey}/>}
{/* Always mounted (hidden on screen) so the browser print dialog has the full table + summary to render. */}
<InventoryPrint name={current.name} fields={fields} items={filteredItems}
<InventoryPrint name={current.name} fields={fields} items={items}
groupKey={exportGroupKey} sumKey={exportSumKey}/>
<FieldSchemaEditor fields={fields} open={editFieldsOpen}

View file

@ -1,7 +1,6 @@
import React, {useMemo, useState} from "react";
import {Select, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {Header, Segment, Table} from "../Theme";
import {RationEstimatePanel} from "../calculators/RationCalculator";
import {Header, Table} from "../Theme";
import {
defaultGroupKey, defaultSumKey, findCaloriesKey, findCountKey, groupFieldsOf, sortSummaryRows,
summableFieldsOf, summarizeInventory,
@ -9,8 +8,8 @@ import {
import {ThemeContext} from "../../contexts/contexts";
// Aggregate the inventory client-side: group items by a chosen text/select field and sum a chosen quantity, number,
// or calories field. When the inventory has a `calories` field, a ration estimate is shown below the summary table.
// The grouping math lives in summarize.js (shared with the PDF export).
// or calories field. The grouping math lives in summarize.js (shared with the PDF export). The ration estimate
// lives in its own "Ration" tab (see RationEstimatePanel).
export function InventorySummary({fields, items}) {
const groupFields = groupFieldsOf(fields);
const summableFields = summableFieldsOf(fields);
@ -81,11 +80,5 @@ export function InventorySummary({fields, items}) {
</TableRow>)}
</TableBody>
</Table>
{caloriesKey &&
<Segment style={{marginTop: '2em'}}>
<Header as='h3'>Ration Estimate</Header>
<RationEstimatePanel items={items} caloriesKey={caloriesKey} countKey={countKey}/>
</Segment>}
</>;
}

View file

@ -23,6 +23,21 @@ export function toCSV(fields, items) {
return [header, ...rows].map(row => row.join(',')).join('\r\n');
}
// Column layout for an exported supply-plan shopping list, mirroring the on-screen table. No `type` is set, so
// the shared CSV writer formats every value as plain text/number.
const SHOPPING_LIST_FIELDS = [
{key: 'name', label: 'Item'},
{key: 'current', label: 'Have'},
{key: 'additional', label: 'Buy'},
{key: 'target', label: 'New Total'},
];
// Build a CSV of a supply-plan shopping list (rows from planSupplyPurchase: {name, current, additional, target}),
// reusing the inventory CSV writer so quoting/escaping stays identical.
export function shoppingListCSV(rows) {
return toCSV(SHOPPING_LIST_FIELDS, rows || []);
}
// Filesystem-safe export filename derived from the inventory name (e.g. "Food Storage" -> "food-storage.csv").
export function inventoryExportFilename(name, ext) {
const base = (name || 'inventory').trim().toLowerCase()

View file

@ -1,4 +1,4 @@
import {inventoryExportFilename, toCSV} from "./inventoryExport";
import {inventoryExportFilename, shoppingListCSV, toCSV} from "./inventoryExport";
const FIELDS = [
{key: 'name', label: 'Name', type: 'text', order: 0},
@ -48,6 +48,26 @@ describe('toCSV', () => {
});
});
describe('shoppingListCSV', () => {
test('emits the Item/Have/Buy/New Total columns for each plan row', () => {
const rows = [
{name: 'Canned Beans', current: 96, additional: 29, target: 125},
{name: 'Mixed Vegetables', current: 180, additional: 55, target: 235},
];
expect(shoppingListCSV(rows)).toBe(
'Item,Have,Buy,New Total\r\n' +
'Canned Beans,96,29,125\r\n' +
'Mixed Vegetables,180,55,235'
);
});
test('quotes a name containing a comma, and handles no rows', () => {
expect(shoppingListCSV([{name: 'Beans, dried', current: 1, additional: 1, target: 2}]).split('\r\n')[1])
.toBe('"Beans, dried",1,1,2');
expect(shoppingListCSV([])).toBe('Item,Have,Buy,New Total');
});
});
describe('inventoryExportFilename', () => {
test('slugifies the inventory name with the given extension', () => {
expect(inventoryExportFilename('Food Storage', 'csv')).toBe('food-storage.csv');

View file

@ -52,6 +52,54 @@ export function findCountKey(fields) {
return firstNumber ? firstNumber.key : null;
}
// The field whose value names each item (for the shopping-list label): prefer a field keyed "name", else the first
// text field, else none.
export function findNameKey(fields) {
const named = (fields || []).find(f => f.key === 'name');
if (named) {
return named.key;
}
const firstText = (fields || []).find(f => f.type === 'text');
return firstText ? firstText.key : null;
}
/**
* Build a proportional "buy more" shopping list to grow the whole inventory by `scale` (the target duration divided
* by the current duration). Every item is scaled by the same factor so the mix stays balanced — matching the
* user's mental model ("100 cans lasting 2 months, extend to 3 → buy 50 more").
*
* Each item's target count = ceil(currentCount × scale) — any fractional package is rounded UP to a whole one (a
* bucket of wheat that extrapolates to 1.6 buckets means buying 1 more, not 0). `additional` is the positive
* shortfall (items already at or above target are omitted). Items with no positive count have no basis to scale
* from and are skipped. Returns `{rows, addedCalories}` where rows = [{name, current, target, additional}] sorted
* by largest purchase first, and addedCalories is the calories the purchases would add (to project the new duration).
*/
export function planSupplyPurchase(items, {countKey, nameKey, caloriesKey, scale}) {
const rows = [];
let addedCalories = 0;
if (scale > 1) {
(items || []).forEach(item => {
const current = countKey ? Number(item[countKey]) : NaN;
if (!(current > 0)) {
return;
}
const target = Math.ceil(current * scale);
const additional = target - current;
if (additional <= 0) {
return;
}
const name = (nameKey && item[nameKey]) || '(unnamed)';
rows.push({name, current, target, additional});
const calories = caloriesKey ? Number(item[caloriesKey]) : 0;
if (calories > 0) {
addedCalories += calories * additional;
}
});
}
rows.sort((a, b) => b.additional - a.additional || a.name.localeCompare(b.name));
return {rows, addedCalories};
}
// Parse an item's field value into a finite number, or null when blank/non-numeric.
function numericValue(item, key) {
const raw = item[key];

View file

@ -1,6 +1,6 @@
import {
defaultGroupKey, defaultSumKey, findCaloriesKey, findCountKey, groupFieldsOf, sortSummaryRows,
summableFieldsOf, summarizeInventory,
defaultGroupKey, defaultSumKey, findCaloriesKey, findCountKey, findNameKey, groupFieldsOf, planSupplyPurchase,
sortSummaryRows, summableFieldsOf, summarizeInventory,
} from "./summarize";
const FIELDS = [
@ -45,6 +45,59 @@ describe('field-role helpers', () => {
expect(findCaloriesKey(FIELDS)).toBe('calories');
expect(findCountKey(FIELDS)).toBe('count');
});
test('findNameKey prefers a "name" field, else the first text field', () => {
expect(findNameKey(FIELDS)).toBe('name');
expect(findNameKey([{key: 'label', type: 'text'}, {key: 'note', type: 'text'}])).toBe('label');
expect(findNameKey([{key: 'qty', type: 'number'}])).toBe(null);
});
});
describe('planSupplyPurchase', () => {
const opts = (scale) => ({countKey: 'count', nameKey: 'name', caloriesKey: 'calories', scale});
test('the canonical example: 100 cans lasting 2 months, extend to 3 → buy 50 more', () => {
const items = [{name: 'Beans', count: '100', calories: '370'}];
const {rows} = planSupplyPurchase(items, opts(3 / 2));
expect(rows).toEqual([{name: 'Beans', current: 100, target: 150, additional: 50}]);
});
test('rounds a split package UP to a whole one', () => {
// One 50 lb bucket extrapolating to ~1.6 buckets → recommend buying 1 (not 0).
const items = [{name: 'Wheat', count: '1', calories: '7500'}];
expect(planSupplyPurchase(items, opts(1.6)).rows).toEqual(
[{name: 'Wheat', current: 1, target: 2, additional: 1}]);
// Even a small fraction rounds up.
expect(planSupplyPurchase(items, opts(1.05)).rows[0].additional).toBe(1);
});
test('scales every item proportionally (balanced restock) and reports added calories', () => {
const items = [
{name: 'Rice', count: '14', calories: '8040'},
{name: 'Beans', count: '96', calories: '370'},
{name: 'Salt', count: '6', calories: '0'}, // zero-calorie items still scale
];
const {rows, addedCalories} = planSupplyPurchase(items, opts(1.25));
const byName = Object.fromEntries(rows.map(r => [r.name, r]));
expect(byName.Rice.additional).toBe(4); // ceil(14×1.25)=18
expect(byName.Beans.additional).toBe(24); // ceil(96×1.25)=120
expect(byName.Salt.additional).toBe(2); // ceil(6×1.25)=8, still listed
// Added calories ignore the zero-calorie salt: 8040×4 + 370×24.
expect(addedCalories).toBe(8040 * 4 + 370 * 24);
// Sorted by largest purchase first.
expect(rows.map(r => r.name)).toEqual(['Beans', 'Rice', 'Salt']);
});
test('a scale of 1 or less yields no purchases', () => {
const items = [{name: 'Rice', count: '14', calories: '8040'}];
expect(planSupplyPurchase(items, opts(1)).rows).toEqual([]);
expect(planSupplyPurchase(items, opts(0.5)).rows).toEqual([]);
});
test('items with no positive count are skipped (no basis to scale)', () => {
const items = [{name: 'Mystery', count: '', calories: '500'}, {name: 'Rice', count: '0', calories: '8040'}];
expect(planSupplyPurchase(items, opts(2)).rows).toEqual([]);
});
});
describe('summarizeInventory', () => {