From 947ee01b253b99d082e34bd710ae90a264d6a229 Mon Sep 17 00:00:00 2001 From: Roland Date: Fri, 19 Jun 2026 11:00:01 -0600 Subject: [PATCH] Add CSV/PDF export and a search filter to Inventory MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- app/src/App.css | 65 ++++++++ .../calculators/RationCalculator.js | 23 +-- .../inventory/InventoryExportPanel.js | 60 ++++++++ .../components/inventory/InventoryPrint.js | 57 +++++++ .../inventory/InventoryPrint.test.js | 64 ++++++++ .../components/inventory/InventoryRoute.js | 70 ++++++--- .../components/inventory/InventorySummary.js | 82 +++------- .../components/inventory/InventoryTable.js | 31 +++- .../inventory/InventoryTable.test.js | 90 ++++++++++- .../components/inventory/inventoryExport.js | 48 ++++++ .../inventory/inventoryExport.test.js | 61 ++++++++ app/src/components/inventory/summarize.js | 144 ++++++++++++++++++ .../components/inventory/summarize.test.js | 142 +++++++++++++++++ 13 files changed, 835 insertions(+), 102 deletions(-) create mode 100644 app/src/components/inventory/InventoryExportPanel.js create mode 100644 app/src/components/inventory/InventoryPrint.js create mode 100644 app/src/components/inventory/InventoryPrint.test.js create mode 100644 app/src/components/inventory/inventoryExport.js create mode 100644 app/src/components/inventory/inventoryExport.test.js create mode 100644 app/src/components/inventory/summarize.js create mode 100644 app/src/components/inventory/summarize.test.js diff --git a/app/src/App.css b/app/src/App.css index 58bd3514..6f949ac5 100644 --- a/app/src/App.css +++ b/app/src/App.css @@ -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; + } +} diff --git a/app/src/components/calculators/RationCalculator.js b/app/src/components/calculators/RationCalculator.js index 6c35b4d1..448ce2cf 100644 --- a/app/src/components/calculators/RationCalculator.js +++ b/app/src/components/calculators/RationCalculator.js @@ -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 diff --git a/app/src/components/inventory/InventoryExportPanel.js b/app/src/components/inventory/InventoryExportPanel.js new file mode 100644 index 00000000..601a40ee --- /dev/null +++ b/app/src/components/inventory/InventoryExportPanel.js @@ -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 <> + +
CSV
+

+ 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. +

+ +
+ + +
PDF
+

+ 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. +

+ {groupFields.length > 0 && +
+ + Summary group:{' '} + onSumKey(data.value || undefined)}/> + } +
} + +
+ ; +} diff --git a/app/src/components/inventory/InventoryPrint.js b/app/src/components/inventory/InventoryPrint.js new file mode 100644 index 00000000..40e61419 --- /dev/null +++ b/app/src/components/inventory/InventoryPrint.js @@ -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
+

{name}

+

{list.length} item{list.length === 1 ? '' : 's'} · printed {printed}

+ + + {cols.map(f => )} + + + {list.map(item => + {cols.map(f => )} + )} + +
{f.label || f.key}
{formatValue(item, f)}
+ + {summaryRows.length > 0 && <> +

Summary by {groupLabel}

+ + + + + + {sumKey && } + {caloriesKey && } + + + + {summaryRows.map(row => + + + {sumKey && } + {caloriesKey && } + )} + +
{groupLabel}ItemsTotalCalories
{row.name}{row.count}{row.total}{row.calories > 0 ? `${row.calories.toLocaleString()} kcal` : '—'}
+ } +
; +} diff --git a/app/src/components/inventory/InventoryPrint.test.js b/app/src/components/inventory/InventoryPrint.test.js new file mode 100644 index 00000000..89edd97f --- /dev/null +++ b/app/src/components/inventory/InventoryPrint.test.js @@ -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( + ); + + 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( + ); + 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( + ); + expect(container.querySelector('h2')).toBeNull(); + expect(tables(container).length).toBe(1); + }); +}); diff --git a/app/src/components/inventory/InventoryRoute.js b/app/src/components/inventory/InventoryRoute.js index bd57cf22..9e8bd96f 100644 --- a/app/src/components/inventory/InventoryRoute.js +++ b/app/src/components/inventory/InventoryRoute.js @@ -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() { } + {current && + setSearch(data.value)}/>} {current ? <> setTab('items')}/> setTab('summary')}/> + setTab('export')}/> - {tab === 'items' - ? <> - {/* Portrait mobile: condensed, read-only. Rotate to landscape (tablet+) for the full editor. */} - - - - - persistInventory(slug, {items: newItems})}/> - - - : } + {tab === 'items' && <> + {/* Portrait mobile: condensed, read-only. Rotate to landscape (tablet+) for the full editor. */} + + + + + {/* 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. */} + persistInventory(slug, {items: newItems})}/> + + } + {tab === 'summary' && } + {tab === 'export' && + } + + {/* Always mounted (hidden on screen) so the browser print dialog has the full table + summary to render. */} + setEditFieldsOpen(false)} diff --git a/app/src/components/inventory/InventorySummary.js b/app/src/components/inventory/InventorySummary.js index 227ca00a..9cc32c43 100644 --- a/app/src/components/inventory/InventorySummary.js +++ b/app/src/components/inventory/InventorySummary.js @@ -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}) { setQuantityKey(data.value)}/> +