mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-04 05:39:57 -05:00
Format inventory expiration dates instead of epoch timestamps (#901)
Legacy inventory items stored date fields as Unix epoch seconds. The table showed the raw numbers, and sorting and expired highlighting did not treat them as dates. - Frontend parses date values as YYYY-MM-DD or legacy epoch seconds; display, mobile view, export, search, sort and the expired check all use calendar dates with no timezone shift. - The legacy migration converts epoch seconds to YYYY-MM-DD, and import repairs already-migrated files once. - Jest runs with a pinned timezone; the expiry tests pass under any process timezone. Closes #41 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
parent
d69f8317aa
commit
fe85815c35
11 changed files with 389 additions and 23 deletions
|
|
@ -9,8 +9,7 @@ from typing import List, Optional
|
|||
|
||||
from wrolpi.common import logger, MultiFileConfig, read_config_data
|
||||
from wrolpi.errors import ValidationError
|
||||
from .defaults import (DEFAULT_INVENTORIES, FIELD_TYPES, default_fields, slugify)
|
||||
|
||||
from .defaults import (DEFAULT_INVENTORIES, FIELD_TYPES, default_fields, normalize_item_dates, slugify)
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
|
|
@ -62,6 +61,7 @@ def _normalize_items(items: list, fields_: list) -> list:
|
|||
normalized = []
|
||||
for raw in items:
|
||||
clean = {k: (v.strip() if isinstance(v, str) else v) for k, v in raw.items() if k in allowed}
|
||||
normalize_item_dates([clean], fields_)
|
||||
item_id = raw.get('id')
|
||||
if not isinstance(item_id, int) or item_id in used:
|
||||
counter += 1
|
||||
|
|
@ -88,6 +88,27 @@ class InventoriesConfig(MultiFileConfig):
|
|||
# Exclude reserved files (e.g. catalog.yaml) that share the directory but are not inventories.
|
||||
return [slug for slug in super().discover() if slug not in RESERVED_SLUGS]
|
||||
|
||||
def import_all(self, send_events: bool = False):
|
||||
super().import_all(send_events=send_events)
|
||||
self._repair_legacy_dates()
|
||||
|
||||
def _repair_legacy_dates(self):
|
||||
"""One-time repair: inventories migrated before dates were normalized hold epoch seconds in their date
|
||||
fields. Rewrite those files as YYYY-MM-DD so every reader (API, MCP, frontend) sees a calendar date."""
|
||||
for slug in list(self._configs.keys()):
|
||||
entity = dict(self._configs[slug])
|
||||
items = [dict(i) for i in entity.get('items') or [] if isinstance(i, dict)]
|
||||
if not normalize_item_dates(items, entity.get('fields') or []):
|
||||
continue
|
||||
entity['items'] = items
|
||||
try:
|
||||
with self.save_lock():
|
||||
self._configs[slug] = entity
|
||||
self._persist_slug(slug)
|
||||
logger.info(f'Normalized legacy epoch dates in inventory {slug}')
|
||||
except Exception as e:
|
||||
logger.error(f'Failed to normalize legacy epoch dates in inventory {slug}', exc_info=e)
|
||||
|
||||
def all_inventories(self) -> List[dict]:
|
||||
"""Return every inventory in full (fields + items), sorted by name.
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ add/remove/reorder/retype fields freely. Quantity-field default units use mathj
|
|||
not ``pound``); all unit math happens in the frontend via mathjs.
|
||||
"""
|
||||
import re
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# Supported field types. The backend treats every value as an opaque string/number; only the frontend interprets
|
||||
# `quantity` (magnitude + `<key>_unit`), `date`, `select` (enum `options`), `location`, and `calories` (a number of
|
||||
|
|
@ -12,6 +13,42 @@ import re
|
|||
FIELD_TYPES = ('text', 'number', 'quantity', 'date', 'select', 'location', 'calories')
|
||||
|
||||
|
||||
_DATE_ONLY_RE = re.compile(r'^\d{4}-\d{2}-\d{2}$')
|
||||
# Legacy inventory dates were stored as Unix epoch seconds (optionally ``str(float)``, e.g. ``1893456000.0``).
|
||||
_EPOCH_SECONDS_RE = re.compile(r'^\d{9,10}(\.0+)?$')
|
||||
|
||||
|
||||
def normalize_date_value(value):
|
||||
"""Normalize a ``date``-field value: legacy epoch seconds become ``YYYY-MM-DD`` (UTC); anything else is
|
||||
returned unchanged (stripped if a string)."""
|
||||
if value is None or value == '':
|
||||
return value
|
||||
s = value.strip() if isinstance(value, str) else str(value)
|
||||
if _DATE_ONLY_RE.match(s):
|
||||
return s
|
||||
if _EPOCH_SECONDS_RE.match(s):
|
||||
return datetime.fromtimestamp(int(float(s)), tz=timezone.utc).strftime('%Y-%m-%d')
|
||||
return s
|
||||
|
||||
|
||||
def date_field_keys(fields_) -> set:
|
||||
"""The keys of every ``date``-type field in a field schema."""
|
||||
return {f['key'] for f in fields_ or [] if isinstance(f, dict) and f.get('type') == 'date'}
|
||||
|
||||
|
||||
def normalize_item_dates(items: list, fields_: list) -> bool:
|
||||
"""Normalize every date-field value of ``items`` in place. Returns True if anything changed."""
|
||||
changed = False
|
||||
for key in date_field_keys(fields_):
|
||||
for item in items or []:
|
||||
if isinstance(item, dict) and key in item:
|
||||
new = normalize_date_value(item[key])
|
||||
if new != item[key]:
|
||||
item[key] = new
|
||||
changed = True
|
||||
return changed
|
||||
|
||||
|
||||
def _field(key, label, type_, order, **kwargs):
|
||||
d = dict(key=key, label=label, type=type_, order=order)
|
||||
d.update({k: v for k, v in kwargs.items() if v is not None})
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ import shutil
|
|||
|
||||
from wrolpi.common import logger, read_config_data
|
||||
from wrolpi.dates import now
|
||||
from .defaults import default_fields, slugify
|
||||
from .defaults import default_fields, normalize_item_dates, slugify
|
||||
|
||||
logger = logger.getChild(__name__)
|
||||
|
||||
|
|
@ -42,6 +42,8 @@ def _convert_item(legacy: dict, item_id: int) -> dict:
|
|||
unit = normalize_unit(legacy.get('unit'))
|
||||
if unit:
|
||||
item['item_size_unit'] = unit
|
||||
# Legacy expiration dates are epoch seconds; store calendar dates like the rest of the app.
|
||||
normalize_item_dates([item], default_fields('food'))
|
||||
return item
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -79,7 +79,20 @@ def test_save_inventory_strips_whitespace(food_inventory_factory, test_inventory
|
|||
assert item['name'] == 'Rice'
|
||||
assert item['category'] == 'grains'
|
||||
assert item['count'] == '4'
|
||||
|
||||
|
||||
|
||||
def test_save_inventory_normalizes_legacy_epoch_expiration(food_inventory_factory, test_inventory_configs):
|
||||
config = test_inventory_configs
|
||||
slug = food_inventory_factory()
|
||||
saved = config.save_inventory(slug, dict(items=[
|
||||
dict(name='Rice', expiration_date='1893456000'),
|
||||
]))
|
||||
assert saved['items'][0]['expiration_date'] == '2030-01-01'
|
||||
# Short digit strings are not mistaken for epoch seconds.
|
||||
saved = config.save_inventory(slug, dict(items=[
|
||||
dict(name='Weird', expiration_date='2030'),
|
||||
]))
|
||||
assert saved['items'][0]['expiration_date'] == '2030'
|
||||
|
||||
def test_save_inventory_fields(food_inventory_factory, test_inventory_configs):
|
||||
config = test_inventory_configs
|
||||
|
|
|
|||
|
|
@ -55,6 +55,55 @@ def test_migrate_legacy_yaml(test_inventory_configs):
|
|||
assert legacy_file.with_suffix('.yaml.migrated').is_file()
|
||||
|
||||
|
||||
def test_migrate_converts_epoch_expiration_dates(test_inventory_configs):
|
||||
"""Legacy items stored expiration dates as epoch seconds (sometimes ``str(float)``); the migration writes
|
||||
calendar dates so no reader has to guess what an all-digit string means."""
|
||||
config = test_inventory_configs
|
||||
_write_legacy(config, [
|
||||
dict(name='Food Storage', created_at='2024-01-01', items=[
|
||||
dict(id=1, name='Salt', item_size='25', unit='lb', count='8', expiration_date=1893456000),
|
||||
dict(id=2, name='Rice', item_size='25', unit='lb', count='8', expiration_date='1893456000.0'),
|
||||
dict(id=3, name='Beans', item_size='25', unit='lb', count='8', expiration_date='2030-01-01'),
|
||||
dict(id=4, name='Odd', item_size='25', unit='lb', count='8', expiration_date='2030'),
|
||||
]),
|
||||
])
|
||||
|
||||
assert migrate_legacy_inventory(config) is True
|
||||
config.import_all()
|
||||
|
||||
inventory = config.get_inventory(config.all_inventories()[0]['slug'])
|
||||
assert [i['expiration_date'] for i in inventory['items']] == ['2030-01-01', '2030-01-01', '2030-01-01', '2030']
|
||||
# The file on disk holds calendar dates too.
|
||||
assert '1893456000' not in config.get_file(inventory['slug']).read_text()
|
||||
|
||||
|
||||
def test_import_repairs_legacy_epoch_dates(test_inventory_configs):
|
||||
"""Inventories migrated before dates were normalized are rewritten once on import."""
|
||||
config = test_inventory_configs
|
||||
directory = config.get_directory()
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
file = directory / 'food.yaml'
|
||||
with file.open('wt') as fh:
|
||||
yaml.dump(dict(
|
||||
version=3, slug='food', name='Food', type='food', created_at='2024-01-01', viewed_at='2024-01-01',
|
||||
fields=[dict(key='name', label='Name', type='text', order=0),
|
||||
dict(key='expiration_date', label='Expires', type='date', order=1)],
|
||||
items=[dict(id=1, name='Salt', expiration_date='1893456000'),
|
||||
dict(id=2, name='Rice', expiration_date='2030-06-01')],
|
||||
), fh)
|
||||
|
||||
config.import_all()
|
||||
inventory = config.get_inventory('food')
|
||||
assert [i['expiration_date'] for i in inventory['items']] == ['2030-01-01', '2030-06-01']
|
||||
# Repaired on disk, with a version bump so stale clients notice.
|
||||
assert '1893456000' not in file.read_text()
|
||||
assert inventory['version'] == 4
|
||||
|
||||
# A second import finds nothing to repair and does not rewrite the file.
|
||||
config.import_all()
|
||||
assert config.get_inventory('food')['version'] == 4
|
||||
|
||||
|
||||
def test_migrate_is_idempotent(test_inventory_configs):
|
||||
config = test_inventory_configs
|
||||
_write_legacy(config, [dict(name='Food', items=[])])
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue