wrolpi/app/src/components/inventory/units.test.js

129 lines
5.1 KiB
JavaScript
Raw Normal View History

import {convert, countByWeight, evaluateExpression, formatTotals, sumQuantities} from "./units";
describe('evaluateExpression', () => {
test('evaluates arithmetic to a numeric string', () => {
expect(evaluateExpression('400 - 20')).toBe('380');
expect(evaluateExpression('400-20')).toBe('380');
expect(evaluateExpression('(400 - 20) * 2')).toBe('760');
expect(evaluateExpression('10/4')).toBe('2.5');
});
test('rounds off floating-point noise', () => {
expect(evaluateExpression('0.1 + 0.2')).toBe('0.3');
});
test('leaves a plain number or bare negative unchanged', () => {
expect(evaluateExpression('380')).toBe('380');
expect(evaluateExpression('-20')).toBe('-20');
expect(evaluateExpression('')).toBe('');
expect(evaluateExpression(' ')).toBe(' ');
});
test('refuses anything with letters (no functions/constants) or unparseable input', () => {
expect(evaluateExpression('2 kg')).toBe('2 kg'); // unit text left for the unit field
expect(evaluateExpression('sqrt(9)')).toBe('sqrt(9)');
expect(evaluateExpression('400 -')).toBe('400 -'); // incomplete expression
expect(evaluateExpression('1/0')).toBe('1/0'); // Infinity is not finite -> unchanged
});
});
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
describe('countByWeight', () => {
test('divides total by unit weight and rounds to a whole number', () => {
expect(countByWeight('1000', 'g', '5', 'g')).toBe(200);
// 403.7 nails -> 404 (rounded to a whole number).
expect(countByWeight('1009.25', 'g', '2.5', 'g')).toBe(404);
});
test('converts mismatched units before dividing', () => {
expect(countByWeight('2', 'kg', '5', 'g')).toBe(400); // 2 kg / 5 g
expect(countByWeight('1', 'lb', '1', 'oz')).toBe(16);
});
test('a sub-unit or zero total yields a count of 0 (not null)', () => {
expect(countByWeight('1', 'g', '5', 'g')).toBe(0); // round(0.2) = 0
expect(countByWeight('0', 'g', '5', 'g')).toBe(0);
});
test('returns null when a weight is missing, zero, or incompatible', () => {
expect(countByWeight('', 'g', '5', 'g')).toBeNull();
expect(countByWeight('1000', 'g', '', 'g')).toBeNull();
expect(countByWeight('1000', 'g', '0', 'g')).toBeNull();
expect(countByWeight('1000', 'lb', '5', 'gallon')).toBeNull(); // incompatible dimensions
});
test('refuses to divide when only one side has a unit', () => {
expect(countByWeight('2', '', '1', 'oz')).toBeNull();
expect(countByWeight('2', 'oz', '1', '')).toBeNull();
// Both unitless divides the raw magnitudes.
expect(countByWeight('100', '', '4', '')).toBe(25);
});
});
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
describe('convert', () => {
test('converts within mass', () => {
expect(convert(16, 'oz', 'lb')).toBeCloseTo(1, 5);
expect(convert(2000, 'lb', 'ton')).toBeCloseTo(1, 5);
});
test('converts within volume', () => {
expect(convert(1, 'gallon', 'quart')).toBeCloseTo(4, 5);
});
test('returns null for incompatible or unparseable units', () => {
expect(convert(1, 'lb', 'gallon')).toBeNull();
expect(convert(1, 'each', 'lb')).toBeNull();
expect(convert('', 'lb', 'oz')).toBeNull();
});
});
describe('sumQuantities', () => {
test('sums compatible units and compacts', () => {
const result = sumQuantities([
{value: '16', unit: 'oz'},
{value: '1', unit: 'lb'},
]);
expect(result.totals).toHaveLength(1);
expect(result.totals[0].unit).toBe('lb');
expect(result.totals[0].magnitude).toBeCloseTo(2, 5);
expect(result.unitlessCount).toBeNull();
});
test('compacts pounds to tons past the threshold', () => {
const result = sumQuantities([{value: '2000', unit: 'lb'}]);
expect(result.totals[0].unit).toBe('ton');
expect(result.totals[0].magnitude).toBeCloseTo(1, 5);
});
test('keeps incompatible dimensions in separate buckets', () => {
const result = sumQuantities([
{value: '1', unit: 'lb'},
{value: '1', unit: 'gallon'},
]);
expect(result.totals).toHaveLength(2);
const unitNames = result.totals.map(t => t.unit).sort();
expect(unitNames).toEqual(['gallon', 'lb']);
});
test('counts unitless / non-standard-unit entries separately', () => {
const result = sumQuantities([
{value: '5', unit: 'each'},
{value: '3', unit: ''},
{value: '1', unit: 'lb'},
]);
expect(result.unitlessCount).toBeCloseTo(8, 5);
expect(result.totals).toHaveLength(1);
expect(result.totals[0].unit).toBe('lb');
});
});
describe('formatTotals', () => {
test('joins totals and unitless count', () => {
const summed = {totals: [{magnitude: 1.5, unit: 'lb'}, {magnitude: 2, unit: 'gallon'}], unitlessCount: 3};
expect(formatTotals(summed)).toBe('1.5 lb + 2 gallon + 3 unitless');
});
test('em-dash when empty', () => {
expect(formatTotals({totals: [], unitlessCount: null})).toBe('—');
});
});