wrolpi/app/src/components/inventory/inventoryExport.js

64 lines
2.8 KiB
JavaScript
Raw Normal View History

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>
2026-06-19 11:00:01 -06:00
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');
}
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>
2026-06-19 12:39:58 -06:00
// 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 || []);
}
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>
2026-06-19 11:00:01 -06:00
// 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);
}