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

@ -1,9 +1,12 @@
import React from "react";
import {GridColumn, Input, Label, TableBody, TableCell, TableRow} from "semantic-ui-react";
import {GridColumn, Input, Label, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import Grid from "semantic-ui-react/dist/commonjs/collections/Grid";
import {Form, Header, Table} from "../Theme";
import {Button, Form, Header, Icon, Table} from "../Theme";
import {InfoPopup, roundDigits, useLocalStorage} from "../Common";
import {formatDuration} from "./WaterCalculator";
import {findNameKey, planSupplyPurchase} from "../inventory/summarize";
import {downloadCSV, inventoryExportFilename, shoppingListCSV} from "../inventory/inventoryExport";
import {ThemeContext} from "../../contexts/contexts";
// Field-role detection lives in inventory/summarize.js (single source of truth); re-exported here for back-compat.
export {findCaloriesKey, findCountKey} from "../inventory/summarize";
@ -109,7 +112,7 @@ function fmt(value, unit) {
* 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}) {
export function RationEstimatePanel({name, items, fields, 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});
@ -178,8 +181,167 @@ export function RationEstimatePanel({items, caloriesKey, countKey}) {
</TableRow>
</TableBody>
</Table>
<SupplyPlan name={name} items={items} fields={fields} caloriesKey={caloriesKey} countKey={countKey}
currentDays={days} total={total} daily={daily}/>
</Form>;
}
// Print only the supply-plan shopping list (not the whole-inventory print block): toggle a body class that the
// `@media print` rules use to pick which printable block is visible, then open the print dialog.
function printShoppingList() {
document.body.classList.add('printing-shopping');
let timer;
const cleanup = () => {
clearTimeout(timer); // ensure the backstop can't fire later and clear the class during a new print
window.removeEventListener('afterprint', cleanup);
document.body.classList.remove('printing-shopping');
};
window.addEventListener('afterprint', cleanup, {once: true});
window.print();
// Backstop in case afterprint never fires (cancelled above once afterprint runs), so a later whole-inventory
// print isn't stuck in shopping mode.
timer = setTimeout(cleanup, 1000);
}
// Length of a "month" used for the supply plan, matching formatDuration()'s 30-day months so the slider label and
// the duration text agree.
const PLAN_MONTH_DAYS = 30;
const PLAN_INFO = 'Drag the slider to a target duration longer than your current estimate to see what to buy. '
+ 'Your whole inventory is scaled up proportionally — every item grows by the same factor so the mix stays '
+ 'balanced — and any split package is rounded up to a whole one. The projection assumes you keep the same '
+ 'variety of food and the same household/activity settings above.';
/**
* Extrapolation: a slider to pick a target duration longer than the current ration estimate, and a shopping list of
* the additional packages to buy to reach it (the inventory scaled up proportionally — see planSupplyPurchase).
*/
function SupplyPlan({name, items, fields, caloriesKey, countKey, currentDays, total, daily}) {
const {t} = React.useContext(ThemeContext);
const nameKey = findNameKey(fields);
const currentMonths = (currentDays || 0) / PLAN_MONTH_DAYS;
const minMonths = Math.max(1, Math.ceil(currentMonths));
const maxMonths = minMonths + 24;
const [targetMonths, setTargetMonths] = React.useState(minMonths);
// Keep the target within range as the estimate shifts (editing the household above moves the current duration).
React.useEffect(() => {
setTargetMonths(m => Math.min(Math.max(m, minMonths), maxMonths));
}, [minMonths, maxMonths]);
// Default to largest purchase first; clicking a header re-sorts.
const [sort, setSort] = React.useState({key: 'additional', dir: 'desc'});
const toggleSort = (key) => setSort(prev =>
prev.key === key
? {key, dir: prev.dir === 'asc' ? 'desc' : 'asc'}
: {key, dir: key === 'name' ? 'asc' : 'desc'});
if (!(currentDays > 0)) {
return null; // No usable estimate yet (no calories or no household) — nothing to extrapolate from.
}
const targetDays = targetMonths * PLAN_MONTH_DAYS;
const scale = targetDays / currentDays;
const {rows, addedCalories} = planSupplyPurchase(items, {countKey, nameKey, caloriesKey, scale});
const projectedDays = daily > 0 ? (total + addedCalories) / daily : null;
const totalToBuy = rows.reduce((sum, r) => sum + r.additional, 0);
const sortedRows = [...rows].sort((a, b) => {
const r = sort.key === 'name' ? a.name.localeCompare(b.name) : a[sort.key] - b[sort.key];
return sort.dir === 'desc' ? -r : r;
});
const sortDir = (key) => sort.key === key ? (sort.dir === 'asc' ? 'ascending' : 'descending') : undefined;
const headerCell = (key, label) =>
<TableHeaderCell sorted={sortDir(key)} onClick={() => toggleSort(key)} style={{cursor: 'pointer'}}>
{label}
</TableHeaderCell>;
return <div style={{marginTop: '2em'}}>
<Header as='h3'>Plan More Supply <InfoPopup content={PLAN_INFO}/></Header>
{!countKey
? <p {...t}>Add a <strong>Count</strong> field to this inventory to plan purchases.</p>
: <>
<div style={{padding: '0 0.5em'}}>
<input type='range' min={minMonths} max={maxMonths} step={1} value={targetMonths}
aria-label='Target duration (months)' style={{width: '100%'}}
onChange={e => setTargetMonths(Number(e.target.value))}/>
<Header as='h2' textAlign='center' style={{marginTop: '0.25em'}}>
Target: {formatDuration(targetDays)}
</Header>
<p {...t} style={{...t.style, textAlign: 'center', opacity: 0.8}}>
Currently {formatDuration(currentDays)}
</p>
</div>
{rows.length === 0
? <p {...t}>Drag the slider above your current estimate to see a shopping list.</p>
: <>
<Table celled unstackable sortable>
<TableHeader>
<TableRow>
{headerCell('name', 'Item')}
{headerCell('current', 'Have')}
{headerCell('additional', 'Buy')}
{headerCell('target', 'New Total')}
</TableRow>
</TableHeader>
<TableBody>
{sortedRows.map((r, i) => <TableRow key={`${r.name}-${i}`}>
<TableCell>{r.name}</TableCell>
<TableCell>{r.current}</TableCell>
<TableCell><strong>+{r.additional}</strong></TableCell>
<TableCell>{r.target}</TableCell>
</TableRow>)}
</TableBody>
</Table>
<p {...t}>
Buy <strong>{totalToBuy.toLocaleString()}</strong> additional package{totalToBuy === 1 ? '' : 's'}
{' '}across <strong>{rows.length}</strong> item{rows.length === 1 ? '' : 's'}
{projectedDays ? <> to reach about <strong>{formatDuration(projectedDays)}</strong> of food.</> : '.'}
</p>
<Button primary
onClick={() => downloadCSV(
inventoryExportFilename(`${name || 'inventory'} shopping list`, 'csv'),
shoppingListCSV(sortedRows))}>
<Icon name='download'/> Download CSV
</Button>
<Button onClick={printShoppingList}>
<Icon name='print'/> Print / Save as PDF
</Button>
{/* Hidden printable block — `printShoppingList` makes this the only thing printed. */}
<ShoppingListPrint name={name} rows={sortedRows}
targetText={formatDuration(targetDays)}
currentText={formatDuration(currentDays)}/>
</>}
</>}
</div>;
}
// Printable rendering of just the shopping list (no inventory or summary), shown only when printing via the
// `body.printing-shopping` toggle. Reuses the `.inventory-print` styling for headings and the table.
function ShoppingListPrint({name, rows, targetText, currentText}) {
return <div className='inventory-print shopping-print'>
<h1>{name || 'Inventory'} — Shopping List</h1>
<p className='inventory-print-meta'>
Target {targetText} (currently {currentText}) · {rows.length} item{rows.length === 1 ? '' : 's'} to buy
</p>
<table>
<thead>
<tr><th>Item</th><th>Have</th><th>Buy</th><th>New Total</th></tr>
</thead>
<tbody>
{rows.map((r, i) => <tr key={`${r.name}-${i}`}>
<td>{r.name}</td>
<td>{r.current}</td>
<td>+{r.additional}</td>
<td>{r.target}</td>
</tr>)}
</tbody>
</table>
</div>;
}
// 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

@ -1,4 +1,8 @@
import {dailyCalorieDemand, daysOfFood, findCaloriesKey, findCountKey, totalCalories} from "./RationCalculator";
import React from "react";
import {fireEvent, render, screen, within} from "@testing-library/react";
import {
dailyCalorieDemand, daysOfFood, findCaloriesKey, findCountKey, RationEstimatePanel, totalCalories,
} from "./RationCalculator";
describe('findCaloriesKey', () => {
test('detects a calories-type field', () => {
@ -71,3 +75,76 @@ describe('daysOfFood', () => {
expect(daysOfFood(14000, 0)).toBeNull();
});
});
describe('RationEstimatePanel supply plan', () => {
const FIELDS = [
{key: 'name', label: 'Name', type: 'text', order: 0},
{key: 'count', label: 'Count', type: 'number', order: 1},
{key: 'calories', label: 'kcal', type: 'calories', order: 2},
];
// 100 cans × 450 kcal = 45,000 kcal; with a survival ration for one man (1,500/day) that lasts exactly 30 days.
const ITEMS = [{name: 'Beans', count: '100', calories: '450'}];
beforeEach(() => {
window.localStorage.clear();
// Deterministic household: one man on the Survival preset → 1,500 kcal/day.
window.localStorage.setItem('ration_preset', JSON.stringify('survival'));
window.localStorage.setItem('ration_counts', JSON.stringify({men: '1', women: '', children: ''}));
});
test('dragging the target slider produces a round-up shopping list', () => {
render(<RationEstimatePanel items={ITEMS} fields={FIELDS} caloriesKey='calories' countKey='count'/>);
// Current estimate is 1 month, so the slider starts there with no purchases yet.
expect(screen.getByText(/drag the slider/i)).toBeTruthy();
// Drag to a 2-month target: scale ×2 → 100 → 200 cans, buy 100.
fireEvent.change(screen.getByLabelText(/target duration/i), {target: {value: '2'}});
// Scope to the on-screen table (the hidden print block duplicates these texts in the DOM).
const plan = within(document.querySelector('table.sortable'));
expect(plan.getByText('Beans')).toBeTruthy();
expect(plan.getByText('+100')).toBeTruthy();
// Summary line reports the total to buy.
expect(screen.getByText(/additional packages/).textContent).toMatch(/100 additional packages/);
});
test('clicking a column header re-sorts the shopping list', () => {
const items = [
{name: 'Apples', count: '10', calories: '100'},
{name: 'Beans', count: '200', calories: '100'},
];
render(<RationEstimatePanel items={items} fields={FIELDS} caloriesKey='calories' countKey='count'/>);
fireEvent.change(screen.getByLabelText(/target duration/i), {target: {value: '2'}});
const itemNames = () =>
[...document.querySelectorAll('table.sortable tbody tr td:first-child')].map(td => td.textContent);
// Default sort is largest purchase first (Beans buys far more than Apples).
expect(itemNames()).toEqual(['Beans', 'Apples']);
// Sorting by Item ascending flips to alphabetical (scope to the sortable table; the print block also has an
// "Item" header).
fireEvent.click(within(document.querySelector('table.sortable')).getByText('Item'));
expect(itemNames()).toEqual(['Apples', 'Beans']);
});
test('a populated plan offers CSV and PDF export, and printing scopes to the shopping list', () => {
const printSpy = jest.spyOn(window, 'print').mockImplementation(() => {});
render(<RationEstimatePanel name='Food Storage' items={ITEMS} fields={FIELDS}
caloriesKey='calories' countKey='count'/>);
fireEvent.change(screen.getByLabelText(/target duration/i), {target: {value: '2'}});
expect(screen.getByText(/Download CSV/i)).toBeTruthy();
// Printing toggles the body class the @media print rules use to show only the shopping list.
fireEvent.click(screen.getByText(/Print/i));
expect(printSpy).toHaveBeenCalled();
expect(document.body.classList.contains('printing-shopping')).toBe(true);
printSpy.mockRestore();
});
test('without a count field, the plan asks for one instead of a list', () => {
render(<RationEstimatePanel items={ITEMS} fields={FIELDS} caloriesKey='calories' countKey={null}/>);
expect(screen.getByText(/add a/i).textContent.toLowerCase()).toContain('count');
});
});