mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-02 20:59:56 -05:00
Rebuild Inventory as a config-only system with food catalog and calculators
Replace the DB-backed inventory module with a config-only design and build out food-storage tooling around it. Inventory (config-only, no database) - Each inventory is a YAML file at config/inventory/<slug>.yaml, loaded once into memory and the single source of truth. New reusable MultiFileConfig (wrolpi/common.py) manages a directory of per-entity files. - Inventory types (food/fuel/tool) seed a customizable field schema (text/number/quantity/date/select/location/calories). Unit math/aggregation moved to the frontend (mathjs); Pint dropped from the backend. - Minimal API: GET / (all inventories full), POST /, PUT /<slug> (whole- inventory save with version-based optimistic concurrency; 404 for missing), DELETE. Legacy inventories.yaml / old tables migrate to per-inventory files (pound->lb), and an alembic migration drops the tables. Frontend - New app/src/components/inventory/ package: spreadsheet-style table with Tab/Enter keyboard entry, sortable columns, expired-row highlighting, customizable field editor, and pooled cross-inventory location autocomplete. - A single useInventories store loads everything once and persists whole inventories optimistically; list/items/summary/locations derive client-side. - Summary groups items (default by Category), totals size x count, shows a calories column, and embeds a ration estimate (how long the stock lasts). Food catalog - Shared, editable catalog (config/inventory/catalog.yaml) seeded from catalog_defaults.yaml (~60 generic items, total calories per package) with merge-keep-edits + tombstones. GET/PUT /api/inventory/catalog, a management modal, and entry-row pre-fill of category/size/calories from a name match. Calculators - Generic Food Storage planner (like the Water calculator): household + editable per-person/year amounts -> total to store over a chosen duration, with women/children weighted by DGA calorie shares and an imperial/metric toggle. Also fixes ConfigFile.save() to accept nested file_names. Backend pytest and frontend jest suites updated/added throughout; alembic check clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
ae5f64424d
commit
3d6aead072
46 changed files with 3612 additions and 2697 deletions
141
app/src/components/inventory/units.js
Normal file
141
app/src/components/inventory/units.js
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
import {all, create} from "mathjs";
|
||||
|
||||
// A scoped mathjs instance so inventory unit handling never affects the global mathjs (used elsewhere). All
|
||||
// inventory quantity math (conversion + aggregation) lives here — the backend stores quantities as opaque
|
||||
// {magnitude, unit} strings and does no unit math.
|
||||
const math = create(all);
|
||||
|
||||
// Units offered in the unit dropdown for `quantity` fields, grouped by physical dimension. Names are mathjs unit
|
||||
// names (note: mathjs uses `lb`/`lbs`/`lbm`, NOT `pound`).
|
||||
export const UNIT_GROUPS = [
|
||||
{label: 'Mass', units: ['lb', 'oz', 'kg', 'g', 'mg', 'ton', 'tonne', 'grain']},
|
||||
{label: 'Volume', units: ['gallon', 'quart', 'pint', 'cup', 'floz', 'liter', 'ml', 'tablespoon', 'teaspoon']},
|
||||
{label: 'Length', units: ['inch', 'foot', 'yard', 'mile', 'meter', 'cm', 'mm', 'km']},
|
||||
];
|
||||
|
||||
export const ALL_UNITS = UNIT_GROUPS.flatMap(g => g.units);
|
||||
|
||||
// Compaction ladders (ascending): a summed quantity is displayed in the largest unit on a compatible ladder where
|
||||
// the magnitude is still >= 1 (mirrors the old backend `compact_unit`, e.g. 2000 lb -> 1 ton, 16 oz + 1 lb -> 2 lb).
|
||||
const COMPACTION_LADDERS = [
|
||||
['oz', 'lb', 'ton'],
|
||||
];
|
||||
|
||||
// Parse a magnitude + unit into a mathjs Unit, or null if it can't be parsed (blank value, or a non-standard unit
|
||||
// like "can"/"each" the user typed). Note: Number('') === 0, so blank strings are rejected explicitly.
|
||||
function toUnit(value, unit) {
|
||||
if (value === '' || value === null || value === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (typeof value === 'string' && value.trim() === '') {
|
||||
return null;
|
||||
}
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n) || !unit) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return math.unit(n, unit);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Convert a {value, unit} to another unit. Returns a number, or null when incompatible/unparseable.
|
||||
export function convert(value, fromUnit, toUnitName) {
|
||||
const u = toUnit(value, fromUnit);
|
||||
if (!u) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return u.toNumber(toUnitName);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function compact(unitValue) {
|
||||
// unitValue is a mathjs Unit. On a compatible ladder, pick the largest unit where the value is still >= 1.
|
||||
for (const ladder of COMPACTION_LADDERS) {
|
||||
let compatible = false;
|
||||
try {
|
||||
unitValue.toNumber(ladder[0]);
|
||||
compatible = true;
|
||||
} catch {
|
||||
// Not this ladder's dimension.
|
||||
}
|
||||
if (!compatible) {
|
||||
continue;
|
||||
}
|
||||
let chosen = ladder[0];
|
||||
for (const u of ladder) {
|
||||
if (unitValue.toNumber(u) >= 1) {
|
||||
chosen = u;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return math.unit(unitValue.toNumber(chosen), chosen);
|
||||
}
|
||||
return unitValue;
|
||||
}
|
||||
|
||||
function roundNumber(n) {
|
||||
return Math.round(n * 1e5) / 1e5;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sum a list of {value, unit} entries, combining compatible units and compacting the result.
|
||||
*
|
||||
* Returns {totals: [{magnitude, unit}], unitlessCount}:
|
||||
* - `totals` is one entry per distinct physical dimension (mass, volume, ...), each summed and compacted.
|
||||
* - `unitlessCount` counts entries with no/blank/non-standard unit but a numeric value (e.g. "5 cans"),
|
||||
* so the UI can still show a plain count.
|
||||
*/
|
||||
export function sumQuantities(entries) {
|
||||
const buckets = []; // [{unit: mathjsUnit, sample: unitName}]
|
||||
let unitlessTotal = 0;
|
||||
let hasUnitless = false;
|
||||
|
||||
for (const {value, unit} of entries) {
|
||||
const parsed = toUnit(value, unit);
|
||||
if (!parsed) {
|
||||
const n = Number(value);
|
||||
if (Number.isFinite(n) && n !== 0) {
|
||||
unitlessTotal += n;
|
||||
hasUnitless = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Find an existing bucket with a matching dimension.
|
||||
const bucket = buckets.find(b => {
|
||||
try {
|
||||
return b.unit.equalBase(parsed);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
if (bucket) {
|
||||
bucket.unit = math.add(bucket.unit, parsed);
|
||||
} else {
|
||||
buckets.push({unit: parsed});
|
||||
}
|
||||
}
|
||||
|
||||
const totals = buckets.map(b => {
|
||||
const compacted = compact(b.unit);
|
||||
const {value, unit} = compacted.toJSON();
|
||||
return {magnitude: roundNumber(value), unit};
|
||||
});
|
||||
|
||||
return {totals, unitlessCount: hasUnitless ? roundNumber(unitlessTotal) : null};
|
||||
}
|
||||
|
||||
// Format the result of sumQuantities into a short human string, e.g. "1.5 lb + 2 gallon (3 unitless)".
|
||||
export function formatTotals(summed) {
|
||||
const parts = (summed.totals || []).map(t => `${t.magnitude} ${t.unit}`);
|
||||
if (summed.unitlessCount) {
|
||||
parts.push(`${summed.unitlessCount} unitless`);
|
||||
}
|
||||
return parts.length ? parts.join(' + ') : '—';
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue