Add manual import + backup Restore/Merge/Overwrite for inventory configs

Inventories are a config-only MultiFileConfig (config/inventory/<slug>.yaml) and
were not reachable by the admin config Restore UI, so there was no way to re-import
a hand-edited/copied-in file or restore an inventory from its daily backup.

Backend:
- MultiFileConfig gains generic helpers: get_backup_dates(slug)/_get_backup_file
  (surface the daily config/backup/<subdir>/<slug>-DATE.yaml files) and reimport()
  (rebuild the in-memory store from disk; picks up hand-edits and copied-in files,
  drops files deleted on disk).  backup_date is constrained to YYYYMMDD so it cannot
  traverse out of the backup directory.
- InventoriesConfig.preview_restore/apply_restore: overwrite replaces the whole
  inventory; merge unions items by id (keeps current fields and existing items).
  The pre-restore state is backed up automatically, so a restore is undoable.
- API: POST /inventory/reimport, GET /inventory/<slug>/backups,
  POST /inventory/<slug>/restore/preview, POST /inventory/<slug>/restore.

Frontend:
- New InventoryImportModal (opened from a Restore button in the Inventory toolbar):
  Re-import from disk, plus a dated-backup table with per-row Merge/Overwrite that
  previews the change before applying.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Roland 2026-06-19 16:13:56 -06:00
parent e7c737fe0c
commit 6a46cfd17d
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
11 changed files with 642 additions and 2 deletions

View file

@ -629,6 +629,47 @@ export async function deleteInventory(slug) {
return response;
}
export async function reimportInventories() {
// Re-read every inventory config file from disk (picks up hand-edits and copied-in files).
const response = await apiPost(`${API_URI}/inventory/reimport`);
if (response.ok) {
return (await response.json())['inventories'];
}
const message = await getErrorMessage(response, 'Failed to re-import inventories');
toast({type: 'error', title: 'Unexpected server response', description: message, time: 5000});
return null;
}
export async function getInventoryBackups(slug) {
const response = await apiGet(`${API_URI}/inventory/${slug}/backups`);
if (response.ok) {
return (await response.json())['dates'];
}
return [];
}
export async function postInventoryRestorePreview(slug, backupDate, mode) {
const body = {backup_date: backupDate, mode};
const response = await apiPost(`${API_URI}/inventory/${slug}/restore/preview`, body);
if (response.ok) {
return (await response.json())['preview'];
}
const message = await getErrorMessage(response, 'Failed to preview the backup');
toast({type: 'error', title: 'Unexpected server response', description: message, time: 5000});
return null;
}
export async function postInventoryRestore(slug, backupDate, mode) {
const body = {backup_date: backupDate, mode};
const response = await apiPost(`${API_URI}/inventory/${slug}/restore`, body);
if (response.ok) {
return (await response.json())['inventory'];
}
const message = await getErrorMessage(response, 'Failed to restore the backup');
toast({type: 'error', title: 'Unexpected server response', description: message, time: 5000});
return null;
}
export async function getCatalog() {
// The shared food catalog (known items with total calories per package).
const response = await apiGet(`${API_URI}/inventory/catalog`);

View file

@ -0,0 +1,193 @@
import React, {useContext, useEffect, useState} from "react";
import {toast} from "react-semantic-toasts-2";
import {TableBody, TableCell, TableHeader, TableHeaderCell, TableRow} from "semantic-ui-react";
import {Button, Divider, Header, Icon, Loader, Modal, Table} from "../Theme";
import {
getInventoryBackups, postInventoryRestore, postInventoryRestorePreview, reimportInventories,
} from "../../api";
import {ThemeContext} from "../../contexts/contexts";
const formatDate = (d) => d && d.length === 8 ? `${d.substring(0, 4)}-${d.substring(4, 6)}-${d.substring(6, 8)}` : d;
const itemName = (item) => (item && (item.name || `Item ${item.id}`)) || 'Item';
// Compact list of item names from a preview's add/remove arrays.
function ItemNameList({items}) {
const {t} = useContext(ThemeContext);
if (!items || items.length === 0) {
return null;
}
return <ul style={{marginTop: '0.25em'}}>
{items.map((i, idx) => <li key={`${i.id}-${idx}`} {...t}>{itemName(i)}</li>)}
</ul>;
}
/**
* Per-inventory import/restore modal (opened from the Inventory toolbar). Two actions:
* - Re-import from disk: reload every inventory's config file (picks up hand-edits and copied-in files).
* - Restore from a backup: pick a dated backup and Merge (add items missing by id) or Overwrite (replace).
* `onChanged` refreshes the page's inventory state after a successful action.
*/
export function InventoryImportModal({open, onClose, slug, name, onChanged}) {
const {t} = useContext(ThemeContext);
const [dates, setDates] = useState(null); // null while loading
const [reimporting, setReimporting] = useState(false);
const [selected, setSelected] = useState(null); // {date, mode, preview} confirmation view
const [previewing, setPreviewing] = useState(null); // `${date}:${mode}` currently loading a preview
const [applying, setApplying] = useState(false);
useEffect(() => {
if (!open) {
return;
}
let cancelled = false;
setDates(null);
setSelected(null);
setReimporting(false);
setApplying(false);
setPreviewing(null);
getInventoryBackups(slug).then(result => {
if (!cancelled) {
setDates(result || []);
}
});
return () => {
cancelled = true;
};
}, [open, slug]);
const doReimport = async () => {
setReimporting(true);
const result = await reimportInventories();
setReimporting(false);
if (result) {
await onChanged();
toast({type: 'success', title: 'Re-imported', description: 'Inventories reloaded from disk.', time: 4000});
onClose();
}
};
const selectAction = async (date, mode) => {
setPreviewing(`${date}:${mode}`);
const preview = await postInventoryRestorePreview(slug, date, mode);
setPreviewing(null);
if (preview) {
setSelected({date, mode, preview});
}
};
const applyRestore = async () => {
setApplying(true);
const inventory = await postInventoryRestore(slug, selected.date, selected.mode);
setApplying(false);
if (inventory) {
await onChanged();
toast({type: 'success', title: 'Restored', description: `Restored from ${formatDate(selected.date)}.`,
time: 4000});
onClose();
}
};
// Confirmation view: show what the chosen restore would change.
if (selected) {
const {date, mode, preview} = selected;
const modeLabel = mode === 'merge' ? 'Merge' : 'Overwrite';
return <Modal open={open} onClose={onClose} closeIcon size='small'>
<Modal.Header>{modeLabel} backup from {formatDate(date)}</Modal.Header>
<Modal.Content>
{applying
? <Loader active inline='centered'>Restoring…</Loader>
: <>
{mode === 'overwrite'
? <p {...t}>
Replace <strong>{name}</strong> entirely with the {formatDate(date)} backup
({preview.backup_count} item{preview.backup_count === 1 ? '' : 's'}).
</p>
: <p {...t}>
Add items from the {formatDate(date)} backup that aren't already present; your
current items and fields are kept.
</p>}
{preview.add.length > 0 && <>
<Header as='h5' color='green'><Icon name='plus'/> {preview.add.length} to add</Header>
<ItemNameList items={preview.add}/>
</>}
{preview.remove.length > 0 && <>
<Header as='h5' color='red'><Icon name='minus'/> {preview.remove.length} to remove</Header>
<ItemNameList items={preview.remove}/>
</>}
{preview.fields_change &&
<p {...t}><Icon name='columns'/> The field columns will also change.</p>}
{preview.add.length === 0 && preview.remove.length === 0 && !preview.fields_change &&
<p {...t}>No changes — this backup matches the current inventory.</p>}
<p style={{color: 'grey'}}>{preview.unchanged} unchanged
item{preview.unchanged === 1 ? '' : 's'}</p>
</>}
</Modal.Content>
<Modal.Actions>
{!applying && <>
<Button onClick={() => setSelected(null)}>Back</Button>
<Button color='green' onClick={applyRestore}><Icon name='check'/> Apply</Button>
</>}
</Modal.Actions>
</Modal>;
}
return <Modal open={open} onClose={onClose} closeIcon size='small'>
<Modal.Header>Import / Restore: {name}</Modal.Header>
<Modal.Content>
<Header as='h4'>Re-import from disk</Header>
<p {...t}>
Reload every inventory from its config file. Use this after editing a file by hand, or after copying
an inventory file in from another WROLPi.
</p>
<Button primary onClick={doReimport} loading={reimporting} disabled={reimporting}>
<Icon name='sync'/> Re-import from disk
</Button>
<Divider/>
<Header as='h4'>Restore from a backup</Header>
<p {...t}>
<strong>Merge</strong> adds items from the backup that aren't already present.
{' '}<strong>Overwrite</strong> replaces this inventory entirely with the backup.
</p>
{dates === null
? <Loader active inline='centered'>Loading backups…</Loader>
: dates.length === 0
? <p {...t}>No backups yet. A backup is saved automatically whenever this inventory changes.</p>
: <div style={{maxHeight: '320px', overflowY: 'auto'}}>
<Table compact unstackable>
<TableHeader>
<TableRow>
<TableHeaderCell>Date</TableHeaderCell>
<TableHeaderCell>Merge</TableHeaderCell>
<TableHeaderCell>Overwrite</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
{dates.map(date => <TableRow key={date}>
<TableCell>{formatDate(date)}</TableCell>
<TableCell>
<Button size='mini' color='green' loading={previewing === `${date}:merge`}
onClick={() => selectAction(date, 'merge')}>
<Icon name='plus'/> Merge
</Button>
</TableCell>
<TableCell>
<Button size='mini' color='orange'
loading={previewing === `${date}:overwrite`}
onClick={() => selectAction(date, 'overwrite')}>
<Icon name='refresh'/> Overwrite
</Button>
</TableCell>
</TableRow>)}
</TableBody>
</Table>
</div>}
</Modal.Content>
<Modal.Actions>
<Button onClick={onClose}>Close</Button>
</Modal.Actions>
</Modal>;
}

View file

@ -0,0 +1,69 @@
import React from "react";
import {fireEvent, render, screen, waitFor, within} from "@testing-library/react";
jest.mock("react-semantic-toasts-2", () => ({toast: jest.fn()}));
jest.mock("../../api", () => ({
getInventoryBackups: jest.fn(),
postInventoryRestorePreview: jest.fn(),
postInventoryRestore: jest.fn(),
reimportInventories: jest.fn(),
}));
import {InventoryImportModal} from "./InventoryImportModal";
import {getInventoryBackups, postInventoryRestore, postInventoryRestorePreview, reimportInventories} from "../../api";
const renderModal = (props = {}) => {
const onChanged = jest.fn(() => Promise.resolve());
const onClose = jest.fn();
render(<InventoryImportModal open slug='food-storage' name='Food Storage'
onChanged={onChanged} onClose={onClose} {...props}/>);
return {onChanged, onClose};
};
describe('InventoryImportModal', () => {
// CRA's jest config resets mock implementations before each test, so (re)set them here.
beforeEach(() => {
getInventoryBackups.mockResolvedValue(['20260115', '20260101']);
postInventoryRestorePreview.mockResolvedValue({
mode: 'merge', add: [{id: 2, name: 'Beans'}], remove: [], unchanged: 1,
fields_change: false, current_count: 1, backup_count: 2, backup_name: 'Food Storage',
});
postInventoryRestore.mockResolvedValue({slug: 'food-storage', items: []});
reimportInventories.mockResolvedValue([{slug: 'food-storage'}]);
});
test('lists backups and applies a merge restore', async () => {
const {onChanged, onClose} = renderModal();
// Backup dates load (newest first).
const row = (await screen.findByText('2026-01-15')).closest('tr');
fireEvent.click(within(row).getByRole('button', {name: /merge/i}));
// Preview is requested for that date/mode, then the confirmation view appears.
await waitFor(() => expect(postInventoryRestorePreview)
.toHaveBeenCalledWith('food-storage', '20260115', 'merge'));
await screen.findByText(/Merge backup from 2026-01-15/);
expect(screen.getByText(/1 to add/)).toBeInTheDocument();
expect(screen.getByText('Beans')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', {name: /apply/i}));
await waitFor(() => expect(postInventoryRestore)
.toHaveBeenCalledWith('food-storage', '20260115', 'merge'));
await waitFor(() => expect(onChanged).toHaveBeenCalled());
await waitFor(() => expect(onClose).toHaveBeenCalled());
});
test('re-import from disk reloads inventories', async () => {
const {onChanged} = renderModal();
await screen.findByText('2026-01-15'); // wait for initial load to settle
fireEvent.click(screen.getByRole('button', {name: /re-import from disk/i}));
await waitFor(() => expect(reimportInventories).toHaveBeenCalled());
await waitFor(() => expect(onChanged).toHaveBeenCalled());
});
test('fetches backups for the inventory on open', async () => {
renderModal();
await waitFor(() => expect(getInventoryBackups).toHaveBeenCalledWith('food-storage'));
});
});

View file

@ -12,6 +12,7 @@ import {RationEstimatePanel} from "../calculators/RationCalculator";
import {defaultGroupKey, defaultSumKey, findCaloriesKey, findCountKey} from "./summarize";
import {FieldSchemaEditor} from "./FieldSchemaEditor";
import {CatalogEditor} from "./CatalogEditor";
import {InventoryImportModal} from "./InventoryImportModal";
import {Media, ThemeContext} from "../../contexts/contexts";
const INVENTORY_TYPES = [
@ -56,7 +57,7 @@ function NewInventoryModal({open, onClose, onCreate}) {
export function InventoryRoute() {
useTitle('Inventory');
const {inventories, persistInventory, addInventory, removeInventory} = useInventories();
const {inventories, fetchInventories, persistInventory, addInventory, removeInventory} = useInventories();
const {catalog, persistCatalog} = useCatalog();
const [slug, setSlug] = useState(null);
@ -64,6 +65,7 @@ export function InventoryRoute() {
const [newOpen, setNewOpen] = useState(false);
const [catalogOpen, setCatalogOpen] = useState(false);
const [editFieldsOpen, setEditFieldsOpen] = useState(false);
const [importOpen, setImportOpen] = useState(false);
const [renaming, setRenaming] = useState(false);
const [renameValue, setRenameValue] = useState('');
const [confirmDelete, setConfirmDelete] = useState(false);
@ -164,6 +166,9 @@ export function InventoryRoute() {
<Button icon onClick={() => setEditFieldsOpen(true)} aria-label='Customize fields'>
<Icon name='columns'/> Fields
</Button>
<Button icon onClick={() => setImportOpen(true)} aria-label='Import or restore inventory'>
<Icon name='history'/> Restore
</Button>
<Button color='red' icon onClick={() => setConfirmDelete(true)} aria-label='Delete inventory'>
<Icon name='trash'/>
</Button>
@ -213,6 +218,9 @@ export function InventoryRoute() {
<FieldSchemaEditor fields={fields} open={editFieldsOpen}
onClose={() => setEditFieldsOpen(false)}
onSave={newFields => persistInventory(slug, {fields: newFields})}/>
<InventoryImportModal open={importOpen} onClose={() => setImportOpen(false)}
slug={slug} name={current.name} onChanged={fetchInventories}/>
</> : <p {...t}>Create an inventory to get started.</p>}
<NewInventoryModal open={newOpen} onClose={() => setNewOpen(false)} onCreate={onCreate}/>

View file

@ -38,6 +38,14 @@ def post_inventory(_: Request, body: schema.InventoryPostRequest):
return json_response(dict(inventory=inventory), HTTPStatus.CREATED)
@inventory_bp.post('/reimport')
@openapi.description('Re-read every inventory config file from disk (picks up hand-edits and copied-in files).')
def post_inventory_reimport(_: Request):
inventories = get_inventory_configs().reimport()
inventories = sorted(inventories, key=lambda i: (i.get('name') or '').lower())
return json_response(dict(inventories=inventories))
# Shared food catalog (static routes, declared before the dynamic /<slug> routes).
@inventory_bp.get('/catalog')
@openapi.description('Get the shared food catalog entries.')
@ -70,3 +78,40 @@ def inventory_delete(_: Request, slug: str):
raise UnknownInventory(f'No inventory: {slug}')
get_inventory_configs().delete_inventory(slug)
return response.empty()
@inventory_bp.get('/<slug:str>/backups')
@openapi.description('List the dated backups available for an inventory, newest first.')
def get_inventory_backups(_: Request, slug: str):
config = get_inventory_configs()
if config.get_inventory(slug) is None:
raise UnknownInventory(f'No inventory: {slug}')
return json_response(dict(dates=config.get_backup_dates(slug)))
@inventory_bp.post('/<slug:str>/restore/preview')
@openapi.definition(
summary='Preview restoring an inventory from a backup',
body=schema.InventoryRestoreRequest,
)
@validate(schema.InventoryRestoreRequest)
def post_inventory_restore_preview(_: Request, slug: str, body: schema.InventoryRestoreRequest):
config = get_inventory_configs()
if config.get_inventory(slug) is None:
raise UnknownInventory(f'No inventory: {slug}')
preview = config.preview_restore(slug, body.backup_date, body.mode)
return json_response(dict(preview=preview))
@inventory_bp.post('/<slug:str>/restore')
@openapi.definition(
summary='Restore an inventory from a backup (merge or overwrite)',
body=schema.InventoryRestoreRequest,
)
@validate(schema.InventoryRestoreRequest)
def post_inventory_restore(_: Request, slug: str, body: schema.InventoryRestoreRequest):
config = get_inventory_configs()
if config.get_inventory(slug) is None:
raise UnknownInventory(f'No inventory: {slug}')
inventory = config.apply_restore(slug, body.backup_date, body.mode)
return json_response(dict(inventory=inventory))

View file

@ -8,7 +8,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import List, Optional
from wrolpi.common import logger, MultiFileConfig
from wrolpi.common import logger, MultiFileConfig, read_config_data
from wrolpi.errors import ValidationError
from .defaults import (DEFAULT_INVENTORIES, FIELD_TYPES, default_fields, slugify)
@ -178,6 +178,86 @@ class InventoriesConfig(MultiFileConfig):
self._persist_slug(slug)
return self.get(slug)
def _load_backup(self, slug: str, backup_date: str) -> dict:
"""Read and validate a dated backup file for an inventory."""
file = self._get_backup_file(slug, backup_date)
if not file.is_file():
raise ValidationError(f'No backup for {slug} on {backup_date}')
data = read_config_data(file)
if not self.is_valid(data):
raise ValidationError(f'Backup is not a valid inventory config: {file}')
return data
def preview_restore(self, slug: str, backup_date: str, mode: str) -> dict:
"""Describe what restoring a backup would change, without applying it.
`overwrite` replaces the whole inventory (items present only in the backup are added, items present only in
the current inventory are removed, and the field schema may change). `merge` only adds backup items whose
id isn't already present (current fields and items are kept).
"""
if mode not in ('merge', 'overwrite'):
raise ValidationError('mode must be "merge" or "overwrite"')
if slug not in self._configs:
raise ValidationError(f'No inventory: {slug}')
backup = self._load_backup(slug, backup_date)
current = self.get(slug)
current_items = current.get('items') or []
backup_items = backup.get('items') or []
current_ids = {i.get('id') for i in current_items}
backup_ids = {i.get('id') for i in backup_items}
add = [i for i in backup_items if i.get('id') not in current_ids]
if mode == 'overwrite':
remove = [i for i in current_items if i.get('id') not in backup_ids]
unchanged = sum(1 for i in current_items if i.get('id') in backup_ids)
fields_change = (current.get('fields') or []) != (backup.get('fields') or [])
else:
remove = []
unchanged = len(current_items)
fields_change = False
return dict(
mode=mode,
add=add,
remove=remove,
unchanged=unchanged,
fields_change=fields_change,
current_count=len(current_items),
backup_count=len(backup_items),
backup_name=backup.get('name'),
)
def apply_restore(self, slug: str, backup_date: str, mode: str) -> dict:
"""Restore an inventory from a dated backup (see `preview_restore` for `merge`/`overwrite` semantics).
The pre-restore state is backed up by `_persist_slug`, so a restore can itself be undone."""
from wrolpi.dates import now
if mode not in ('merge', 'overwrite'):
raise ValidationError('mode must be "merge" or "overwrite"')
if slug not in self._configs:
raise ValidationError(f'No inventory: {slug}')
backup = self._load_backup(slug, backup_date)
with self.save_lock():
current = dict(self._configs[slug])
if mode == 'overwrite':
# Replace the editable parts with the backup; `slug`/`version` stay (version bumps on persist).
current['name'] = backup.get('name') or current.get('name')
current['type'] = backup.get('type') or current.get('type')
current['fields'] = backup.get('fields') or []
# Validate the field dicts (a corrupt backup field without a 'key' would otherwise raise a 500
# inside _normalize_items); raises a 400 ValidationError instead.
_validate_fields(current['fields'])
current['items'] = _normalize_items(backup.get('items') or [], current['fields'])
else:
current_items = current.get('items') or []
current_ids = {i.get('id') for i in current_items}
add = [i for i in (backup.get('items') or []) if i.get('id') not in current_ids]
current['items'] = _normalize_items(current_items + add, current.get('fields') or [])
current['viewed_at'] = now().isoformat()
self._configs[slug] = current
self._persist_slug(slug)
return self.get(slug)
def seed_defaults(self):
"""Create the default example inventories if the directory is empty."""
if self._configs:

View file

@ -6,3 +6,9 @@ from typing import Optional
class InventoryPostRequest:
name: str
type: Optional[str] = 'food'
@dataclass
class InventoryRestoreRequest:
backup_date: str
mode: str

View file

@ -80,3 +80,52 @@ async def test_put_version_conflict_api(food_inventory_factory, async_client):
async def test_missing_inventory_404(test_inventory_configs, async_client):
request, response = await async_client.put('/api/inventory/does-not-exist', content=json.dumps(dict(name='x')))
assert response.status_code == HTTPStatus.NOT_FOUND, response.status_code
@pytest.mark.asyncio
async def test_backups_and_restore_api(food_inventory_factory, test_inventory_configs, async_client):
"""List backups, preview, and apply a merge restore via the API."""
from modules.inventory.defaults import default_fields
from wrolpi.common import write_config_data
config = test_inventory_configs
slug = food_inventory_factory(items=[{'id': 1, 'name': 'Rice', 'count': '4'}])
backup = config._get_backup_file(slug, '20260101')
backup.parent.mkdir(parents=True, exist_ok=True)
write_config_data(dict(version=9, slug=slug, name='Food Storage', type='food', fields=default_fields('food'),
items=[{'id': 1, 'name': 'Rice', 'count': '4'}, {'id': 2, 'name': 'Beans', 'count': '2'}]),
backup)
request, response = await async_client.get(f'/api/inventory/{slug}/backups')
assert response.status_code == HTTPStatus.OK
# Saving the seed items also wrote today's backup, so just assert our dated backup is listed.
assert '20260101' in response.json['dates']
request, response = await async_client.post(f'/api/inventory/{slug}/restore/preview',
content=json.dumps(dict(backup_date='20260101', mode='merge')))
assert response.status_code == HTTPStatus.OK, response.json
assert {i['id'] for i in response.json['preview']['add']} == {2}
request, response = await async_client.post(f'/api/inventory/{slug}/restore',
content=json.dumps(dict(backup_date='20260101', mode='merge')))
assert response.status_code == HTTPStatus.OK, response.json
assert {i['name'] for i in response.json['inventory']['items']} == {'Rice', 'Beans'}
# A bad mode is rejected.
request, response = await async_client.post(f'/api/inventory/{slug}/restore',
content=json.dumps(dict(backup_date='20260101', mode='bogus')))
assert response.status_code == HTTPStatus.BAD_REQUEST, response.status_code
@pytest.mark.asyncio
async def test_reimport_api(food_inventory_factory, test_inventory_configs, async_client):
"""POST /reimport picks up an inventory file copied onto disk by hand."""
from modules.inventory.defaults import default_fields
from wrolpi.common import write_config_data
config = test_inventory_configs
food_inventory_factory(name='Food Storage')
write_config_data(dict(version=1, slug='tools-box', name='Tools Box', type='tool',
fields=default_fields('tool'), items=[]), config.get_file('tools-box'))
request, response = await async_client.post('/api/inventory/reimport')
assert response.status_code == HTTPStatus.OK, response.json
assert {i['slug'] for i in response.json['inventories']} == {'food-storage', 'tools-box'}

View file

@ -173,6 +173,78 @@ def test_seed_defaults_idempotent(test_inventory_configs):
assert len(config.all_inventories()) == 1
def _write_backup(config, slug, date, items, name='Food Storage'):
"""Write a dated backup file for an inventory (as the daily save would)."""
from wrolpi.common import write_config_data
backup = config._get_backup_file(slug, date)
backup.parent.mkdir(parents=True, exist_ok=True)
write_config_data(dict(version=9, slug=slug, name=name, type='food',
fields=default_fields('food'), items=items), backup)
return backup
def test_restore_overwrite_replaces_inventory(food_inventory_factory, test_inventory_configs):
config = test_inventory_configs
slug = food_inventory_factory(items=[dict(id=1, name='Rice', count='4'), dict(id=2, name='Beans', count='2')])
_write_backup(config, slug, '20260101', name='Old Name',
items=[dict(id=1, name='Rice', count='99'), dict(id=3, name='Oats', count='5')])
preview = config.preview_restore(slug, '20260101', 'overwrite')
assert {i['id'] for i in preview['add']} == {3} # Oats only in the backup
assert {i['id'] for i in preview['remove']} == {2} # Beans only in the current inventory
assert preview['unchanged'] == 1 # Rice (id 1) is in both
restored = config.apply_restore(slug, '20260101', 'overwrite')
assert restored['name'] == 'Old Name'
assert {i['name'] for i in restored['items']} == {'Rice', 'Oats'}
# Overwrite takes the backup's value for the shared item.
assert next(i for i in restored['items'] if i['name'] == 'Rice')['count'] == '99'
def test_restore_merge_unions_items_by_id(food_inventory_factory, test_inventory_configs):
config = test_inventory_configs
slug = food_inventory_factory(items=[dict(id=1, name='Rice', count='4')])
_write_backup(config, slug, '20260101',
items=[dict(id=1, name='Rice', count='99'), dict(id=2, name='Beans', count='2')])
preview = config.preview_restore(slug, '20260101', 'merge')
assert {i['id'] for i in preview['add']} == {2} # only Beans is new; id 1 already present
assert preview['remove'] == []
restored = config.apply_restore(slug, '20260101', 'merge')
assert {i['name'] for i in restored['items']} == {'Rice', 'Beans'}
# Merge keeps the existing item untouched (does NOT take the backup's count=99 for id 1).
assert next(i for i in restored['items'] if i['name'] == 'Rice')['count'] == '4'
def test_restore_rejects_bad_mode_and_missing_backup(food_inventory_factory, test_inventory_configs):
from wrolpi.errors import ValidationError
config = test_inventory_configs
slug = food_inventory_factory()
with pytest.raises(ValidationError):
config.preview_restore(slug, '20260101', 'bogus')
with pytest.raises(ValidationError):
config.preview_restore(slug, '20260101', 'overwrite') # no such backup file
# A non-YYYYMMDD backup_date must be rejected (path-traversal guard), not used to build a path.
with pytest.raises(ValidationError):
config.preview_restore(slug, '../../../../etc/passwd', 'overwrite')
def test_restore_overwrite_rejects_corrupt_fields(food_inventory_factory, test_inventory_configs):
"""A backup with a malformed field (no 'key') is rejected with a 400, not a 500 inside the save lock."""
from wrolpi.common import write_config_data
from wrolpi.errors import ValidationError
config = test_inventory_configs
slug = food_inventory_factory(items=[dict(id=1, name='Rice', count='4')])
backup = config._get_backup_file(slug, '20260101')
backup.parent.mkdir(parents=True, exist_ok=True)
write_config_data(dict(version=9, slug=slug, name='Food Storage', type='food',
fields=[dict(label='Broken', type='text')], # missing 'key'
items=[]), backup)
with pytest.raises(ValidationError):
config.apply_restore(slug, '20260101', 'overwrite')
def test_config_round_trip(food_inventory_factory, test_inventory_configs):
"""Saving to per-inventory YAML and re-importing preserves fields and items."""
config = test_inventory_configs

View file

@ -40,3 +40,42 @@ def test_invalid_file_is_skipped(test_inventory_configs):
# import_all must not raise; the bad file is skipped.
config.import_all()
assert 'broken' not in config.slugs
def test_reimport_picks_up_and_drops_files(food_inventory_factory, test_inventory_configs):
from modules.inventory.defaults import default_fields
from wrolpi.common import write_config_data
config = test_inventory_configs
food_inventory_factory(name='Food Storage')
# A file copied onto disk by hand is not in memory until a reimport.
new_file = config.get_file('tools-box')
write_config_data(dict(version=1, slug='tools-box', name='Tools Box', type='tool',
fields=default_fields('tool'), items=[]), new_file)
assert config.get('tools-box') is None
config.reimport()
assert config.get('tools-box') is not None
# Deleting the file on disk and re-importing drops it from memory (memory matches disk).
new_file.unlink()
config.reimport()
assert config.get('tools-box') is None
assert 'food-storage' in config.slugs
def test_get_backup_dates(food_inventory_factory, test_inventory_configs):
from modules.inventory.defaults import default_fields
from wrolpi.common import write_config_data
config = test_inventory_configs
slug = food_inventory_factory(name='Food Storage')
assert config.get_backup_dates(slug) == []
for date in ('20260101', '20260115'):
backup = config._get_backup_file(slug, date)
backup.parent.mkdir(parents=True, exist_ok=True)
write_config_data(dict(version=1, slug=slug, name='Food Storage', type='food',
fields=default_fields('food'), items=[]), backup)
# Newest first.
assert config.get_backup_dates(slug) == ['20260115', '20260101']
# A different slug that merely shares this slug's prefix is not matched (slug 'food' vs 'food-storage-...').
assert config.get_backup_dates('food') == []

View file

@ -969,6 +969,44 @@ class MultiFileConfig:
date_str = now().strftime('%Y%m%d')
return get_media_directory() / 'config' / 'backup' / self.subdirectory / f'{slug}-{date_str}.yaml'
def _backup_directory(self) -> Path:
return get_media_directory() / 'config' / 'backup' / self.subdirectory
def get_backup_dates(self, slug: str) -> list:
"""Scan the entity's backup directory for `<slug>-YYYYMMDD.yaml` files, return the dates newest-first."""
backup_dir = self._backup_directory()
if not backup_dir.is_dir():
return []
dates = []
for f in backup_dir.iterdir():
# The length+digit check rejects a different slug that merely shares this slug's prefix
# (e.g. slug 'food' must not match 'food-storage-20260101.yaml').
if f.is_file() and f.suffix == '.yaml' and f.name.startswith(f'{slug}-'):
date_str = f.name[len(slug) + 1:-len('.yaml')]
if len(date_str) == 8 and date_str.isdigit():
dates.append(date_str)
dates.sort(reverse=True)
return dates
def _get_backup_file(self, slug: str, backup_date: str) -> Path:
# `backup_date` is request-controlled; constrain it to YYYYMMDD so it cannot traverse out of the backup
# directory (e.g. '../../etc/something'). `slug` is already constrained to a known, in-memory entity.
if not re.fullmatch(r'\d{8}', backup_date or ''):
raise ValidationError('backup_date must be YYYYMMDD')
return self._backup_directory() / f'{slug}-{backup_date}.yaml'
def reimport(self) -> List[dict]:
"""Re-read every entity file from disk into memory so hand-edits and copied-in files are picked up.
The in-memory store is made to match the directory: entities whose file was deleted on disk are dropped,
edited files are reloaded, and newly-added files are discovered. Returns the resulting entities."""
discovered = set(self.discover())
for slug in list(self._configs.keys()):
if slug not in discovered:
self._configs.pop(slug, None)
self.import_all()
return self.all()
def dump_all(self):
"""Write every in-memory entity to disk."""
for slug in list(self._configs.keys()):