Add CSV/PDF export and a search filter to Inventory

New Export tab with two client-side formats (no new dependencies):
- CSV: the raw items table (RFC-4180 quoting, UTF-8 BOM for Excel), generated
  entirely in the browser.  The download anchor is attached to the DOM and the
  object URL is revoked on the next tick for cross-browser robustness.
- PDF: a printable full-inventory table followed by a group-by summary table,
  via the browser's print dialog ("Save as PDF").  The summary's grouping is
  chosen in the Export tab.

Search filter: a box on its own line under the inventory selector filters the
active inventory across every column's displayed value (case-insensitive;
whitespace-separated terms are AND-ed).  It narrows the whole view — Items
table, Summary aggregation, and Export/PDF — while edits/adds in the table
still operate on the full inventory, so filtering never drops data.

Summary/export grouping:
- The group-by aggregation is extracted into a shared summarize.js (field-role
  detection + count-aware totals via units.js + calories), now the single
  source of truth for the Summary tab, the PDF summary, and the ration
  calculator.  findCaloriesKey/findCountKey moved here from RationCalculator
  (re-exported for back-compat).
- The Sum selector now offers number and calories fields in addition to
  quantity: number/calories are summed as a plain column total, while quantity
  stays count-aware and unit-compacted and the dedicated Calories column stays
  count-aware.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Roland 2026-06-19 11:00:01 -06:00
parent cc5afe3fbc
commit 947ee01b25
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
13 changed files with 835 additions and 102 deletions

View file

@ -479,3 +479,68 @@ tr.drag-deselecting td {
color: rgba(0, 0, 0, 0.87) !important;
}
/* Inventory "PDF" export: the printable table is hidden on screen and becomes the only
visible content when printing, so a user can use the browser dialog to Save as PDF. */
.inventory-print {
display: none;
}
@media print {
body * {
visibility: hidden;
}
.inventory-print,
.inventory-print * {
visibility: visible;
}
.inventory-print {
display: block;
position: absolute;
top: 0;
left: 0;
width: 100%;
color: #000;
}
.inventory-print h1 {
font-size: 18pt;
margin: 0 0 0.25em;
}
.inventory-print h2 {
font-size: 13pt;
margin: 1.25em 0 0.5em;
}
.inventory-print-meta {
font-size: 9pt;
color: #444;
margin: 0 0 0.75em;
}
.inventory-print table {
width: 100%;
border-collapse: collapse;
font-size: 10pt;
}
.inventory-print th,
.inventory-print td {
border: 1px solid #999;
padding: 4px 6px;
text-align: left;
vertical-align: top;
}
/* Repeat the header row at the top of each printed page. */
.inventory-print thead {
display: table-header-group;
}
.inventory-print tr {
page-break-inside: avoid;
}
}

View file

@ -4,6 +4,8 @@ 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";
// Field-role detection lives in inventory/summarize.js (single source of truth); re-exported here for back-compat.
export {findCaloriesKey, findCountKey} from "../inventory/summarize";
// Pure calculation functions for the Ration (food storage) estimate.
//
@ -46,27 +48,6 @@ export function daysOfFood(total, dailyDemand) {
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

View file

@ -0,0 +1,60 @@
import React from "react";
import {Select} from "semantic-ui-react";
import {Button, Header, Icon, Segment} from "../Theme";
import {downloadCSV, inventoryExportFilename, toCSV} from "./inventoryExport";
import {groupFieldsOf, summableFieldsOf} from "./summarize";
const fieldOptions = (fs) => fs.map(f => ({key: f.key, value: f.key, text: f.label}));
/**
* The "Export" tab: explains each export format and provides the action to produce it. CSV is the raw items table,
* generated entirely in the browser. "PDF" opens the print dialog over the hidden printable view (see
* InventoryPrint), which includes a summary table grouped by the field chosen here.
*/
export function InventoryExportPanel({name, fields, items, groupKey, sumKey, onGroupKey, onSumKey}) {
const count = (items || []).length;
const groupFields = groupFieldsOf(fields);
const summableFields = summableFieldsOf(fields);
const exportCSV = () =>
downloadCSV(inventoryExportFilename(name, 'csv'), toCSV(fields, items));
return <>
<Segment>
<Header as='h3'><Icon name='file alternate outline'/> CSV</Header>
<p>
A comma-separated spreadsheet of all {count} item{count === 1 ? '' : 's'} and every field, openable
in Excel, Numbers, or Google Sheets. Generated entirely on this device.
</p>
<Button primary onClick={exportCSV} disabled={count === 0}>
<Icon name='download'/> Download CSV
</Button>
</Segment>
<Segment>
<Header as='h3'><Icon name='file pdf outline'/> PDF</Header>
<p>
A printable table of the whole inventory, followed by a summary grouped by the field you choose.
This opens your browser's print dialog — choose "Save as PDF" as the destination to get a PDF file,
or print it on paper.
</p>
{groupFields.length > 0 &&
<div style={{marginBottom: '1em', display: 'flex', gap: '1em', flexWrap: 'wrap'}}>
<span>
Summary group:{' '}
<Select options={fieldOptions(groupFields)} value={groupKey || ''}
onChange={(e, data) => onGroupKey(data.value)}/>
</span>
{summableFields.length > 0 &&
<span>
Sum:{' '}
<Select clearable options={fieldOptions(summableFields)} value={sumKey || ''}
onChange={(e, data) => onSumKey(data.value || undefined)}/>
</span>}
</div>}
<Button onClick={() => window.print()} disabled={count === 0}>
<Icon name='print'/> Print / Save as PDF
</Button>
</Segment>
</>;
}

View file

@ -0,0 +1,57 @@
import React from "react";
import {formatValue} from "./InventoryTable";
import {findCaloriesKey, findCountKey, summarizeInventory} from "./summarize";
/**
* Printable rendering of a full inventory (every field, every item) plus a summary table grouped by `groupKey`,
* used for the "PDF" export via the browser's print dialog. It is hidden on screen
* (`.inventory-print { display: none }` in App.css) and becomes the only visible content when printing — so the
* user can "Save as PDF" without the app chrome.
*/
export function InventoryPrint({name, fields, items, groupKey, sumKey}) {
const cols = [...(fields || [])].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
const list = items || [];
const printed = new Date().toLocaleString();
const caloriesKey = findCaloriesKey(fields);
const countKey = findCountKey(fields);
const summaryRows = summarizeInventory(list, {fields, groupKey, sumKey, countKey, caloriesKey});
const groupLabel = cols.find(f => f.key === groupKey)?.label || 'Group';
return <div className='inventory-print'>
<h1>{name}</h1>
<p className='inventory-print-meta'>{list.length} item{list.length === 1 ? '' : 's'} · printed {printed}</p>
<table>
<thead>
<tr>{cols.map(f => <th key={f.key}>{f.label || f.key}</th>)}</tr>
</thead>
<tbody>
{list.map(item => <tr key={item.id}>
{cols.map(f => <td key={f.key}>{formatValue(item, f)}</td>)}
</tr>)}
</tbody>
</table>
{summaryRows.length > 0 && <>
<h2>Summary by {groupLabel}</h2>
<table>
<thead>
<tr>
<th>{groupLabel}</th>
<th>Items</th>
{sumKey && <th>Total</th>}
{caloriesKey && <th>Calories</th>}
</tr>
</thead>
<tbody>
{summaryRows.map(row => <tr key={row.name}>
<td>{row.name}</td>
<td>{row.count}</td>
{sumKey && <td>{row.total}</td>}
{caloriesKey && <td>{row.calories > 0 ? `${row.calories.toLocaleString()} kcal` : '—'}</td>}
</tr>)}
</tbody>
</table>
</>}
</div>;
}

View file

@ -0,0 +1,64 @@
import React from "react";
import {render} from "@testing-library/react";
import {InventoryPrint} from "./InventoryPrint";
const FIELDS = [
{key: 'name', label: 'Name', type: 'text', order: 0},
{key: 'category', label: 'Category', type: 'select', order: 1},
{key: 'item_size', label: 'Size', type: 'quantity', unit: 'lb', order: 2},
{key: 'count', label: 'Count', type: 'number', order: 3},
{key: 'calories', label: 'kcal', type: 'calories', order: 4},
];
const ITEMS = [
{id: 1, name: 'White Rice', category: 'grains', item_size: '30', item_size_unit: 'lb', count: '3', calories: '100'},
{id: 2, name: 'Oats', category: 'grains', item_size: '10', item_size_unit: 'lb', count: '2', calories: '50'},
{id: 3, name: 'Beans', category: 'legumes', item_size: '25', item_size_unit: 'lb', count: '1'},
];
describe('InventoryPrint', () => {
const tables = (container) => [...container.querySelectorAll('table')];
test('renders the full items table and a summary grouped by the chosen field', () => {
const {container} = render(
<InventoryPrint name='Food Storage' fields={FIELDS} items={ITEMS}
groupKey='category' sumKey='item_size'/>);
expect(container.querySelector('h1').textContent).toBe('Food Storage');
expect(container.querySelector('.inventory-print-meta').textContent).toMatch(/3 items/);
// Two tables: items, then summary.
const [itemsTable, summaryTable] = tables(container);
expect(itemsTable.querySelectorAll('tbody tr').length).toBe(3);
// Summary section header + grouped rows.
expect(container.querySelector('h2').textContent).toBe('Summary by Category');
const summaryRows = [...summaryTable.querySelectorAll('tbody tr')]
.map(tr => [...tr.querySelectorAll('td')].map(td => td.textContent));
// grains: 2 items, 110 lb, 400 kcal; legumes: 1 item, 25 lb, no calories.
expect(summaryRows).toEqual([
['grains', '2', '110 lb', '400 kcal'],
['legumes', '1', '25 lb', '—'],
]);
});
test('summing a number field shows a plain column total', () => {
const {container} = render(
<InventoryPrint name='Food Storage' fields={FIELDS} items={ITEMS}
groupKey='category' sumKey='count'/>);
const summaryRows = [...tables(container)[1].querySelectorAll('tbody tr')]
.map(tr => [...tr.querySelectorAll('td')].map(td => td.textContent));
// grains: 2 items, count 3+2=5; legumes: 1 item, count 1.
expect(summaryRows).toEqual([
['grains', '2', '5', '400 kcal'],
['legumes', '1', '1', '—'],
]);
});
test('omits the summary when there is no group key', () => {
const {container} = render(
<InventoryPrint name='X' fields={FIELDS} items={ITEMS} groupKey={undefined} sumKey='item_size'/>);
expect(container.querySelector('h2')).toBeNull();
expect(tables(container).length).toBe(1);
});
});

View file

@ -1,11 +1,14 @@
import React, {useState} from "react";
import React, {useMemo, 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 {filterItems, InventoryTable} from "./InventoryTable";
import {InventoryItemsMobile} from "./InventoryItemsMobile";
import {InventorySummary} from "./InventorySummary";
import {InventoryExportPanel} from "./InventoryExportPanel";
import {InventoryPrint} from "./InventoryPrint";
import {defaultGroupKey, defaultSumKey} from "./summarize";
import {FieldSchemaEditor} from "./FieldSchemaEditor";
import {CatalogEditor} from "./CatalogEditor";
import {Media} from "../../contexts/contexts";
@ -62,6 +65,12 @@ export function InventoryRoute() {
const [renaming, setRenaming] = useState(false);
const [renameValue, setRenameValue] = useState('');
const [confirmDelete, setConfirmDelete] = useState(false);
// Grouping for the PDF export's summary table (chosen in the Export tab, rendered by the always-mounted print
// view). null until seeded from the current inventory's schema.
const [exportGroupKey, setExportGroupKey] = useState(null);
const [exportSumKey, setExportSumKey] = useState(null);
// Free-text filter applied to the active inventory's items across every column.
const [search, setSearch] = useState('');
// Default to the first inventory once loaded.
React.useEffect(() => {
@ -71,8 +80,21 @@ export function InventoryRoute() {
}, [inventories, slug]);
const current = inventories?.find(i => i.slug === slug);
const fields = current ? current.fields : [];
const items = current ? current.items : [];
const fields = useMemo(() => (current ? current.fields : []), [current]);
const items = useMemo(() => (current ? current.items : []), [current]);
// Re-seed the export grouping when the selected inventory (or its schema) changes.
React.useEffect(() => {
setExportGroupKey(defaultGroupKey(fields));
setExportSumKey(defaultSumKey(fields));
}, [fields]);
// Clear the search when switching inventories.
React.useEffect(() => setSearch(''), [slug]);
// 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.
const filteredItems = useMemo(() => filterItems(items, fields, search), [items, fields, search]);
// Location suggestions are pooled across every inventory.
const locations = collectLocations(inventories);
@ -133,27 +155,41 @@ 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')}/>
<Menu.Item name='Export' active={tab === 'export'} onClick={() => setTab('export')}/>
</Menu>
{tab === 'items'
? <>
{/* Portrait mobile: condensed, read-only. Rotate to landscape (tablet+) for the full editor. */}
<Media at='mobile'>
<InventoryItemsMobile fields={fields} items={items}/>
</Media>
<Media greaterThanOrEqual='tablet'>
<InventoryTable slug={slug} fields={fields} items={items} locations={locations}
catalog={catalog}
onChange={newItems => persistInventory(slug, {items: newItems})}/>
</Media>
</>
: <InventorySummary fields={fields} items={items}/>}
{tab === 'items' && <>
{/* Portrait mobile: condensed, read-only. Rotate to landscape (tablet+) for the full editor. */}
<Media at='mobile'>
<InventoryItemsMobile fields={fields} items={filteredItems}/>
</Media>
<Media greaterThanOrEqual='tablet'>
{/* The table gets the FULL items (so edits/adds don't drop filtered-out rows) plus the search,
which it applies to its displayed rows only. */}
<InventoryTable slug={slug} fields={fields} items={items} locations={locations}
catalog={catalog} search={search}
onChange={newItems => persistInventory(slug, {items: newItems})}/>
</Media>
</>}
{tab === 'summary' && <InventorySummary fields={fields} items={filteredItems}/>}
{tab === 'export' &&
<InventoryExportPanel name={current.name} fields={fields} items={filteredItems}
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}
groupKey={exportGroupKey} sumKey={exportSumKey}/>
<FieldSchemaEditor fields={fields} open={editFieldsOpen}
onClose={() => setEditFieldsOpen(false)}

View file

@ -1,22 +1,26 @@
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 {RationEstimatePanel} from "../calculators/RationCalculator";
import {
defaultGroupKey, defaultSumKey, findCaloriesKey, findCountKey, groupFieldsOf, sortSummaryRows,
summableFieldsOf, summarizeInventory,
} from "./summarize";
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.
// 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).
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 groupFields = groupFieldsOf(fields);
const summableFields = summableFieldsOf(fields);
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 [groupKey, setGroupKey] = useState(defaultGroupKey(fields));
const [sumKey, setSumKey] = useState(defaultSumKey(fields));
const [sort, setSort] = useState({key: 'name', dir: 'asc'});
const toggleSort = (key) => setSort(prev =>
@ -25,53 +29,9 @@ export function InventorySummary({fields, items}) {
: {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 summarized = summarizeInventory(items, {fields, groupKey, sumKey, countKey, caloriesKey});
return sortSummaryRows(summarized, sort);
}, [items, fields, groupKey, sumKey, countKey, caloriesKey, sort]);
const sortDir = (key) => sort.key === key ? (sort.dir === 'asc' ? 'ascending' : 'descending') : undefined;
@ -89,11 +49,11 @@ export function InventorySummary({fields, items}) {
<Select options={fieldOptions(groupFields)} value={groupKey}
onChange={(e, data) => setGroupKey(data.value)}/>
</span>
{quantityFields.length > 0 &&
{summableFields.length > 0 &&
<span>
Sum:{' '}
<Select clearable options={fieldOptions(quantityFields)} value={quantityKey}
onChange={(e, data) => setQuantityKey(data.value)}/>
<Select clearable options={fieldOptions(summableFields)} value={sumKey || ''}
onChange={(e, data) => setSumKey(data.value || undefined)}/>
</span>}
</div>
<Table celled unstackable sortable>
@ -105,8 +65,8 @@ export function InventorySummary({fields, items}) {
</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>}
{sumKey && <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>
@ -115,7 +75,7 @@ export function InventorySummary({fields, items}) {
{rows.map(row => <TableRow key={row.name}>
<TableCell>{row.name}</TableCell>
<TableCell>{row.count}</TableCell>
{quantityKey && <TableCell>{row.total}</TableCell>}
{sumKey && <TableCell>{row.total}</TableCell>}
{caloriesKey &&
<TableCell>{row.calories > 0 ? `${row.calories.toLocaleString()} kcal` : '—'}</TableCell>}
</TableRow>)}

View file

@ -48,7 +48,7 @@ function compareByField(a, b, field) {
* 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}) {
export function InventoryTable({slug, fields, items, locations, catalog, search, onChange}) {
const [draft, setDraft] = useState(() => emptyItem(fields));
const [edits, setEdits] = useState({}); // itemId -> edited copy
const [selected, setSelected] = useState(new Set());
@ -120,6 +120,9 @@ export function InventoryTable({slug, fields, items, locations, catalog, onChang
return sort.dir === 'desc' ? sorted.reverse() : sorted;
}, [items, fields, sort]);
// The search filters which rows are shown; mutations below still operate on the full `items` prop.
const visibleItems = useMemo(() => filterItems(displayItems, fields, search), [displayItems, fields, search]);
const focusFirst = () => {
const node = firstInputRef.current;
if (node && node.focus) {
@ -213,7 +216,7 @@ export function InventoryTable({slug, fields, items, locations, catalog, onChang
</TableRow>
</TableHeader>
<TableBody>
{displayItems.map(item => {
{visibleItems.map(item => {
const editing = edits[item.id];
const expired = isExpired(item);
return <TableRow key={item.id} negative={expired}>
@ -239,6 +242,12 @@ export function InventoryTable({slug, fields, items, locations, catalog, onChang
</TableCell>)}
</TableRow>;
})}
{search && visibleItems.length === 0 && (items || []).length > 0 &&
<TableRow>
<TableCell colSpan={sortedFields.length + 1} style={{opacity: 0.7}}>
No items match "{search}".
</TableCell>
</TableRow>}
</TableBody>
<TableFooter>
{/* The persistent new-item entry row. */}
@ -289,3 +298,21 @@ export function isItemExpired(item, fields) {
return !isNaN(t) && t < start.getTime();
});
}
/**
* Filter items by a free-text search across every column's displayed value (using the same formatting as the
* table, so quantities match as "30 lb", dates as "2030-01-01", etc.). Case-insensitive; whitespace-separated
* terms are AND-ed. A blank search returns all items. Shared by the Items table, Summary, and export views.
*/
export function filterItems(items, fields, search) {
const query = (search || '').trim().toLowerCase();
if (!query) {
return items || [];
}
const terms = query.split(/\s+/);
const cols = [...(fields || [])].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
return (items || []).filter(item => {
const haystack = cols.map(f => formatValue(item, f)).join(' ').toLowerCase();
return terms.every(term => haystack.includes(term));
});
}

View file

@ -1,6 +1,6 @@
import React from "react";
import {fireEvent, render, screen} from "@testing-library/react";
import {InventoryTable} from "./InventoryTable";
import {filterItems, InventoryTable} from "./InventoryTable";
const FIELDS = [
{key: 'name', label: 'Name', type: 'text', order: 0},
@ -141,3 +141,91 @@ describe('InventoryTable expired highlighting', () => {
expect(container.querySelectorAll('i.warning.sign.icon').length).toBe(1);
});
});
describe('filterItems', () => {
const FIELDS = [
{key: 'name', label: 'Name', type: 'text', order: 0},
{key: 'category', label: 'Category', type: 'select', order: 1},
{key: 'item_size', label: 'Size', type: 'quantity', unit: 'lb', order: 2},
{key: 'count', label: 'Count', type: 'number', order: 3},
{key: 'expiration_date', label: 'Expires', type: 'date', order: 4},
];
const ITEMS = [
{id: 1, name: 'White Rice', category: 'grains', item_size: '30', item_size_unit: 'lb', count: '3',
expiration_date: '2030-01-01'},
{id: 2, name: 'Pinto Beans', category: 'legumes', item_size: '25', item_size_unit: 'lb', count: '2',
expiration_date: '2033-01-01'},
{id: 3, name: 'Canned Chicken', category: 'meats', item_size: '12.5', item_size_unit: 'oz', count: '12',
expiration_date: '2030-06-01'},
];
const names = (rows) => rows.map(r => r.name);
test('blank or whitespace search returns all items', () => {
expect(filterItems(ITEMS, FIELDS, '')).toHaveLength(3);
expect(filterItems(ITEMS, FIELDS, ' ')).toHaveLength(3);
});
test('matches a text column, case-insensitively', () => {
expect(names(filterItems(ITEMS, FIELDS, 'rice'))).toEqual(['White Rice']);
expect(names(filterItems(ITEMS, FIELDS, 'RICE'))).toEqual(['White Rice']);
});
test('matches a select column (category)', () => {
expect(names(filterItems(ITEMS, FIELDS, 'legumes'))).toEqual(['Pinto Beans']);
});
test('matches a date column', () => {
expect(names(filterItems(ITEMS, FIELDS, '2030'))).toEqual(['White Rice', 'Canned Chicken']);
});
test('matches a quantity column by its formatted value', () => {
expect(names(filterItems(ITEMS, FIELDS, '25 lb'))).toEqual(['Pinto Beans']);
});
test('whitespace-separated terms are AND-ed', () => {
expect(names(filterItems(ITEMS, FIELDS, 'canned chicken'))).toEqual(['Canned Chicken']);
expect(filterItems(ITEMS, FIELDS, 'rice beans')).toEqual([]);
});
test('a non-matching search returns nothing', () => {
expect(filterItems(ITEMS, FIELDS, 'xyzzy')).toEqual([]);
});
});
describe('InventoryTable search', () => {
const FIELDS = [
{key: 'name', label: 'Name', type: 'text', order: 0},
{key: 'count', label: 'Count', type: 'number', order: 1},
];
const items = [
{id: 1, name: 'White Rice', count: '3'},
{id: 2, name: 'Pinto Beans', count: '2'},
];
test('only matching rows are rendered, and the entry row remains', () => {
render(<InventoryTable slug='s' fields={FIELDS} items={items} locations={[]} search='rice'
onChange={jest.fn()}/>);
expect(screen.getByText('White Rice')).toBeTruthy();
expect(screen.queryByText('Pinto Beans')).toBeNull();
// The persistent draft entry row is still present.
expect(screen.getAllByLabelText('Name').length).toBeGreaterThan(0);
});
test('adding from the entry row while filtered preserves the hidden items', () => {
const onChange = jest.fn();
render(<InventoryTable slug='s' fields={FIELDS} items={items} locations={[]} search='rice'
onChange={onChange}/>);
const draftName = screen.getAllByLabelText('Name').slice(-1)[0];
fireEvent.change(draftName, {target: {value: 'Oats'}});
fireEvent.keyDown(draftName, {key: 'Enter'});
// onChange gets the FULL inventory (both originals + new), not just the filtered view.
const newItems = onChange.mock.calls[0][0];
expect(newItems.map(i => i.name)).toEqual(['White Rice', 'Pinto Beans', 'Oats']);
});
test('a non-matching search shows a no-match message', () => {
render(<InventoryTable slug='s' fields={FIELDS} items={items} locations={[]} search='xyzzy'
onChange={jest.fn()}/>);
expect(screen.getByText(/no items match/i)).toBeTruthy();
});
});

View file

@ -0,0 +1,48 @@
import {formatValue} from "./InventoryTable";
// Fields in display (column) order.
function orderedFields(fields) {
return [...(fields || [])].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
}
// Quote a single CSV cell per RFC 4180: wrap in double-quotes (escaping internal quotes by doubling) when the value
// contains a comma, quote, or newline.
function escapeCell(value) {
const s = value == null ? '' : String(value);
return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
/**
* Build an RFC-4180 CSV string for an inventory: a header row of field labels followed by one row per item, using
* the same value formatting as the on-screen table (quantity fields render as `<magnitude> <unit>`).
*/
export function toCSV(fields, items) {
const cols = orderedFields(fields);
const header = cols.map(f => escapeCell(f.label || f.key));
const rows = (items || []).map(item => cols.map(f => escapeCell(formatValue(item, f))));
return [header, ...rows].map(row => row.join(',')).join('\r\n');
}
// 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()
.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'inventory';
return `${base}.${ext}`;
}
// Trigger a browser download of `csv` as `filename`. A UTF-8 BOM is prepended so spreadsheet apps (notably Excel)
// detect the encoding and render non-ASCII characters correctly.
export function downloadCSV(filename, csv) {
const BOM = String.fromCharCode(0xFEFF);
const blob = new Blob([BOM + csv], {type: 'text/csv;charset=utf-8'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
// The anchor must be attached to the document for click() to trigger a download in some browsers, and the
// object URL must stay alive until the browser has started fetching it — so revoke on the next tick.
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 0);
}

View file

@ -0,0 +1,61 @@
import {inventoryExportFilename, toCSV} from "./inventoryExport";
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},
];
describe('toCSV', () => {
test('emits a header row of labels then one row per item, in field order', () => {
const items = [
{id: 1, name: 'White Rice', item_size: '30', item_size_unit: 'lb', count: '3'},
{id: 2, name: 'Honey', item_size: '12', item_size_unit: 'lb', count: '1'},
];
expect(toCSV(FIELDS, items)).toBe(
'Name,Size,Count\r\n' +
'White Rice,30 lb,3\r\n' +
'Honey,12 lb,1'
);
});
test('orders columns by field order, not array order', () => {
const unordered = [
{key: 'count', label: 'Count', type: 'number', order: 2},
{key: 'name', label: 'Name', type: 'text', order: 0},
];
const csv = toCSV(unordered, [{id: 1, name: 'Salt', count: '5'}]);
expect(csv.split('\r\n')[0]).toBe('Name,Count');
expect(csv.split('\r\n')[1]).toBe('Salt,5');
});
test('quotes values containing commas, quotes, or newlines (RFC 4180)', () => {
const fields = [{key: 'name', label: 'Name', type: 'text', order: 0}];
expect(toCSV(fields, [{id: 1, name: 'Beans, dried'}]).split('\r\n')[1])
.toBe('"Beans, dried"');
expect(toCSV(fields, [{id: 1, name: 'Bob\'s "Best"'}]).split('\r\n')[1])
.toBe('"Bob\'s ""Best"""');
expect(toCSV(fields, [{id: 1, name: 'line1\nline2'}]).split('\r\n').slice(1).join('\r\n'))
.toBe('"line1\nline2"');
});
test('blank/missing values render as empty cells', () => {
expect(toCSV(FIELDS, [{id: 1, name: 'Salt'}])).toBe('Name,Size,Count\r\nSalt,,');
});
test('no items yields just the header row', () => {
expect(toCSV(FIELDS, [])).toBe('Name,Size,Count');
});
});
describe('inventoryExportFilename', () => {
test('slugifies the inventory name with the given extension', () => {
expect(inventoryExportFilename('Food Storage', 'csv')).toBe('food-storage.csv');
expect(inventoryExportFilename(' My Tools!! ', 'csv')).toBe('my-tools.csv');
});
test('falls back to "inventory" for an empty name', () => {
expect(inventoryExportFilename('', 'csv')).toBe('inventory.csv');
expect(inventoryExportFilename(null, 'csv')).toBe('inventory.csv');
});
});

View file

@ -0,0 +1,144 @@
import {formatTotals, sumQuantities} from "./units";
// Field-role detection and client-side aggregation for an inventory. This is the single source of truth shared by
// the Summary tab, the PDF export, and the ration calculator — the backend stores raw items and does no aggregation.
// Fields the summary can group by (categorical), in schema order.
export function groupFieldsOf(fields) {
return (fields || []).filter(f => ['text', 'select', 'location'].includes(f.type));
}
// Fields the summary can sum, in schema order: quantity (unit-aware), plus number and calories (plain totals).
export function summableFieldsOf(fields) {
return (fields || []).filter(f => ['quantity', 'number', 'calories'].includes(f.type));
}
// Default grouping: prefer Category (so grains/dairy/etc. are visible), else the first group field.
export function defaultGroupKey(fields) {
const groups = groupFieldsOf(fields);
return (groups.find(f => f.key === 'category') || groups[0])?.key;
}
// Default field to sum: the first quantity field, else the first number, else the first calories field.
export function defaultSumKey(fields) {
const summable = summableFieldsOf(fields);
for (const type of ['quantity', 'number', 'calories']) {
const f = summable.find(s => s.type === type);
if (f) {
return f.key;
}
}
return undefined;
}
// 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;
}
// Parse an item's field value into a finite number, or null when blank/non-numeric.
function numericValue(item, key) {
const raw = item[key];
if (raw === '' || raw == null) {
return null;
}
const n = Number(raw);
return Number.isFinite(n) ? n : null;
}
/**
* Group items by `groupKey` and aggregate each group, returning rows sorted by group name.
*
* The "Total" depends on the summed field's type (looked up in `fields`):
* - `quantity` → count-aware, unit-compacted (Σ per-container size × count), e.g. "110 lb".
* - `number`/`calories`→ a plain column total of the raw values (Σ value, NOT × count), e.g. "280".
* The dedicated `calories` total in each row stays count-aware (Σ per-unit calories × count), independent of the
* chosen sum field.
*
* Each row: {name, count, total, totalSort, calories}. Returns [] when there is no group field. A blank/zero
* count is treated as a single unit (matches the ration estimate's convention).
*/
export function summarizeInventory(items, {fields, groupKey, sumKey, countKey, caloriesKey}) {
if (!groupKey) {
return [];
}
const sumType = (fields || []).find(f => f.key === sumKey)?.type;
const isQuantitySum = sumType === 'quantity';
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: [], plainTotal: 0, hasPlain: false, count: 0, calories: 0};
}
const group = groups[key];
group.count += 1;
const units = unitsOf(item);
if (sumKey && isQuantitySum) {
const size = Number(item[sumKey]);
group.entries.push({
value: (size > 0 ? size : 0) * units,
unit: item[`${sumKey}_unit`],
});
} else if (sumKey) {
// number / calories: a plain sum of the column's raw values.
const n = numericValue(item, sumKey);
if (n !== null) {
group.plainTotal += n;
group.hasPlain = true;
}
}
if (caloriesKey) {
const cal = Number(item[caloriesKey]);
if (cal > 0) {
group.calories += cal * units;
}
}
});
return Object.entries(groups).map(([name, g]) => {
let total, totalSort;
if (sumKey && isQuantitySum) {
const summed = sumQuantities(g.entries);
total = formatTotals(summed);
totalSort = (summed.totals || []).reduce((s, x) => s + x.magnitude, 0) + (summed.unitlessCount || 0);
} else if (sumKey) {
total = g.hasPlain ? g.plainTotal.toLocaleString() : '—';
totalSort = g.plainTotal;
} else {
total = '—';
totalSort = 0;
}
return {name, count: g.count, total, totalSort, calories: g.calories};
}).sort((a, b) => a.name.localeCompare(b.name));
}
// Return a copy of summary rows sorted by the given column (`name`|`count`|`total`|`calories`) and direction.
export function sortSummaryRows(rows, sort) {
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 [...rows].sort(compare);
}

View file

@ -0,0 +1,142 @@
import {
defaultGroupKey, defaultSumKey, findCaloriesKey, findCountKey, groupFieldsOf, sortSummaryRows,
summableFieldsOf, summarizeInventory,
} from "./summarize";
const FIELDS = [
{key: 'name', label: 'Name', type: 'text', order: 0},
{key: 'category', label: 'Category', type: 'select', order: 1},
{key: 'item_size', label: 'Size', type: 'quantity', unit: 'lb', order: 2},
{key: 'count', label: 'Count', type: 'number', order: 3},
{key: 'calories', label: 'kcal', type: 'calories', order: 4},
];
const ITEMS = [
{id: 1, name: 'White Rice', category: 'grains', item_size: '30', item_size_unit: 'lb', count: '3', calories: '100'},
{id: 2, name: 'Oats', category: 'grains', item_size: '10', item_size_unit: 'lb', count: '2', calories: '50'},
{id: 3, name: 'Beans', category: 'legumes', item_size: '25', item_size_unit: 'lb', count: '1', calories: '0'},
];
describe('field-role helpers', () => {
test('groupFieldsOf picks categorical (text/select/location) fields', () => {
expect(groupFieldsOf(FIELDS).map(f => f.key)).toEqual(['name', 'category']);
});
test('summableFieldsOf includes quantity, number, and calories fields', () => {
expect(summableFieldsOf(FIELDS).map(f => f.key)).toEqual(['item_size', 'count', 'calories']);
});
test('defaults: group by Category, sum the first quantity field', () => {
expect(defaultGroupKey(FIELDS)).toBe('category');
expect(defaultSumKey(FIELDS)).toBe('item_size');
});
test('defaultGroupKey falls back to the first group field when no Category', () => {
const noCat = [{key: 'fuel_type', label: 'Fuel', type: 'select', order: 0}];
expect(defaultGroupKey(noCat)).toBe('fuel_type');
});
test('defaultSumKey falls back to a number field when there is no quantity field', () => {
const noQty = [{key: 'qty', label: 'Qty', type: 'number', order: 0}];
expect(defaultSumKey(noQty)).toBe('qty');
});
test('findCaloriesKey / findCountKey detect by type/key', () => {
expect(findCaloriesKey(FIELDS)).toBe('calories');
expect(findCountKey(FIELDS)).toBe('count');
});
});
describe('summarizeInventory', () => {
test('quantity sum is count-aware and unit-compacted, with grouped calories', () => {
const rows = summarizeInventory(ITEMS, {
fields: FIELDS, groupKey: 'category', sumKey: 'item_size', countKey: 'count', caloriesKey: 'calories',
});
expect(rows.map(r => r.name)).toEqual(['grains', 'legumes']);
const grains = rows.find(r => r.name === 'grains');
expect(grains.count).toBe(2);
expect(grains.total).toBe('110 lb'); // 30×3 + 10×2
expect(grains.calories).toBe(400); // 100×3 + 50×2
const legumes = rows.find(r => r.name === 'legumes');
expect(legumes.total).toBe('25 lb'); // 25×1
expect(legumes.calories).toBe(0);
});
test('number sum is a plain column total (NOT multiplied by count)', () => {
const rows = summarizeInventory(ITEMS, {
fields: FIELDS, groupKey: 'category', sumKey: 'count', countKey: 'count',
});
expect(rows.find(r => r.name === 'grains').total).toBe('5'); // 3 + 2
expect(rows.find(r => r.name === 'legumes').total).toBe('1');
});
test('calories sum is a plain column total of the per-unit values', () => {
const rows = summarizeInventory(ITEMS, {
fields: FIELDS, groupKey: 'category', sumKey: 'calories', countKey: 'count',
});
expect(rows.find(r => r.name === 'grains').total).toBe('150'); // 100 + 50, not ×count
expect(rows.find(r => r.name === 'legumes').total).toBe('0');
});
test('a large plain total is formatted with grouping separators', () => {
const fields = [{key: 'g', type: 'select'}, {key: 'count', type: 'number'}];
const items = [{id: 1, g: 'x', count: '1500'}, {id: 2, g: 'x', count: '2500'}];
const rows = summarizeInventory(items, {fields, groupKey: 'g', sumKey: 'count'});
expect(rows[0].total).toBe((4000).toLocaleString());
});
test('a plain total with no numeric values shows —', () => {
const fields = [{key: 'g', type: 'select'}, {key: 'count', type: 'number'}];
const items = [{id: 1, g: 'x'}, {id: 2, g: 'x', count: ''}];
const rows = summarizeInventory(items, {fields, groupKey: 'g', sumKey: 'count'});
expect(rows[0].total).toBe('—');
});
test('blank/zero count counts as a single unit for quantity sums', () => {
const fields = [{key: 'g', type: 'select'}, {key: 'item_size', type: 'quantity', unit: 'lb'},
{key: 'count', type: 'number'}];
const items = [{id: 1, g: 'grains', item_size: '5', item_size_unit: 'lb', count: ''}];
const rows = summarizeInventory(items, {fields, groupKey: 'g', sumKey: 'item_size', countKey: 'count'});
expect(rows[0].total).toBe('5 lb');
});
test('missing group values bucket under "(none)"', () => {
const fields = [{key: 'name', type: 'text'}, {key: 'category', type: 'select'},
{key: 'item_size', type: 'quantity', unit: 'lb'}];
const items = [{id: 1, name: 'x', item_size: '5', item_size_unit: 'lb'}];
const rows = summarizeInventory(items, {fields, groupKey: 'category', sumKey: 'item_size'});
expect(rows[0].name).toBe('(none)');
});
test('returns [] when there is no group key', () => {
expect(summarizeInventory(ITEMS, {fields: FIELDS, groupKey: undefined})).toEqual([]);
});
test('no sum key yields a — total', () => {
const rows = summarizeInventory(ITEMS, {fields: FIELDS, groupKey: 'category'});
expect(rows.every(r => r.total === '—')).toBe(true);
});
});
describe('sortSummaryRows', () => {
const rows = [
{name: 'grains', count: 2, totalSort: 110, calories: 400},
{name: 'legumes', count: 1, totalSort: 25, calories: 0},
];
test('sorts by count descending', () => {
expect(sortSummaryRows(rows, {key: 'count', dir: 'desc'}).map(r => r.name)).toEqual(['grains', 'legumes']);
});
test('sorts by total ascending', () => {
expect(sortSummaryRows(rows, {key: 'total', dir: 'asc'}).map(r => r.name)).toEqual(['legumes', 'grains']);
});
test('does not mutate the input array', () => {
const copy = [...rows];
sortSummaryRows(rows, {key: 'calories', dir: 'desc'});
expect(rows).toEqual(copy);
});
});