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>
2026-06-14 14:20:10 -06:00
|
|
|
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);
|
|
|
|
|
|
2026-06-19 15:07:29 -06:00
|
|
|
// Field types whose value is a number the user may type as an arithmetic expression (e.g. "400 - 20"). Shared
|
|
|
|
|
// so the table editor and cell editor can't drift apart when a new numeric type is added.
|
|
|
|
|
export const NUMERIC_TYPES = ['number', 'quantity', 'calories'];
|
|
|
|
|
|
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>
2026-06-14 14:20:10 -06:00
|
|
|
// 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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-19 15:07:29 -06:00
|
|
|
/**
|
|
|
|
|
* Evaluate a simple arithmetic expression typed into a numeric field to its numeric string, so a user can do math
|
|
|
|
|
* inline — e.g. "400 - 20" -> "380" (weigh a 400 g box of nails, subtract the 20 g box). Only bare arithmetic is
|
|
|
|
|
* allowed (digits, `. + - * / ( )` and spaces); anything containing a letter is rejected, so there are no function
|
|
|
|
|
* calls or constants to evaluate. A plain number, a bare negative, or anything unparseable is returned unchanged.
|
|
|
|
|
* Float noise is rounded off (0.1 + 0.2 -> 0.3).
|
|
|
|
|
*/
|
|
|
|
|
export function evaluateExpression(value) {
|
|
|
|
|
if (typeof value !== 'string') {
|
|
|
|
|
return value;
|
|
|
|
|
}
|
|
|
|
|
const expr = value.trim();
|
|
|
|
|
// Must look like arithmetic AND contain an operator beyond an optional leading sign (so "380" and "-20" are
|
|
|
|
|
// left alone rather than needlessly rewritten).
|
|
|
|
|
if (expr === '' || !/^[\d\s.+\-*/()]+$/.test(expr) || !/[+\-*/]/.test(expr.replace(/^[+-]/, ''))) {
|
|
|
|
|
return value;
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
const result = math.evaluate(expr);
|
|
|
|
|
if (typeof result === 'number' && Number.isFinite(result)) {
|
|
|
|
|
return String(Math.round(result * 1e6) / 1e6);
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
// Not a valid expression (e.g. "400-") — leave it as typed.
|
|
|
|
|
}
|
|
|
|
|
return value;
|
|
|
|
|
}
|
|
|
|
|
|
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>
2026-06-14 14:20:10 -06:00
|
|
|
// 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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
Add "Count by Weight" to estimate item counts from weighing
Counting bulk hardware (screws, nails) by hand is slow. This adds a workflow
to estimate the count from weight instead: weigh one item, weigh the lot, and
the count is filled in automatically.
- The Fields modal gains a "Count by Weight" button that adds two quantity
fields, Unit Weight and Total Weight (default grams), and tags the Count
field as computed. An existing `count` field is linked in place rather than
duplicated, so hand-counted items keep their values.
- The link is plain metadata on the Count field
(`compute: {kind: 'count_by_weight', total, unit}`), so it round-trips
through the config/API with no backend change (covered by a backend test).
- During item entry, Count = round(Total Weight / Unit Weight), converting
mismatched units first (g/kg/oz) and refusing to divide when only one side
has a unit. It rounds to a whole number (no 403.7 nails).
- When a weight changes, the count always reflects the new reality: it is set
to the computed value (0 for a sub-unit total) when both weights are present,
or cleared when they can't produce one (a weight blanked, incompatible
units) — so a stale count can never persist against edited weights. A
hand-typed count is only touched when a weight actually changes.
countByWeight lives in units.js; the field preset, config detection, and the
entry-time apply hook live in a new computeFields.js. Covered by unit tests
(countByWeight, computeFields), InventoryTable auto-fill / clear / sub-unit on
draft and inline edit, the FieldSchemaEditor preset, and a backend
field-metadata round-trip.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 14:36:26 -06:00
|
|
|
/**
|
|
|
|
|
* Estimate how many items a lot contains from a total weight and a single item's weight:
|
|
|
|
|
* count = round(total / unit), converting `total` into the unit-weight's unit first (so e.g. a 2 kg total and a
|
|
|
|
|
* 5 g unit weight give 400). The result is rounded to a whole number — you can't have 403.7 nails. A total below
|
|
|
|
|
* one item (or zero) gives 0, not null, so a corrected-down weight doesn't leave a stale count behind.
|
|
|
|
|
* Returns null when a weight is blank, the unit weight is non-positive, or the units are incompatible.
|
|
|
|
|
*/
|
|
|
|
|
export function countByWeight(total, totalUnit, unitWeight, unitWeightUnit) {
|
|
|
|
|
const each = Number(unitWeight);
|
|
|
|
|
if (!(each > 0) || total === '' || total === null || total === undefined) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
let totalInEachUnit;
|
|
|
|
|
if (totalUnit && unitWeightUnit && totalUnit !== unitWeightUnit) {
|
|
|
|
|
totalInEachUnit = convert(total, totalUnit, unitWeightUnit); // null if incompatible
|
|
|
|
|
} else if ((totalUnit || '') === (unitWeightUnit || '')) {
|
|
|
|
|
// Same unit (or both unitless) — divide the raw magnitudes.
|
|
|
|
|
const t = Number(total);
|
|
|
|
|
totalInEachUnit = Number.isFinite(t) ? t : null;
|
|
|
|
|
} else {
|
|
|
|
|
// One side has a unit and the other doesn't — can't safely divide, so refuse to guess.
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
if (totalInEachUnit === null || !Number.isFinite(totalInEachUnit) || totalInEachUnit < 0) {
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
return Math.round(totalInEachUnit / each); // 0 for a sub-unit (or zero) total
|
|
|
|
|
}
|
|
|
|
|
|
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>
2026-06-14 14:20:10 -06:00
|
|
|
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(' + ') : '—';
|
|
|
|
|
}
|